diff --git a/.github/workflows/check-pr.yaml b/.github/workflows/check-pr.yaml index 8ba1de3c422..d6ed8cc982a 100644 --- a/.github/workflows/check-pr.yaml +++ b/.github/workflows/check-pr.yaml @@ -13,15 +13,15 @@ jobs: outputs: lang-changed: ${{ steps.filter.outputs.lang == 'true' }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' gpg-private-key: ${{ secrets.OSSRH_GPG_KEY }} gpg-passphrase: ${{ secrets.OSSRH_GPG_PASSPHRASE }} - - uses: sbt/setup-sbt@v1 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 - name: Check PR run: sbt -J-Xlog:gc*=debug:file=./gc.log --batch checkPR #- if: always() @@ -61,7 +61,7 @@ jobs: report_paths: '**/target/test-reports/*.xml' create_check: false check_name: 'Check PR' - - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 + - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: filter with: filters: | @@ -69,17 +69,17 @@ jobs: - 'lang/**' - 'build.sbt' - 'project/*' - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 with: name: waves-fat-jar path: node/target/waves-all-*.jar - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 if: steps.filter.outputs.lang == 'true' with: name: file-compiler path: lang/jvm/target/file-compiler.jar - name: Save debug data - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 if: always() with: if-no-files-found: ignore @@ -97,11 +97,11 @@ jobs: matrix: os: [macos-15-intel, macos-15, ubuntu-24.04, ubuntu-24.04-arm, windows-2022] steps: - - uses: actions/setup-java@v4 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' - - uses: actions/download-artifact@v7 + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # 8.0.1 with: name: waves-fat-jar - run: java -cp '*' com.wavesplatform.utils.UtilApp smoke @@ -119,30 +119,30 @@ jobs: - waves-ducks-core/wavesducks-public - swopfi/swopfi-smart-contracts steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: ${{ matrix.repo }} - - uses: actions/setup-java@v4 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' - - uses: actions/download-artifact@v7 + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # 8.0.1 with: name: file-compiler - run: find -name "*.ride" -type f -exec java -jar file-compiler.jar {} +; run-integration-tests: name: Run integration tests - needs: check-pr + # needs: check-pr runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' - - uses: sbt/setup-sbt@v1 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 - name: Run Integration Tests run: sbt --batch "node-it/docker;node-it/test" env: @@ -154,13 +154,14 @@ jobs: create_check: false check_name: 'Run integration tests' - name: Upload Logs - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 if: always() with: if-no-files-found: ignore name: test-logs path: | node-it/target/logs/*/ + node-it/target/test-reports publish-snapshots: name: Publish snapshot packages @@ -170,15 +171,15 @@ jobs: env: PR_NUMBER: ${{ github.event.number }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' gpg-private-key: ${{ secrets.OSSRH_GPG_KEY }} gpg-passphrase: ${{ secrets.OSSRH_GPG_PASSPHRASE }} - - uses: sbt/setup-sbt@v1 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 - run: sbt -Dproject.version=$(awk -F '[".]' '{print $3"."$4"."$5+1}' version.sbt)-$PR_NUMBER-SNAPSHOT --batch publish env: SONATYPE_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} diff --git a/.github/workflows/on-push-default-branch.yml b/.github/workflows/on-push-default-branch.yml index a638ba51d55..a6c921d2075 100644 --- a/.github/workflows/on-push-default-branch.yml +++ b/.github/workflows/on-push-default-branch.yml @@ -10,29 +10,29 @@ jobs: name: Update Dependency Graph runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' - - uses: sbt/setup-sbt@v1 - - uses: scalacenter/sbt-dependency-submission@v3 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 + - uses: scalacenter/sbt-dependency-submission@f43202114d7522a4b233e052f82c2eea8d658134 # v3.2.1 with: configs-ignore: test compile-internal provided publish-snapshot: name: Publish Snapshots to Sonatype runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' gpg-private-key: ${{ secrets.OSSRH_GPG_KEY }} gpg-passphrase: ${{ secrets.OSSRH_GPG_PASSPHRASE }} - - uses: sbt/setup-sbt@v1 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 - name: Publish snapshots env: SONATYPE_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} diff --git a/.github/workflows/on-release-published.yml b/.github/workflows/on-release-published.yml index 03a377fa30d..ed500d9ef06 100644 --- a/.github/workflows/on-release-published.yml +++ b/.github/workflows/on-release-published.yml @@ -28,21 +28,21 @@ jobs: needs: publish-node-image runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 + - uses: docker/login-action@b45d80f862d83dbcd57f89517bcf500b2ab88fb2 # v4.0.0 with: username: ${{ secrets.DOCKERHUB_USER }} password: ${{ secrets.DOCKERHUB_PASSWORD }} - id: meta-private - uses: docker/metadata-action@v5 + uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6.0.0 with: images: wavesplatform/waves-private-node flavor: latest=false tags: | type=ref,event=tag type=raw,value=latest,enable=${{ github.event.release.prerelease == false }} - - uses: docker/build-push-action@v5 + - uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0 with: platforms: linux/amd64,linux/arm64 context: ./docker/private @@ -57,28 +57,28 @@ jobs: environment: Docker Hub runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' - - uses: sbt/setup-sbt@v1 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 - run: sbt --batch 'buildRIDERunnerForDocker' - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 + - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 + - uses: docker/login-action@b45d80f862d83dbcd57f89517bcf500b2ab88fb2 # v4.0.0 with: username: ${{ secrets.DOCKERHUB_USER }} password: ${{ secrets.DOCKERHUB_PASSWORD }} - id: meta-ride-runner - uses: docker/metadata-action@v5 + uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6.0.0 with: images: wavesplatform/ride-runner flavor: latest=false tags: | type=match,pattern=v(.*),group=1 type=raw,value=latest,enable=${{ github.event.release.prerelease == false }} - - uses: docker/build-push-action@v5 + - uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0 with: context: ./ride-runner/docker push: ${{ github.event_name == 'release' }} @@ -91,7 +91,7 @@ jobs: runs-on: ubuntu-latest if: github.event_name == 'release' steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - id: sbt-version run: | sbt_version=$(cut -d\" -f2 version.sbt) @@ -103,14 +103,14 @@ jobs: run: | echo "::error::Release version $RELEASE_VERSION does not match SBT version $SBT_VERSION" exit 1 - - uses: actions/setup-java@v4 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' gpg-private-key: ${{ secrets.OSSRH_GPG_KEY }} gpg-passphrase: ${{ secrets.OSSRH_GPG_PASSPHRASE }} - - uses: sbt/setup-sbt@v1 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 - name: Publish release jars env: SONATYPE_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} diff --git a/.github/workflows/prepare-release-draft.yml b/.github/workflows/prepare-release-draft.yml index 6707d1a7ed3..f47bc7b4668 100644 --- a/.github/workflows/prepare-release-draft.yml +++ b/.github/workflows/prepare-release-draft.yml @@ -20,13 +20,13 @@ jobs: attestations: write id-token: write steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' - - uses: sbt/setup-sbt@v1 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 - run: ./.github/workflows/prepare-release-draft.sh id: prepare-release-draft env: @@ -35,6 +35,6 @@ jobs: RELEASE_BRANCH: ${{ github.ref_name }} GITHUB_TOKEN: ${{ github.token }} GITHUB_REPO: ${{ github.repository }} - - uses: actions/attest-build-provenance@v2 + - uses: actions/attest-build-provenance@a2bbfa25375fe432b6a289bc6b6cd05ecd0c4c32 # v4.1.0 with: subject-path: ${{ steps.prepare-release-draft.outputs.subject-path }} diff --git a/.github/workflows/publish-aptly-repo.yml b/.github/workflows/publish-aptly-repo.yml index 4f5b665d280..d7a3c8dac23 100644 --- a/.github/workflows/publish-aptly-repo.yml +++ b/.github/workflows/publish-aptly-repo.yml @@ -30,7 +30,7 @@ jobs: echo "aptly_cachekey=aptly-$APTLY_VERSION" >> "$GITHUB_OUTPUT" - name: Cache aptly id: cache-aptly - uses: actions/cache@v4 + uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 with: path: ${{ steps.cache-aptly-path.outputs.aptly_toolpath }} key: ${{ steps.cache-aptly-path.outputs.aptly_cachekey }} @@ -50,14 +50,14 @@ jobs: cd "$APTLY_TOOLPATH" ls -la aptly_${APTLY_VERSION}_linux_amd64/aptly echo "$PWD/aptly_${APTLY_VERSION}_linux_amd64" >> "$GITHUB_PATH" - - uses: actions/checkout@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - run: ./.github/workflows/create-aptly-repo.sh env: GITHUB_TOKEN: ${{ github.token }} GPG_KEY_ID: ${{ secrets.GPG_KEY_ID }} GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }} GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} - - uses: actions/upload-pages-artifact@v3 + - uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b # v4.0.0 with: path: /home/runner/.aptly/public - - uses: actions/deploy-pages@v4 + - uses: actions/deploy-pages@cd2ce8fcbc39b97be8ca5fce6e763baed58fa128 # v5.0.0 diff --git a/.github/workflows/publish-docker-image.yml b/.github/workflows/publish-docker-image.yml index faaa60011ef..f4f6f762abb 100644 --- a/.github/workflows/publish-docker-image.yml +++ b/.github/workflows/publish-docker-image.yml @@ -48,7 +48,7 @@ jobs: digest: ${{ steps.push.outputs.digest }} node-version: ${{ steps.versions.outputs.node-version }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: ref: ${{ inputs.ref }} - uses: regclient/actions/regctl-installer@4d6888fcc4842c9630f60ebc91715a45dd9bd7a3 @@ -64,12 +64,12 @@ jobs: echo "base-image-digest=$(regctl manifest digest $BASE_IMAGE)" >> "$GITHUB_OUTPUT" echo "node-version=$(echo ${{ steps.ghd.outputs.describe }} | cut -c 2-)" >> "$GITHUB_OUTPUT" id: versions - - uses: actions/setup-java@v4 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' - - uses: sbt/setup-sbt@v1 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 - name: Build tarballs for docker run: sbt --batch -Dproject.version=${{ steps.versions.outputs.node-version }} buildTarballsForDocker - name: Extract image name and tags from workflow_call inputs @@ -107,18 +107,18 @@ jobs: echo EOF } >> "$GITHUB_OUTPUT" id: annotations - - uses: docker/login-action@v3 + - uses: docker/login-action@b45d80f862d83dbcd57f89517bcf500b2ab88fb2 # v4.0.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - uses: docker/login-action@v3 + - uses: docker/login-action@b45d80f862d83dbcd57f89517bcf500b2ab88fb2 # v4.0.0 if: inputs.environment != '' with: username: ${{ secrets.DOCKERHUB_USER }} password: ${{ secrets.DOCKERHUB_PASSWORD }} - - uses: docker/setup-buildx-action@v3 - - uses: docker/metadata-action@v5 + - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 + - uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6.0.0 id: meta env: DOCKER_METADATA_ANNOTATIONS_LEVELS: index,manifest-descriptor,index-descriptor @@ -127,7 +127,7 @@ jobs: flavor: latest=${{ contains(inputs.docker-tags, 'latest') }} tags: ${{ env.TAGS }} annotations: ${{ steps.annotations.outputs.annotations }} - - uses: docker/build-push-action@v6 + - uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0 id: push with: context: ./docker @@ -159,8 +159,8 @@ jobs: id-token: write if: ${{ inputs.publish-private-node }} steps: - - uses: actions/checkout@v4 - - uses: docker/setup-buildx-action@v3 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 - run: | { echo 'description<> "$GITHUB_ENV" - - uses: docker/login-action@v3 + - uses: docker/login-action@b45d80f862d83dbcd57f89517bcf500b2ab88fb2 # v4.0.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - id: meta-private - uses: docker/metadata-action@v5 + uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6.0.0 env: DOCKER_METADATA_ANNOTATIONS_LEVELS: index,manifest-descriptor,index-descriptor with: @@ -193,7 +193,7 @@ jobs: org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} org.opencontainers.image.version=${{ needs.publish.outputs.node-version }} org.opencontainers.image.base.digest=${{ needs.publish.outputs.digest }} - - uses: docker/build-push-action@v5 + - uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0 with: platforms: linux/amd64,linux/arm64 context: ./docker/private diff --git a/.github/workflows/publish-to-npmjs.yml b/.github/workflows/publish-to-npmjs.yml index 303ef5d7fb5..a4ac90d601d 100644 --- a/.github/workflows/publish-to-npmjs.yml +++ b/.github/workflows/publish-to-npmjs.yml @@ -28,17 +28,17 @@ jobs: attestations: write id-token: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: proudust/gh-describe@70f72d4f6304ea053cf5a3d71c36211d5acc0c73 id: ghd - - uses: actions/setup-java@v4 + - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: distribution: 'temurin' java-version: '17' cache: 'sbt' - - uses: sbt/setup-sbt@v1 + - uses: sbt/setup-sbt@508b753e53cb6095967669e0911487d2b9bc9f41 # v1.1.22 - run: sbt -Dproject.version=${{ steps.ghd.outputs.describe }} --batch ';lang-tests/test;lang-tests-js/test;repl/test;langJS/fullOptJS;replJS/fullOptJS' - - uses: actions/setup-node@v4 + - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: registry-url: 'https://registry.npmjs.org' node-version: '>=24.7.0' # Trusted publishing requires npm CLI version 11.5.1 or later. diff --git a/benchmark/src/test/scala/com/wavesplatform/common/BLSBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/common/BLSBenchmark.scala new file mode 100644 index 00000000000..25dc1d23637 --- /dev/null +++ b/benchmark/src/test/scala/com/wavesplatform/common/BLSBenchmark.scala @@ -0,0 +1,45 @@ +package com.wavesplatform.common + +import com.wavesplatform.account.PrivateKey +import com.wavesplatform.crypto.bls.{BlsKeyPair, BlsPublicKey, BlsSignature} +import org.openjdk.jmh.annotations.* +import org.openjdk.jmh.infra.Blackhole +import com.wavesplatform.common.utils.EitherExt2.explicitGet + +import java.util.concurrent.TimeUnit +import scala.compiletime.uninitialized + +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@BenchmarkMode(Array(Mode.AverageTime)) +@Threads(1) +@Fork(1) +@Warmup(iterations = 30, time = 1) +@Measurement(iterations = 30, time = 1) +class BLSBenchmark { + @Benchmark + def verifyAgg(st: EndorsementSt, bh: Blackhole) = bh.consume(st.aggregatedSignature.verifyAgg(st.message, st.publicKeys).explicitGet()) +} + +@State(Scope.Benchmark) +class EndorsementSt { + @Param(Array("32", "64", "128")) + var generatorCount = 0 + var publicKeys = Seq.empty[BlsPublicKey] + var aggregatedSignature: BlsSignature = uninitialized + val message: Array[Byte] = { + val bs = new Array[Byte](64) + bs + } + + @Setup + def setup(): Unit = { + val privateKeys = Seq.tabulate(generatorCount) { i => + val bs = new Array[Byte](32) + bs(0) = i.toByte + BlsKeyPair(PrivateKey(bs)) + } + + publicKeys = privateKeys.map(_.publicKey) + aggregatedSignature = BlsSignature.agg(privateKeys.map(sk => sk.sign(message))).explicitGet() + } +} diff --git a/benchmark/src/test/scala/com/wavesplatform/state/StateSyntheticBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/state/StateSyntheticBenchmark.scala index 738376d4504..ab9d3c33e20 100644 --- a/benchmark/src/test/scala/com/wavesplatform/state/StateSyntheticBenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/state/StateSyntheticBenchmark.scala @@ -13,7 +13,7 @@ import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.settings.FunctionalitySettings import com.wavesplatform.state.StateSyntheticBenchmark.* import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.Transaction +import com.wavesplatform.transaction.{Proofs, Transaction} import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.transfer.* import org.openjdk.jmh.annotations.* @@ -43,7 +43,7 @@ object StateSyntheticBenchmark { for { amount <- Gen.choose(1L, waves(1)) recipient <- accountGen - } yield TransferTransaction.selfSigned(1.toByte, sender, recipient.toAddress, Waves, amount, Waves, 100000, ByteStr.empty, ts).explicitGet() + } yield TransferTransaction.create(1.toByte, sender.publicKey, recipient.toAddress, Waves, amount, Waves, 100000, ByteStr.empty, ts, Proofs.empty).map(_.signWith(sender.privateKey)).explicitGet() } @State(Scope.Benchmark) @@ -58,7 +58,8 @@ object StateSyntheticBenchmark { recipient: KeyPair <- accountGen amount <- Gen.choose(1L, waves(1)) } yield TransferTransaction - .selfSigned(2.toByte, sender, recipient.toAddress, Waves, amount, Waves, 1000000, ByteStr.empty, ts) + .create(2.toByte, sender.publicKey, recipient.toAddress, Waves, amount, Waves, 1000000, ByteStr.empty, ts, Proofs.empty) + .map(_.signWith(sender.privateKey)) .explicitGet() @Setup @@ -72,7 +73,8 @@ object StateSyntheticBenchmark { val setScriptBlock = nextBlock( Seq( SetScriptTransaction - .selfSigned(1.toByte, richAccount, Some(ExprScript(typedScript).explicitGet()), 1000000, System.currentTimeMillis()) + .create(1.toByte, richAccount.publicKey, Some(ExprScript(typedScript).explicitGet()), 1000000, System.currentTimeMillis(), Proofs.empty) + .map(_.signWith(richAccount.privateKey)) .explicitGet() ) ) diff --git a/benchmark/src/test/scala/com/wavesplatform/transaction/smart/VerifierLoggerBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/transaction/smart/VerifierLoggerBenchmark.scala index 08d4f97946f..9c530ec3481 100644 --- a/benchmark/src/test/scala/com/wavesplatform/transaction/smart/VerifierLoggerBenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/transaction/smart/VerifierLoggerBenchmark.scala @@ -3,7 +3,6 @@ package com.wavesplatform.transaction.smart import java.io.BufferedWriter import java.nio.file.{Files, Path, Paths} import java.util.concurrent.TimeUnit - import cats.Id import com.wavesplatform.account.KeyPair import com.wavesplatform.common.state.ByteStr @@ -14,7 +13,7 @@ import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BOOLEAN, EVALUATED} import com.wavesplatform.lang.v1.evaluator.Log import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.Bindings import com.wavesplatform.state.BinaryDataEntry -import com.wavesplatform.transaction.DataTransaction +import com.wavesplatform.transaction.{DataTransaction, TxHelpers} import com.wavesplatform.transaction.smart.VerifierLoggerBenchmark.BigLog import org.openjdk.jmh.annotations.* import org.openjdk.jmh.infra.Blackhole @@ -42,9 +41,8 @@ object VerifierLoggerBenchmark { val resultFile: Path = Paths.get("log.txt") val writer: BufferedWriter = Files.newBufferedWriter(resultFile) - private val dataTx: DataTransaction = DataTransaction - .selfSigned(1.toByte, KeyPair(Array[Byte]()), (1 to 4).map(i => BinaryDataEntry(s"data$i", ByteStr(Array.fill(1024 * 30)(1)))).toList, 100000000, 0) - .explicitGet() + private val dataTx: DataTransaction = + TxHelpers.data(KeyPair(Array[Byte]()), (1 to 4).map(i => BinaryDataEntry(s"data$i", ByteStr(Array.fill(1024 * 30)(1)))).toList, 100000000, 0) private val dataTxObj: Terms.CaseObj = Bindings.transactionObject( RealTransactionWrapper(dataTx, ???, ???, ???).explicitGet(), diff --git a/build.sbt b/build.sbt index 1263b47f452..50429e3d251 100644 --- a/build.sbt +++ b/build.sbt @@ -102,7 +102,7 @@ lazy val `node-tests` = project .settings(libraryDependencies ++= Dependencies.logDeps) lazy val `grpc-server` = - project.dependsOn(node % "compile;runtime->provided", `node-testkit`) + project.dependsOn(node % "compile;runtime->provided", `node-testkit` % "test") lazy val `ride-runner` = project.dependsOn(node, `grpc-server`, `node-testkit`) lazy val `node-it` = project.dependsOn(`repl-jvm`, `grpc-server`, `node-testkit`) diff --git a/docker/Dockerfile b/docker/Dockerfile index 3528541196c..8e5b27d532b 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -6,6 +6,8 @@ ARG CORRETTO_VERSION=2.5.0 ARG ROCKSDB_VERSION=10.2.1 ENV WAVES_LOG_LEVEL=INFO +ENV WAVES_LOG_JAVA_OPTS=true + ENV WAVES_HEAP_SIZE=2g ENV WAVES_NETWORK=mainnet diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index d9267aa8a74..9b77ae68a9b 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -13,7 +13,9 @@ JAVA_OPTS="-XX:+ExitOnOutOfMemoryError -Dwaves.rest-api.bind-address=0.0.0.0 ${JAVA_OPTS}" -echo "JAVA_OPTS=${JAVA_OPTS}" | tee -a ${WVLOG}/waves.log +if [ "$WAVES_LOG_JAVA_OPTS" = "true" ] ; then + echo "JAVA_OPTS=${JAVA_OPTS}" | tee -a ${WVLOG}/waves.log +fi if [ -n "$WAVES_WALLET_SEED" ] ; then JAVA_OPTS="-Dwaves.wallet.seed=${WAVES_WALLET_SEED} ${JAVA_OPTS}" diff --git a/docker/private/waves.custom.conf b/docker/private/waves.custom.conf index 460f5019743..f8693a862c3 100755 --- a/docker/private/waves.custom.conf +++ b/docker/private/waves.custom.conf @@ -21,6 +21,7 @@ waves { reset-effective-balances-at-height: 1 allow-leased-balance-transfer-until: 0 block-version-3-after-height: 0 + generation-period-length = 1000 pre-activated-features = { 1 = 0 2 = 0 diff --git a/grpc-server/src/test/scala/com/wavesplatform/events/BlockchainUpdatesSpec.scala b/grpc-server/src/test/scala/com/wavesplatform/events/BlockchainUpdatesSpec.scala index e369c2fc313..f54651b48a1 100644 --- a/grpc-server/src/test/scala/com/wavesplatform/events/BlockchainUpdatesSpec.scala +++ b/grpc-server/src/test/scala/com/wavesplatform/events/BlockchainUpdatesSpec.scala @@ -29,8 +29,6 @@ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.features.BlockchainFeatures.BlockReward import com.wavesplatform.history.Domain import com.wavesplatform.lang.directives.values.{V5, V6} -import com.wavesplatform.lang.v1.FunctionHeader -import com.wavesplatform.lang.v1.compiler.Terms.FUNCTION_CALL import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.protobuf.* import com.wavesplatform.protobuf.block.PBBlocks @@ -46,8 +44,7 @@ import com.wavesplatform.transaction.assets.{IssueTransaction, ReissueTransactio import com.wavesplatform.transaction.lease.LeaseTransaction import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.utils.Signed -import com.wavesplatform.transaction.{Asset, CreateAliasTransaction, DataTransaction, GenesisTransaction, PaymentTransaction, TxHelpers} +import com.wavesplatform.transaction.{Asset, CreateAliasTransaction, DataTransaction, GenesisTransaction, PaymentTransaction, Proofs, TxHelpers} import com.wavesplatform.utils.{Schedulers, byteStrOrdering} import io.grpc.StatusException import monix.execution.ExecutionModel.SynchronousExecution @@ -71,7 +68,7 @@ class BlockchainUpdatesSpec extends FreeSpec with WithBUDomain with ScalaFutures val issue: IssueTransaction = TxHelpers.issue(amount = 1000) val reissue: ReissueTransaction = TxHelpers.reissue(issue.asset) val data: DataTransaction = TxHelpers.dataSingle(fee = TestValues.fee * 3) // for compatibility with expected values - val createAlias: CreateAliasTransaction = TxHelpers.createAlias("alias") + val createAlias: CreateAliasTransaction = TxHelpers.createAlias() val setScript1: SetScriptTransaction = TxHelpers.setScript( TxHelpers.defaultSigner, TestCompiler(V6).compileContract( @@ -715,20 +712,21 @@ class BlockchainUpdatesSpec extends FreeSpec with WithBUDomain with ScalaFutures |} """.stripMargin ) - val invoke = Signed.invokeScript( - 2.toByte, - invoker, + val invoke = TxHelpers.invoke( issuer.toAddress, - Some(FUNCTION_CALL(FunctionHeader.User("issue"), Nil)), + Some("issue"), + Seq.empty, Seq.empty, + invoker, 2.waves, Asset.Waves, + 2.toByte, ntpTime.getTimestamp() ) d.appendBlock( GenesisTransaction.create(issuerAddress, 1000.waves, ntpTime.getTimestamp()).explicitGet(), GenesisTransaction.create(invoker.toAddress, 1000.waves, ntpTime.getTimestamp()).explicitGet(), - SetScriptTransaction.selfSigned(2.toByte, issuer, Some(dAppScript), 0.01.waves, ntpTime.getTimestamp()).explicitGet(), + SetScriptTransaction.create(2.toByte, issuer.publicKey, Some(dAppScript), 0.01.waves, ntpTime.getTimestamp(), Proofs.empty).map(_.signWith(issuer.privateKey)).explicitGet(), invoke ) diff --git a/node-generator/src/main/scala/com/wavesplatform/generator/MultisigTransactionGenerator.scala b/node-generator/src/main/scala/com/wavesplatform/generator/MultisigTransactionGenerator.scala index 9961404fbde..0fc19991e1e 100644 --- a/node-generator/src/main/scala/com/wavesplatform/generator/MultisigTransactionGenerator.scala +++ b/node-generator/src/main/scala/com/wavesplatform/generator/MultisigTransactionGenerator.scala @@ -32,8 +32,9 @@ class MultisigTransactionGenerator(settings: MultisigTransactionGenerator.Settin val script: Script = Gen.multiSigScript(owners, 3, estimator) - val now = System.currentTimeMillis() - val setScript = SetScriptTransaction.selfSigned(1.toByte, bank, Some(script), enoughFee, now).explicitGet() + val now = System.currentTimeMillis() + val setScript = + SetScriptTransaction.create(1.toByte, bank.publicKey, Some(script), enoughFee, now, Proofs.empty).map(_.signWith(bank.privateKey)).explicitGet() val res = Range(0, settings.transactions).map { i => val tx = TransferTransaction( diff --git a/node-generator/src/main/scala/com/wavesplatform/generator/NarrowTransactionGenerator.scala b/node-generator/src/main/scala/com/wavesplatform/generator/NarrowTransactionGenerator.scala index 6ac79b9c2a3..2fa59ce3074 100644 --- a/node-generator/src/main/scala/com/wavesplatform/generator/NarrowTransactionGenerator.scala +++ b/node-generator/src/main/scala/com/wavesplatform/generator/NarrowTransactionGenerator.scala @@ -9,14 +9,13 @@ import com.wavesplatform.common.utils.Base58 import com.wavesplatform.generator.config.ConfigReaders import com.wavesplatform.generator.utils.{Gen, Universe} import com.wavesplatform.lang.ValidationError -import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.estimator.ScriptEstimator import com.wavesplatform.state.DataEntry.{MaxValueSize, Type} import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, IntegerDataEntry, StringDataEntry} import com.wavesplatform.transaction.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.TransactionType.TransactionType +import com.wavesplatform.transaction.TransactionType import com.wavesplatform.transaction.assets.* import com.wavesplatform.transaction.assets.exchange.* import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} @@ -24,7 +23,6 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.transfer.* import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTransfer -import com.wavesplatform.transaction.utils.Signed import com.wavesplatform.utils.NTP import org.slf4j.LoggerFactory import org.web3j.crypto.Bip32ECKeyPair @@ -79,20 +77,18 @@ class NarrowTransactionGenerator( val description = random.nextString(5) val reissuable = random.nextBoolean() val amount = 100000000L + Random.nextInt(Int.MaxValue) - logOption( - IssueTransaction - .selfSigned( - correctVersion(TxVersion.V2), - sender, - name, - description, - amount, - Random.nextInt(9).toByte, - reissuable, - None, - 100400000L, - timestamp - ) + Some( + TxHelpers.issue( + version = correctVersion(TxVersion.V2), + issuer = sender, + name = name, + description = description, + amount = amount, + decimals = Random.nextInt(9).toByte, + reissuable = reissuable, + script = None, + fee = 100400000L + ) ) case TransactionType.Transfer => @@ -103,17 +99,19 @@ class NarrowTransactionGenerator( recipient <- if (useAlias && aliases.nonEmpty) randomFrom(aliases).map(_.alias) else randomFrom(accounts).map(_.toAddress) tx <- logOption( TransferTransaction - .selfSigned( + .create( correctVersion(TxVersion.V2), - sender, + sender.publicKey, recipient, Asset.fromCompatId(asset), Random.nextInt(100), Waves, 500000L, createAttachment(), - timestamp + timestamp, + Proofs.empty ) + .map(_.signWith(sender.privateKey)) ) } yield tx ).logNone("There is no issued assets, may be you need to increase issue transaction's probability or pre-configure them") @@ -123,19 +121,14 @@ class NarrowTransactionGenerator( for { assetTx <- randomFrom(reissuableIssueTxs) orElse randomFrom(Universe.IssuedAssets.filter(_.reissuable)) sender <- accountByAddress(assetTx.sender.toAddress.toString) - tx <- logOption( - ReissueTransaction - .selfSigned( - correctVersion(TxVersion.V2), - sender, - IssuedAsset(assetTx.id()), - Random.nextInt(Int.MaxValue), - true, - 100400000L, - timestamp - ) + } yield TxHelpers + .reissue( + IssuedAsset(assetTx.id()), + version = correctVersion(TxVersion.V2), + sender = sender, + amount = Random.nextInt(Int.MaxValue), + fee = 100400000L ) - } yield tx ).logNone("There is no reissuable assets, may be you need to increase issue transaction's probability or pre-configure them") case TransactionType.Burn => @@ -143,17 +136,13 @@ class NarrowTransactionGenerator( for { assetTx <- randomFrom(validIssueTxs).orElse(randomFrom(Universe.IssuedAssets)) sender <- accountByAddress(assetTx.sender.toAddress.toString) - tx <- logOption( - BurnTransaction.selfSigned( - correctVersion(TxVersion.V2), - sender, - IssuedAsset(assetTx.id()), - Random.nextInt(1000), - 500000L, - timestamp - ) - ) - } yield tx + } yield TxHelpers.burn( + version = correctVersion(TxVersion.V2), + sender = sender, + asset = IssuedAsset(assetTx.id()), + amount = Random.nextInt(1000), + fee = 500000L + ) ).logNone("There is no issued assets, may be you need to increase issue transaction's probability or pre-configure them") case TransactionType.Exchange => @@ -190,21 +179,7 @@ class NarrowTransactionGenerator( 300000L ) .explicitGet() - tx <- logOption( - ExchangeTransaction.signed( - correctVersion(TxVersion.V2), - matcher.privateKey, - buyOrder, - sellOrder, - 10000000L + delta, - 10, - 300000L, - 300000L, - 700000L, - timestamp - ) - ) - } yield tx + } yield TxHelpers.exchange(buyOrder, sellOrder, matcher, 10000000L + delta, 10, 300000L, 300000L, 700000L, timestamp) ).logNone("Can't define seller/matcher/buyer of transaction, check your configuration") case TransactionType.Lease => @@ -215,7 +190,9 @@ class NarrowTransactionGenerator( recipient <- (if (useAlias && aliases.nonEmpty) randomFrom(aliases.filter(_.sender != sender)).map(_.alias) else randomFrom(accounts.filter(_ != sender).map(_.toAddress))) orElse Some(preconditions.leaseRecipient.toAddress) tx <- logOption( - LeaseTransaction.selfSigned(correctVersion(TxVersion.V2), sender, recipient, random.nextLong(1, 100), 500000L, timestamp) + LeaseTransaction + .create(correctVersion(TxVersion.V2), sender.publicKey, recipient, random.nextLong(1, 100), 500000L, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) ) } yield tx ).logNone("Can't define recipient of transaction, check your configuration") @@ -225,16 +202,18 @@ class NarrowTransactionGenerator( for { lease <- activeLeaseTransactions.headOption sender <- accountByAddress(lease.sender.toAddress.toString) - tx <- logOption(LeaseCancelTransaction.selfSigned(2.toByte, sender, lease.id(), 500000L, timestamp)) + tx <- logOption( + LeaseCancelTransaction + .create(2.toByte, sender.publicKey, lease.id(), 500000L, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + ) } yield tx ).logNone("There is no active lease transactions, may be you need to increase lease transaction's probability") case TransactionType.CreateAlias => val sender = randomFrom(accounts).get val aliasString = NarrowTransactionGenerator.generateAlias() - logOption( - CreateAliasTransaction.selfSigned(correctVersion(TxVersion.V2), sender, aliasString, 500000L, timestamp) - ) + Some(TxHelpers.createAlias(aliasString, sender, 500000L, correctVersion(TxVersion.V2))) case TransactionType.MassTransfer => ( @@ -249,15 +228,17 @@ class NarrowTransactionGenerator( } tx <- logOption( MassTransferTransaction - .selfSigned( + .create( correctVersion(TxVersion.V1), - sender, + sender.publicKey, Asset.fromCompatId(asset), transfers.toList, 100000L + 50000L * transferCount + 400000L, timestamp, - createAttachment() + createAttachment(), + Proofs.empty ) + .map(_.signWith(sender.privateKey)) ) } yield tx ).logNone("There is no issued assets, may be you need to increase issue transaction's probability or pre-configure them") @@ -281,7 +262,7 @@ class NarrowTransactionGenerator( } val size = 128 + data.map(_.toBytes.length).sum val fee = 500000L * (size / 1024 + 1) - logOption(DataTransaction.selfSigned(correctVersion(TxVersion.V1), sender, data.toList, fee, timestamp)) + Some(TxHelpers.data(sender, data, fee)) case TransactionType.SponsorFee => ( @@ -289,14 +270,17 @@ class NarrowTransactionGenerator( assetTx <- randomFrom(validIssueTxs).orElse(randomFrom(Universe.IssuedAssets)) sender <- accountByAddress(assetTx.sender.toAddress.toString) tx <- logOption( - SponsorFeeTransaction.selfSigned( - correctVersion(TxVersion.V1), - sender, - IssuedAsset(assetTx.id()), - Some(Random.nextInt(1000)), - 100400000L, - timestamp - ) + SponsorFeeTransaction + .create( + correctVersion(TxVersion.V1), + sender.publicKey, + IssuedAsset(assetTx.id()), + Some(Random.nextInt(1000).toLong), + 100400000L, + timestamp, + Proofs.empty + ) + .map(_.signWith(sender.privateKey)) ) } yield tx ).logNone("There is no issued assets, may be you need to increase issue transaction's probability or pre-configure them") @@ -318,25 +302,19 @@ class NarrowTransactionGenerator( case "binary" => Terms.CONST_BYTESTR(ByteStr.decodeBase58(value).get).explicitGet() } - val maybeFunctionCall = - if (function.name.isEmpty) None - else Some(Terms.FUNCTION_CALL(FunctionHeader.User(function.name), data.toList)) - val asset = randomFrom(Universe.IssuedAssets.filter(a => script.paymentAssets.contains(a.name.toStringUtf8))) .fold(Waves: Asset)(tx => IssuedAsset(tx.id())) - logOption( - Right( - Signed.invokeScript( - correctVersion(TxVersion.V1), - sender, - GeneratorSettings.toKeyPair(script.dappAccount).toAddress, - maybeFunctionCall, - Seq(InvokeScriptTransaction.Payment(random.nextInt(100) + 1, asset)), - 5300000L, - Waves, - timestamp - ) + Some( + TxHelpers.invoke( + GeneratorSettings.toKeyPair(script.dappAccount).toAddress, + Some(function.name).filter(_.nonEmpty), + data, + Seq(InvokeScriptTransaction.Payment(random.nextInt(100) + 1, asset)), + sender, + 5300000L, + Waves, + correctVersion(TxVersion.V1) ) ) @@ -376,13 +354,16 @@ class NarrowTransactionGenerator( sender <- randomFrom(preconditions.setScriptAccounts) script = Gen.script(complexity = false, estimator) tx <- logOption( - SetScriptTransaction.selfSigned( - correctVersion(TxVersion.V1), - sender, - Some(script), - 1400000L + random.nextLong(100), - timestamp - ) + SetScriptTransaction + .create( + correctVersion(TxVersion.V1), + sender.publicKey, + Some(script), + 1400000L + random.nextLong(100), + timestamp, + Proofs.empty + ) + .map(_.signWith(sender.privateKey)) ) } yield tx @@ -551,11 +532,26 @@ object NarrowTransactionGenerator extends ConfigReaders { val account = GeneratorSettings.toKeyPair(s"${UUID.randomUUID().toString}") val transferTx = TransferTransaction - .selfSigned(2.toByte, richAccount, account.toAddress, Waves, balance, Waves, fee, ByteStr.empty, time.correctedTime()) + .create( + 2.toByte, + richAccount.publicKey, + account.toAddress, + Waves, + balance, + Waves, + fee, + ByteStr.empty, + time.correctedTime(), + Proofs.empty + ) + .map(_.signWith(richAccount.privateKey)) .explicitGet() - val script = ScriptCompiler.compile(new String(Files.readAllBytes(Paths.get(scriptFile))), estimator).explicitGet()._1 - val scriptTx = SetScriptTransaction.selfSigned(TxVersion.V1, account, Some(script), fee, time.correctedTime()).explicitGet() + val script = ScriptCompiler.compile(new String(Files.readAllBytes(Paths.get(scriptFile))), estimator).explicitGet()._1 + val scriptTx = SetScriptTransaction + .create(TxVersion.V1, account.publicKey, Some(script), fee, time.correctedTime(), Proofs.empty) + .map(_.signWith(account.privateKey)) + .explicitGet() (initTxs :+ transferTx, tailInitTxs :+ scriptTx, accounts :+ account) } @@ -566,20 +562,18 @@ object NarrowTransactionGenerator extends ConfigReaders { import assetsSettings.* val issuer = randomFrom(accounts).get - val tx = IssueTransaction - .selfSigned( - TxVersion.V3, - issuer, - UUID.randomUUID().toString.take(16), - s"$description #$i", - amount, - decimals.toByte, - reissuable, - None, - 100000000 + fee, - time.correctedTime() - ) - .explicitGet() + val tx = TxHelpers.issue( + issuer, + amount, + decimals.toByte, + UUID.randomUUID().toString.take(16), + s"$description #$i", + 100000000 + fee, + None, + reissuable, + time.correctedTime(), + TxVersion.V3 + ) txs :+ tx } else Seq() @@ -591,36 +585,30 @@ object NarrowTransactionGenerator extends ConfigReaders { val trader = randomFrom(accounts).get - val tradeAsset = IssueTransaction - .selfSigned( - TxVersion.V2, - trader, - "TRADE", - "Waves DEX is the best exchange ever", - 100000000, - 2, - reissuable = true, - fee = 100400000L, - timestamp = System.currentTimeMillis(), - script = None - ) - .explicitGet() + val tradeAsset = TxHelpers.issue( + trader, + 100000000, + 2, + "TRADE", + "Waves DEX is the best exchange ever", + 100400000L, + None, + true, + System.currentTimeMillis(), + TxVersion.V2 + ) val tradeAssetDistribution: Seq[Transaction] = { (accounts.toSet - trader).toSeq.map(acc => { - TransferTransaction - .selfSigned( - TxVersion.V2, - trader, - acc.toAddress, - IssuedAsset(tradeAsset.id()), - tradeAsset.quantity.value / accounts.size, - Waves, - 900000, - ByteStr(Array.fill(random.nextInt(100))(random.nextInt().toByte)), - System.currentTimeMillis() - ) - .explicitGet() + TxHelpers.transfer( + from = trader, + to = acc.toAddress, + asset = IssuedAsset(tradeAsset.id()), + amount = tradeAsset.quantity.value / accounts.size, + feeAsset = Waves, + fee = 900000, + attachment = ByteStr(Array.fill(random.nextInt(100))(random.nextInt().toByte)) + ) }) } @@ -633,18 +621,45 @@ object NarrowTransactionGenerator extends ConfigReaders { import com.wavesplatform.transaction.utils.EthConverters.* val ethAccount = kp.toEthWavesAddress TransferTransaction - .selfSigned(TxVersion.V1, accounts.head, ethAccount, Waves, 100_0000_0000L, Waves, 500000L, ByteStr.empty, System.currentTimeMillis()) + .create( + TxVersion.V1, + accounts.head.publicKey, + ethAccount, + Waves, + 100_0000_0000L, + Waves, + 500000L, + ByteStr.empty, + System.currentTimeMillis(), + Proofs.empty + ) + .map(_.signWith(accounts.head.privateKey)) .explicitGet() } val setPredefScripts = settings.scripts.collect { case s if s.scriptFile.nonEmpty => val transferTx = TransferTransaction - .selfSigned(2.toByte, accounts.head, s.dappAddress, Waves, 1_0000_000L, Waves, 500000L, ByteStr.empty, time.correctedTime()) + .create( + 2.toByte, + accounts.head.publicKey, + s.dappAddress, + Waves, + 1_0000_000L, + Waves, + 500000L, + ByteStr.empty, + time.correctedTime(), + Proofs.empty + ) + .map(_.signWith(accounts.head.privateKey)) .explicitGet() - val script = ScriptCompiler.compile(new String(Files.readAllBytes(Paths.get(s.scriptFile.get))), estimator).explicitGet()._1 - val scriptTx = SetScriptTransaction.selfSigned(TxVersion.V1, s.dappAccountKP, Some(script), 500000L, time.correctedTime()).explicitGet() + val script = ScriptCompiler.compile(new String(Files.readAllBytes(Paths.get(s.scriptFile.get))), estimator).explicitGet()._1 + val scriptTx = SetScriptTransaction + .create(TxVersion.V1, s.dappAccountKP.publicKey, Some(script), 500000L, time.correctedTime(), Proofs.empty) + .map(_.signWith(s.dappAccountKP.privateKey)) + .explicitGet() Seq(transferTx, scriptTx) }.flatten diff --git a/node-generator/src/main/scala/com/wavesplatform/generator/OracleTransactionGenerator.scala b/node-generator/src/main/scala/com/wavesplatform/generator/OracleTransactionGenerator.scala index 181f837eda7..5b50d189d84 100644 --- a/node-generator/src/main/scala/com/wavesplatform/generator/OracleTransactionGenerator.scala +++ b/node-generator/src/main/scala/com/wavesplatform/generator/OracleTransactionGenerator.scala @@ -3,7 +3,6 @@ package com.wavesplatform.generator import cats.Show import com.wavesplatform.account.KeyPair import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.explicitGet import com.wavesplatform.generator.OracleTransactionGenerator.Settings import com.wavesplatform.generator.config.ConfigReaders import com.wavesplatform.generator.utils.Gen @@ -11,9 +10,7 @@ import com.wavesplatform.generator.utils.Implicits.DoubleExt import com.wavesplatform.lang.v1.estimator.ScriptEstimator import com.wavesplatform.state.* import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{DataTransaction, Transaction} +import com.wavesplatform.transaction.{Transaction, TxHelpers} import pureconfig.ConfigReader class OracleTransactionGenerator(settings: Settings, val accounts: Seq[KeyPair], estimator: ScriptEstimator) extends TransactionGenerator { @@ -29,19 +26,13 @@ class OracleTransactionGenerator(settings: Settings, val accounts: Seq[KeyPair], val enoughFee = 0.005.waves val setScript: Transaction = - SetScriptTransaction - .selfSigned(1.toByte, scriptedAccount, Some(script), enoughFee, timestamp = System.currentTimeMillis()) - .explicitGet() + TxHelpers.setScript(scriptedAccount, script, enoughFee) - val setDataTx: Transaction = DataTransaction - .selfSigned(1.toByte, oracle, settings.requiredData.toList, enoughFee, System.currentTimeMillis()) - .explicitGet() + val setDataTx: Transaction = TxHelpers.data(oracle, settings.requiredData.toSeq, enoughFee) val now = System.currentTimeMillis() val transactions: List[Transaction] = (1 to settings.transactions).map { i => - TransferTransaction - .selfSigned(2.toByte, scriptedAccount, oracle.toAddress, Waves, 1.waves, Waves, enoughFee, ByteStr.empty, now + i) - .explicitGet() + TxHelpers.transfer(scriptedAccount, oracle.toAddress, 1.waves, Waves, enoughFee, Waves, ByteStr.empty, now + i, 2.toByte) }.toList setScript +: setDataTx +: transactions diff --git a/node-generator/src/main/scala/com/wavesplatform/generator/Preconditions.scala b/node-generator/src/main/scala/com/wavesplatform/generator/Preconditions.scala index 89a09bf1287..c6154574a03 100644 --- a/node-generator/src/main/scala/com/wavesplatform/generator/Preconditions.scala +++ b/node-generator/src/main/scala/com/wavesplatform/generator/Preconditions.scala @@ -7,8 +7,7 @@ import com.wavesplatform.common.utils.EitherExt2.explicitGet import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.lease.LeaseTransaction -import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{Transaction, TxVersion} +import com.wavesplatform.transaction.{Transaction, TxHelpers, TxVersion} import com.wavesplatform.utils.Time import pureconfig.ConfigReader @@ -38,62 +37,54 @@ object Preconditions { ): (UniverseHolder, List[Transaction], List[Transaction]) = { val transfers = accounts.map { account => // val acc = GeneratorSettings.toKeyPair(accountSeed) - TransferTransaction - .selfSigned(2.toByte, settings.faucet, account.toAddress, Waves, settings.balance, Waves, Fee, ByteStr.empty, time.correctedTime()) - .explicitGet() + TxHelpers.transfer(settings.faucet, account.toAddress, settings.balance, Waves, Fee, Waves, ByteStr.empty, time.correctedTime()) }.toList val issuedAssets = (1 to settings.assetsCount) .map(_ => - IssueTransaction - .selfSigned( - TxVersion.V3, - accounts(Random.nextInt(accounts.size)), - UUID.randomUUID().toString.take(8), - Random.nextString(100), - 10_000_000_000L, - Random.nextLong(9).toByte, - true, - None, - 100000000, - time.correctedTime() - ) - .explicitGet() + TxHelpers.issue( + accounts(Random.nextInt(accounts.size)), + 10_000_000_000L, + Random.nextLong(9).toByte, + UUID.randomUUID().toString.take(8), + Random.nextString(100), + 100000000, + None, + true, + time.correctedTime(), + TxVersion.V3 + ) ) .toList val leaseTxs = (1 to settings.leasesCount).map { _ => val rndAccount = Random.nextInt(accounts.size - 1) - LeaseTransaction - .selfSigned( - TxVersion.V3, - accounts(rndAccount), - GeneratorSettings.toKeyPair(Random.nextString(10)).toAddress, - 1 + Random.nextInt(1000), - Fee, - time.correctedTime() - ) - .explicitGet() + TxHelpers.lease( + accounts(rndAccount), + GeneratorSettings.toKeyPair(Random.nextString(10)).toAddress, + 1 + Random.nextInt(1000), + Fee, + time.correctedTime(), + TxVersion.V3 + ) }.toList val transferAssets = issuedAssets.flatMap(issuedAsset => val issuer = accounts.find(_.publicKey == issuedAsset.sender).get val balance = issuedAsset.quantity.value / accounts.size accounts.map { acc => - TransferTransaction - .selfSigned( - TxVersion.V3, - issuer, - acc.toAddress, - IssuedAsset(issuedAsset.assetId), - balance, - Waves, - Fee, - ByteStr.empty, - time.correctedTime() - ) - .explicitGet() + TxHelpers.transfer( + issuer, + acc.toAddress, + balance, + IssuedAsset(issuedAsset.assetId), + Fee, + Waves, + ByteStr.empty, + time.correctedTime(), + TxVersion.V3 + ) } ) val holder = UniverseHolder(issuedAssets, leaseTxs) diff --git a/node-generator/src/main/scala/com/wavesplatform/generator/SmartGenerator.scala b/node-generator/src/main/scala/com/wavesplatform/generator/SmartGenerator.scala index 59320546731..8500db5d784 100644 --- a/node-generator/src/main/scala/com/wavesplatform/generator/SmartGenerator.scala +++ b/node-generator/src/main/scala/com/wavesplatform/generator/SmartGenerator.scala @@ -9,10 +9,10 @@ import com.wavesplatform.generator.utils.Implicits.DoubleExt import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.estimator.ScriptEstimator import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.assets.exchange.{AssetPair, ExchangeTransaction, Order} +import com.wavesplatform.transaction.assets.exchange.{AssetPair, Order} import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{Asset, Transaction, TxVersion} +import com.wavesplatform.transaction.{Asset, Proofs, Transaction, TxHelpers, TxVersion} import pureconfig.ConfigReader import java.util.concurrent.ThreadLocalRandom @@ -33,14 +33,18 @@ class SmartGenerator(settings: SmartGenerator.Settings, val accounts: Seq[KeyPai val setScripts = Range(0, settings.scripts) flatMap (_ => accounts.map { i => - SetScriptTransaction.selfSigned(1.toByte, i, Some(script), 1.waves, System.currentTimeMillis()).explicitGet() + SetScriptTransaction + .create(1.toByte, i.publicKey, Some(script), 1.waves, System.currentTimeMillis(), Proofs.empty) + .map(_.signWith(i.privateKey)) + .explicitGet() } ) val now = System.currentTimeMillis() val txs = Range(0, settings.transfers).map { i => TransferTransaction - .selfSigned(2.toByte, bank, bank.toAddress, Waves, 1.waves - 2 * fee, Waves, fee, ByteStr.empty, now + i) + .create(2.toByte, bank.publicKey, bank.toAddress, Waves, 1.waves - 2 * fee, Waves, fee, ByteStr.empty, now + i, Proofs.empty) + .map(_.signWith(bank.privateKey)) .explicitGet() } @@ -56,9 +60,7 @@ class SmartGenerator(settings: SmartGenerator.Settings, val accounts: Seq[KeyPai val sellOrder = Order.sell(TxVersion.V2, seller, matcher.publicKey, pair, 100000000L, 1, ts, ts + 30.days.toMillis, 0.003.waves).explicitGet() val buyOrder = Order.buy(TxVersion.V2, buyer, matcher.publicKey, pair, 100000000L, 1, ts, ts + 1.day.toMillis, 0.003.waves).explicitGet() - ExchangeTransaction - .signed(TxVersion.V2, matcher.privateKey, buyOrder, sellOrder, 100000000, 1, 0.003.waves, 0.003.waves, 0.011.waves, ts) - .explicitGet() + TxHelpers.exchange(buyOrder, sellOrder, matcher, 100000000, 1, 0.003.waves, 0.003.waves, 0.011.waves, ts) } setScripts ++ txs ++ extxs diff --git a/node-generator/src/main/scala/com/wavesplatform/generator/config/ConfigReaders.scala b/node-generator/src/main/scala/com/wavesplatform/generator/config/ConfigReaders.scala index 00ac564241c..9012a9fe4f5 100644 --- a/node-generator/src/main/scala/com/wavesplatform/generator/config/ConfigReaders.scala +++ b/node-generator/src/main/scala/com/wavesplatform/generator/config/ConfigReaders.scala @@ -6,7 +6,6 @@ import com.wavesplatform.generator.Worker import com.wavesplatform.settings.* import com.wavesplatform.state.DataEntry import com.wavesplatform.transaction.TransactionType -import com.wavesplatform.transaction.TransactionType.TransactionType import play.api.libs.json.* import pureconfig.* import pureconfig.error.ThrowableFailure @@ -18,7 +17,7 @@ trait ConfigReaders { given ConfigReader[Map[TransactionType, Double]] = { val converter = CaseFormat.LOWER_HYPHEN.converterTo(CaseFormat.UPPER_CAMEL) - def toTxType(key: String): TransactionType = TransactionType.withName(converter.convert(key).replace("Transaction", "")) + def toTxType(key: String): TransactionType = TransactionType.valueOf(converter.convert(key).replace("Transaction", "")) CollectionReaders.mapReader[Double].map { xs => xs.map { case (k, v) => diff --git a/node-generator/src/main/scala/com/wavesplatform/generator/utils/Gen.scala b/node-generator/src/main/scala/com/wavesplatform/generator/utils/Gen.scala index 2176bc2fa45..79385df5834 100644 --- a/node-generator/src/main/scala/com/wavesplatform/generator/utils/Gen.scala +++ b/node-generator/src/main/scala/com/wavesplatform/generator/utils/Gen.scala @@ -12,7 +12,7 @@ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.* import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTransfer -import com.wavesplatform.transaction.{Transaction, TxNonNegativeAmount} +import com.wavesplatform.transaction.{Proofs, Transaction, TxNonNegativeAmount} import java.util.concurrent.ThreadLocalRandom @@ -121,7 +121,9 @@ object Gen { .zip(feeGen) .zipWithIndex .map { case (((src, dst), fee), i) => - TransferTransaction.selfSigned(2.toByte, src, dst, Waves, fee, Waves, fee, ByteStr.empty, now + i) + TransferTransaction + .create(2.toByte, src.publicKey, dst, Waves, fee, Waves, fee, ByteStr.empty, now + i, Proofs.empty) + .map(_.signWith(src.privateKey)) } .collect { case Right(x) => x } } @@ -135,7 +137,9 @@ object Gen { .map { case ((sender, count), i) => val transfers = List.tabulate(count)(_ => ParsedTransfer(recipientGen.next(), TxNonNegativeAmount.unsafeFrom(amountGen.next()))) val fee = 100000 + count * 50000 - MassTransferTransaction.selfSigned(1.toByte, sender, Waves, transfers, fee, now + i, ByteStr.empty) + MassTransferTransaction + .create(1.toByte, sender.publicKey, Waves, transfers, fee, now + i, ByteStr.empty, Proofs.empty) + .map(_.signWith(sender.privateKey)) } .collect { case Right(tx) => tx } } diff --git a/node-it/src/test/resources/template.conf b/node-it/src/test/resources/template.conf index b3606e68568..612773f390b 100644 --- a/node-it/src/test/resources/template.conf +++ b/node-it/src/test/resources/template.conf @@ -62,7 +62,7 @@ waves { genesis { average-block-delay = 10s initial-base-target = 50000 - initial-balance = 6420000000000000 + initial-balance = 6620000000000000 transactions = [ # Initial balances are balanced (pun intended) in such way that initial block # generation delay doesn't vary much, no matter which node is chosen as a miner. @@ -95,6 +95,8 @@ waves { # node09 { recipient = 3HnGfdhUuA948dYjQHnrz2ZHxfT4P72oBBy, amount = 100000000000000 } + { recipient = 3HPU48mFd8x1feg5kaoZgKc3EzZrkaSpaMA, amount = 100000000000000 } + { recipient = 3HSZpkVTvboaj5PjLtjsJGMX1qfJTtDwzU5, amount = 100000000000000 } # node10 { recipient = 3HmFkAoQRs4Y3PE2uR6ohN7wS4VqPBGKv7k, amount = 6000000000000000 } @@ -108,6 +110,7 @@ waves { quorum = 1 interval-after-last-block-then-generation-is-allowed = 1h min-micro-block-age = 0s + micro-block-interval = 1s } rest-api { enable = yes diff --git a/node-it/src/test/scala/com/wavesplatform/it/BaseSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/BaseSuite.scala index 022d829756a..86dfd75dcf0 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/BaseSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/BaseSuite.scala @@ -21,12 +21,11 @@ trait BaseSuite with BeforeAndAfterEach { this: TestSuite & Nodes => protected implicit val ec: ExecutionContext = ExecutionContext.Implicits.global - protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + import com.wavesplatform.it.NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0), + Default.head.notMiner + ) def miner: Node = nodes.head def notMiner: Node = nodes.last diff --git a/node-it/src/test/scala/com/wavesplatform/it/IntegrationSuiteWithThreeAddresses.scala b/node-it/src/test/scala/com/wavesplatform/it/IntegrationSuiteWithThreeAddresses.scala index 15095bacf5e..485adfd11f5 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/IntegrationSuiteWithThreeAddresses.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/IntegrationSuiteWithThreeAddresses.scala @@ -3,17 +3,14 @@ package com.wavesplatform.it import com.wavesplatform.account.{KeyPair, SeedKeyPair} import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.api.SyncHttpApi.* -import com.wavesplatform.test.NumericExt import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 -import com.wavesplatform.transaction.smart.SetScriptTransaction +import com.wavesplatform.test.NumericExt +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.* -import com.wavesplatform.state.Height -import com.wavesplatform.utils.ScorexLogging import org.scalatest.* -import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures} -trait IntegrationSuiteWithThreeAddresses extends BaseSuite with ScalaFutures with IntegrationPatience with RecoverMethods with ScorexLogging { +trait IntegrationSuiteWithThreeAddresses extends BaseSuite { this: TestSuite & Nodes => protected lazy val firstKeyPair: SeedKeyPair = SeedKeyPair("firstKeyPair".getBytes()) @@ -28,22 +25,10 @@ trait IntegrationSuiteWithThreeAddresses extends BaseSuite with ScalaFutures wit abstract protected override def beforeAll(): Unit = { super.beforeAll() - val defaultBalance: Long = 100.waves - - def makeTransfers(accounts: Seq[KeyPair]): Seq[String] = accounts.map { acc => - sender.transfer(sender.keyPair, acc.toAddress.toString, defaultBalance, sender.fee(TransferTransaction.typeId)).id - } - - def correctStartBalancesFuture(): Unit = { - val accounts = Seq(firstKeyPair, secondKeyPair, thirdKeyPair) - - withClue("waitForTxsToReachAllNodes") { - nodes.waitForHeight(Height(makeTransfers(accounts).map(ts => nodes.waitForTransaction(ts).height).max + 1)) - } - } - withClue("beforeAll") { - correctStartBalancesFuture() + nodes.waitForHeightAriseAndTxPresent( + sender.massTransfer(sender.keyPair, List(firstAddress, secondAddress, thirdAddress).map(MassTransferTransaction.Transfer(_, 100.waves)), 0.003.waves, version = 1.toByte).id + ) } } @@ -52,9 +37,10 @@ trait IntegrationSuiteWithThreeAddresses extends BaseSuite with ScalaFutures wit val scriptText = x.stripMargin ScriptCompiler.compile(scriptText, ScriptEstimatorV2).explicitGet()._1 } - val setScriptTransaction = SetScriptTransaction - .selfSigned(1.toByte, acc, script, 0.014.waves, System.currentTimeMillis()) - .explicitGet() + val setScriptTransaction = script.fold(TxHelpers.removeScript(acc, 0.014.waves)) { s => + TxHelpers.setScript(acc, s, 0.014.waves) + } + sender .signedBroadcast(setScriptTransaction.json(), waitForTx = true) .id diff --git a/node-it/src/test/scala/com/wavesplatform/it/Node.scala b/node-it/src/test/scala/com/wavesplatform/it/Node.scala index b2aad4340d0..2f0363c9b37 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/Node.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/Node.scala @@ -60,7 +60,7 @@ object Node { implicit class NodeExt(val n: Node) extends AnyVal { def name: String = n.settings.networkSettings.derivedNodeName def publicKeyStr: String = n.publicKey.toString - def fee(txTypeId: Byte): Long = FeeValidation.FeeConstants(TransactionType(txTypeId)) * FeeValidation.FeeUnit + def fee(txTypeId: Byte): Long = FeeValidation.FeeConstants(TransactionType.fromId(txTypeId)) * FeeValidation.FeeUnit def blockDelay: FiniteDuration = n.settings.blockchainSettings.genesisSettings.averageBlockDelay } } diff --git a/node-it/src/test/scala/com/wavesplatform/it/NodeConfigs.scala b/node-it/src/test/scala/com/wavesplatform/it/NodeConfigs.scala index 414d941c947..9631cf5da0e 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/NodeConfigs.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/NodeConfigs.scala @@ -1,6 +1,7 @@ package com.wavesplatform.it import com.typesafe.config.{Config, ConfigFactory} +import com.wavesplatform.features.BlockchainFeature import scala.jdk.CollectionConverters.* import scala.util.Random @@ -15,6 +16,27 @@ object NodeConfigs { val NotMiner: Config = Default.last def randomMiner: Config = Random.shuffle(Miners).head + val BiggestMiner: Config = Miners.last + + case class PreactivatedFeature(feature: BlockchainFeature, activationHeight: Height) + + implicit def preactivateFeature(f: BlockchainFeature): PreactivatedFeature = preactivateFeatureAt(f -> Height(0)) + implicit def preactivateFeatureAt(f: (BlockchainFeature, Height)): PreactivatedFeature = PreactivatedFeature(f._1, f._2) + + extension (c: Config) { + def overrides(s: String): Config = ConfigFactory.parseString(s).withFallback(c) + def quorum(n: Int): Config = overrides(s"waves.miner.quorum = $n") + def preactivatedFeatures(fs: PreactivatedFeature*): Config = overrides( + s"""waves.blockchain.custom.functionality.pre-activated-features { + ${fs.map(f => s"${f.feature.id} = ${f.activationHeight}").mkString("\n")} + }""" + ) + def minAssetInfoUpdateInterval(blocks: Int): Config = + overrides(s"waves.blockchain.custom.functionality.min-asset-info-update-interval = $blocks") + + def notMiner: Config = overrides("waves.miner.enable = no") + } + def newBuilder: Builder = Builder(Default, Default.size, Seq.empty) case class Builder(baseConfigs: Seq[Config], defaultEntities: Int, specialsConfigs: Seq[Config]) { diff --git a/node-it/src/test/scala/com/wavesplatform/it/TransferSending.scala b/node-it/src/test/scala/com/wavesplatform/it/TransferSending.scala index 771548ca7cc..26e2e117066 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/TransferSending.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/TransferSending.scala @@ -1,7 +1,6 @@ package com.wavesplatform.it import java.util.concurrent.ThreadLocalRandom - import com.google.common.primitives.Ints import com.typesafe.config.Config import com.wavesplatform.account.* @@ -12,6 +11,7 @@ import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.TransferSending.Req import com.wavesplatform.it.api.AsyncHttpApi.* import com.wavesplatform.it.api.Transaction +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer.* import com.wavesplatform.utils.ScorexLogging @@ -46,9 +46,8 @@ trait TransferSending extends ScorexLogging { Address.fromPublicKey(PublicKey(destPk)).toString } - val requests = sourceAndDest.foldLeft(List.empty[Req]) { - case (rs, dstAddr) => - rs :+ Req(srcSeed, dstAddr, fee, fee) + val requests = sourceAndDest.foldLeft(List.empty[Req]) { case (rs, dstAddr) => + rs :+ Req(srcSeed, dstAddr, fee, fee) } requests @@ -57,10 +56,9 @@ trait TransferSending extends ScorexLogging { def generateTransfersBetweenAccounts(n: Int, balances: Map[Config, Long]): Seq[Req] = { val fee = 100000 val srcDest = balances.toSeq - .map { - case (config, _) => - val accountSeed = config.getString("account-seed") - (config, KeyPair(Base58.decode(accountSeed))) + .map { case (config, _) => + val accountSeed = config.getString("account-seed") + (config, KeyPair(Base58.decode(accountSeed))) } val sourceAndDest = (1 to n).map { _ => @@ -68,13 +66,12 @@ trait TransferSending extends ScorexLogging { (srcConfig, destPrivateKey.toAddress.toString) } - val requests = sourceAndDest.foldLeft(List.empty[Req]) { - case (rs, (srcConfig, destAddr)) => - val a = Random.nextDouble() - val b = balances(srcConfig) - val transferAmount = (1e-8 + a * 1e-9 * b).toLong - if (transferAmount < 0) log.warn(s"Negative amount: (1e-8 + $a * 1e-8 * $b) = $transferAmount") - rs :+ Req(srcConfig.getString("account-seed"), destAddr, Math.max(transferAmount, 1L), fee) + val requests = sourceAndDest.foldLeft(List.empty[Req]) { case (rs, (srcConfig, destAddr)) => + val a = Random.nextDouble() + val b = balances(srcConfig) + val transferAmount = (1e-8 + a * 1e-9 * b).toLong + if (transferAmount < 0) log.warn(s"Negative amount: (1e-8 + $a * 1e-8 * $b) = $transferAmount") + rs :+ Req(srcConfig.getString("account-seed"), destAddr, Math.max(transferAmount, 1L), fee) } requests @@ -96,9 +93,8 @@ trait TransferSending extends ScorexLogging { (srcSeed, destAddr) } - val requests = sourceAndDest.foldLeft(List.empty[Req]) { - case (rs, (srcSeed, dstAddr)) => - rs :+ Req(srcSeed, dstAddr, fee, fee) + val requests = sourceAndDest.foldLeft(List.empty[Req]) { case (rs, (srcSeed, dstAddr)) => + rs :+ Req(srcSeed, dstAddr, fee, fee) } requests @@ -109,26 +105,21 @@ trait TransferSending extends ScorexLogging { def processRequests(requests: Seq[Req], includeAttachment: Boolean = false): Future[Seq[Transaction]] = { val start = System.currentTimeMillis() - requests.size val signedTransfers = requests.zipWithIndex - .map { - case (x, i) => - createSignedTransferRequest( - TransferTransaction - .selfSigned( - version = 2.toByte, - sender = KeyPair(Base58.decode(x.senderSeed)), - recipient = AddressOrAlias.fromString(x.targetAddress).explicitGet(), - asset = Waves, - amount = x.amount, - feeAsset = Waves, - fee = x.fee, - attachment = - if (includeAttachment) - ByteStr(Array.fill(TransferTransaction.MaxAttachmentSize)(ThreadLocalRandom.current().nextInt().toByte)) - else ByteStr.empty, - timestamp = start + i - ) - .explicitGet() + .map { case (x, i) => + createSignedTransferRequest( + TxHelpers.transfer( + KeyPair(Base58.decode(x.senderSeed)), + AddressOrAlias.fromString(x.targetAddress).explicitGet(), + x.amount, + Waves, + x.fee, + Waves, + if (includeAttachment) + ByteStr(Array.fill(TransferTransaction.MaxAttachmentSize)(ThreadLocalRandom.current().nextInt().toByte)) + else ByteStr.empty, + timestamp = start + i ) + ) } signedTransfers.zip(Iterator.continually(nodes).flatten).foldLeft(Future.successful(Seq.empty[Transaction])) { @@ -143,9 +134,8 @@ trait TransferSending extends ScorexLogging { protected def createSignedTransferRequest(tx: TransferTransaction): TransferRequest = { import tx.* TransferRequest( - Some(2.toByte), - None, - Some(tx.sender.toString), + 2.toByte, + tx.sender.toString, recipient.toString, Some(assetId), amount.value, diff --git a/node-it/src/test/scala/com/wavesplatform/it/WaitForHeight2.scala b/node-it/src/test/scala/com/wavesplatform/it/WaitForHeight2.scala deleted file mode 100644 index f0c4345a864..00000000000 --- a/node-it/src/test/scala/com/wavesplatform/it/WaitForHeight2.scala +++ /dev/null @@ -1,21 +0,0 @@ -package com.wavesplatform.it - -import com.wavesplatform.it.api.AsyncHttpApi.* -import org.scalatest.* - -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future -import scala.concurrent.Future.traverse - -trait WaitForHeight2 extends ReportingTestName with Nodes { - this: Suite => - - def waitForTxsToReachAllNodes(nodes: Seq[Node] = nodes, txIds: Seq[String]): Future[?] = { - val txNodePairs = for { - txId <- txIds - node <- nodes - } yield (node, txId) - traverse(txNodePairs) { case (node, tx) => node.waitForTransaction(tx) } - } - -} diff --git a/node-it/src/test/scala/com/wavesplatform/it/account/storage/RemoveEntrySuite.scala b/node-it/src/test/scala/com/wavesplatform/it/account/storage/RemoveEntrySuite.scala index 2209e08ca17..1c9e06ee106 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/account/storage/RemoveEntrySuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/account/storage/RemoveEntrySuite.scala @@ -1,5 +1,6 @@ package com.wavesplatform.it.account.storage +import com.typesafe.config.Config import com.wavesplatform.account.KeyPair import com.wavesplatform.api.http.ApiError.ScriptExecutionError import com.wavesplatform.common.state.ByteStr @@ -17,6 +18,9 @@ case class WriteEntry(ct: String, t: String, v: Any, k: String = "somekey") class RemoveEntrySuite extends BaseFreeSpec { + import com.wavesplatform.it.NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(Miners(5).quorum(0)) + private val stringTestData = WriteEntry("String", "String", "somevalue") private val integerTestData = WriteEntry("Integer", "Int", 1) private val booleanTestData = WriteEntry("Boolean", "Boolean", true) @@ -56,7 +60,7 @@ class RemoveEntrySuite extends BaseFreeSpec { invokeScript(keyPair, s"write${data.ct}", data.k, data.v.toString) - nodes.waitForHeightArise() //TODO: delete this line after NODE-2099 will be done + nodes.waitForHeightArise() // TODO: delete this line after NODE-2099 will be done val address = keyPair.toAddress.toString miner.getData(address) should have size 1 diff --git a/node-it/src/test/scala/com/wavesplatform/it/api/AsyncHttpApi.scala b/node-it/src/test/scala/com/wavesplatform/it/api/AsyncHttpApi.scala index 2c37bba5622..1f14e2288b0 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/api/AsyncHttpApi.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/api/AsyncHttpApi.scala @@ -9,7 +9,8 @@ import com.wavesplatform.api.http.{ConnectReq, DebugMessage, RollbackParams, `X- import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.common.utils.{Base58, Base64} -import com.wavesplatform.features.api.{ActivationStatus, activationStatusFormat} +import com.wavesplatform.features.BlockchainFeatures +import com.wavesplatform.features.api.{ActivationStatus, FinalityStatus, activationStatusFormat} import com.wavesplatform.it.Node import com.wavesplatform.it.sync.invokeExpressionFee import com.wavesplatform.it.util.* @@ -30,10 +31,8 @@ import com.wavesplatform.transaction.transfer.* import com.wavesplatform.transaction.transfer.MassTransferTransaction.{ParsedTransfer, Transfer} import com.wavesplatform.transaction.{ Asset, - CreateAliasTransaction, DataTransaction, Proofs, - TransactionSignOps, TransactionValidationOps, TxDecimals, TxExchangeAmount, @@ -228,6 +227,13 @@ object AsyncHttpApi extends Assertions { def finalizedHeightAt(at: Height): Future[Height] = get(s"/blocks/finalized/at/$at").as[JsValue].map(v => (v \ "height").as[Height]) + def finalityStatus: Future[FinalityStatus] = for { + as <- activationStatus + jsv <- get("/blockchain/finality").as[JsValue] + } yield jsv.as[FinalityStatus](using + FinalityStatus.parse(as.features.find(_.id == BlockchainFeatures.DeterministicFinality.id).flatMap(_.activationHeight)) + ) + def blockAt(height: Height, amountsAsStrings: Boolean = false): Future[Block] = get(s"/blocks/at/$height", amountsAsStrings).as[Block](amountsAsStrings) @@ -777,15 +783,13 @@ object AsyncHttpApi extends Assertions { signedBroadcast(issue.toTx.explicitGet().json()) def batchSignedTransfer(transfers: Seq[TransferRequest]): Future[Seq[Transaction]] = { - import TransferRequest.jsonFormat Future.sequence(transfers.map(v => signedBroadcast(toJson(v).as[JsObject] ++ Json.obj("type" -> TransferTransaction.typeId.toInt)))) } def createAlias(target: KeyPair, alias: String, fee: Long, version: TxVersion = TxVersion.V2): Future[Transaction] = signedBroadcast( - CreateAliasTransaction - .selfSigned(version, target, alias, fee, System.currentTimeMillis()) - .explicitGet() + com.wavesplatform.transaction.TxHelpers + .createAlias(alias, target, fee, version) .json() ) diff --git a/node-it/src/test/scala/com/wavesplatform/it/api/SyncHttpApi.scala b/node-it/src/test/scala/com/wavesplatform/it/api/SyncHttpApi.scala index 88b252bae01..df959b439ab 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/api/SyncHttpApi.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/api/SyncHttpApi.scala @@ -2,23 +2,20 @@ package com.wavesplatform.it.api import com.wavesplatform.account.{AddressOrAlias, KeyPair, SeedKeyPair} import com.wavesplatform.api.http.RewardApiRoute.RewardStatus -import com.wavesplatform.api.http.requests.{CommitToGenerationRequest, IssueRequest} +import com.wavesplatform.api.http.requests.IssueRequest import com.wavesplatform.api.http.{ApiError, DebugMessage} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* -import com.wavesplatform.features.BlockchainFeatures -import com.wavesplatform.features.api.{ActivationStatus, FeatureActivationStatus} +import com.wavesplatform.features.api.{ActivationStatus, FeatureActivationStatus, FinalityStatus} import com.wavesplatform.it.Node import com.wavesplatform.it.sync.* import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.state.{AssetDistribution, AssetDistributionPage, DataEntry, GenerationPeriod, Height} import com.wavesplatform.transaction.assets.exchange.Order -import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer -import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{Asset, TransactionType, TxExchangeAmount, TxExchangePrice, TxVersion} +import com.wavesplatform.transaction.{Asset, TransactionType, TxExchangeAmount, TxExchangePrice, TxHelpers, TxVersion} import io.grpc.Status.Code import org.apache.pekko.http.scaladsl.model.StatusCodes.BadRequest import org.apache.pekko.http.scaladsl.model.{StatusCode, StatusCodes} @@ -388,19 +385,17 @@ object SyncHttpApi extends Assertions with matchers.should.Matchers { version: Byte = TxVersion.V2, waitForTx: Boolean = false ): Transaction = { - val tx = TransferTransaction - .selfSigned( - version = version, - sender = source, - recipient = AddressOrAlias.fromString(recipient).explicitGet(), - asset = Asset.fromString(assetId), - amount = amount, - feeAsset = Asset.fromString(feeAssetId), - fee = fee, - attachment = attachment, - timestamp = System.currentTimeMillis() - ) - .explicitGet() + val tx = TxHelpers.transfer( + source, + AddressOrAlias.fromString(recipient).explicitGet(), + amount, + Asset.fromString(assetId), + fee, + Asset.fromString(feeAssetId), + attachment, + version = version, + timestamp = System.currentTimeMillis() + ) maybeWaitForTransaction(sync(async(n).broadcastRequest(tx.json())), wait = waitForTx) } @@ -479,16 +474,15 @@ object SyncHttpApi extends Assertions with matchers.should.Matchers { leasingFee: Long = minFee, waitForTx: Boolean = false ): Transaction = { - val tx = LeaseTransaction - .selfSigned( - 2.toByte, - sender = source, - recipient = AddressOrAlias.fromString(recipient).explicitGet(), - amount = leasingAmount, - fee = leasingFee, - timestamp = System.currentTimeMillis() + val tx = TxHelpers + .lease( + source, + AddressOrAlias.fromString(recipient).explicitGet(), + leasingAmount, + leasingFee, + System.currentTimeMillis(), + 2.toByte ) - .explicitGet() maybeWaitForTransaction(sync(async(n).broadcastRequest(tx.json())), wait = waitForTx) } @@ -548,8 +542,8 @@ object SyncHttpApi extends Assertions with matchers.should.Matchers { def getMerkleProofPost(ids: String*): Seq[MerkleProofResponse] = sync(async(n).getMerkleProofPost(ids*)) - def sign(req: CommitToGenerationRequest): Transaction = - sign(Json.obj("type" -> TransactionType.CommitToGeneration.id) ++ Json.toJsObject(req)).tap { r => + def signCommitToGenerationRequest(sender: String): Transaction = + sign(Json.obj("type" -> TransactionType.CommitToGeneration.id, "sender" -> sender)).tap { r => require(r._type == TransactionType.CommitToGeneration.id) } @@ -563,15 +557,14 @@ object SyncHttpApi extends Assertions with matchers.should.Matchers { sync(async(n).activeLeases(sourceAddress)) def broadcastCancelLease(source: KeyPair, leaseId: String, fee: Long = minFee, waitForTx: Boolean = false): Transaction = { - val tx = LeaseCancelTransaction - .selfSigned( - TxVersion.V2, - source, + val tx = TxHelpers + .leaseCancel( ByteStr.decodeBase58(leaseId).get, + source, fee, - System.currentTimeMillis() + System.currentTimeMillis(), + TxVersion.V2 ) - .explicitGet() maybeWaitForTransaction(sync(async(n).broadcastRequest(tx.json())), wait = waitForTx) } @@ -610,11 +603,7 @@ object SyncHttpApi extends Assertions with matchers.should.Matchers { def waitForHeight(expectedHeight: Height, requestAwaitTime: FiniteDuration = RequestAwaitTime): Height = sync(async(n).waitForHeight(expectedHeight), requestAwaitTime) - def currentGenerationPeriod: Option[GenerationPeriod] = for { - activationStatus <- sync(async(n).activationStatus).features.find(_.id == BlockchainFeatures.DeterministicFinality.id) - activation <- activationStatus.activationHeight - r <- GenerationPeriod.from(sync(async(n).height), activation, n.settings) - } yield r + def currentGenerationPeriod: Option[GenerationPeriod] = sync(async(n).finalityStatus).currentGenerationPeriod def waitForGenerationPeriod(p: GenerationPeriod, requestAwaitTime: FiniteDuration = 3.minutes): Height = waitForHeight(p.start, requestAwaitTime) @@ -641,6 +630,8 @@ object SyncHttpApi extends Assertions with matchers.should.Matchers { def finalizedHeightAt(at: Height): Height = sync(async(n).finalizedHeightAt(at)) + def finalityStatus: FinalityStatus = sync(async(n).finalityStatus) + def blockAt(height: Height, amountsAsStrings: Boolean = false): Block = sync(async(n).blockAt(height, amountsAsStrings)) def blockSeq(fromHeight: Height, toHeight: Height, amountsAsStrings: Boolean = false): Seq[Block] = diff --git a/node-it/src/test/scala/com/wavesplatform/it/asset/GrpcIssueReissueBurnAssetSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/asset/GrpcIssueReissueBurnAssetSuite.scala index 078db68bb1a..5b35dcf65c6 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/asset/GrpcIssueReissueBurnAssetSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/asset/GrpcIssueReissueBurnAssetSuite.scala @@ -14,8 +14,7 @@ import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BOOLEAN, CONST_BYTESTR, C import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.protobuf.transaction.{PBRecipients, PBTransactions} import com.wavesplatform.test.* -import com.wavesplatform.transaction.TxVersion -import com.wavesplatform.transaction.smart.SetScriptTransaction +import com.wavesplatform.transaction.{TxHelpers, TxVersion} import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalatest.freespec.AnyFreeSpec @@ -260,9 +259,7 @@ class GrpcIssueReissueBurnAssetSuite extends AnyFreeSpec with GrpcBaseTransactio miner .signedBroadcast( PBTransactions.protobuf( - SetScriptTransaction - .selfSigned(1.toByte, address, Some(compiledScript), setScriptFee, System.currentTimeMillis()) - .explicitGet() + TxHelpers.setScript(address, compiledScript, setScriptFee) ) ) .id diff --git a/node-it/src/test/scala/com/wavesplatform/it/asset/HttpScriptAssetActionLimitsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/asset/HttpScriptAssetActionLimitsSuite.scala index dc49effa305..0ecd430b07b 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/asset/HttpScriptAssetActionLimitsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/asset/HttpScriptAssetActionLimitsSuite.scala @@ -10,7 +10,7 @@ import com.wavesplatform.lang.v1.ContractLimits import com.wavesplatform.lang.v1.compiler.Terms.CONST_BYTESTR import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.test.* -import com.wavesplatform.transaction.smart.SetScriptTransaction +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.smart.script.ScriptCompiler class HttpScriptAssetActionLimitsSuite extends ScriptAssetActionLimitsSuite { @@ -30,9 +30,8 @@ class HttpScriptAssetActionLimitsSuite extends ScriptAssetActionLimitsSuite { nodes.waitForHeightAriseAndTxPresent( miner .signedBroadcast( - SetScriptTransaction - .selfSigned(1.toByte, address, Some(compiledScript), 1.waves, System.currentTimeMillis()) - .explicitGet() + TxHelpers + .setScript(address, compiledScript, 1.waves, timestamp = System.currentTimeMillis()) .json() ) .id diff --git a/node-it/src/test/scala/com/wavesplatform/it/asset/IssueReissueBurnAssetSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/asset/IssueReissueBurnAssetSuite.scala index 6452de14fff..f56baba6e44 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/asset/IssueReissueBurnAssetSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/asset/IssueReissueBurnAssetSuite.scala @@ -14,18 +14,15 @@ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} +import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.{TxHelpers, TxVersion} import monix.execution.atomic.AtomicInt import scala.concurrent.duration.* class IssueReissueBurnAssetSuite extends BaseFreeSpec { - override val nodeConfigs: Seq[Config] = - com.wavesplatform.it.NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .buildNonConflicting() + import com.wavesplatform.it.NodeConfigs.* + override val nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0)) private val initialWavesBalance = 100.waves private val setScriptPrice = 0.01.waves private val accountCounter = AtomicInt(1000) @@ -328,9 +325,7 @@ class IssueReissueBurnAssetSuite extends BaseFreeSpec { nodes.waitForHeightAriseAndTxPresent( miner .signedBroadcast( - SetScriptTransaction - .selfSigned(1.toByte, address, Some(compiledScript), setScriptFee, System.currentTimeMillis()) - .explicitGet() + TxHelpers.setScript(acc = address, script = compiledScript, fee = setScriptFee, version = 1.toByte) .json() ) .id diff --git a/node-it/src/test/scala/com/wavesplatform/it/asset/LeaseActionGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/asset/LeaseActionGrpcSuite.scala index 195c97a5497..607595d6b76 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/asset/LeaseActionGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/asset/LeaseActionGrpcSuite.scala @@ -7,7 +7,6 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncGrpcApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.sync.grpc.GrpcBaseTransactionSuite @@ -23,11 +22,9 @@ import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.smart.script.ScriptCompiler class LeaseActionGrpcSuite extends GrpcBaseTransactionSuite { + import NodeConfigs.* override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 2, Seq.empty) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.SynchronousCalls.id, Height(1)))) - .buildNonConflicting() + Seq(BiggestMiner, Miners(3)).map(_.preactivatedFeatures((BlockchainFeatures.SynchronousCalls, Height(1)))) private def compile(script: String): Script = ScriptCompiler.compile(script, ScriptEstimatorV3.latest).explicitGet()._1 diff --git a/node-it/src/test/scala/com/wavesplatform/it/asset/LeaseActionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/asset/LeaseActionSuite.scala index 621fa3f9dc5..9865cf9ca6c 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/asset/LeaseActionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/asset/LeaseActionSuite.scala @@ -5,7 +5,6 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.LeaseInfo import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* @@ -18,11 +17,9 @@ import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.smart.script.ScriptCompiler class LeaseActionSuite extends BaseTransactionSuite { + import NodeConfigs.* override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 2, Seq.empty) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.SynchronousCalls.id, Height(1)))) - .buildNonConflicting() + Seq(BiggestMiner, Miners(6)).map(_.preactivatedFeatures((BlockchainFeatures.SynchronousCalls, Height(1)))) private def compile(script: String): String = ScriptCompiler.compile(script, ScriptEstimatorV3.latest).explicitGet()._1.bytes().base64 @@ -37,23 +34,23 @@ class LeaseActionSuite extends BaseTransactionSuite { test("set script") { val dApp = compile( s""" - | {-# STDLIB_VERSION 5 #-} - | {-# CONTENT_TYPE DAPP #-} - | {-# SCRIPT_TYPE ACCOUNT #-} - | - | @Callable(i) - | func lease() = { - | [ - | Lease(i.caller, $dAppLeaseAmount) - | ] - | } - | - | @Callable(i) - | func leaseCancel(leaseId: ByteVector) = { - | [ - | LeaseCancel(leaseId) - | ] - | } + | {-# STDLIB_VERSION 5 #-} + | {-# CONTENT_TYPE DAPP #-} + | {-# SCRIPT_TYPE ACCOUNT #-} + | + | @Callable(i) + | func lease() = { + | [ + | Lease(i.caller, $dAppLeaseAmount) + | ] + | } + | + | @Callable(i) + | func leaseCancel(leaseId: ByteVector) = { + | [ + | LeaseCancel(leaseId) + | ] + | } """.stripMargin ) sender.setScript(dAppAcc, Some(dApp), waitForTx = true) diff --git a/node-it/src/test/scala/com/wavesplatform/it/asset/ScriptAssetActionLimitsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/asset/ScriptAssetActionLimitsSuite.scala index 230ce82d27b..f91aa710679 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/asset/ScriptAssetActionLimitsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/asset/ScriptAssetActionLimitsSuite.scala @@ -4,21 +4,16 @@ import com.typesafe.config.Config import com.wavesplatform.account.KeyPair import com.wavesplatform.features.BlockchainFeatures.{RideV6, SynchronousCalls} import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs} -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.lang.directives.values.StdLibVersion import com.wavesplatform.test.* -import com.wavesplatform.state.Height trait ScriptAssetActionLimitsSuite extends BaseFreeSpec { def createDApp(script: String, address: KeyPair = miner.generateKeyPair()): KeyPair + import NodeConfigs.* override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((SynchronousCalls.id, Height(0)), (RideV6.id, Height(0)))) - .buildNonConflicting() + Seq(BiggestMiner.quorum(0).preactivatedFeatures(SynchronousCalls, RideV6)) protected val initialWavesBalance: Long = 1000.waves protected val minSponsoredAssetFee: Long = 1001 diff --git a/node-it/src/test/scala/com/wavesplatform/it/asset/SponsorFeeActionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/asset/SponsorFeeActionSuite.scala index 7c8e202cabe..9d0858cd969 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/asset/SponsorFeeActionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/asset/SponsorFeeActionSuite.scala @@ -9,7 +9,7 @@ import com.wavesplatform.it.sync.* import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state.Sponsorship import com.wavesplatform.test.* -import com.wavesplatform.transaction.smart.SetScriptTransaction +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.smart.script.ScriptCompiler class SponsorFeeActionSuite extends BaseFreeSpec { @@ -468,9 +468,8 @@ class SponsorFeeActionSuite extends BaseFreeSpec { nodes.waitForTransaction( miner .signedBroadcast( - SetScriptTransaction - .selfSigned(1.toByte, address, Some(compiledScript), setScriptFee, System.currentTimeMillis()) - .explicitGet() + TxHelpers + .setScript(address, compiledScript, setScriptFee, timestamp = System.currentTimeMillis()) .json() ) .id diff --git a/node-it/src/test/scala/com/wavesplatform/it/async/WideStateGenerationSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/async/WideStateGenerationSuite.scala index 6a172eb03ca..b095de5f92a 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/async/WideStateGenerationSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/async/WideStateGenerationSuite.scala @@ -12,7 +12,7 @@ import scala.concurrent.duration.* import scala.concurrent.{Await, Future} @LoadTest -class WideStateGenerationSuite extends BaseFreeSpec with WaitForHeight2 with TransferSending { +class WideStateGenerationSuite extends BaseFreeSpec with TransferSending { override protected def createDocker: Docker = new Docker( suiteConfig = ConfigFactory.parseString( @@ -40,11 +40,9 @@ class WideStateGenerationSuite extends BaseFreeSpec with WaitForHeight2 with Tra enableProfiling = true ) - override protected val nodeConfigs: Seq[Config] = NodeConfigs.newBuilder - .overrideBase(_.quorum(3)) - .withDefault(2) - .withSpecial(2, _.nonMiner) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = + (Seq(BiggestMiner, Miners(6)) ++ Seq(NotMiner, Miners.head).map(_.notMiner)).map(_.quorum(3)) private val nodeAddresses = nodeConfigs.map(_.getString("address")).toSet private val requestsCount = 10000 diff --git a/node-it/src/test/scala/com/wavesplatform/it/repl/ReplTest.scala b/node-it/src/test/scala/com/wavesplatform/it/repl/ReplTest.scala index d40a2556f93..ded9aec2b20 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/repl/ReplTest.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/repl/ReplTest.scala @@ -6,7 +6,7 @@ import com.wavesplatform.common.utils.* import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.api.SyncHttpApi.* -import com.wavesplatform.it.sync.transactions.{FailedTransactionSuiteLike, OverflowBlock} +import com.wavesplatform.it.sync.transactions.FailedTransactionSuiteLike import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.lang.v1.repl.Repl @@ -19,16 +19,13 @@ import com.wavesplatform.transaction.{TxHelpers, TxVersion} import scala.concurrent.duration.* import scala.concurrent.{Await, Future} -class ReplTest extends BaseTransactionSuite with FailedTransactionSuiteLike[String] with OverflowBlock { +class ReplTest extends BaseTransactionSuite with FailedTransactionSuiteLike[String] { override protected def waitForHeightArise(): Unit = nodes.waitForHeightArise() - override def nodeConfigs: Seq[Config] = - com.wavesplatform.it.NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures(BlockchainFeatures.BlockV5.id.toInt -> Height(0))) - .withDefault(1) - .buildNonConflicting() + import com.wavesplatform.it.NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = + Seq(BiggestMiner.quorum(0).preactivatedFeatures(BlockchainFeatures.BlockV5)) def await[A](f: Future[A]): A = Await.result(f, 2 seconds) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/AddressApiSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/AddressApiSuite.scala index e26b4077743..343abeaa7ae 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/AddressApiSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/AddressApiSuite.scala @@ -149,11 +149,7 @@ class AddressApiSuite extends BaseTransactionSuite with NTPTime { postResult should contain theSameElementsAs expected } + import NodeConfigs.* override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.raw("waves.rest-api.transactions-by-address-limit = 20")) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + Seq(BiggestMiner.quorum(0).overrides("waves.rest-api.transactions-by-address-limit = 20"), NotMiner) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/AmountAsStringSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/AmountAsStringSuite.scala index 45d82eba44d..e6777bbafce 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/AmountAsStringSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/AmountAsStringSuite.scala @@ -1,22 +1,31 @@ package com.wavesplatform.it.sync +import com.typesafe.config.Config import com.wavesplatform.account.KeyPair import com.wavesplatform.common.utils.Base58 import com.wavesplatform.common.utils.EitherExt2.* +import com.wavesplatform.it.BaseFunSuite +import com.wavesplatform.it.NodeConfigs.* import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.{Transaction, TransactionInfo} -import com.wavesplatform.it.sync.transactions.OverflowBlock -import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.state.{IntegerDataEntry, Height} +import com.wavesplatform.state.{Height, IntegerDataEntry} import com.wavesplatform.transaction.assets.exchange.{AssetPair, Order} import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer import com.wavesplatform.transaction.{CreateAliasTransaction, TxExchangeAmount, TxExchangePrice, TxVersion} +import com.wavesplatform.utils.ScorexLogging import org.asynchttpclient.Response import org.scalatest import org.scalatest.Assertion import play.api.libs.json.{JsString, JsValue, Json} -class AmountAsStringSuite extends BaseTransactionSuite with OverflowBlock { +class AmountAsStringSuite extends BaseFunSuite with ScorexLogging { + override protected def nodeConfigs: Seq[Config] = Seq( + Miners(1).quorum(0).overrides("waves.miner.micro-block-interval = 5s"), // when UTX is empty, retry building microblock in 2 seconds + NotMiner + ) + + private def firstKeyPair = notMiner.keyPair + private def firstAddress = firstKeyPair.toAddress.toString val (headerName, headerValue) = ("Accept", "application/json;large-significand-format=string") @@ -201,13 +210,13 @@ class AmountAsStringSuite extends BaseTransactionSuite with OverflowBlock { } test("amount as string in masstransfer transaction") { nodes.waitForHeightArise() - overflowBlock() def checkMassTransferTx(tx: Transaction): Assertion = { + log.info(s"Transaction: $tx") tx.transfers.get.head.amount shouldBe transferAmount tx.totalAmount shouldBe Some(transferAmount) } - val (transfers, massTransferFee) = (List(Transfer(secondAddress, transferAmount)), calcMassTransferFee(1)) + val (transfers, massTransferFee) = (List(Transfer(miner.address, transferAmount)), calcMassTransferFee(1)) val massTransferTx = sender.massTransfer(firstKeyPair, transfers, massTransferFee, amountsAsStrings = true) checkMassTransferTx(massTransferTx) @@ -229,7 +238,7 @@ class AmountAsStringSuite extends BaseTransactionSuite with OverflowBlock { val tx = Json.obj( "type" -> CreateAliasTransaction.typeId, - "sender" -> firstKeyPair, + "sender" -> firstKeyPair.publicKey.toString, "alias" -> "alias", "fee" -> 100000, "timestamp" -> System.currentTimeMillis(), diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/BlockV5TestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/BlockV5TestSuite.scala index 2cc5c8c1e08..b23a118b1a5 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/BlockV5TestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/BlockV5TestSuite.scala @@ -6,22 +6,20 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.Base58 import com.wavesplatform.crypto import com.wavesplatform.crypto.Blake2b256 +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.activation.ActivationStatusRequest -import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs} import com.wavesplatform.state.Height import org.scalatest.* import scala.concurrent.duration.* class BlockV5TestSuite extends BaseFreeSpec with ActivationStatusRequest with OptionValues { - - override def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .withSpecial(1, _.nonMiner) - .buildNonConflicting() + import com.wavesplatform.it.NodeConfigs.* + override val nodeConfigs: Seq[Config] = Seq( + Miners(3).quorum(0), + Default.head.notMiner + ) var currentHeight = Height(0) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/CustomFeeTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/CustomFeeTransactionSuite.scala index 703f3119a39..31ff380bb8a 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/CustomFeeTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/CustomFeeTransactionSuite.scala @@ -8,8 +8,7 @@ import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.state.{Height, Sponsorship} import com.wavesplatform.test.* -import com.wavesplatform.transaction.TxVersion -import com.wavesplatform.transaction.assets.IssueTransaction +import com.wavesplatform.transaction.{TxHelpers, TxVersion} import org.scalatest.CancelAfterFailure class CustomFeeTransactionSuite extends BaseTransactionSuite with CancelAfterFailure { @@ -76,20 +75,7 @@ object CustomFeeTransactionSuite { private val defaultAssetQuantity = 999999999999L private val featureCheckBlocksPeriod = 13 - private val assetTx = IssueTransaction - .selfSigned( - TxVersion.V1, - sender = senderKeyPair, - "asset", - "asset description", - quantity = defaultAssetQuantity, - decimals = 2, - reissuable = false, - script = None, - fee = 1.waves, - timestamp = System.currentTimeMillis() - ) - .explicitGet() + private val assetTx = TxHelpers.issue(issuer = senderKeyPair, amount = defaultAssetQuantity, decimals = 2, name = "asset", description = "asset description", fee = 1.waves, script = None, reissuable = false, version = TxVersion.V1) private val assetId = assetTx.id() diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/MicroblocksSponsoredFeeTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/MicroblocksSponsoredFeeTestSuite.scala index 2f4b9f7ac9c..2b39f7a7c22 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/MicroblocksSponsoredFeeTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/MicroblocksSponsoredFeeTestSuite.scala @@ -1,6 +1,7 @@ package com.wavesplatform.it.sync import com.typesafe.config.Config +import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs} import com.wavesplatform.state.{Height, Sponsorship} @@ -64,14 +65,14 @@ class MicroblocksSponsoredFeeTestSuite extends BaseFreeSpec with ScorexLogging { } } - override def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.raw("waves.blockchain.custom.functionality.blocks-for-feature-activation=1")) - .overrideBase(_.raw("waves.blockchain.custom.functionality.feature-check-blocks-period=1")) - .overrideBase(_.preactivatedFeatures((14, Height(1000000)))) - .withDefault(1) - .withSpecial(2, _.nonMiner) - .buildNonConflicting() - + import NodeConfigs.* + override def nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0).overrides( + """waves.blockchain.custom.functionality { + | blocks-for-feature-activation = 1 + | feature-check-blocks-period = 1 + |}""".stripMargin), + Default(1).notMiner, + Default(2).notMiner + ).map(_.preactivatedFeatures((BlockchainFeatures.BlockReward, Height(1000000)))) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/MinerWithAccountScriptTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/MinerWithAccountScriptTestSuite.scala index 53edec07d17..b29604e6ae9 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/MinerWithAccountScriptTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/MinerWithAccountScriptTestSuite.scala @@ -14,12 +14,9 @@ import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.Height class MinerWithAccountScriptTestSuite extends BaseFunSuite { + import NodeConfigs.* override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.preactivatedFeatures(Seq(BlockchainFeatures.RideV6.id.toInt -> Height(0))*)) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + Seq(BiggestMiner, NotMiner).map(_.preactivatedFeatures(BlockchainFeatures.RideV6)) val allowedRecipient: String = KeyPair("allowedRecipient".getBytes).toAddress('I').toString val dataKey = "testKey" diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/NFTBalanceSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/NFTBalanceSuite.scala index 7ff0e5267b7..48978d4e72b 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/NFTBalanceSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/NFTBalanceSuite.scala @@ -3,16 +3,14 @@ package com.wavesplatform.it.sync import com.typesafe.config.Config import com.wavesplatform.account.KeyPair import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.* import com.wavesplatform.it.api.* import com.wavesplatform.it.api.AsyncHttpApi.* import com.wavesplatform.state.Height import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.assets.IssueTransaction -import com.wavesplatform.transaction.transfer.TransferTransaction +import com.wavesplatform.transaction.{TxHelpers, TxVersion} import play.api.libs.json.* import scala.concurrent.Future.traverse @@ -22,13 +20,8 @@ import scala.util.Random class NFTBalanceSuite extends BaseFreeSpec { import NFTBalanceSuite.* - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(BiggestMiner, NotMiner) private def node: Node = nodes.head @@ -83,9 +76,17 @@ class NFTBalanceSuite extends BaseFreeSpec { "returns only nft with balance > 0 on /nft/{address}/limit/{limit}" in { val other = KeyPair("other".getBytes) - val transfer = TransferTransaction - .selfSigned(1.toByte, issuer, other.toAddress, randomTokenToTransfer, 1, Waves, 0.001.waves, ByteStr.empty, System.currentTimeMillis()) - .explicitGet() + val transfer = TxHelpers.transfer( + from = issuer, + to = other.toAddress, + amount = 1, + asset = randomTokenToTransfer, + fee = 0.001.waves, + feeAsset = Waves, + attachment = ByteStr.empty, + timestamp = System.currentTimeMillis(), + version = 1.toByte + ) val assertion = for { tx <- node.signedBroadcast(transfer.json()) @@ -156,37 +157,31 @@ object NFTBalanceSuite { def fillPortfolio(issuer: KeyPair, nft: Int, simple: Int): (List[IssueTransaction], List[IssueTransaction]) = { val simpleAssets = List.fill[IssueTransaction](simple) { - IssueTransaction - .selfSigned( - TxVersion.V1, - issuer, - "SimpleAsset", - s"Simple Test Asset ${Random.nextInt(1000)}", - 1000, - 8, - reissuable = true, - script = None, - 1.waves, - System.currentTimeMillis() - ) - .explicitGet() + TxHelpers.issue( + issuer = issuer, + amount = 1000, + decimals = 8, + name = "SimpleAsset", + description = s"Simple Test Asset ${Random.nextInt(1000)}", + fee = 1.waves, + script = None, + reissuable = true, + version = TxVersion.V1 + ) } val nonFungibleAssets = List.fill[IssueTransaction](nft) { - IssueTransaction - .selfSigned( - TxVersion.V1, - issuer, - "NonFungibleAsset", - s"NFT Test Asset ${Random.nextInt(1000)}", - 1, - 0, - reissuable = false, - script = None, - 1.waves, - System.currentTimeMillis() - ) - .explicitGet() + TxHelpers.issue( + issuer = issuer, + amount = 1, + decimals = 0, + name = "NonFungibleAsset", + description = s"NFT Test Asset ${Random.nextInt(1000)}", + fee = 1.waves, + script = None, + reissuable = false, + version = TxVersion.V1 + ) } (simpleAssets, nonFungibleAssets) @@ -242,9 +237,13 @@ object NFTBalanceSuite { .get(s"/assets/balance/$address") .as[JsObject] .map { json => - (json \ "balances").as[List[String]](using Reads.list(using Reads { details => - (details \ "issueTransaction" \ "assetId").validate[String] - })) + (json \ "balances").as[List[String]](using + Reads.list(using + Reads { details => + (details \ "issueTransaction" \ "assetId").validate[String] + } + ) + ) } } } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/NodeRestartTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/NodeRestartTestSuite.scala index dd59b868479..ecb09072b96 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/NodeRestartTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/NodeRestartTestSuite.scala @@ -6,13 +6,13 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.TransactionInfo -import com.wavesplatform.it.{BaseFreeSpec, WaitForHeight2} +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.state.Height import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.transfer.TransferTransaction +import com.wavesplatform.transaction.TxHelpers -class NodeRestartTestSuite extends BaseFreeSpec with WaitForHeight2 { +class NodeRestartTestSuite extends BaseFreeSpec { import NodeRestartTestSuite.* override protected def nodeConfigs: Seq[Config] = Configs @@ -34,19 +34,7 @@ class NodeRestartTestSuite extends BaseFreeSpec with WaitForHeight2 { } "after restarting all the nodes, the duplicate transaction cannot be put into the blockchain" in { - val txJson = TransferTransaction - .selfSigned( - 1.toByte, - nodeB.keyPair, - AddressOrAlias.fromString(nodeA.address).explicitGet(), - Waves, - 1.waves, - Waves, - minFee, - ByteStr.empty, - System.currentTimeMillis() - ) - .explicitGet() + val txJson = TxHelpers.transfer(from = nodeB.keyPair, to = AddressOrAlias.fromString(nodeA.address).explicitGet(), amount = 1.waves, asset = Waves, fee = minFee, feeAsset = Waves, attachment = ByteStr.empty, timestamp = System.currentTimeMillis(), version = 1.toByte) .json() val tx = nodeB.signedBroadcast(txJson, waitForTx = true) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/PoSSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/PoSSuite.scala index 8dd7d10ca56..6113ea52a0c 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/PoSSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/PoSSuite.scala @@ -12,14 +12,14 @@ import com.wavesplatform.consensus.nxt.NxtLikeConsensusBlockData import com.wavesplatform.crypto import com.wavesplatform.it.api.AsyncNetworkApi.NodeAsyncNetworkApi import com.wavesplatform.it.api.SyncHttpApi.* -import com.wavesplatform.it.{BaseFunSuite, NodeConfigs, WaitForHeight2} +import com.wavesplatform.it.{BaseFunSuite, NodeConfigs} import com.wavesplatform.network.RawBytes import com.wavesplatform.state.Height import play.api.libs.json.{JsSuccess, Json, Reads} import scala.util.Random -class PoSSuite extends BaseFunSuite with WaitForHeight2 { +class PoSSuite extends BaseFunSuite { private val signerPK = KeyPair.fromSeed(nodeConfigs.last.getString("account-seed")).explicitGet() diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/RollbackSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/RollbackSuite.scala index 5c31c960cbc..fd606ba35b4 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/RollbackSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/RollbackSuite.scala @@ -1,6 +1,7 @@ package com.wavesplatform.it.sync import com.typesafe.config.Config +import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.* import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.state.{BooleanDataEntry, Height, IntegerDataEntry} @@ -13,13 +14,11 @@ import scala.util.Random @LoadTest class RollbackSuite extends BaseFunSuite with TransferSending with TableDrivenPropertyChecks { - override def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((14, Height(1000000)))) - .withDefault(1) - .withSpecial(1, _.nonMiner) - .buildNonConflicting() + import NodeConfigs.* + override def nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0).preactivatedFeatures((BlockchainFeatures.BlockReward, Height(1000000))), + NotMiner + ) private lazy val nodeAddresses = nodeConfigs.map(_.getString("address")).toSet diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/ScriptLogSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/ScriptLogSuite.scala index d4aa9b275cb..3b9f06e46d9 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/ScriptLogSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/ScriptLogSuite.scala @@ -7,8 +7,7 @@ import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state.BinaryDataEntry -import com.wavesplatform.transaction.DataTransaction -import com.wavesplatform.transaction.smart.SetScriptTransaction +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalatest.CancelAfterFailure @@ -24,7 +23,7 @@ class ScriptLogSuite extends BaseTransactionSuite with CancelAfterFailure { s""" |let self = Address(base58'$firstAddress') | - |match tx { + |match tx { | case dtx: DataTransaction => | let v00 = extract(getBinary(self, "k0")) | let v01 = extract(getBinary(self, "k1")) @@ -66,10 +65,8 @@ class ScriptLogSuite extends BaseTransactionSuite with CancelAfterFailure { sender.putData(firstKeyPair, data, ENOUGH_FEE, waitForTx = true).id - val script = ScriptCompiler.compile(scriptSrc, ScriptEstimatorV2).explicitGet()._1 - val setScriptTransaction = SetScriptTransaction - .selfSigned(1.toByte, firstKeyPair, Some(script), setScriptFee, System.currentTimeMillis()) - .explicitGet() + val script = ScriptCompiler.compile(scriptSrc, ScriptEstimatorV2).explicitGet()._1 + val setScriptTransaction = TxHelpers.setScript(firstKeyPair, script, setScriptFee, timestamp = System.currentTimeMillis()) val sstx = sender.signedBroadcast(setScriptTransaction.json()).id @@ -80,18 +77,14 @@ class ScriptLogSuite extends BaseTransactionSuite with CancelAfterFailure { Random.nextBytes(signature) def mkInvData() = - DataTransaction - .selfSigned( - 1.toByte, - firstKeyPair, - List( - BinaryDataEntry("pk", firstKeyPair.publicKey.byteStr), - BinaryDataEntry("sig", ByteStr(signature)) - ), - ENOUGH_FEE, - System.currentTimeMillis() - ) - .explicitGet() + TxHelpers.data( + firstKeyPair, + List( + BinaryDataEntry("pk", firstKeyPair.publicKey.byteStr), + BinaryDataEntry("sig", ByteStr(signature)) + ), + ENOUGH_FEE + ) assertApiErrorRaised(sender.signedBroadcast(mkInvData().json())) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/UtxSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/UtxSuite.scala index d01ce8a917d..2c76a8e0d44 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/UtxSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/UtxSuite.scala @@ -1,19 +1,20 @@ package com.wavesplatform.it.sync -import scala.util.{Random, Try} import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.account.KeyPair import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* -import com.wavesplatform.it.{BaseFunSuite, Node} import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.{AsyncHttpApi, TransactionInfo} +import com.wavesplatform.it.{BaseFunSuite, Node} import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 -import com.wavesplatform.transaction.{TxVersion, utils} import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.TransferTransaction +import com.wavesplatform.transaction.{Proofs, TxHelpers, TxVersion} + +import scala.util.{Random, Try} class UtxSuite extends BaseFunSuite { private var whitelistedAccount: KeyPair = scala.compiletime.uninitialized @@ -26,7 +27,19 @@ class UtxSuite extends BaseFunSuite { val account = UtxSuite.createAccount val transferToAccount = TransferTransaction - .selfSigned(1.toByte, miner.keyPair, account.toAddress, Waves, AMOUNT, Waves, ENOUGH_FEE, ByteStr.empty, System.currentTimeMillis()) + .create( + 1.toByte, + miner.keyPair.publicKey, + account.toAddress, + Waves, + AMOUNT, + Waves, + ENOUGH_FEE, + ByteStr.empty, + System.currentTimeMillis(), + Proofs.empty + ) + .map(_.signWith(miner.keyPair.privateKey)) .explicitGet() miner.signedBroadcast(transferToAccount.json()) @@ -34,31 +47,35 @@ class UtxSuite extends BaseFunSuite { nodes.waitForHeightAriseAndTxPresent(transferToAccount.id().toString) val firstTransfer = TransferTransaction - .selfSigned( + .create( 1.toByte, - account, + account.publicKey, miner.keyPair.toAddress, Waves, AMOUNT - ENOUGH_FEE, Waves, ENOUGH_FEE, ByteStr.empty, - System.currentTimeMillis() + System.currentTimeMillis(), + Proofs.empty ) + .map(_.signWith(account.privateKey)) .explicitGet() val secondTransfer = TransferTransaction - .selfSigned( + .create( 1.toByte, - account, + account.publicKey, notMiner.keyPair.toAddress, Waves, AMOUNT - ENOUGH_FEE, Waves, ENOUGH_FEE, ByteStr.empty, - System.currentTimeMillis() + System.currentTimeMillis(), + Proofs.empty ) + .map(_.signWith(account.privateKey)) .explicitGet() val tx2Id = notMiner.signedBroadcast(secondTransfer.json()).id @@ -84,44 +101,50 @@ class UtxSuite extends BaseFunSuite { val whitelistedAccountTransfer = TransferTransaction - .selfSigned( + .create( TxVersion.V1, - miner.keyPair, + miner.keyPair.publicKey, whitelistedAccount.toAddress, Waves, 5 * minTransferFee + 5 + (1 to 5).sum, Waves, minTransferFee, ByteStr.empty, - time + time, + Proofs.empty ) + .map(_.signWith(miner.keyPair.privateKey)) .explicitGet() val whitelistedDAppAccountTransfer = TransferTransaction - .selfSigned( + .create( TxVersion.V1, - miner.keyPair, + miner.keyPair.publicKey, whitelistedDAppAccount.toAddress, Waves, minSetScriptFee, Waves, minTransferFee, ByteStr.empty, - time + time, + Proofs.empty ) + .map(_.signWith(miner.keyPair.privateKey)) .explicitGet() val invokeAccountTransfer = TransferTransaction - .selfSigned( + .create( TxVersion.V1, - miner.keyPair, + miner.keyPair.publicKey, invokeAccount.toAddress, Waves, 5 * minInvokeFee + (1 to 5).sum, Waves, minTransferFee, ByteStr.empty, - time + time, + Proofs.empty ) + .map(_.signWith(miner.keyPair.privateKey)) .explicitGet() Seq(whitelistedAccountTransfer, whitelistedDAppAccountTransfer, invokeAccountTransfer) @@ -136,25 +159,52 @@ class UtxSuite extends BaseFunSuite { |@Callable(i) |func default() = { WriteSet([DataEntry("0", true)]) } |""".stripMargin - val script = ScriptCompiler.compile(scriptText, ScriptEstimatorV1).explicitGet()._1 - val setScript = SetScriptTransaction.selfSigned(TxVersion.V1, whitelistedDAppAccount, Some(script), minSetScriptFee, time).explicitGet() + val script = ScriptCompiler.compile(scriptText, ScriptEstimatorV1).explicitGet()._1 + val setScript = SetScriptTransaction + .create(TxVersion.V1, whitelistedDAppAccount.publicKey, Some(script), minSetScriptFee, time, Proofs.empty) + .map(_.signWith(whitelistedDAppAccount.privateKey)) + .explicitGet() miner.signedBroadcast(setScript.json()) nodes.waitForHeightAriseAndTxPresent(setScript.id().toString) val txs = (1 to 10).map { _ => TransferTransaction - .selfSigned(TxVersion.V1, miner.keyPair, UtxSuite.createAccount.toAddress, Waves, 1L, Waves, higherFee, ByteStr.empty, time) + .create( + TxVersion.V1, + miner.keyPair.publicKey, + UtxSuite.createAccount.toAddress, + Waves, + 1L, + Waves, + higherFee, + ByteStr.empty, + time, + Proofs.empty + ) + .map(_.signWith(miner.keyPair.privateKey)) .explicitGet() } val whitelistedTxs = { val bySender = (1 to 5).map { i => TransferTransaction - .selfSigned(TxVersion.V1, whitelistedAccount, UtxSuite.createAccount.toAddress, Waves, 1L, Waves, minTransferFee + i, ByteStr.empty, time) + .create( + TxVersion.V1, + whitelistedAccount.publicKey, + UtxSuite.createAccount.toAddress, + Waves, + 1L, + Waves, + minTransferFee + i, + ByteStr.empty, + time, + Proofs.empty + ) + .map(_.signWith(whitelistedAccount.privateKey)) .explicitGet() } val byDApp = (1 to 5).map { i => - utils.Signed.invokeScript(TxVersion.V1, invokeAccount, whitelistedDAppAccount.toAddress, None, Seq.empty, minInvokeFee + i, Waves, time) + TxHelpers.invoke(whitelistedDAppAccount.toAddress, None, Seq.empty, Seq.empty, invokeAccount, minInvokeFee + i, Waves, timestamp = time) } bySender ++ byDApp } @@ -164,7 +214,9 @@ class UtxSuite extends BaseFunSuite { miner.waitForEmptyUtx() val endHeight = miner.height - miner.blockSeq(startHeight, endHeight).flatMap(_.transactions).map(_.id).take(10) should contain theSameElementsAs whitelistedTxs.map(_.id().toString) + miner.blockSeq(startHeight, endHeight).flatMap(_.transactions).map(_.id).take(10) should contain theSameElementsAs whitelistedTxs.map( + _.id().toString + ) } def txInBlockchain(txId: String, nodes: Seq[Node]): Boolean = { diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/AcceptFailedScriptActivationSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/AcceptFailedScriptActivationSuite.scala index 159d3018c0a..24584e40d95 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/AcceptFailedScriptActivationSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/AcceptFailedScriptActivationSuite.scala @@ -1,30 +1,28 @@ package com.wavesplatform.it.sync.activation -import scala.concurrent.duration.* - import com.typesafe.config.Config import com.wavesplatform.api.http.ApiError.StateCheckFailed import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.features.BlockchainFeatures -import com.wavesplatform.it.{NodeConfigs, NTPTime} -import com.wavesplatform.it.NodeConfigs.Default +import com.wavesplatform.it.NTPTime import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.TransactionStatus import com.wavesplatform.it.sync.* -import com.wavesplatform.it.sync.transactions.OverflowBlock import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.state.Height import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.IssuedAsset -import com.wavesplatform.transaction.{TxExchangePrice, TxVersion} import com.wavesplatform.transaction.assets.exchange.{AssetPair, Order} import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler +import com.wavesplatform.transaction.{TxExchangePrice, TxVersion} import play.api.libs.json.JsObject -class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTime with OverflowBlock { +import scala.concurrent.duration.* + +class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTime { import AcceptFailedScriptActivationSuite.* private lazy val (dApp, dAppKP) = (firstAddress, firstKeyPair) @@ -70,7 +68,6 @@ class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTim } test("reject failed transaction before activation height") { - overflowBlock() sender.waitForHeight( Height( sender @@ -109,7 +106,6 @@ class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTim val startHeight = sender.height sender.setAssetScript(asset, dAppKP, setAssetScriptFee + smartFee, assetScript(true), waitForTx = true) - overflowBlock() sender.setAssetScript(asset, dAppKP, priorityFee, assetScript(false)) val txs = (1 to MaxTxsInMicroBlock * 2).map { _ => @@ -182,8 +178,6 @@ class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTim test("accept invalid by asset script InvokeScriptTransaction to utx and save it as failed after activation height") { sender.setAssetScript(asset, dAppKP, priorityFee, assetScript(true), waitForTx = true) - overflowBlock() - val txs = (1 to MaxTxsInMicroBlock * 2).map { i => sender.invokeScript(callerKP, dApp, Some("transfer"), fee = minInvokeFee + i)._1.id @@ -220,7 +214,6 @@ class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTim nodes.waitFor("empty utx")(_.utxSize)(_.forall(_ == 0)) nodes.waitForHeightArise() - overflowBlock() val txs = (1 to invokesCount).map { _ => @@ -403,7 +396,6 @@ class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTim { val (buy, sell) = orders - overflowBlock() sender.setAssetScript(tradeAsset, dAppKP, priorityFee, assetScript(false)) val tx = sender @@ -433,7 +425,6 @@ class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTim val (buy, sell) = orders sender.setAssetScript(tradeAsset, dAppKP, setAssetScriptFee + smartFee, assetScript(true), waitForTx = true) - overflowBlock() sender.setAssetScript(feeAsset, dAppKP, setAssetScriptFee + smartFee, assetScript(false)) val tx = sender .broadcastExchange( @@ -486,16 +477,20 @@ object AcceptFailedScriptActivationSuite { private def mkScript(scriptText: String): Option[String] = Some(ScriptCompiler.compile(scriptText, estimator).explicitGet()._1.bytes().base64) + import com.wavesplatform.it.NodeConfigs.* + private def configs(activate: Boolean): Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase( - _.preactivatedFeatures( - (BlockchainFeatures.BlockV5.id, Height(if (activate) 0 else 9999)) - ) - ) - .overrideBase(_.raw(s"waves.blockchain.custom.functionality.min-asset-info-update-interval = $UpdateInterval")) - .overrideBase(_.raw(s"waves.miner.max-transactions-in-micro-block = $MaxTxsInMicroBlock")) - .buildNonConflicting() + Seq( + Miners(3) + .quorum(0) + .preactivatedFeatures((BlockchainFeatures.BlockV5, Height(if (activate) 0 else 9999))) + .overrides(s""" + waves { + blockchain.custom.functionality.min-asset-info-update-interval = $UpdateInterval + miner { + max-transactions-in-micro-block = $MaxTxsInMicroBlock + micro-block-interval = 5s + } + }""") + ) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/FeatureActivationTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/FeatureActivationTestSuite.scala index 6cd7ea94834..38317ae2e52 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/FeatureActivationTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/FeatureActivationTestSuite.scala @@ -14,20 +14,17 @@ class FeatureActivationTestSuite extends BaseFreeSpec with ActivationStatusReque private val featureNum: Short = BlockchainFeatures.SmallerMinimalGeneratingBalance.id private val featureDescr = BlockchainFeatures.SmallerMinimalGeneratingBalance.description - override protected def nodeConfigs: Seq[Config] = { - NodeConfigs.newBuilder - .overrideBase(_.raw(s"""waves { - | blockchain.custom.functionality { - | pre-activated-features = {} - | feature-check-blocks-period = $votingInterval - | blocks-for-feature-activation = $blocksForActivation - | } - | features.supported = [$featureNum] - | miner.quorum = 1 - |}""".stripMargin)) - .withDefault(2) - .buildNonConflicting() - } + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = + Seq(BiggestMiner, Miners(5)).map(_.overrides(s"""waves { + | blockchain.custom.functionality { + | pre-activated-features = {} + | feature-check-blocks-period = $votingInterval + | blocks-for-feature-activation = $blocksForActivation + | } + | features.supported = [$featureNum] + | miner.quorum = 1 + |}""".stripMargin)) "supported blocks increased when voting starts" in { nodes.waitForHeight(Height(votingInterval * 2 / 3)) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/NotActivateFeatureTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/NotActivateFeatureTestSuite.scala index 6139e2c1a2d..ccf776d0930 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/NotActivateFeatureTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/NotActivateFeatureTestSuite.scala @@ -15,27 +15,25 @@ class NotActivateFeatureTestSuite extends BaseFreeSpec with ActivationStatusRequ private val votingFeatureNum: Short = 1 private val nonVotingFeatureNum: Short = 2 + import NodeConfigs.* override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase( - _.raw( - s"""waves { - | blockchain { - | custom { - | functionality { - | pre-activated-features = {} - | feature-check-blocks-period = $votingInterval - | blocks-for-feature-activation = $blocksForActivation - | } - | } - | } - | features.supported=[$nonVotingFeatureNum] - | miner.quorum = 1 - |}""".stripMargin - ) + Seq(BiggestMiner, Miners(5)).map( + _.overrides( + s"""waves { + | blockchain { + | custom { + | functionality { + | pre-activated-features = {} + | feature-check-blocks-period = $votingInterval + | blocks-for-feature-activation = $blocksForActivation + | } + | } + | } + | features.supported=[$nonVotingFeatureNum] + | miner.quorum = 1 + |}""".stripMargin ) - .withDefault(2) - .buildNonConflicting() + ) private var activationStatusInfoBefore = Seq.empty[FeatureActivationStatus] private var activationStatusInfoAfter = Seq.empty[FeatureActivationStatus] diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/VRFProtobufActivationSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/VRFProtobufActivationSuite.scala index 9500a93b4ae..b8dfd677b91 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/VRFProtobufActivationSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/VRFProtobufActivationSuite.scala @@ -8,7 +8,6 @@ import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.crypto import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.TransactionInfo import com.wavesplatform.it.sync.* @@ -20,15 +19,15 @@ import com.wavesplatform.transaction.assets.exchange.{AssetPair, Order} import scala.concurrent.duration.* class VRFProtobufActivationSuite extends BaseTransactionSuite { - val activationHeight = Height(9) - val updateInterval = 3 - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.BlockV5.id, activationHeight))) - .overrideBase(_.raw(s"waves.blockchain.custom.functionality.min-asset-info-update-interval = $updateInterval")) - .buildNonConflicting() + val activationHeight = Height(10) + val updateInterval = 10 + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + Miners(5) + .quorum(0) + .preactivatedFeatures((BlockchainFeatures.BlockV5, activationHeight)) + .overrides(s"waves.blockchain.custom.functionality.min-asset-info-update-interval = $updateInterval") + ) private def senderAcc = firstKeyPair private def recipientAcc = secondKeyPair @@ -41,14 +40,15 @@ class VRFProtobufActivationSuite extends BaseTransactionSuite { val (defaultName, defaultDescription) = ("asset", "description") assetId = sender.broadcastIssue(senderAcc, defaultName, defaultDescription, someAssetAmount, 8, reissuable = true, script = None, waitForTx = true).id - sender.waitForHeight(Height(7), 3.minutes) + sender.waitForHeight(Height(6), 3.minutes) otherAssetId = sender.broadcastIssue(senderAcc, defaultName, defaultDescription, someAssetAmount, 8, reissuable = true, script = None, waitForTx = true).id } test("miner generates block v4 before activation") { - val blockBeforeActivationHeight = sender.blockAt(sender.height) - val blockHeaderBeforeActivationHeight = sender.blockHeaderAt(sender.height) + val height = sender.height + val blockBeforeActivationHeight = sender.blockAt(height) + val blockHeaderBeforeActivationHeight = sender.blockHeaderAt(height) blockBeforeActivationHeight.version.get shouldBe Block.RewardBlockVersion blockHeaderBeforeActivationHeight.version.get shouldBe Block.RewardBlockVersion Base58.decode(blockBeforeActivationHeight.generationSignature.get).length shouldBe Block.GenerationSignatureLength @@ -72,10 +72,11 @@ class VRFProtobufActivationSuite extends BaseTransactionSuite { } test("only able to get block by signature (that is equal to id) before activation") { - sender.blockById(sender.blockAt(sender.height).signature) shouldBe sender.blockAt(sender.height) - sender.blockAt(sender.height).signature shouldBe sender.blockAt(sender.height).id - Base58.decode(sender.blockAt(sender.height).signature).length shouldBe crypto.SignatureLength - Base58.decode(sender.blockAt(sender.height).id).length shouldBe crypto.SignatureLength + val height = sender.height + sender.blockById(sender.blockAt(height).signature) shouldBe sender.blockAt(height) + sender.blockAt(height).signature shouldBe sender.blockAt(height).id + Base58.decode(sender.blockAt(height).signature).length shouldBe crypto.SignatureLength + Base58.decode(sender.blockAt(height).id).length shouldBe crypto.SignatureLength } test("not able to broadcast ExchangeTransaction with reversed buy/sell orders") { @@ -108,8 +109,9 @@ class VRFProtobufActivationSuite extends BaseTransactionSuite { } test("miner generates block v5 after activation") { - val blockAtActivationHeight = sender.blockAt(sender.height) - val blockHeaderAtActivationHeight = sender.blockHeaderAt(sender.height) + val height = sender.height + val blockAtActivationHeight = sender.blockAt(height) + val blockHeaderAtActivationHeight = sender.blockHeaderAt(height) blockAtActivationHeight.version.get shouldBe Block.ProtoBlockVersion blockHeaderAtActivationHeight.version.get shouldBe Block.ProtoBlockVersion @@ -118,13 +120,15 @@ class VRFProtobufActivationSuite extends BaseTransactionSuite { } test("only able to get block by id (that is not equal to signature) after activation") { - sender.blockById(sender.blockAt(sender.height).id) shouldBe sender.blockAt(sender.height) - sender.blockAt(sender.height).signature should not be sender.blockAt(sender.height).id - Base58.decode(sender.blockAt(sender.height).signature).length shouldBe crypto.SignatureLength - Base58.decode(sender.blockAt(sender.height).id).length shouldBe crypto.DigestLength + val height = sender.height + sender.blockById(sender.blockAt(height).id) shouldBe sender.blockAt(height) + sender.blockAt(height).signature should not be sender.blockAt(height).id + Base58.decode(sender.blockAt(height).signature).length shouldBe crypto.SignatureLength + Base58.decode(sender.blockAt(height).id).length shouldBe crypto.DigestLength } test("able to broadcast UpdateAssetInfoTransaction if interval's reached before activation") { + sender.waitForHeight(Height(sender.waitForTransaction(assetId).height + updateInterval)) sender.updateAssetInfo(senderAcc, assetId, "updatedName", "updatedDescription", minFee, waitForTx = true) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/finalization/OneNodeFinalizationTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/finalization/OneNodeFinalizationTestSuite.scala index 7b09d2b7a9d..445c73a4e47 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/finalization/OneNodeFinalizationTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/finalization/OneNodeFinalizationTestSuite.scala @@ -1,11 +1,10 @@ package com.wavesplatform.it.sync.finalization import com.typesafe.config.Config -import com.wavesplatform.api.http.requests.CommitToGenerationRequest import com.wavesplatform.features.BlockchainFeatures +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.it.api.* import com.wavesplatform.it.api.SyncHttpApi.* -import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs} import com.wavesplatform.state.Height import com.wavesplatform.test.NumericExt import com.wavesplatform.utils.ScorexLogging @@ -15,12 +14,13 @@ import org.scalatest.OptionValues import scala.concurrent.duration.DurationInt class OneNodeFinalizationTestSuite extends BaseFreeSpec, OptionValues, ScorexLogging { - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.DeterministicFinality.id, Height(0)))) - .withDefault(1) - .buildNonConflicting() + import com.wavesplatform.it.NodeConfigs.* + override val nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0).preactivatedFeatures( + BlockchainFeatures.FairPoS, + BlockchainFeatures.DeterministicFinality + ) + ) private def node = dockerNodes().last private lazy val miner1Acc = node.keyPair @@ -31,13 +31,15 @@ class OneNodeFinalizationTestSuite extends BaseFreeSpec, OptionValues, ScorexLog val miner2Addr = miner2Acc.toAddress.toString val miner3Addr = miner3Acc.toAddress.toString + log.warn(s"M2=$miner2Addr, M3=$miner3Addr") + step("Commit to generation") val period1 = node.currentGenerationPeriod.value.next - val commitTxn1 = node.sign(CommitToGenerationRequest(sender = Some(miner1Addr))) + val commitTxn1 = node.signCommitToGenerationRequest(miner1Addr) commitTxn1.generationPeriodStart.value shouldBe period1.start.toInt - val commitTxn2 = node.sign(CommitToGenerationRequest(sender = Some(miner2Addr))) + val commitTxn2 = node.signCommitToGenerationRequest(miner2Addr) commitTxn2.generationPeriodStart.value shouldBe period1.start.toInt node.broadcastRequest(commitTxn1) @@ -48,23 +50,14 @@ class OneNodeFinalizationTestSuite extends BaseFreeSpec, OptionValues, ScorexLog isolated { val generators = node.generators(period1.start) generators.size shouldBe 2 - generators shouldBe Seq( - GeneratorsResponse.Entry( - address = miner1Addr, - balance = 9990598000000L, - transactionId = commitTxn1.id - ), - GeneratorsResponse.Entry( - address = miner2Addr, - balance = 9989990000000L, - transactionId = commitTxn2.id - ) + generators.map(e => e.address -> e.transactionId) should contain theSameElementsAs Seq( + miner1Addr -> commitTxn1.id, + miner2Addr -> commitTxn2.id ) } step("Finalized height checks") - val deadline = 2.minutes.fromNow - var finalizedHeight1 = node.finalizedHeight + val finalizedHeight1 = node.finalizedHeight val waitingFinalizedHeight = finalizedHeight1 + 2 withClue("Finalized height is unknown: ") { @@ -79,28 +72,19 @@ class OneNodeFinalizationTestSuite extends BaseFreeSpec, OptionValues, ScorexLog } } - var done = false - while (!done && deadline.hasTimeLeft()) { - val currHeight = node.height - if (currHeight > waitingFinalizedHeight + 2) - fail( - s"Finalization height doesn't rise: height=$currHeight, waiting for finalized height=$waitingFinalizedHeight, last finalized height=$finalizedHeight1" - ) - - // We need at least one transaction, otherwise there won't be a microblock, thus no voting, no finalization - node.transfer(miner1Acc, miner3Addr, 1.waves, waitForTx = true) - - val updatedFinalizedHeight = node.finalizedHeight - if (updatedFinalizedHeight < finalizedHeight1) - fail(s"Finalized height $updatedFinalizedHeight became lower than the previous $finalizedHeight1") - else if (updatedFinalizedHeight != finalizedHeight1) - log.debug(s"New finalized height: $finalizedHeight1 -> $updatedFinalizedHeight") - - finalizedHeight1 = updatedFinalizedHeight - done = finalizedHeight1 >= waitingFinalizedHeight - } + // We need at least one transaction, otherwise there won't be a microblock, thus no voting, no finalization + // Finalization happened in a microblock + node.waitForHeight(Height(node.waitForTransaction(node.transfer(miner1Acc, miner3Addr, 1.waves, waitForTx = true).id).height + 1)) + val fs = node.finalityStatus + if (fs.height > waitingFinalizedHeight + 2) + fail( + s"Finalization height doesn't rise: height=${fs.height}, waiting for finalized height=$waitingFinalizedHeight, last finalized height=$finalizedHeight1" + ) - node.waitForHeight(node.height + 1) // Finalization happened in a microblock + if (fs.finalizedHeight < finalizedHeight1) + fail(s"Finalized height ${fs.finalizedHeight} became lower than the previous $finalizedHeight1") + else if (fs.finalizedHeight != finalizedHeight1) + log.debug(s"New finalized height: $finalizedHeight1 -> ${fs.finalizedHeight}") step("Survives restart") isolated { @@ -115,7 +99,7 @@ class OneNodeFinalizationTestSuite extends BaseFreeSpec, OptionValues, ScorexLog node.finalizedHeightAt(finalizedBlock1.height) should be <= finalizedBlock1.height step("Finalization voting in a block header") - val votingBlockHeader = node.blockHeaderAt(finalizedHeight1 + 1) + val votingBlockHeader = node.blockHeaderAt(finalizedBlock1.height + 1) val finalizationVoting = votingBlockHeader.finalizationVoting.value val generators: Seq[(data: GeneratorsResponse.Entry, index: Int)] = node.generators(votingBlockHeader.height).zipWithIndex diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/finalization/TwoNodesFinalizationTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/finalization/TwoNodesFinalizationTestSuite.scala index b9cffe929f3..3bedf4bfff0 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/finalization/TwoNodesFinalizationTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/finalization/TwoNodesFinalizationTestSuite.scala @@ -1,7 +1,6 @@ package com.wavesplatform.it.sync.finalization import com.typesafe.config.Config -import com.wavesplatform.api.http.requests.CommitToGenerationRequest import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.api.* import com.wavesplatform.it.api.SyncHttpApi.* @@ -14,12 +13,13 @@ import org.scalatest.OptionValues import scala.concurrent.duration.DurationInt class TwoNodesFinalizationTestSuite extends BaseFreeSpec, OptionValues, ScorexLogging { + import NodeConfigs.* override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.DeterministicFinality.id, Height(0)))) - .overrideBase(_.raw("waves.miner.minimal-block-generation-offset = 10s")) - .withDefault(2) - .buildNonConflicting() + Seq(Miners.head, Miners(3)).map( + _.preactivatedFeatures(BlockchainFeatures.DeterministicFinality) + .overrides("waves.waves.blockchain.custom.functionality.min-block-time = 10s") + .quorum(1) + ) private def node1 = dockerNodes().head private def node2 = dockerNodes().last @@ -33,10 +33,10 @@ class TwoNodesFinalizationTestSuite extends BaseFreeSpec, OptionValues, ScorexLo val period1 = node1.currentGenerationPeriod.value.next step("Commit to generation") - val commitTxn1 = node1.sign(CommitToGenerationRequest(sender = Some(miner1Addr))) - node1.broadcastRequest(commitTxn1) + val commitTxn1 = node1.signCommitToGenerationRequest(miner1Addr) + val commitTxn2 = node2.signCommitToGenerationRequest(miner2Addr) - val commitTxn2 = node2.sign(CommitToGenerationRequest(sender = Some(miner2Addr))) + node2.broadcastRequest(commitTxn1) node2.broadcastRequest(commitTxn2) node1.waitForGenerationPeriod(period1) @@ -45,17 +45,9 @@ class TwoNodesFinalizationTestSuite extends BaseFreeSpec, OptionValues, ScorexLo isolated { val generators = node1.generators(period1.start) generators.size shouldBe 2 - generators should contain theSameElementsAs Seq( - GeneratorsResponse.Entry( - address = miner1Addr, - balance = 9989990000000L, - transactionId = commitTxn1.id - ), - GeneratorsResponse.Entry( - address = miner2Addr, - balance = 24990598000000L, - transactionId = commitTxn2.id - ) + generators.map(ge => ge.address -> ge.transactionId) should contain theSameElementsAs Seq( + miner1Addr -> commitTxn1.id, + miner2Addr -> commitTxn2.id ) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/AssetsApiGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/AssetsApiGrpcSuite.scala index 0b34c4eea64..7393d2ab5b3 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/AssetsApiGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/AssetsApiGrpcSuite.scala @@ -40,9 +40,6 @@ class AssetsApiGrpcSuite extends BaseFreeSpec with ActivationStatusRequest with nftHeightsWithSequences.groupMap(_._1)(_._2).values.foreach(nums => nums shouldBe (1 to nums.size)) } - override def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .buildNonConflicting() + import com.wavesplatform.it.NodeConfigs.* + override val nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0)) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/DataTransactionGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/DataTransactionGrpcSuite.scala index 41778686b0d..198b6217741 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/DataTransactionGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/DataTransactionGrpcSuite.scala @@ -10,7 +10,7 @@ import com.wavesplatform.protobuf.transaction.* import com.wavesplatform.state.StringDataEntry import com.wavesplatform.test.* import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.{DataTransaction, TxVersion} +import com.wavesplatform.transaction.{TxHelpers, TxVersion} import io.grpc.Status.Code import scala.concurrent.duration.* @@ -35,10 +35,10 @@ class DataTransactionGrpcSuite extends GrpcBaseTransactionSuite { ScriptCompiler .compile( """{-# STDLIB_VERSION 2 #-} - |{-# CONTENT_TYPE EXPRESSION #-} - |{-# SCRIPT_TYPE ACCOUNT #-} - | - |true""".stripMargin, + |{-# CONTENT_TYPE EXPRESSION #-} + |{-# SCRIPT_TYPE ACCOUNT #-} + | + |true""".stripMargin, ScriptEstimatorV1 ) .explicitGet() @@ -50,7 +50,7 @@ class DataTransactionGrpcSuite extends GrpcBaseTransactionSuite { ) val dataTx = PBTransactions.protobuf( - DataTransaction.selfSigned(TxVersion.V1, keyPair, Seq(StringDataEntry("1", "test")), 700000L, System.currentTimeMillis()).explicitGet() + TxHelpers.data(keyPair, Seq(StringDataEntry("1", "test")), 700000L) ) assertGrpcError( @@ -121,14 +121,14 @@ class DataTransactionGrpcSuite extends GrpcBaseTransactionSuite { } test("max transaction size") { - //Max size of transaction V1 + // Max size of transaction V1 val maxKeySizeV1 = 100 val key = "\u6fae" * (maxKeySizeV1 - 1) val data = List.tabulate(26)(n => DataEntry(key + n.toChar, DataEntry.Value.BinaryValue(ByteString.copyFrom(Array.fill(5599)(n.toByte))))) val fee = calcDataFee(data, TxVersion.V1) sender.putData(firstAcc, data, fee, version = TxVersion.V1, waitForTx = true) - //Max size of transaction V2 + // Max size of transaction V2 val maxKeySizeV2 = 400 val key2 = "u" * (maxKeySizeV2 - 1) val data2 = @@ -282,23 +282,21 @@ class DataTransactionGrpcSuite extends GrpcBaseTransactionSuite { test("try to make address with 1000 DataEntries") { for (v <- dataTxSupportedVersions) { - val dataSet = 0 until 200 flatMap ( - i => - List( - DataEntry(s"int$i", DataEntry.Value.IntValue(1000 + i)), - DataEntry(s"bool$i", DataEntry.Value.BoolValue(false)), - DataEntry(s"blob$i", DataEntry.Value.BinaryValue(ByteString.copyFrom(Array[Byte](127.toByte, 0, 1, 1)))), - DataEntry(s"str$i", DataEntry.Value.StringValue(s"hi there! + $i")), - DataEntry(s"integer$i", DataEntry.Value.IntValue(1000 - i)) - ) + val dataSet = 0 until 200 flatMap (i => + List( + DataEntry(s"int$i", DataEntry.Value.IntValue(1000 + i)), + DataEntry(s"bool$i", DataEntry.Value.BoolValue(false)), + DataEntry(s"blob$i", DataEntry.Value.BinaryValue(ByteString.copyFrom(Array[Byte](127.toByte, 0, 1, 1)))), + DataEntry(s"str$i", DataEntry.Value.StringValue(s"hi there! + $i")), + DataEntry(s"integer$i", DataEntry.Value.IntValue(1000 - i)) ) + ) val txIds = dataSet .grouped(100) .map(_.toList) - .map( - data => - PBTransactions.vanilla(sender.putData(fourthAcc, data, calcDataFee(data, v), version = v), unsafe = false).explicitGet().id().toString + .map(data => + PBTransactions.vanilla(sender.putData(fourthAcc, data, calcDataFee(data, v), version = v), unsafe = false).explicitGet().id().toString ) txIds.foreach(tx => sender.waitForTransaction(tx)) val r = scala.util.Random.nextInt(199) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/ExchangeTransactionGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/ExchangeTransactionGrpcSuite.scala index 48d47b05318..7a6a7f46ca3 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/ExchangeTransactionGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/ExchangeTransactionGrpcSuite.scala @@ -8,7 +8,7 @@ import com.wavesplatform.it.sync.{matcherFee, minFee, someAssetAmount} import com.wavesplatform.test.* import com.wavesplatform.protobuf.transaction.{PBTransactions, Recipient} import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.TxVersion +import com.wavesplatform.transaction.{TxHelpers, TxVersion} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.assets.exchange.{AssetPair, Order} import com.wavesplatform.utils.* @@ -116,20 +116,16 @@ class ExchangeTransactionGrpcSuite extends GrpcBaseTransactionSuite with NTPTime } test("cannot exchange non-issued assets") { - val exchAsset: IssueTransaction = IssueTransaction - .selfSigned( - TxVersion.V1, + val exchAsset: IssueTransaction = TxHelpers.issue( sender.keyPair, + someAssetAmount, + 2, "myasset", "my asset description", - quantity = someAssetAmount, - decimals = 2, - reissuable = true, - script = None, fee = 1.waves, + script = None, timestamp = System.currentTimeMillis() ) - .explicitGet() for ((o1ver, o2ver, tver) <- versions) { val assetId = exchAsset.id().toString diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/network/NetworkSeparationTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/network/NetworkSeparationTestSuite.scala index 47e971199b5..0033bb481c3 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/network/NetworkSeparationTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/network/NetworkSeparationTestSuite.scala @@ -3,14 +3,13 @@ package com.wavesplatform.it.sync.network import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.{issueAmount, issueFee, minFee} -import com.wavesplatform.it.{BaseFreeSpec, Node, WaitForHeight2} +import com.wavesplatform.it.{BaseFreeSpec, Node} import com.wavesplatform.state.Height import com.wavesplatform.utils.ScorexLogging -import scala.concurrent.Await import scala.concurrent.duration.* -class NetworkSeparationTestSuite extends BaseFreeSpec, WaitForHeight2, ScorexLogging { +class NetworkSeparationTestSuite extends BaseFreeSpec, ScorexLogging { import NetworkSeparationTestSuite.* override protected def nodeConfigs: Seq[Config] = Configs @@ -49,7 +48,7 @@ class NetworkSeparationTestSuite extends BaseFreeSpec, WaitForHeight2, ScorexLog docker.disconnectFromNetwork(dockerNodes().head) val burnNoOwnerTxTd = nodeB.burn(nodeB.keyPair, issuedAssetId, issueAmount / 2, minFee).id - Await.ready(waitForTxsToReachAllNodes(Seq(nodeB), Seq(burnNoOwnerTxTd)), 2.minute) + nodeB.waitForTransaction(burnNoOwnerTxTd, 2.minute) val heightAfter = nodeB.height Thread.sleep(60.seconds.toMillis) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/network/PeersApiRouteSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/network/PeersApiRouteSuite.scala index dece4ec5b0a..0c08b39e26c 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/network/PeersApiRouteSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/network/PeersApiRouteSuite.scala @@ -3,18 +3,18 @@ package com.wavesplatform.it.sync.network import com.typesafe.config.Config import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.{KnownPeer, Peer} -import com.wavesplatform.it.{BaseFreeSpec, Node, NodeConfigs} +import com.wavesplatform.it.{BaseFreeSpec, Node} import org.scalatest.concurrent.Eventually import org.scalatest.time.Span import scala.concurrent.duration.DurationInt class PeersApiRouteSuite extends BaseFreeSpec with Eventually { - override protected def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + import com.wavesplatform.it.NodeConfigs.* + override val nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0), + Default.head.notMiner + ) private def ofANode(node: Node): PartialFunction[Any, Unit] = { case Peer(_, declaredAddress, name) :: Nil if name == node.name && declaredAddress == node.networkAddress.toString => diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/network/SimpleTransactionsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/network/SimpleTransactionsSuite.scala index 5f824eac9c6..21e805ee6a8 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/network/SimpleTransactionsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/network/SimpleTransactionsSuite.scala @@ -1,45 +1,27 @@ package com.wavesplatform.it.sync.network -import java.nio.charset.StandardCharsets - import com.typesafe.config.Config import com.wavesplatform.account.Address -import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* -import com.wavesplatform.it.NodeConfigs import com.wavesplatform.it.api.AsyncNetworkApi.* import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.network.{RawBytes, TransactionSpec} import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.transfer.* +import com.wavesplatform.transaction.TxHelpers +import java.nio.charset.StandardCharsets import scala.concurrent.duration.* class SimpleTransactionsSuite extends BaseTransactionSuite { - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(entitiesNumber = 1) - .buildNonConflicting() + import com.wavesplatform.it.NodeConfigs.* + override val nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0)) private def node = nodes.head test("valid tx send by network to node should be in blockchain") { - val tx = TransferTransaction - .selfSigned( - 1.toByte, - node.keyPair, - Address.fromString(node.address).explicitGet(), - Waves, - 1L, - Waves, - minFee, - ByteStr.empty, - System.currentTimeMillis() - ) - .explicitGet() + val tx = TxHelpers.transfer(node.keyPair, Address.fromString(node.address).explicitGet(), 1L, Waves, minFee, Waves) node.sendByNetwork(RawBytes.fromTransaction(tx)) node.waitForTransaction(tx.id().toString) @@ -47,19 +29,15 @@ class SimpleTransactionsSuite extends BaseTransactionSuite { } test("invalid tx send by network to node should be not in UTX or blockchain") { - val tx = TransferTransaction - .selfSigned( - 1.toByte, - node.keyPair, - Address.fromString(node.address).explicitGet(), - Waves, - 1L, - Waves, - minFee, - ByteStr.empty, - System.currentTimeMillis() + (1 days).toMillis - ) - .explicitGet() + val tx = TxHelpers.transfer( + node.keyPair, + Address.fromString(node.address).explicitGet(), + 1L, + Waves, + minFee, + Waves, + timestamp = System.currentTimeMillis() + (1 days).toMillis + ) node.sendByNetwork(RawBytes.fromTransaction(tx)) val maxHeight = nodes.map(_.height).max diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/package.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/package.scala index 0f956156317..88ba32d5e8e 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/package.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/package.scala @@ -80,9 +80,8 @@ package object sync { def createIssueRequest(tx: IssueTransaction): IssueRequest = { import tx.* IssueRequest( - Some(tx.version), - None, - Some(tx.sender.toString), + tx.version, + tx.sender.toString, tx.name.toStringUtf8, tx.description.toStringUtf8, quantity.value, diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/AtomicSwapSmartContractSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/AtomicSwapSmartContractSuite.scala index b38d07c0c41..6bfd3ea59fd 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/AtomicSwapSmartContractSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/AtomicSwapSmartContractSuite.scala @@ -12,10 +12,9 @@ import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.{Proofs, TxPositiveAmount} -import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.* +import com.wavesplatform.transaction.{Proofs, TxHelpers, TxPositiveAmount} import org.scalatest.CancelAfterFailure /* @@ -36,11 +35,8 @@ class AtomicSwapSmartContractSuite extends BaseTransactionSuite with CancelAfter This breaks the test. 2. We have RollbackSuite */ - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0)) private lazy val BobBC1: KeyPair = sender.createKeyPair() private lazy val AliceBC1: KeyPair = sender.createKeyPair() @@ -59,7 +55,7 @@ class AtomicSwapSmartContractSuite extends BaseTransactionSuite with CancelAfter test("step2 - Create and setup smart contract for swapBC1") { val beforeHeight = sender.height - val scriptText = s""" + val scriptText = s""" let Bob = Address(base58'${BobBC1.toAddress}') let Alice = Address(base58'${AliceBC1.toAddress}') @@ -74,9 +70,7 @@ class AtomicSwapSmartContractSuite extends BaseTransactionSuite with CancelAfter val pkSwapBC1 = swapBC1 val script = ScriptCompiler.compile(scriptText, ScriptEstimatorV2).explicitGet()._1 - val sc1SetTx = SetScriptTransaction - .selfSigned(1.toByte, sender = pkSwapBC1, script = Some(script), fee = setScriptFee, timestamp = System.currentTimeMillis()) - .explicitGet() + val sc1SetTx = TxHelpers.setScript(pkSwapBC1, script, setScriptFee, timestamp = System.currentTimeMillis()) val setScriptId = sender .signedBroadcast(sc1SetTx.json()) @@ -92,19 +86,15 @@ class AtomicSwapSmartContractSuite extends BaseTransactionSuite with CancelAfter test("step3 - Alice makes transfer to swapBC1") { val txToSwapBC1 = - TransferTransaction - .selfSigned( - version = 2.toByte, - sender = AliceBC1, - recipient = swapBC1.toAddress, - asset = Waves, - amount = transferAmount + setScriptFee + smartFee, - feeAsset = Waves, - fee = setScriptFee + smartFee, - attachment = ByteStr.empty, - timestamp = System.currentTimeMillis() + TxHelpers + .transfer( + AliceBC1, + swapBC1.toAddress, + transferAmount + setScriptFee + smartFee, + Waves, + setScriptFee + smartFee, + Waves ) - .explicitGet() val transferId = sender .signedBroadcast(txToSwapBC1.json()) @@ -114,19 +104,14 @@ class AtomicSwapSmartContractSuite extends BaseTransactionSuite with CancelAfter test("step4 - Alice cannot make transfer from swapBC1 if height is incorrect") { val txToSwapBC1 = - TransferTransaction - .selfSigned( - version = 2.toByte, - sender = swapBC1, - recipient = AliceBC1.toAddress, - asset = Waves, - amount = transferAmount, - feeAsset = Waves, - fee = setScriptFee + smartFee, - attachment = ByteStr.empty, - timestamp = System.currentTimeMillis() - ) - .explicitGet() + TxHelpers.transfer( + swapBC1, + AliceBC1.toAddress, + transferAmount, + Waves, + setScriptFee + smartFee, + Waves + ) assertApiErrorRaised(sender.signedBroadcast(txToSwapBC1.json())) } @@ -176,19 +161,14 @@ class AtomicSwapSmartContractSuite extends BaseTransactionSuite with CancelAfter miner.accountBalances(swapBC1.toAddress.toString) assertBadRequestAndMessage(miner.transactionInfo[TransactionInfo](versionedTransferId), "transactions does not exist", 404) - val selfSignedToAlice = TransferTransaction - .selfSigned( - version = 2.toByte, - sender = swapBC1, - recipient = AliceBC1.toAddress, - asset = Waves, - amount = transferAmount, - feeAsset = Waves, - fee = setScriptFee + smartFee, - attachment = ByteStr.empty, - timestamp = System.currentTimeMillis() - ) - .explicitGet() + val selfSignedToAlice = TxHelpers.transfer( + swapBC1, + AliceBC1.toAddress, + transferAmount, + Waves, + setScriptFee + smartFee, + Waves + ) val transferToAlice = sender.signedBroadcast(selfSignedToAlice.json()).id diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/BigLetChain.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/BigLetChain.scala index 89fca1a17bd..25007f25a96 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/BigLetChain.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/BigLetChain.scala @@ -1,19 +1,28 @@ package com.wavesplatform.it.sync.smartcontract +import com.typesafe.config.Config import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* +import com.wavesplatform.features.BlockchainFeatures +import com.wavesplatform.features.BlockchainFeatures.RideV6 +import com.wavesplatform.it.BaseFunSuite import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* -import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.test.* import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.Waves +import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.TransferTransaction import org.scalatest.CancelAfterFailure -class BigLetChain extends BaseTransactionSuite with CancelAfterFailure { +class BigLetChain extends BaseFunSuite with CancelAfterFailure { + import com.wavesplatform.it.NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + Miners(5).quorum(0).preactivatedFeatures(BlockchainFeatures.BlockV5, RideV6) + ) + test("big let assignment chain") { val count = 280 val scriptText = @@ -33,23 +42,24 @@ class BigLetChain extends BaseTransactionSuite with CancelAfterFailure { val pkNewAddress = sender.createKeyPair() - sender.transfer(firstKeyPair, pkNewAddress.toAddress.toString, 10.waves, minFee, waitForTx = true) + sender.transfer(sender.keyPair, pkNewAddress.toAddress.toString, 10.waves, minFee, waitForTx = true) - val scriptSet = SetScriptTransaction.selfSigned(1.toByte, pkNewAddress, Some(compiledScript), setScriptFee, System.currentTimeMillis()) + val scriptSet = SetScriptTransaction.create(1.toByte, pkNewAddress.publicKey, Some(compiledScript), setScriptFee, System.currentTimeMillis(), Proofs.empty).map(_.signWith(pkNewAddress.privateKey)) val scriptSetBroadcast = sender.signedBroadcast(scriptSet.explicitGet().json()) nodes.waitForHeightAriseAndTxPresent(scriptSetBroadcast.id) - val transfer = TransferTransaction.selfSigned( + val transfer = TransferTransaction.create( 2.toByte, - pkNewAddress, + pkNewAddress.publicKey, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, - System.currentTimeMillis() - ) + System.currentTimeMillis(), + Proofs.empty + ).map(_.signWith(pkNewAddress.privateKey)) val transferBroadcast = sender.signedBroadcast(transfer.explicitGet().json()) nodes.waitForHeightAriseAndTxPresent(transferBroadcast.id) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/BigStringSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/BigStringSuite.scala index 905f321120b..ee4782b3f5e 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/BigStringSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/BigStringSuite.scala @@ -7,12 +7,11 @@ import com.wavesplatform.crypto import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.{minFee, setScriptFee, transferAmount} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.test.* import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 -import com.wavesplatform.transaction.Proofs +import com.wavesplatform.test.* import com.wavesplatform.transaction.lease.LeaseTransaction -import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler +import com.wavesplatform.transaction.{Proofs, TxHelpers} import org.scalatest.CancelAfterFailure class BigStringSuite extends BaseTransactionSuite with CancelAfterFailure { @@ -44,10 +43,8 @@ class BigStringSuite extends BaseTransactionSuite with CancelAfterFailure { } """.stripMargin - val script = ScriptCompiler.compile(scriptText, ScriptEstimatorV2).explicitGet()._1 - val setScriptTransaction = SetScriptTransaction - .selfSigned(1.toByte, acc0, Some(script), setScriptFee, System.currentTimeMillis()) - .explicitGet() + val script = ScriptCompiler.compile(scriptText, ScriptEstimatorV2).explicitGet()._1 + val setScriptTransaction = TxHelpers.setScript(acc0, script, setScriptFee) val setScriptId = sender .signedBroadcast(setScriptTransaction.json()) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/DataTransactionBodyBytesByteVectorSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/DataTransactionBodyBytesByteVectorSuite.scala index 6e7111e24b0..1ed61a5c300 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/DataTransactionBodyBytesByteVectorSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/DataTransactionBodyBytesByteVectorSuite.scala @@ -19,11 +19,8 @@ class DataTransactionBodyBytesByteVectorSuite extends BaseTransactionSuite { private def compile(scriptText: String) = ScriptCompiler.compile(scriptText, ScriptEstimatorV2).explicitGet()._1.bytes().base64 - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0)) private val maxDataTxV1bodyBytesSize = 153530 // actually lower than Terms.DataTxMaxBytes diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/DataTransactionEntryMatchSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/DataTransactionEntryMatchSuite.scala index ed81b4dd23a..e72c092970f 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/DataTransactionEntryMatchSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/DataTransactionEntryMatchSuite.scala @@ -15,17 +15,15 @@ import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.smart.script.ScriptCompiler class DataTransactionEntryMatchSuite extends BaseTransactionSuite { - private val activationHeight = Height(5) + private val activationHeight = Height(10) private def compile(scriptText: String) = ScriptCompiler.compile(scriptText, ScriptEstimatorV2).explicitGet()._1.bytes().base64 - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.SynchronousCalls.id, activationHeight))) - .withDefault(1) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0).preactivatedFeatures((BlockchainFeatures.SynchronousCalls, activationHeight)) + ) private def script(dApp: Boolean) = compile( diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/EstimatorTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/EstimatorTestSuite.scala index 534fa34560f..37f95002ec7 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/EstimatorTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/EstimatorTestSuite.scala @@ -3,7 +3,6 @@ package com.wavesplatform.it.sync.smartcontract import com.typesafe.config.Config import com.wavesplatform.common.state.ByteStr import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite @@ -14,24 +13,23 @@ import org.scalatest.CancelAfterFailure import scala.concurrent.duration.* class EstimatorTestSuite extends BaseTransactionSuite with CancelAfterFailure { - private val featureHeight = Height(8) - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase( - _.raw( - s""" - | waves.blockchain.custom.functionality { - | estimator-pre-check-height = $featureHeight - | estimator-sum-overflow-fix-height = 999999 - | pre-activated-features = {14 = 0, 15 = 999999} - | } + private val featureHeight = Height(10) + + import NodeConfigs.* + + override protected def nodeConfigs: Seq[Config] = Seq( + Miners(5) + .quorum(0) + .overrides( + s""" + | waves.blockchain.custom.functionality { + | estimator-pre-check-height = $featureHeight + | estimator-sum-overflow-fix-height = 999999 + | pre-activated-features = {14 = 0, 15 = 999999} + | } """.stripMargin - ) ) - .buildNonConflicting() + ) private def smartAcc = firstKeyPair private def callerAcc = secondKeyPair diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/ExchangeWithContractsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/ExchangeWithContractsSuite.scala index 67efd57da07..f48932ffa4a 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/ExchangeWithContractsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/ExchangeWithContractsSuite.scala @@ -1,14 +1,13 @@ package com.wavesplatform.it.sync.smartcontract import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.NTPTime import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.state.* import com.wavesplatform.transaction.assets.exchange.* -import com.wavesplatform.transaction.{DataTransaction, TxVersion} +import com.wavesplatform.transaction.{DataTransaction, TxHelpers, TxVersion} import org.scalatest.CancelAfterFailure class ExchangeWithContractsSuite extends BaseTransactionSuite with CancelAfterFailure with NTPTime { @@ -22,15 +21,15 @@ class ExchangeWithContractsSuite extends BaseTransactionSuite with CancelAfterFa val sc1: Option[String] = Some(s"true") val sc2: Option[String] = Some(s""" - |match tx { - | case _: SetScriptTransaction => true - | case _ => false - |}""".stripMargin) + |match tx { + | case _: SetScriptTransaction => true + | case _ => false + |}""".stripMargin) val sc3: Option[String] = Some(s""" - |match tx { - | case _: SetScriptTransaction => true - | case _ => throw("Some generic error") - |}""".stripMargin) + |match tx { + | case _: SetScriptTransaction => true + | case _ => throw("Some generic error") + |}""".stripMargin) protected override def beforeAll(): Unit = { super.beforeAll() @@ -56,7 +55,7 @@ class ExchangeWithContractsSuite extends BaseTransactionSuite with CancelAfterFa val entry3 = BinaryDataEntry("blob", ByteStr.decodeBase64("YWxpY2U=").get) val entry4 = StringDataEntry("str", "test") - dtx = DataTransaction.selfSigned(1.toByte, acc0, List(entry1, entry2, entry3, entry4), minFee, ntpTime.correctedTime()).explicitGet() + dtx = TxHelpers.data(acc0, List(entry1, entry2, entry3, entry4), minFee) sender.signedBroadcast(dtx.json(), waitForTx = true) } @@ -66,29 +65,33 @@ class ExchangeWithContractsSuite extends BaseTransactionSuite with CancelAfterFa val sc5 = Some(pureContextScript(dtx, accountScript = true)) val sc6 = Some(wavesContextScript(dtx, accountScript = true)) - for ((contr1, contr2, mcontr) <- Seq( - (sc1, sc1, sc1), - (None, sc1, None), - (None, None, sc1), - (None, None, sc4), - (None, None, sc5), - (None, None, sc6), - (sc5, None, sc5) - )) { + for ( + (contr1, contr2, mcontr) <- Seq( + (sc1, sc1, sc1), + (None, sc1, None), + (None, None, sc1), + (None, None, sc4), + (None, None, sc5), + (None, None, sc6), + (sc5, None, sc5) + ) + ) { setContracts( (contr1, acc0), (contr2, acc1), (mcontr, acc2) ) - for ((o1ver, o2ver) <- Seq( - (2: Byte, 2: Byte), - (2: Byte, 3: Byte) - )) { + for ( + (o1ver, o2ver) <- Seq( + (2: Byte, 2: Byte), + (2: Byte, 3: Byte) + ) + ) { sender.signedBroadcast(exchangeTx(pair, smartMatcherFee, orderFee, ntpTime, o1ver, o2ver, acc1, acc0, acc2), waitForTx = true) - //TODO : add assert balances + // TODO : add assert balances } } @@ -100,26 +103,30 @@ class ExchangeWithContractsSuite extends BaseTransactionSuite with CancelAfterFa } test("negative - set simple contracts and put exchange transaction in blockchain") { - for ((contr1, contr2, mcontr) <- Seq( - (sc1, sc2, sc1), - (sc1, sc1, sc2), - (None, None, sc2), - (None, sc2, None) - )) { + for ( + (contr1, contr2, mcontr) <- Seq( + (sc1, sc2, sc1), + (sc1, sc1, sc2), + (None, None, sc2), + (None, sc2, None) + ) + ) { setContracts( (contr1, acc0), (contr2, acc1), (mcontr, acc2) ) - for ((o1ver, o2ver) <- Seq( - (2: Byte, 2: Byte), - (3: Byte, 3: Byte) - )) { + for ( + (o1ver, o2ver) <- Seq( + (2: Byte, 2: Byte), + (3: Byte, 3: Byte) + ) + ) { assertBadRequestAndMessage( sender.signedBroadcast(exchangeTx(pair, smartMatcherFee, orderFee, ntpTime, o1ver, o2ver, acc1, acc0, acc2)), "Transaction is not allowed by account-script" ) - //TODO : add assert balances + // TODO : add assert balances } } setContracts( @@ -130,21 +137,25 @@ class ExchangeWithContractsSuite extends BaseTransactionSuite with CancelAfterFa } test("negative - check custom exception") { - for ((contr1, contr2, mcontr) <- Seq( - (sc1, sc1, sc3) - )) { + for ( + (contr1, contr2, mcontr) <- Seq( + (sc1, sc1, sc3) + ) + ) { setContracts( (contr1, acc0), (contr2, acc1), (mcontr, acc2) ) - for ((o1ver, o2ver) <- Seq( - (2: Byte, 2: Byte), - (3: Byte, 3: Byte) - )) { + for ( + (o1ver, o2ver) <- Seq( + (2: Byte, 2: Byte), + (3: Byte, 3: Byte) + ) + ) { val tx = exchangeTx(pair, smartMatcherFee, orderFee, ntpTime, o1ver, o2ver, acc1, acc0, acc2) assertBadRequestAndMessage(sender.signedBroadcast(tx), "Error while executing account-script: Some generic error") - //TODO : add assert balances + // TODO : add assert balances } } setContracts( @@ -155,11 +166,13 @@ class ExchangeWithContractsSuite extends BaseTransactionSuite with CancelAfterFa } test("positive - versioning verification") { - for ((contr1, contr2, mcontr) <- Seq( - (None, None, None), - (sc1, None, None), - (None, None, sc1) - )) { + for ( + (contr1, contr2, mcontr) <- Seq( + (None, None, None), + (sc1, None, None), + (None, None, sc1) + ) + ) { setContracts( (contr1, acc0), (contr2, acc1), @@ -168,34 +181,34 @@ class ExchangeWithContractsSuite extends BaseTransactionSuite with CancelAfterFa val matcher = acc2 val sellPrice = (0.50 * Order.PriceConstant).toLong - for ((o1ver, o2ver) <- Seq( - (1: Byte, 2: Byte), - (1: Byte, 3: Byte) - )) { + for ( + (o1ver, o2ver) <- Seq( + (1: Byte, 2: Byte), + (1: Byte, 3: Byte) + ) + ) { val (buy, sell) = orders(pair, o1ver, o2ver, orderFee, ntpTime, acc1, acc0, acc2) val amount = math.min(buy.amount.value, sell.amount.value) - val tx = ExchangeTransaction - .signed( - 3.toByte, - matcher = matcher.privateKey, - order1 = sell, - order2 = buy, - amount = amount, - price = sellPrice, - buyMatcherFee = (BigInt(orderFee) * amount / buy.amount.value).toLong, - sellMatcherFee = (BigInt(orderFee) * amount / sell.amount.value).toLong, - fee = smartMatcherFee, - timestamp = ntpTime.correctedTime() + val tx = TxHelpers + .exchange( + sell, + buy, + matcher, + amount, + sellPrice, + (BigInt(orderFee) * amount / buy.amount.value).toLong, + (BigInt(orderFee) * amount / sell.amount.value).toLong, + smartMatcherFee, + version = 3.toByte ) - .explicitGet() .json() val txId = sender.signedBroadcast(tx).id nodes.waitForTransaction(txId) - //TODO : add assert balances + // TODO : add assert balances } } setContracts( @@ -211,27 +224,27 @@ class ExchangeWithContractsSuite extends BaseTransactionSuite with CancelAfterFa val matcher = acc2 val sellPrice = (0.50 * Order.PriceConstant).toLong - for ((o1ver, o2ver) <- Seq( - (2: Byte, 1: Byte), - (3: Byte, 1: Byte) - )) { + for ( + (o1ver, o2ver) <- Seq( + (2: Byte, 1: Byte), + (3: Byte, 1: Byte) + ) + ) { val (buy, sell) = orders(pair, o1ver, o2ver, orderFee, ntpTime, acc1, acc0, acc2) val amount = math.min(buy.amount.value, sell.amount.value) - val tx = ExchangeTransaction - .signed( - 2.toByte, - matcher = matcher.privateKey, - order1 = buy, - order2 = sell, - amount = amount, - price = sellPrice, - buyMatcherFee = (BigInt(orderFee) * amount / buy.amount.value).toLong, - sellMatcherFee = (BigInt(orderFee) * amount / sell.amount.value).toLong, - fee = smartMatcherFee, - timestamp = ntpTime.correctedTime() + val tx = TxHelpers + .exchange( + buy, + sell, + matcher, + amount, + sellPrice, + (BigInt(orderFee) * amount / buy.amount.value).toLong, + (BigInt(orderFee) * amount / sell.amount.value).toLong, + smartMatcherFee, + version = 2.toByte ) - .explicitGet() .json() assertBadRequestAndMessage(sender.signedBroadcast(tx), "Reason: Can't process order with signature from scripted account") diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeCalcIssueSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeCalcIssueSuite.scala index 0af864f25e9..105f54c66e1 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeCalcIssueSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeCalcIssueSuite.scala @@ -4,25 +4,21 @@ import com.typesafe.config.Config import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.it.util.* import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 -import com.wavesplatform.state.{BinaryDataEntry, Height} +import com.wavesplatform.state.BinaryDataEntry import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalatest.* class InvokeCalcIssueSuite extends BaseTransactionSuite with CancelAfterFailure with OptionValues { import InvokeCalcIssueSuite.* - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.BlockV5.id, Height(0)), (BlockchainFeatures.BlockV5.id, Height(0)))) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0).preactivatedFeatures(BlockchainFeatures.BlockV5) + ) private def smartAcc = firstKeyPair private def callerAcc = secondKeyPair @@ -81,15 +77,15 @@ object InvokeCalcIssueSuite { private val dAppV4: String = s"""{-# STDLIB_VERSION 4 #-} - |{-# CONTENT_TYPE DAPP #-} - | - |@Callable(i) - |func i() = { - |let issue = Issue("$assetName", "$assetDescr", $amount, $decimals, $reissuable, unit, 0) - |let id = calculateAssetId(issue) - |[issue, - | BinaryEntry("id", id)] - |} - | - |""".stripMargin + |{-# CONTENT_TYPE DAPP #-} + | + |@Callable(i) + |func i() = { + |let issue = Issue("$assetName", "$assetDescr", $amount, $decimals, $reissuable, unit, 0) + |let id = calculateAssetId(issue) + |[issue, + | BinaryEntry("id", id)] + |} + | + |""".stripMargin } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokePaymentsAvailabilitySuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokePaymentsAvailabilitySuite.scala index a34c870e98f..aaef3255fac 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokePaymentsAvailabilitySuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokePaymentsAvailabilitySuite.scala @@ -5,75 +5,83 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs +import com.wavesplatform.it.NodeConfigs.BiggestMiner import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 -import com.wavesplatform.state.Height import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler class InvokePaymentsAvailabilitySuite extends BaseTransactionSuite { - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase( - _.preactivatedFeatures( - (BlockchainFeatures.Ride4DApps.id, Height(0)), - (BlockchainFeatures.BlockV5.id, Height(0)), - (BlockchainFeatures.SynchronousCalls.id, Height(0)) - ) + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner + .quorum(0) + .preactivatedFeatures( + BlockchainFeatures.Ride4DApps, + BlockchainFeatures.BlockV5, + BlockchainFeatures.SynchronousCalls ) - .withDefault(1) - .buildNonConflicting() + ) private lazy val (caller, callerAddress) = (firstKeyPair, firstAddress) private lazy val (callingDApp, callingDAppAddress) = (secondKeyPair, secondAddress) private lazy val (proxyDApp, proxyDAppAddress) = (thirdKeyPair, thirdAddress) private def syncDApp(dApp: String) = - ScriptCompiler.compile( - s""" - |{-# STDLIB_VERSION 5 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-# SCRIPT_TYPE ACCOUNT #-} - | - | let dApp2 = Address(base58'$dApp') - | - | @Callable(inv) - | func default() = { - | let pmt = inv.payments[0] - | strict invokeV4 = dApp2.invoke("default", nil, [AttachedPayment(pmt.assetId, pmt.amount)]) - | [ - | IntegerEntry("balance_self", this.assetBalance(pmt.assetId.value())), - | IntegerEntry("balance_calling_dApp", dApp2.assetBalance(pmt.assetId.value())) - | ] - | } - | + ScriptCompiler + .compile( + s""" + |{-# STDLIB_VERSION 5 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-# SCRIPT_TYPE ACCOUNT #-} + | + | let dApp2 = Address(base58'$dApp') + | + | @Callable(inv) + | func default() = { + | let pmt = inv.payments[0] + | strict invokeV4 = dApp2.invoke("default", nil, [AttachedPayment(pmt.assetId, pmt.amount)]) + | [ + | IntegerEntry("balance_self", this.assetBalance(pmt.assetId.value())), + | IntegerEntry("balance_calling_dApp", dApp2.assetBalance(pmt.assetId.value())) + | ] + | } + | """.stripMargin, - ScriptEstimatorV3.latest - ).explicitGet()._1.bytes().base64 + ScriptEstimatorV3.latest + ) + .explicitGet() + ._1 + .bytes() + .base64 private val dApp = - ScriptCompiler.compile( - s""" - | {-# STDLIB_VERSION 5 #-} - | {-# CONTENT_TYPE DAPP #-} - | {-# SCRIPT_TYPE ACCOUNT #-} - | - | @Callable(inv) - | func default() = { - | let pmtAssetId = inv.payments[0].assetId.value() - | [ - | IntegerEntry("balance_self", this.assetBalance(pmtAssetId)), - | IntegerEntry("balance_caller", inv.caller.assetBalance(pmtAssetId)) - | ] - | } + ScriptCompiler + .compile( + s""" + | {-# STDLIB_VERSION 5 #-} + | {-# CONTENT_TYPE DAPP #-} + | {-# SCRIPT_TYPE ACCOUNT #-} + | + | @Callable(inv) + | func default() = { + | let pmtAssetId = inv.payments[0].assetId.value() + | [ + | IntegerEntry("balance_self", this.assetBalance(pmtAssetId)), + | IntegerEntry("balance_caller", inv.caller.assetBalance(pmtAssetId)) + | ] + | } """.stripMargin, - ScriptEstimatorV3.latest - ).explicitGet()._1.bytes().base64 + ScriptEstimatorV3.latest + ) + .explicitGet() + ._1 + .bytes() + .base64 private val paymentAmount = 12345 private val issueAmount = 1000 * 1000 diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokePaymentsFeeSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokePaymentsFeeSuite.scala index 57464adaa4b..a27423b36fc 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokePaymentsFeeSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokePaymentsFeeSuite.scala @@ -9,25 +9,21 @@ import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.smartMinFee import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 -import com.wavesplatform.state.Height import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler class InvokePaymentsFeeSuite extends BaseTransactionSuite { - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase( - _.preactivatedFeatures( - (BlockchainFeatures.Ride4DApps.id, Height(0)), - (BlockchainFeatures.BlockV5.id, Height(0)), - (BlockchainFeatures.SynchronousCalls.id, Height(0)) - ) + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner + .quorum(0) + .preactivatedFeatures( + BlockchainFeatures.Ride4DApps, + BlockchainFeatures.BlockV5, + BlockchainFeatures.SynchronousCalls ) - .withDefault(1) - .buildNonConflicting() + ) private lazy val (caller, callerAddress) = (firstKeyPair, firstAddress) private lazy val (dApp, dAppAddress) = (secondKeyPair, secondAddress) @@ -51,17 +47,17 @@ class InvokePaymentsFeeSuite extends BaseTransactionSuite { ScriptCompiler .compile( s""" - | {-# STDLIB_VERSION 4 #-} - | {-# CONTENT_TYPE DAPP #-} - | {-# SCRIPT_TYPE ACCOUNT #-} - | - | @Callable(i) - | func default() = - | [ - | ScriptTransfer(i.caller, 1, base58'$assetId'), - | Burn(base58'$assetId', 1), - | Reissue(base58'$assetId', 1, false) - | ] + | {-# STDLIB_VERSION 4 #-} + | {-# CONTENT_TYPE DAPP #-} + | {-# SCRIPT_TYPE ACCOUNT #-} + | + | @Callable(i) + | func default() = + | [ + | ScriptTransfer(i.caller, 1, base58'$assetId'), + | Burn(base58'$assetId', 1), + | Reissue(base58'$assetId', 1, false) + | ] """.stripMargin, ScriptEstimatorV3.latest ) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionRideV5Suite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionRideV5Suite.scala index d70cd04a481..187306b960d 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionRideV5Suite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionRideV5Suite.scala @@ -7,7 +7,6 @@ import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.sync.smartcontract.RideV4ActivationSuite.* import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.state.Height import com.wavesplatform.test.* import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer @@ -28,19 +27,16 @@ class InvokeScriptTransactionRideV5Suite extends BaseTransactionSuite with Cance private def alias(name: String): String = s"alias:I:$name" - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(NodeConfigs.Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase( - _.preactivatedFeatures( - (BlockchainFeatures.Ride4DApps.id, Height(0)), - (BlockchainFeatures.BlockV5.id, Height(0)), - (BlockchainFeatures.SynchronousCalls.id, Height(0)) - ) + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner + .quorum(0) + .preactivatedFeatures( + BlockchainFeatures.Ride4DApps, + BlockchainFeatures.BlockV5, + BlockchainFeatures.SynchronousCalls ) - .withDefault(1) - .buildNonConflicting() + ) protected override def beforeAll(): Unit = { super.beforeAll() diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionSuite.scala index b5c37d20176..20f78625030 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionSuite.scala @@ -26,18 +26,16 @@ import scala.concurrent.duration.* class InvokeScriptTransactionSuite extends BaseTransactionSuite with CancelAfterFailure { val activationHeight = Height(8) - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(NodeConfigs.Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase( - _.preactivatedFeatures( - (BlockchainFeatures.Ride4DApps.id, Height(0)), - (BlockchainFeatures.BlockV5.id, activationHeight) - ) + + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner + .quorum(0) + .preactivatedFeatures( + BlockchainFeatures.Ride4DApps, + (BlockchainFeatures.BlockV5, activationHeight) ) - .withDefault(1) - .buildNonConflicting() + ) private def firstContract = firstKeyPair private def secondContract = secondKeyPair diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeSelfPaymentSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeSelfPaymentSuite.scala index 5d44a73a59b..f6c4ec3f945 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeSelfPaymentSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeSelfPaymentSuite.scala @@ -1,33 +1,43 @@ package com.wavesplatform.it.sync.smartcontract +import com.typesafe.config.Config import com.wavesplatform.api.http.ApiError.ScriptExecutionError -import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* +import com.wavesplatform.it.BaseFunSuite import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* -import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.compiler.Terms.CONST_STRING import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 -import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} +import com.wavesplatform.transaction.Asset.Waves +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer +import com.wavesplatform.test.* import org.scalatest.CancelAfterFailure -class InvokeSelfPaymentSuite extends BaseTransactionSuite with CancelAfterFailure { +class InvokeSelfPaymentSuite extends BaseFunSuite with CancelAfterFailure { + import com.wavesplatform.it.NodeConfigs.* + override protected val nodeConfigs: Seq[Config] = Seq(Miners(3).quorum(0)) - private def caller = firstKeyPair - private def dAppV4 = secondKeyPair - private def dAppV3 = thirdKeyPair + private lazy val caller = sender.keyPair + private val dAppV4 = TxHelpers.signer(1002) + private val dAppV3 = TxHelpers.signer(1003) - private var asset1: IssuedAsset = scala.compiletime.uninitialized - private def asset1Id = asset1.id.toString + private lazy val issueTx = TxHelpers.issue(caller) - private lazy val dAppV3Address: String = dAppV3.toAddress.toString - private lazy val dAppV4Address: String = dAppV4.toAddress.toString + private lazy val asset1 = issueTx.asset + private lazy val asset1Id = asset1.id.toString + + private lazy val dAppV3Address = dAppV3.toAddress.toString + private lazy val dAppV4Address = dAppV4.toAddress.toString test("prerequisite: set contract") { - asset1 = IssuedAsset(ByteStr.decodeBase58(sender.issue(caller, waitForTx = true).id).get) + sender.massTransfer(caller, List( + Transfer(dAppV4.toAddress.toString, 100.waves), + Transfer(dAppV3.toAddress.toString, 100.waves), + ), 0.005.waves, waitForTx = true) + sender.signedBroadcast(issueTx.json(), true) val sourceV4 = """{-# STDLIB_VERSION 4 #-} diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/MassTransferSmartContractSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/MassTransferSmartContractSuite.scala index 43a9b8cf8e6..4dbb0b251d1 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/MassTransferSmartContractSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/MassTransferSmartContractSuite.scala @@ -1,22 +1,15 @@ package com.wavesplatform.it.sync.smartcontract import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.Base58 import com.wavesplatform.common.utils.EitherExt2.* -import com.wavesplatform.crypto import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 -import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.Proofs +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer -import com.wavesplatform.transaction.transfer.* import org.scalatest.CancelAfterFailure -import scala.concurrent.duration.* - /* Scenario: every month a foundation makes payments from two MassTransactions(type == 11): @@ -25,7 +18,7 @@ every month a foundation makes payments from two MassTransactions(type == 11): */ class MassTransferSmartContractSuite extends BaseTransactionSuite with CancelAfterFailure { - private lazy val fourthAddress: String = notMiner.createKeyPair().toAddress.toString + private lazy val fourthAddress = notMiner.createKeyPair().toAddress test("airdrop emulation via MassTransfer") { val scriptText = s""" @@ -65,61 +58,31 @@ class MassTransferSmartContractSuite extends BaseTransactionSuite with CancelAft notMiner.addressScriptInfo(notMiner.address).scriptText.isEmpty shouldBe false - //save time - val currTime = System.currentTimeMillis() - - //make transfer to users - val transfers = - MassTransferTransaction - .parseTransfersList(List(Transfer(thirdAddress, 4 * transferAmount), Transfer(secondAddress, 4 * transferAmount))) - .explicitGet() - - val unsigned = - MassTransferTransaction - .create(1.toByte, notMiner.publicKey, Waves, transfers, calcMassTransferFee(2) + smartFee, currTime, ByteStr.empty, Proofs.empty) - .explicitGet() - - val accountSig = crypto.sign(notMiner.keyPair.privateKey, unsigned.bodyBytes()) - val signed = unsigned.copy(1.toByte, proofs = Proofs(Seq(accountSig))) - val toUsersID = notMiner.signedBroadcast(signed.json(), waitForTx = true).id - - //make transfer with incorrect time - val heightBefore = notMiner.height - - val transfersToGov = - MassTransferTransaction.parseTransfersList(List(Transfer(firstAddress, transferAmount), Transfer(fourthAddress, transferAmount))).explicitGet() - - val unsignedToGov = - MassTransferTransaction - .create(1.toByte, notMiner.publicKey, Waves, transfersToGov, calcMassTransferFee(2) + smartFee, currTime, ByteStr.empty, Proofs.empty) - .explicitGet() - val accountSigToGovFail = crypto.sign(notMiner.keyPair.privateKey, unsignedToGov.bodyBytes()) - val signedToGovFail = unsignedToGov.copy(1.toByte, proofs = Proofs(Seq(accountSigToGovFail))) + // make transfer to users + val signedToUsers = TxHelpers.massTransfer( + notMiner.keyPair, + Seq(thirdKeyPair.toAddress -> 4 * transferAmount, secondKeyPair.toAddress -> 4 * transferAmount), + fee = calcMassTransferFee(2) + smartFee + ) + val toUsersID = ByteStr.decodeBase58(notMiner.signedBroadcast(signedToUsers.json(), waitForTx = true).id).get + + val transfersToGov = Seq(firstKeyPair.toAddress -> transferAmount, fourthAddress -> transferAmount) + // make transfer with incorrect time + val signedToGovWithIncorrectTs = TxHelpers.massTransfer( + notMiner.keyPair, + transfersToGov, + fee = calcMassTransferFee(2) + smartFee, + timestamp = signedToUsers.timestamp + ) assertBadRequestAndResponse( - notMiner.signedBroadcast(signedToGovFail.json()), + notMiner.signedBroadcast(signedToGovWithIncorrectTs.addProof(toUsersID).json()), "Transaction is not allowed by account-script" ) - //make correct transfer to government after some time - notMiner.waitForHeight(heightBefore + 10, 5.minutes) - - val unsignedToGovSecond = - MassTransferTransaction - .create( - 1.toByte, - notMiner.publicKey, - Waves, - transfersToGov, - calcMassTransferFee(2) + smartFee, - System.currentTimeMillis(), - ByteStr.empty, - Proofs.empty - ) - .explicitGet() - - val accountSigToGov = crypto.sign(notMiner.keyPair.privateKey, unsignedToGovSecond.bodyBytes()) - val signedToGovGood = unsignedToGovSecond.copy(1.toByte, proofs = Proofs(Seq(accountSigToGov, ByteStr(Base58.tryDecodeWithLimit(toUsersID).get)))) - notMiner.signedBroadcast(signedToGovGood.json(), waitForTx = true).id + // make correct transfer to government with correct timestamp + val signedToGovGood = + TxHelpers.massTransfer(notMiner.keyPair, transfersToGov, fee = calcMassTransferFee(2) + smartFee, timestamp = signedToUsers.timestamp + 30_001) + notMiner.signedBroadcast(signedToGovGood.addProof(toUsersID).json(), waitForTx = true).id } } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/PseudoTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/PseudoTransactionSuite.scala index a006cc083f3..b51e60e0196 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/PseudoTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/PseudoTransactionSuite.scala @@ -6,14 +6,13 @@ import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.lang.v1.FunctionHeader +import com.wavesplatform.lang.v1.compiler.Terms.EXPR import com.wavesplatform.lang.v1.compiler.{Terms, TestCompiler} -import com.wavesplatform.lang.v1.compiler.Terms.{EXPR, FUNCTION_CALL} import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.transaction.Asset.Waves +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.utils.Signed class PseudoTransactionSuite extends BaseTransactionSuite { @@ -30,26 +29,31 @@ class PseudoTransactionSuite extends BaseTransactionSuite { super.beforeAll() smartAssetId = sender.issue(firstDApp, fee = issueFee, script = Some(scriptBase64), waitForTx = true).id - val dAppScript = ScriptCompiler.compile( - s""" - |{-# STDLIB_VERSION 4 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-# SCRIPT_TYPE ACCOUNT #-} - | - |@Callable (i) - |func reissueAsset(a: ByteVector, r: Boolean, q: Int) = [Reissue(a, q, r)] - | - |@Callable (i) - |func burnAsset(a: ByteVector, q: Int) = [Burn(a, q)] - | - |@Callable (i) - |func transferAsset(r: ByteVector, a: ByteVector, q: Int) = [ScriptTransfer(Address(r), q, a)] - | - |@Callable (i) - |func transferAssetByAlias(r: String, a: ByteVector, q: Int) = [ScriptTransfer(Alias(r), q, a)] + val dAppScript = ScriptCompiler + .compile( + s""" + |{-# STDLIB_VERSION 4 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-# SCRIPT_TYPE ACCOUNT #-} + | + |@Callable (i) + |func reissueAsset(a: ByteVector, r: Boolean, q: Int) = [Reissue(a, q, r)] + | + |@Callable (i) + |func burnAsset(a: ByteVector, q: Int) = [Burn(a, q)] + | + |@Callable (i) + |func transferAsset(r: ByteVector, a: ByteVector, q: Int) = [ScriptTransfer(Address(r), q, a)] + | + |@Callable (i) + |func transferAssetByAlias(r: String, a: ByteVector, q: Int) = [ScriptTransfer(Alias(r), q, a)] """.stripMargin, - ScriptEstimatorV3.latest - ).explicitGet()._1.bytes().base64 + ScriptEstimatorV3.latest + ) + .explicitGet() + ._1 + .bytes() + .base64 sender.setScript(firstDApp, Some(dAppScript), waitForTx = true) sender.setScript(recipient, Some(dAppScript), waitForTx = true) @@ -131,55 +135,58 @@ class PseudoTransactionSuite extends BaseTransactionSuite { } private def smartAssetScript(invokeId: String): String = - TestCompiler.DefaultVersion.compileAsset( - s""" - |{-# STDLIB_VERSION 4 #-} - |{-# CONTENT_TYPE EXPRESSION #-} - |{-# SCRIPT_TYPE ASSET #-} - | - | match tx { - | case t: TransferTransaction => t.senderPublicKey.toBase58String() == "${firstDApp.publicKey.toString}" - | && t.assetId.value().toBase58String() == "$smartAssetId" - | && toBase64String(t.attachment) == "" - | && t.bodyBytes.size() == 0 - | && t.fee == 0 - | && t.feeAssetId == unit - | && t.id == fromBase58String("$invokeId") - | && (toBase58String(addressFromRecipient(t.recipient).bytes) == "${recipient.toAddress.toString}" || - | toBase58String(addressFromRecipient(t.recipient).bytes) == "$recipientAlias") - | && toBase58String(t.sender.bytes) == "${firstDApp.toAddress.toString}" - | && t.version == 0 - | case r: ReissueTransaction => r.senderPublicKey.toBase58String() == "${firstDApp.publicKey.toString}" - | && r.assetId.value().toBase58String() == "$smartAssetId" - | && r.bodyBytes.size() == 0 - | && r.fee == 0 - | && r.id.size() != 0 - | && toBase58String(r.sender.bytes) == "${firstDApp.toAddress.toString}" - | && r.version == 0 - | && r.quantity == 100000 - | && r.reissuable == true - | case b: BurnTransaction => b.senderPublicKey.toBase58String() == "${firstDApp.publicKey.toString}" - | && b.assetId.value().toBase58String() == "$smartAssetId" - | && b.bodyBytes.size() == 0 - | && b.fee == 0 - | && b.id.size() != 0 - | && toBase58String(b.sender.bytes) == "${firstDApp.toAddress.toString}" - | && b.version == 0 - | && b.quantity == 100000 - | case _ => true - | } + TestCompiler.DefaultVersion + .compileAsset( + s""" + |{-# STDLIB_VERSION 4 #-} + |{-# CONTENT_TYPE EXPRESSION #-} + |{-# SCRIPT_TYPE ASSET #-} + | + | match tx { + | case t: TransferTransaction => t.senderPublicKey.toBase58String() == "${firstDApp.publicKey.toString}" + | && t.assetId.value().toBase58String() == "$smartAssetId" + | && toBase64String(t.attachment) == "" + | && t.bodyBytes.size() == 0 + | && t.fee == 0 + | && t.feeAssetId == unit + | && t.id == fromBase58String("$invokeId") + | && (toBase58String(addressFromRecipient(t.recipient).bytes) == "${recipient.toAddress.toString}" || + | toBase58String(addressFromRecipient(t.recipient).bytes) == "$recipientAlias") + | && toBase58String(t.sender.bytes) == "${firstDApp.toAddress.toString}" + | && t.version == 0 + | case r: ReissueTransaction => r.senderPublicKey.toBase58String() == "${firstDApp.publicKey.toString}" + | && r.assetId.value().toBase58String() == "$smartAssetId" + | && r.bodyBytes.size() == 0 + | && r.fee == 0 + | && r.id.size() != 0 + | && toBase58String(r.sender.bytes) == "${firstDApp.toAddress.toString}" + | && r.version == 0 + | && r.quantity == 100000 + | && r.reissuable == true + | case b: BurnTransaction => b.senderPublicKey.toBase58String() == "${firstDApp.publicKey.toString}" + | && b.assetId.value().toBase58String() == "$smartAssetId" + | && b.bodyBytes.size() == 0 + | && b.fee == 0 + | && b.id.size() != 0 + | && toBase58String(b.sender.bytes) == "${firstDApp.toAddress.toString}" + | && b.version == 0 + | && b.quantity == 100000 + | case _ => true + | } """.stripMargin - ).bytes().base64 + ) + .bytes() + .base64 private def invokeScriptTransaction(func: String, args: List[EXPR]): InvokeScriptTransaction = - Signed.invokeScript( - 2.toByte, - caller, + TxHelpers.invoke( AddressOrAlias.fromString(firstDApp.toAddress.toString).explicitGet(), - Some(FUNCTION_CALL(FunctionHeader.User(func), args)), + Some(func), + args, Seq.empty, + caller, smartMinFee + smartFee, Waves, - System.currentTimeMillis() + 2.toByte ) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/Ride4DAppsActivationTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/Ride4DAppsActivationTestSuite.scala index 8d2cd8cfb46..c1664f0182d 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/Ride4DAppsActivationTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/Ride4DAppsActivationTestSuite.scala @@ -1,18 +1,19 @@ package com.wavesplatform.it.sync.smartcontract -import com.typesafe.config.{Config, ConfigFactory} +import com.typesafe.config.Config import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* +import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.state.Height import com.wavesplatform.test.* -import com.wavesplatform.transaction.{Asset, AssetIdLength} import com.wavesplatform.transaction.smart.script.ScriptCompiler +import com.wavesplatform.transaction.{Asset, AssetIdLength} import org.scalatest.CancelAfterFailure -import com.wavesplatform.state.Height import scala.concurrent.duration.* @@ -182,18 +183,6 @@ class Ride4DAppsActivationTestSuite extends BaseTransactionSuite with CancelAfte object Ride4DAppsActivationTestSuite { val activationHeight = Height(15) - val configWithRide4DAppsFeature = NodeConfigs.newBuilder - .withDefault(1) - .withSpecial(1, _.nonMiner) - .buildNonConflicting() - .map( - ConfigFactory - .parseString( - s"""waves.blockchain.custom.functionality { - | pre-activated-features.11 = ${activationHeight - 1} - |}""".stripMargin - ) - .withFallback(_) - ) - + import NodeConfigs.* + val configWithRide4DAppsFeature = Seq(BiggestMiner, NotMiner).map(_.preactivatedFeatures((BlockchainFeatures.Ride4DApps, activationHeight - 1))) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideBlockInfoSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideBlockInfoSuite.scala index 150e0cb7b7e..67127340bb9 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideBlockInfoSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideBlockInfoSuite.scala @@ -3,8 +3,8 @@ package com.wavesplatform.it.sync.smartcontract import com.typesafe.config.Config import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* +import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.Block import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.transactions.BaseTransactionSuite @@ -16,13 +16,15 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler class RideBlockInfoSuite extends BaseTransactionSuite { val activationHeight = Height(4) - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((14, Height(2)))) - .overrideBase(_.preactivatedFeatures((15, activationHeight))) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner + .quorum(0) + .preactivatedFeatures( + (BlockchainFeatures.BlockReward, Height(2)), + (BlockchainFeatures.BlockV5, activationHeight) + ) + ) private val dAppScriptV4 = """ diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideFuncSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideFuncSuite.scala index 9d06f5f0803..843bd630a86 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideFuncSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideFuncSuite.scala @@ -10,6 +10,7 @@ import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} +import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.TransferTransaction @@ -17,12 +18,9 @@ import org.scalatest.CancelAfterFailure class RideFuncSuite extends BaseTransactionSuite with CancelAfterFailure { private val estimator = ScriptEstimatorV2 - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(entitiesNumber = 1) - .buildNonConflicting() + + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0)) test("assetBalance() verification") { val asset = sender @@ -46,14 +44,15 @@ class RideFuncSuite extends BaseTransactionSuite with CancelAfterFailure { val tx = sender.signedBroadcast( - SetScriptTransaction.selfSigned(1.toByte, pkNewAddress, Some(compiled), setScriptFee, System.currentTimeMillis()).explicitGet().json() + SetScriptTransaction.create(1.toByte, pkNewAddress.publicKey, Some(compiled), setScriptFee, System.currentTimeMillis(), Proofs.empty).map(_.signWith(pkNewAddress.privateKey)).explicitGet().json() ) nodes.waitForHeightAriseAndTxPresent(tx.id) assertBadRequestAndResponse( sender.signedBroadcast( TransferTransaction - .selfSigned(2.toByte, pkNewAddress, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, System.currentTimeMillis()) + .create(2.toByte, pkNewAddress.publicKey, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, System.currentTimeMillis(), Proofs.empty) + .map(_.signWith(pkNewAddress.privateKey)) .explicitGet() .json() ), @@ -62,17 +61,19 @@ class RideFuncSuite extends BaseTransactionSuite with CancelAfterFailure { sender.signedBroadcast( TransferTransaction - .selfSigned( + .create( 2.toByte, - firstKeyPair, + firstKeyPair.publicKey, pkNewAddress.toAddress, IssuedAsset(ByteStr.decodeBase58(asset).get), 100000000, Waves, smartMinFee, ByteStr.empty, - System.currentTimeMillis() + System.currentTimeMillis(), + Proofs.empty ) + .map(_.signWith(firstKeyPair.privateKey)) .explicitGet() .json(), waitForTx = true @@ -80,7 +81,8 @@ class RideFuncSuite extends BaseTransactionSuite with CancelAfterFailure { val transfer = sender.signedBroadcast( TransferTransaction - .selfSigned(2.toByte, pkNewAddress, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, System.currentTimeMillis()) + .create(2.toByte, pkNewAddress.publicKey, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, System.currentTimeMillis(), Proofs.empty) + .map(_.signWith(pkNewAddress.privateKey)) .explicitGet() .json() ) @@ -99,7 +101,8 @@ class RideFuncSuite extends BaseTransactionSuite with CancelAfterFailure { val updTx = sender.signedBroadcast( SetScriptTransaction - .selfSigned(1.toByte, pkNewAddress, Some(updated), setScriptFee + smartFee, System.currentTimeMillis()) + .create(1.toByte, pkNewAddress.publicKey, Some(updated), setScriptFee + smartFee, System.currentTimeMillis(), Proofs.empty) + .map(_.signWith(pkNewAddress.privateKey)) .explicitGet() .json() ) @@ -108,7 +111,8 @@ class RideFuncSuite extends BaseTransactionSuite with CancelAfterFailure { assertBadRequestAndResponse( sender.signedBroadcast( TransferTransaction - .selfSigned(2.toByte, pkNewAddress, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, System.currentTimeMillis()) + .create(2.toByte, pkNewAddress.publicKey, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, System.currentTimeMillis(), Proofs.empty) + .map(_.signWith(pkNewAddress.privateKey)) .explicitGet() .json() ), @@ -117,17 +121,19 @@ class RideFuncSuite extends BaseTransactionSuite with CancelAfterFailure { sender.signedBroadcast( TransferTransaction - .selfSigned( + .create( 2.toByte, - firstKeyPair, + firstKeyPair.publicKey, pkNewAddress.toAddress, IssuedAsset(ByteStr.decodeBase58(asset).get), 800000000, Waves, smartMinFee, ByteStr.empty, - System.currentTimeMillis() + System.currentTimeMillis(), + Proofs.empty ) + .map(_.signWith(firstKeyPair.privateKey)) .explicitGet() .json(), waitForTx = true @@ -135,7 +141,8 @@ class RideFuncSuite extends BaseTransactionSuite with CancelAfterFailure { val transferAfterUpd = sender.signedBroadcast( TransferTransaction - .selfSigned(2.toByte, pkNewAddress, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, System.currentTimeMillis()) + .create(2.toByte, pkNewAddress.publicKey, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, System.currentTimeMillis(), Proofs.empty) + .map(_.signWith(pkNewAddress.privateKey)) .explicitGet() .json() ) @@ -166,21 +173,22 @@ class RideFuncSuite extends BaseTransactionSuite with CancelAfterFailure { val pkNewAddress = newAddress sender.transfer(firstKeyPair, newAddress.toAddress.toString, 10.waves, minFee, waitForTx = true) - val scriptSet = SetScriptTransaction.selfSigned(1.toByte, pkNewAddress, Some(compiledScript), setScriptFee, System.currentTimeMillis()) + val scriptSet = SetScriptTransaction.create(1.toByte, pkNewAddress.publicKey, Some(compiledScript), setScriptFee, System.currentTimeMillis(), Proofs.empty).map(_.signWith(pkNewAddress.privateKey)) val scriptSetBroadcast = sender.signedBroadcast(scriptSet.explicitGet().json()) nodes.waitForHeightAriseAndTxPresent(scriptSetBroadcast.id) - val transfer = TransferTransaction.selfSigned( + val transfer = TransferTransaction.create( 2.toByte, - pkNewAddress, + pkNewAddress.publicKey, pkNewAddress.toAddress, Waves, 1.waves, Waves, smartMinFee, ByteStr.empty, - System.currentTimeMillis() - ) + System.currentTimeMillis(), + Proofs.empty + ).map(_.signWith(pkNewAddress.privateKey)) val transferBroadcast = sender.signedBroadcast(transfer.explicitGet().json()) nodes.waitForHeightAriseAndTxPresent(transferBroadcast.id) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideIssueTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideIssueTransactionSuite.scala index afbe2033824..a2de0388ce3 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideIssueTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideIssueTransactionSuite.scala @@ -1,13 +1,10 @@ package com.wavesplatform.it.sync.smartcontract -import java.nio.charset.StandardCharsets - import com.typesafe.config.Config import com.wavesplatform.account.KeyPair import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.TransactionInfo import com.wavesplatform.it.sync.* @@ -16,12 +13,11 @@ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalatest.{Assertion, CancelAfterFailure} +import java.nio.charset.StandardCharsets + class RideIssueTransactionSuite extends BaseTransactionSuite with CancelAfterFailure { - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0)) val assetName = "Asset name" val assetDescription = "Asset description" diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideReplBlockchainFunctionsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideReplBlockchainFunctionsSuite.scala index a945cf397e8..331bde0cb35 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideReplBlockchainFunctionsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideReplBlockchainFunctionsSuite.scala @@ -16,8 +16,7 @@ import com.wavesplatform.lang.v1.repl.Repl import com.wavesplatform.lang.v1.repl.node.http.NodeConnectionSettings import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, IntegerDataEntry, StringDataEntry, Height} import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.TxVersion -import com.wavesplatform.transaction.transfer.TransferTransaction +import com.wavesplatform.transaction.{TxHelpers, TxVersion} import org.scalatest.Assertion import org.scalatest.EitherValues.* @@ -25,12 +24,8 @@ import scala.concurrent.Await import scala.concurrent.duration.* class RideReplBlockchainFunctionsSuite extends BaseTransactionSuite { - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(entitiesNumber = 1) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(Miners.head.quorum(0)) private def alice = firstKeyPair private def bob = secondKeyPair @@ -201,19 +196,17 @@ class RideReplBlockchainFunctionsSuite extends BaseTransactionSuite { .foreach { version => val transferTxId = transferTxIds(version) val responseTx = sender.transactionInfo[TransferTransactionInfo](transferTxId) - val bodyBytes = TransferTransaction - .selfSigned( - version = version, - sender = alice, - recipient = Alias.createWithChainId(alias, chainId.toByte).explicitGet(), + val bodyBytes = TxHelpers.transfer( + from = alice, + to = Alias.createWithChainId(alias, chainId.toByte).explicitGet(), asset = IssuedAsset(ByteStr.decodeBase58(assetId).get), amount = transferAmount, feeAsset = Waves, fee = responseTx.fee, attachment = ByteStr(attachment.getBytes(StandardCharsets.UTF_8)), - timestamp = responseTx.timestamp + timestamp = responseTx.timestamp, + version = version ) - .explicitGet() .bodyBytes .value() diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideUpdateAssetInfoTxSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideUpdateAssetInfoTxSuite.scala index 7f9630be277..34c20e568b6 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideUpdateAssetInfoTxSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideUpdateAssetInfoTxSuite.scala @@ -5,7 +5,6 @@ import com.wavesplatform.api.http.ApiError.ScriptCompilerError import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.TransactionInfo import com.wavesplatform.it.sync.* @@ -17,13 +16,8 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalatest.CancelAfterFailure class RideUpdateAssetInfoTxSuite extends BaseTransactionSuite with CancelAfterFailure { - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.minAssetInfoUpdateInterval(1)) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0).minAssetInfoUpdateInterval(1)) private def dApp = firstKeyPair private def smartAcc = secondKeyPair diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideV4ActivationSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideV4ActivationSuite.scala index 7ef2851b5a1..53bf43d606e 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideV4ActivationSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideV4ActivationSuite.scala @@ -6,7 +6,6 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite @@ -21,14 +20,11 @@ import org.scalatest.{Assertion, CancelAfterFailure} import scala.concurrent.duration.* class RideV4ActivationSuite extends BaseTransactionSuite with CancelAfterFailure { + import NodeConfigs.* import RideV4ActivationSuite.* - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.BlockV5.id, activationHeight - 1))) - .buildNonConflicting() + override protected def nodeConfigs: Seq[Config] = Seq( + Miners(7).quorum(0).preactivatedFeatures((BlockchainFeatures.BlockV5, activationHeight - 1)) + ) private def smartAccV4 = firstKeyPair private def callerAcc = secondKeyPair @@ -385,7 +381,7 @@ class RideV4ActivationSuite extends BaseTransactionSuite with CancelAfterFailure object RideV4ActivationSuite { private val estimator = ScriptEstimatorV2 - val activationHeight = Height(9) + val activationHeight = Height(11) def asAssetV3(body: String): String = { s"""{-# STDLIB_VERSION 3 #-} diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideV5ActivationSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideV5ActivationSuite.scala index 7959e8e4b12..422e065f942 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideV5ActivationSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/RideV5ActivationSuite.scala @@ -4,7 +4,6 @@ import com.typesafe.config.Config import com.wavesplatform.api.http.ApiError.* import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.sync.smartcontract.RideV4ActivationSuite.* @@ -15,15 +14,14 @@ import org.scalatest.{Assertion, CancelAfterFailure} import scala.concurrent.duration.DurationInt class RideV5ActivationSuite extends BaseTransactionSuite with CancelAfterFailure { - private val activationHeight = Height(6) - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.Ride4DApps.id, Height(0)))) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.SynchronousCalls.id, activationHeight - 1))) - .buildNonConflicting() + private val activationHeight = Height(10) + + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + Miners(5) + .quorum(0) + .preactivatedFeatures(BlockchainFeatures.Ride4DApps, (BlockchainFeatures.SynchronousCalls, activationHeight - 1)) + ) private def smartAccV5 = firstKeyPair private def callerAcc = secondKeyPair diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/ScriptExecutionErrorSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/ScriptExecutionErrorSuite.scala index 719b7401601..a413408854f 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/ScriptExecutionErrorSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/ScriptExecutionErrorSuite.scala @@ -10,7 +10,7 @@ import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 -import com.wavesplatform.transaction.{CreateAliasTransaction, Transaction} +import com.wavesplatform.transaction.{Proofs, Transaction, TxHelpers} import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler @@ -34,12 +34,12 @@ class ScriptExecutionErrorSuite extends BaseTransactionSuite with CancelAfterFai val compiled = ScriptCompiler.compile(scriptSrc, ScriptEstimatorV2).explicitGet()._1 - val tx = sender.signedBroadcast(SetScriptTransaction.selfSigned(1.toByte, thirdKeyPair, Some(compiled), setScriptFee, ts).explicitGet().json()) + val tx = sender.signedBroadcast(SetScriptTransaction.create(1.toByte, thirdKeyPair.publicKey, Some(compiled), setScriptFee, ts, Proofs.empty).map(_.signWith(thirdKeyPair.privateKey)).explicitGet().json()) nodes.waitForHeightAriseAndTxPresent(tx.id) val alias = Alias.fromString(s"alias:${AddressScheme.current.chainId.toChar}:asdasdasdv").explicitGet() assertBadRequestAndResponse( - sender.signedBroadcast(CreateAliasTransaction.selfSigned(Transaction.V2, thirdKeyPair, alias.name, minFee + smartFee, ts).explicitGet().json()), + sender.signedBroadcast(TxHelpers.createAlias(name = alias.name, sender = thirdKeyPair, fee = minFee + smartFee, version = Transaction.V2).json()), "Your transaction has incorrect type." ) } @@ -54,7 +54,8 @@ class ScriptExecutionErrorSuite extends BaseTransactionSuite with CancelAfterFai val tx = sender.signedBroadcast( SetScriptTransaction - .selfSigned(1.toByte, firstKeyPair, Some(script), setScriptFee, ts) + .create(1.toByte, firstKeyPair.publicKey, Some(script), setScriptFee, ts, Proofs.empty) + .map(_.signWith(firstKeyPair.privateKey)) .explicitGet() .json() ) @@ -63,7 +64,8 @@ class ScriptExecutionErrorSuite extends BaseTransactionSuite with CancelAfterFai assertBadRequestAndResponse( sender.signedBroadcast( TransferTransaction - .selfSigned(2.toByte, firstKeyPair, secondKeyPair.toAddress, Waves, 1000, Waves, minFee + smartFee, ByteStr.empty, ts) + .create(2.toByte, firstKeyPair.publicKey, secondKeyPair.toAddress, Waves, 1000, Waves, minFee + smartFee, ByteStr.empty, ts, Proofs.empty) + .map(_.signWith(firstKeyPair.privateKey)) .explicitGet() .json() ), diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SelfPaymentDappToDappSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SelfPaymentDappToDappSuite.scala index ea6ed045a8e..76de96e595d 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SelfPaymentDappToDappSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SelfPaymentDappToDappSuite.scala @@ -9,23 +9,19 @@ import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 -import com.wavesplatform.state.Height import com.wavesplatform.transaction.smart.script.ScriptCompiler class SelfPaymentDappToDappSuite extends BaseTransactionSuite { - - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase( - _.preactivatedFeatures( - (BlockchainFeatures.Ride4DApps.id, Height(0)), - (BlockchainFeatures.BlockV5.id, Height(0)), - (BlockchainFeatures.SynchronousCalls.id, Height(0)) - ) + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner + .quorum(0) + .preactivatedFeatures( + BlockchainFeatures.Ride4DApps, + BlockchainFeatures.BlockV5, + BlockchainFeatures.SynchronousCalls ) - .withDefault(1) - .buildNonConflicting() + ) private lazy val (caller, callerAddress) = (firstKeyPair, firstAddress) private lazy val (dApp1, dAppAddress1) = (secondKeyPair, secondAddress) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SetScriptBodyBytesByteVectorSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SetScriptBodyBytesByteVectorSuite.scala index a87fc4fa943..fbfad486a4e 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SetScriptBodyBytesByteVectorSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SetScriptBodyBytesByteVectorSuite.scala @@ -4,6 +4,7 @@ import com.typesafe.config.Config import com.wavesplatform.account.KeyPair import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.NodeConfigs +import com.wavesplatform.it.NodeConfigs.BiggestMiner import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.TransactionInfo import com.wavesplatform.it.sync.* @@ -15,11 +16,8 @@ class SetScriptBodyBytesByteVectorSuite extends BaseTransactionSuite { private def compile(scriptText: String) = ScriptCompiler.compile(scriptText, ScriptEstimatorV2).explicitGet()._1.bytes().base64 - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0)) private val expectedBodyBytesSize = 32815 diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/TransferTxFromProtoSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/TransferTxFromProtoSuite.scala index e3418615e67..9503d057365 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/TransferTxFromProtoSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/TransferTxFromProtoSuite.scala @@ -10,9 +10,8 @@ import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.protobuf.transaction.PBTransactions import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.transfer.TransferTransaction +import com.wavesplatform.transaction.{TxHelpers, TxVersion} class TransferTxFromProtoSuite extends BaseTransactionSuite { private def source = firstKeyPair @@ -23,49 +22,47 @@ class TransferTxFromProtoSuite extends BaseTransactionSuite { private val scriptText = s""" - |{-# STDLIB_VERSION 4 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-# SCRIPT_TYPE ACCOUNT #-} - | - |@Callable(i) - |func foo(txProtoBytes: ByteVector) = { - | let transferTx = transferTransactionFromProto(txProtoBytes).value() - | let transferTxAttachment = transferTx.attachment.toBase58String() - | let assetId = if (!transferTx.assetId.isDefined()) then {"WAVES"} else {transferTx.assetId.value().toBase58String()} - | let feeAssetId = if (!transferTx.feeAssetId.isDefined()) then {"WAVES"} else {transferTx.feeAssetId.value().toBase58String()} - |[ - |IntegerEntry("amount", transferTx.amount), - |StringEntry("senderPublicKey", transferTx.senderPublicKey.toBase58String()), - |StringEntry("sender", transferTx.sender.bytes.toBase58String()), - |StringEntry("recipient", addressFromRecipient(transferTx.recipient).bytes.toBase58String()), - |StringEntry("assetId", assetId), - |StringEntry("attachment", transferTxAttachment), - |IntegerEntry("fee", transferTx.fee), - |StringEntry("feeAssetId", feeAssetId), - |StringEntry("id", transferTx.id.toBase58String()), - |IntegerEntry("version", transferTx.version), - |BinaryEntry("bodyBytes",transferTx.bodyBytes) - |] - |} - | - |""".stripMargin + |{-# STDLIB_VERSION 4 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-# SCRIPT_TYPE ACCOUNT #-} + | + |@Callable(i) + |func foo(txProtoBytes: ByteVector) = { + | let transferTx = transferTransactionFromProto(txProtoBytes).value() + | let transferTxAttachment = transferTx.attachment.toBase58String() + | let assetId = if (!transferTx.assetId.isDefined()) then {"WAVES"} else {transferTx.assetId.value().toBase58String()} + | let feeAssetId = if (!transferTx.feeAssetId.isDefined()) then {"WAVES"} else {transferTx.feeAssetId.value().toBase58String()} + |[ + |IntegerEntry("amount", transferTx.amount), + |StringEntry("senderPublicKey", transferTx.senderPublicKey.toBase58String()), + |StringEntry("sender", transferTx.sender.bytes.toBase58String()), + |StringEntry("recipient", addressFromRecipient(transferTx.recipient).bytes.toBase58String()), + |StringEntry("assetId", assetId), + |StringEntry("attachment", transferTxAttachment), + |IntegerEntry("fee", transferTx.fee), + |StringEntry("feeAssetId", feeAssetId), + |StringEntry("id", transferTx.id.toBase58String()), + |IntegerEntry("version", transferTx.version), + |BinaryEntry("bodyBytes",transferTx.bodyBytes) + |] + |} + | + |""".stripMargin private val script = ScriptCompiler.compile(scriptText, ScriptEstimatorV3.latest).explicitGet()._1.bytes().base64 test("TransferTransaction with Waves from proto bytes") { sender.setScript(dApp, Some(script), waitForTx = true) - val transferTx = TransferTransaction - .selfSigned( - version = TxVersion.V3, - sender = source, - recipient = recipient.toAddress, - asset = Waves, - amount = transferAmount, - feeAsset = Waves, - fee = minFee, - attachment = ByteStr("WAVES transfer".getBytes), - timestamp = System.currentTimeMillis() - ) - .explicitGet() + val transferTx = TxHelpers.transfer( + version = TxVersion.V3, + from = source, + to = recipient.toAddress, + asset = Waves, + amount = transferAmount, + feeAsset = Waves, + fee = minFee, + attachment = ByteStr("WAVES transfer".getBytes), + timestamp = System.currentTimeMillis() + ) sender.signedBroadcast(transferTx.json(), waitForTx = true) @@ -95,19 +92,17 @@ class TransferTxFromProtoSuite extends BaseTransactionSuite { val assetId = sender.issue(source, waitForTx = true).id sender.sponsorAsset(source, assetId, minFee, waitForTx = true) - val transferAssetTx = TransferTransaction - .selfSigned( - version = TxVersion.V3, - sender = source, - recipient = recipient.toAddress, - asset = IssuedAsset(ByteStr.decodeBase58(assetId).get), - amount = 10000, - feeAsset = IssuedAsset(ByteStr.decodeBase58(assetId).get), - fee = minFee, - attachment = ByteStr("Some Attachment".getBytes), - timestamp = System.currentTimeMillis() - ) - .explicitGet() + val transferAssetTx = TxHelpers.transfer( + version = TxVersion.V3, + from = source, + to = recipient.toAddress, + asset = IssuedAsset(ByteStr.decodeBase58(assetId).get), + amount = 10000, + feeAsset = IssuedAsset(ByteStr.decodeBase58(assetId).get), + fee = minFee, + attachment = ByteStr("Some Attachment".getBytes), + timestamp = System.currentTimeMillis() + ) sender.signedBroadcast(transferAssetTx.json(), waitForTx = true) @@ -126,19 +121,17 @@ class TransferTxFromProtoSuite extends BaseTransactionSuite { } test("check bodyBytes of transaction returned by transferTransactionFromProto") { - val transferTx = TransferTransaction - .selfSigned( - version = TxVersion.V3, - sender = source, - recipient = recipient.toAddress, - asset = Waves, - amount = 10000, - feeAsset = Waves, - fee = minFee, - attachment = ByteStr("Some Attachment".getBytes), - timestamp = System.currentTimeMillis() - ) - .explicitGet() + val transferTx = TxHelpers.transfer( + version = TxVersion.V3, + from = source, + to = recipient.toAddress, + asset = Waves, + amount = 10000, + feeAsset = Waves, + fee = minFee, + attachment = ByteStr("Some Attachment".getBytes), + timestamp = System.currentTimeMillis() + ) sender.signedBroadcast(transferTx.json(), waitForTx = true) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/UTXAllowance.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/UTXAllowance.scala index 8c25aad3fa9..eb7c899e63d 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/UTXAllowance.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/UTXAllowance.scala @@ -4,12 +4,12 @@ import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* -import com.wavesplatform.it.{BaseFreeSpec, WaitForHeight2} +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.test.* import com.wavesplatform.transaction.smart.script.ScriptCompiler -class UTXAllowance extends BaseFreeSpec with WaitForHeight2 { +class UTXAllowance extends BaseFreeSpec { import UTXAllowance.* override protected def nodeConfigs: Seq[Config] = Configs diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/UtilsEstimatorToggleSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/UtilsEstimatorToggleSuite.scala index 43fd2aba06a..bb4d330b916 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/UtilsEstimatorToggleSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/UtilsEstimatorToggleSuite.scala @@ -14,18 +14,16 @@ class UtilsEstimatorToggleSuite extends BaseTransactionSuite with CancelAfterFai val estimatorV2ActivationHeight = Height(5) val estimatorV3ActivationHeight = Height(8) - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(NodeConfigs.Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase( - _.preactivatedFeatures( - (BlockchainFeatures.BlockReward.id, estimatorV2ActivationHeight), - (BlockchainFeatures.BlockV5.id, estimatorV3ActivationHeight) - ) + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + Miners(5) + .quorum(0) + .overrides("waves.blockchain.custom.functionality.min-block-time = 2s") + .preactivatedFeatures( + (BlockchainFeatures.BlockReward, estimatorV2ActivationHeight), + (BlockchainFeatures.BlockV5, estimatorV3ActivationHeight) ) - .withDefault(1) - .buildNonConflicting() + ) val differentlyEstimatedScript: String = """ diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/freecall/InvokeExpressionGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/freecall/InvokeExpressionGrpcSuite.scala index a1b1baa2835..98fe08c7322 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/freecall/InvokeExpressionGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/freecall/InvokeExpressionGrpcSuite.scala @@ -5,7 +5,6 @@ import com.typesafe.config.Config import com.wavesplatform.account.AddressScheme import com.wavesplatform.features.BlockchainFeatures.ContinuationTransaction import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncGrpcApi.* import com.wavesplatform.it.api.{PutDataResponse, StateChangesDetails} import com.wavesplatform.it.sync.grpc.GrpcBaseTransactionSuite @@ -20,12 +19,10 @@ import com.wavesplatform.transaction.smart.InvokeExpressionTransaction import org.scalatest.{Assertion, CancelAfterFailure} class InvokeExpressionGrpcSuite extends GrpcBaseTransactionSuite with CancelAfterFailure { - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((ContinuationTransaction.id, Height(1)))) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0).preactivatedFeatures((ContinuationTransaction, Height(1))) + ) private val expr: ExprScript = TestCompiler(V6).compileFreeCall( diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/freecall/InvokeExpressionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/freecall/InvokeExpressionSuite.scala index c15f6c54704..6965cb10737 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/freecall/InvokeExpressionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/freecall/InvokeExpressionSuite.scala @@ -4,7 +4,6 @@ import com.wavesplatform.account.AddressScheme import com.wavesplatform.api.http.ApiError.StateCheckFailed import com.wavesplatform.features.BlockchainFeatures.ContinuationTransaction import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.{PutDataResponse, StateChangesDetails, Transaction, TransactionInfo} import com.wavesplatform.it.sync.invokeExpressionFee @@ -16,12 +15,10 @@ import com.wavesplatform.state.Height import org.scalatest.{Assertion, CancelAfterFailure} class InvokeExpressionSuite extends BaseTransactionSuite with CancelAfterFailure { - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((ContinuationTransaction.id, Height(0)))) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0).preactivatedFeatures(ContinuationTransaction) + ) private val expr: ExprScript = TestCompiler(V6).compileFreeCall( diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/package.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/package.scala index 123eafad6e6..08cd37af9fe 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/package.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/package.scala @@ -1,11 +1,11 @@ package com.wavesplatform.it.sync import com.wavesplatform.account.KeyPair -import com.wavesplatform.transaction.DataTransaction -import com.wavesplatform.transaction.assets.exchange.{AssetPair, ExchangeTransaction, Order} +import com.wavesplatform.common.utils.EitherExt2.* +import com.wavesplatform.transaction.assets.exchange.{AssetPair, Order} +import com.wavesplatform.transaction.{DataTransaction, TxHelpers} import com.wavesplatform.utils.Time import play.api.libs.json.JsObject -import com.wavesplatform.common.utils.EitherExt2.* package object smartcontract { val invokeScrTxSupportedVersions: List[Byte] = List(1, 2) @@ -114,7 +114,7 @@ package object smartcontract { """.stripMargin def exchangeTx(pair: AssetPair, exTxFee: Long, orderFee: Long, time: Time, ord1Ver: Byte, ord2Ver: Byte, accounts: KeyPair*): JsObject = { - val buyer = accounts.head // first one + val buyer = accounts.head // first one val seller = accounts.tail.head // second one val matcher = accounts.last val sellPrice = (0.50 * Order.PriceConstant).toLong @@ -126,27 +126,25 @@ package object smartcontract { val buyMatcherFee = (BigInt(orderFee) * amount / buy.amount.value).toLong val sellMatcherFee = (BigInt(orderFee) * amount / sell.amount.value).toLong - val tx = ExchangeTransaction - .signed( - 2.toByte, - matcher = matcher.privateKey, + val tx = TxHelpers + .exchange( + version = 2.toByte, + matcher = matcher, order1 = buy, order2 = sell, amount = amount, price = sellPrice, buyMatcherFee = buyMatcherFee, sellMatcherFee = sellMatcherFee, - fee = matcherFee, - timestamp = time.correctedTime() + fee = matcherFee ) - .explicitGet() .json() tx } def orders(pair: AssetPair, ord1Ver: Byte, ord2Ver: Byte, fee: Long, time: Time, accounts: KeyPair*): (Order, Order) = { - val buyer = accounts.head // first one + val buyer = accounts.head // first one val seller = accounts.tail.head // second one val matcher = accounts.last val ts = time.correctedTime() diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/smartasset/AssetSupportedTransactionsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/smartasset/AssetSupportedTransactionsSuite.scala index 9dbef17c3a2..5e2df9420d7 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/smartasset/AssetSupportedTransactionsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/smartasset/AssetSupportedTransactionsSuite.scala @@ -1,15 +1,14 @@ package com.wavesplatform.it.sync.smartcontract.smartasset import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.IntegerDataEntry import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer -import com.wavesplatform.transaction.transfer.TransferTransaction import scala.concurrent.duration.* @@ -177,33 +176,29 @@ class AssetSupportedTransactionsSuite extends BaseTransactionSuite { .base64 sender.setAssetScript(blackAsset, firstKeyPair, setAssetScriptFee + smartFee, Some(scr), waitForTx = true) - val blackTx = TransferTransaction - .selfSigned( - 2.toByte, - secondKeyPair, - thirdKeyPair.toAddress, - IssuedAsset(ByteStr.decodeBase58(blackAsset).get), - 1, - Waves, - smartMinFee, - ByteStr.empty, - System.currentTimeMillis + 1.minutes.toMillis - ) - .explicitGet() - - val incorrectTx = TransferTransaction - .selfSigned( - 2.toByte, - secondKeyPair, - thirdKeyPair.toAddress, - IssuedAsset(ByteStr.decodeBase58(blackAsset).get), - 1, - Waves, - smartMinFee, - ByteStr.empty, - System.currentTimeMillis + 10.minutes.toMillis - ) - .explicitGet() + val blackTx = TxHelpers.transfer( + from = secondKeyPair, + to = thirdKeyPair.toAddress, + amount = 1, + asset = IssuedAsset(ByteStr.decodeBase58(blackAsset).get), + fee = smartMinFee, + feeAsset = Waves, + attachment = ByteStr.empty, + timestamp = System.currentTimeMillis + 1.minutes.toMillis, + version = 2.toByte + ) + + val incorrectTx = TxHelpers.transfer( + from = secondKeyPair, + to = thirdKeyPair.toAddress, + amount = 1, + asset = IssuedAsset(ByteStr.decodeBase58(blackAsset).get), + fee = smartMinFee, + feeAsset = Waves, + attachment = ByteStr.empty, + timestamp = System.currentTimeMillis + 10.minutes.toMillis, + version = 2.toByte + ) val dataTx = sender.putData(firstKeyPair, List(IntegerDataEntry(s"${blackTx.id()}", 42)), minFee).id nodes.waitForHeightAriseAndTxPresent(dataTx) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/smartasset/ExchangeSmartAssetsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/smartasset/ExchangeSmartAssetsSuite.scala index c2b80ef546c..8eff87fbf1b 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/smartasset/ExchangeSmartAssetsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/smartasset/ExchangeSmartAssetsSuite.scala @@ -6,14 +6,14 @@ import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.NTPTime import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* -import com.wavesplatform.it.sync.smartcontract.{cryptoContextScript, pureContextScript, wavesContextScript, *} +import com.wavesplatform.it.sync.smartcontract.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.DataTransaction import com.wavesplatform.transaction.assets.exchange.* import com.wavesplatform.transaction.smart.script.ScriptCompiler +import com.wavesplatform.transaction.{DataTransaction, TxHelpers} import org.scalatest.CancelAfterFailure class ExchangeSmartAssetsSuite extends BaseTransactionSuite with CancelAfterFailure with NTPTime { @@ -34,7 +34,7 @@ class ExchangeSmartAssetsSuite extends BaseTransactionSuite with CancelAfterFail val entry3 = BinaryDataEntry("blob", ByteStr.decodeBase64("YWxpY2U=").get) val entry4 = StringDataEntry("str", "test") - dtx = DataTransaction.selfSigned(1.toByte, acc0, List(entry1, entry2, entry3, entry4), minFee, ntpTime.correctedTime()).explicitGet() + dtx = TxHelpers.data(acc0, List(entry1, entry2, entry3, entry4), minFee) sender.signedBroadcast(dtx.json(), waitForTx = true) } @@ -43,14 +43,19 @@ class ExchangeSmartAssetsSuite extends BaseTransactionSuite with CancelAfterFail combination of smart accounts and smart assets */ val s = Some( - ScriptCompiler.compile( - s"""{-# SCRIPT_TYPE ASSET #-} - |match tx { - |case _: SetAssetScriptTransaction => true - |case e: ExchangeTransaction => e.sender == addressFromPublicKey(base58'${acc2.publicKey}') - |case _ => false}""".stripMargin, - estimator - ).explicitGet()._1.bytes().base64 + ScriptCompiler + .compile( + s"""{-# SCRIPT_TYPE ASSET #-} + |match tx { + |case _: SetAssetScriptTransaction => true + |case e: ExchangeTransaction => e.sender == addressFromPublicKey(base58'${acc2.publicKey}') + |case _ => false}""".stripMargin, + estimator + ) + .explicitGet() + ._1 + .bytes() + .base64 ) val sAsset = sender @@ -59,10 +64,12 @@ class ExchangeSmartAssetsSuite extends BaseTransactionSuite with CancelAfterFail val smartPair = AssetPair(IssuedAsset(ByteStr.decodeBase58(sAsset).get), Waves) - for ((contr1, contr2, mcontr) <- Seq( - (sc1, sc1, sc1), - (None, sc1, None) - )) { + for ( + (contr1, contr2, mcontr) <- Seq( + (sc1, sc1, sc1), + (None, sc1, None) + ) + ) { setContracts((contr1, acc0), (contr2, acc1), (mcontr, acc2)) @@ -73,14 +80,19 @@ class ExchangeSmartAssetsSuite extends BaseTransactionSuite with CancelAfterFail } val sUpdated = Some( - ScriptCompiler.compile( - s"""{-# SCRIPT_TYPE ASSET #-} - |match tx { - |case _: SetAssetScriptTransaction => true - |case e: ExchangeTransaction => e.sender == addressFromPublicKey(base58'${acc1.publicKey}') - |case _ => false}""".stripMargin, - estimator - ).explicitGet()._1.bytes().base64 + ScriptCompiler + .compile( + s"""{-# SCRIPT_TYPE ASSET #-} + |match tx { + |case _: SetAssetScriptTransaction => true + |case e: ExchangeTransaction => e.sender == addressFromPublicKey(base58'${acc1.publicKey}') + |case _ => false}""".stripMargin, + estimator + ) + .explicitGet() + ._1 + .bytes() + .base64 ) sender.setAssetScript(sAsset, firstKeyPair, setAssetScriptFee, sUpdated, waitForTx = true) @@ -106,16 +118,21 @@ class ExchangeSmartAssetsSuite extends BaseTransactionSuite with CancelAfterFail sender.transfer(firstKeyPair, secondAddress, 1000, minFee + smartFee, Some(assetA), waitForTx = true) val script = Some( - ScriptCompiler.compile( - s"""{-# SCRIPT_TYPE ASSET #-} - |let assetA = base58'$assetA' - |let assetB = base58'$assetB' - |match tx { - |case _: SetAssetScriptTransaction => true - |case e: ExchangeTransaction => (e.sellOrder.assetPair.priceAsset == assetA || e.sellOrder.assetPair.amountAsset == assetA) && (e.sellOrder.assetPair.priceAsset == assetB || e.sellOrder.assetPair.amountAsset == assetB) - |case _ => false}""".stripMargin, - estimator - ).explicitGet()._1.bytes().base64 + ScriptCompiler + .compile( + s"""{-# SCRIPT_TYPE ASSET #-} + |let assetA = base58'$assetA' + |let assetB = base58'$assetB' + |match tx { + |case _: SetAssetScriptTransaction => true + |case e: ExchangeTransaction => (e.sellOrder.assetPair.priceAsset == assetA || e.sellOrder.assetPair.amountAsset == assetA) && (e.sellOrder.assetPair.priceAsset == assetB || e.sellOrder.assetPair.amountAsset == assetB) + |case _ => false}""".stripMargin, + estimator + ) + .explicitGet() + ._1 + .bytes() + .base64 ) sender.setAssetScript(assetA, firstKeyPair, setAssetScriptFee, script, waitForTx = true) @@ -163,7 +180,8 @@ class ExchangeSmartAssetsSuite extends BaseTransactionSuite with CancelAfterFail test("use all functions from RIDE for asset script") { val script1 = Some(ScriptCompiler.compile("{-# SCRIPT_TYPE ASSET #-}" + cryptoContextScript(false), estimator).explicitGet()._1.bytes().base64) val script2 = Some(ScriptCompiler.compile("{-# SCRIPT_TYPE ASSET #-}" + pureContextScript(dtx, false), estimator).explicitGet()._1.bytes().base64) - val script3 = Some(ScriptCompiler.compile("{-# SCRIPT_TYPE ASSET #-}" + wavesContextScript(dtx, false), estimator).explicitGet()._1.bytes().base64) + val script3 = + Some(ScriptCompiler.compile("{-# SCRIPT_TYPE ASSET #-}" + wavesContextScript(dtx, false), estimator).explicitGet()._1.bytes().base64) List(script1, script2, script3) .map { i => diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/AliasTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/AliasTransactionSuite.scala index 5dd29ecfd00..58bc1ece64c 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/AliasTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/AliasTransactionSuite.scala @@ -2,32 +2,29 @@ package com.wavesplatform.it.sync.transactions import com.google.common.primitives.Longs import com.typesafe.config.Config - -import scala.util.{Random, Try} import com.wavesplatform.account.{AddressScheme, KeyPair} import com.wavesplatform.api.http.ApiError.WrongJson import com.wavesplatform.features.BlockchainFeatures.RideV6 import com.wavesplatform.it.NodeConfigs -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.TransactionInfo import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.directives.values.V6 import com.wavesplatform.lang.v1.compiler.TestCompiler -import com.wavesplatform.state.Height import com.wavesplatform.test.* import com.wavesplatform.transaction.* import org.scalatest.prop.TableDrivenPropertyChecks import play.api.libs.json.* +import scala.util.{Random, Try} + class AliasTransactionSuite extends BaseTransactionSuite with TableDrivenPropertyChecks { + import NodeConfigs.* override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 2, Seq.empty) - .overrideBase(_.preactivatedFeatures((RideV6.id, Height(0)))) - .overrideBase(_.raw(s"waves.blockchain.custom.functionality.allow-multiple-proofs-in-create-alias-until = 0")) - .buildNonConflicting() + Seq(BiggestMiner, Miners(3)).map( + _.preactivatedFeatures(RideV6).overrides("waves.blockchain.custom.functionality.allow-multiple-proofs-in-create-alias-until = 0") + ) var version: Byte = 1 @@ -216,12 +213,9 @@ class AliasTransactionSuite extends BaseTransactionSuite with TableDrivenPropert } private def createAliasFromJson(target: KeyPair, alias: String, fee: Long, version: Byte) = { - import com.wavesplatform.common.utils.EitherExt2.* val transactionJson = Try( - CreateAliasTransaction - .selfSigned(version, target, alias, fee, System.currentTimeMillis()) - .foldToTry - ).flatten + TxHelpers.createAlias(name = alias, sender = target, fee = fee, version = version) + ) .map(_.json()) .getOrElse( Json.obj( diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/BurnTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/BurnTransactionSuite.scala index 6b9349ca8c9..8dc03f5a9ac 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/BurnTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/BurnTransactionSuite.scala @@ -3,13 +3,13 @@ package com.wavesplatform.it.sync.transactions import cats.syntax.option.* import com.wavesplatform.account.AddressScheme import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.api.BurnTransactionInfo import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.{issueAmount, issueFee, *} import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.TxVersion +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.assets.BurnTransaction import play.api.libs.json.Json @@ -189,9 +189,7 @@ class BurnTransactionSuite extends BaseTransactionSuite { val issuedAssetId = sender.issue(firstKeyPair, "name", "description", issueAmount, decimals, reissuable = false, fee = issueFee, waitForTx = true).id - val tx = BurnTransaction - .selfSigned(TxVersion.V1, firstKeyPair, IssuedAsset(ByteStr.decodeBase58(issuedAssetId).get), 1, minFee, System.currentTimeMillis()) - .explicitGet() + val tx = TxHelpers.burn(asset = IssuedAsset(ByteStr.decodeBase58(issuedAssetId).get), amount = 1, fee = minFee, sender = firstKeyPair, version = TxVersion.V1) val json = tx.json() - "amount" ++ Json.obj("quantity" -> 1L) sender.signedBroadcast(json, waitForTx = true).id } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/DataTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/DataTransactionSuite.scala index 07926b5e2cb..bc8d15c32bc 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/DataTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/DataTransactionSuite.scala @@ -3,21 +3,21 @@ package com.wavesplatform.it.sync.transactions import com.google.common.primitives.Ints import com.typesafe.config.Config import com.wavesplatform.account.{AddressScheme, KeyPair} -import com.wavesplatform.api.http.ApiError.{CustomValidationError, TooBigArrayAllocation, WrongJson} +import com.wavesplatform.api.http.ApiError.{CustomValidationError, TooBigArrayAllocation} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.Base58 import com.wavesplatform.common.utils.EitherExt2.* +import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.{TransactionInfo, UnexpectedStatusCodeException} -import com.wavesplatform.it.sync.{calcDataFee, minFee, *} +import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.state.Height -import com.wavesplatform.test.* import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, DataEntry, EmptyDataEntry, IntegerDataEntry, StringDataEntry} +import com.wavesplatform.test.* import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.{DataTransaction, Proofs, TxVersion} +import com.wavesplatform.transaction.{DataTransaction, Proofs, TxHelpers, TxVersion} import org.scalatest.{Assertion, Assertions, EitherValues} import play.api.libs.json.* @@ -25,15 +25,18 @@ import scala.concurrent.duration.* import scala.util.{Failure, Random, Try} class DataTransactionSuite extends BaseTransactionSuite with EitherValues { - override def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.raw("waves.blockchain.custom.functionality.blocks-for-feature-activation = 1")) - .overrideBase(_.raw("waves.blockchain.custom.functionality.feature-check-blocks-period = 1")) - .overrideBase(_.preactivatedFeatures(15 -> Height(0))) - .withDefault(1) - .withSpecial(1, _.nonMiner) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq( + BiggestMiner.quorum(0), + NotMiner + ).map( + _.preactivatedFeatures(BlockchainFeatures.BlockV5).overrides( + """waves.blockchain.custom.functionality { + | blocks-for-feature-activation = 1 + | feature-check-blocks-period = 1 + |}""".stripMargin + ) + ) private lazy val fourthKeyPair = sender.createKeyPair() private lazy val fourthAddress: String = fourthKeyPair.toAddress.toString @@ -69,7 +72,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { waitForTx = true ) val dataTx = - DataTransaction.selfSigned(TxVersion.V1, keyPair, Seq(StringDataEntry("1", "test")), 700000L, System.currentTimeMillis()).explicitGet() + TxHelpers.data(account = keyPair, entries = Seq(StringDataEntry("1", "test")), fee = 700000L, version = TxVersion.V1) val brokenProofs = dataTx.copy(proofs = Proofs(dataTx.proofs.proofs :+ ByteStr(new Array[Byte](65)))) assertBadRequestAndResponse(sender.signedBroadcast(brokenProofs.json(), waitForTx = true), "Too large proof") @@ -356,21 +359,17 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { test("transaction requires a valid proof") { for (v <- dataTxSupportedVersions) { def request: JsObject = - DataTransaction - .selfSigned( - v, - firstKeyPair, - List(IntegerDataEntry("int", 333)), - minFee, - System.currentTimeMillis() - ) - .explicitGet() + TxHelpers + .data(account = firstKeyPair, entries = List(IntegerDataEntry("int", 333)), fee = minFee, version = v) .json() def id(obj: JsObject): String = obj.value("id").as[String] val noProof = request - "proofs" - assertBadRequestAndResponse(sender.postJson("/transactions/broadcast", noProof), s"${WrongJson.WrongJsonDataMessage}.*proofs.*missing") + assertBadRequestAndResponse( + sender.postJson("/transactions/broadcast", noProof), + "Transactions from non-scripted accounts must have exactly 1 proof" + ) nodes.foreach(_.ensureTxDoesntExist(id(noProof))) val badProof = request ++ Json.obj("proofs" -> Seq(Base58.encode(Array.fill(64)(Random.nextInt().toByte)))) @@ -478,5 +477,5 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { timestamp: Long = System.currentTimeMillis, version: TxVersion ): DataTransaction = - DataTransaction.selfSigned(version, sender.keyPair, entries, fee, timestamp).explicitGet() + TxHelpers.data(sender.keyPair, entries, fee, version, timestamp) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/ExchangeTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/ExchangeTransactionSuite.scala index 44ce29796af..4a0bd478727 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/ExchangeTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/ExchangeTransactionSuite.scala @@ -9,29 +9,25 @@ import com.wavesplatform.it.sync.* import com.wavesplatform.it.sync.smartcontract.exchangeTx import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.it.{NTPTime, NodeConfigs} -import com.wavesplatform.state.Height import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.assets.exchange.* -import com.wavesplatform.transaction.{TxExchangeAmount, TxExchangePrice, TxVersion} +import com.wavesplatform.transaction.{TxExchangeAmount, TxExchangePrice, TxHelpers, TxVersion} import play.api.libs.json.{JsNumber, JsObject, JsString, Json} class ExchangeTransactionSuite extends BaseTransactionSuite with NTPTime { - private lazy val exchAsset: IssueTransaction = IssueTransaction - .selfSigned( - TxVersion.V1, - sender = sender.keyPair, - "myasset", - "my asset description", - quantity = someAssetAmount, - decimals = 2, - reissuable = true, - script = None, - fee = 1.waves, - timestamp = System.currentTimeMillis() - ) - .explicitGet() + private lazy val exchAsset: IssueTransaction = TxHelpers.issue( + issuer = sender.keyPair, + amount = someAssetAmount, + decimals = 2, + name = "myasset", + description = "my asset description", + fee = 1.waves, + script = None, + reissuable = true, + version = TxVersion.V1 + ) private def acc0 = firstKeyPair private def acc1 = secondKeyPair @@ -162,20 +158,17 @@ class ExchangeTransactionSuite extends BaseTransactionSuite with NTPTime { val assetDescription = "my asset description" - val IssueTx: IssueTransaction = IssueTransaction - .selfSigned( - TxVersion.V1, - buyer, - "myasset", - assetDescription, - quantity = someAssetAmount, - decimals = 8, - reissuable = true, - script = None, - fee = 1.waves, - timestamp = System.currentTimeMillis() - ) - .explicitGet() + val IssueTx: IssueTransaction = TxHelpers.issue( + issuer = buyer, + amount = someAssetAmount, + decimals = 8, + name = "myasset", + description = assetDescription, + fee = 1.waves, + script = None, + reissuable = true, + version = TxVersion.V1 + ) val assetId = IssueTx.id() @@ -220,20 +213,18 @@ class ExchangeTransactionSuite extends BaseTransactionSuite with NTPTime { val amount = 40000000 val tx = - ExchangeTransaction - .signed( - 3.toByte, - matcher = matcher.privateKey, - order1 = buy, - order2 = sell, - amount = amount, - price = sellPrice, - buyMatcherFee = (BigInt(matcherFee) * amount / buy.amount.value).toLong, - sellMatcherFee = (BigInt(matcherFee) * amount / sell.amount.value).toLong, - fee = matcherFee, - timestamp = ntpTime.correctedTime() - ) - .explicitGet() + TxHelpers.exchange( + version = 3.toByte, + matcher = matcher, + order1 = buy, + order2 = sell, + amount = amount, + price = sellPrice, + buyMatcherFee = (BigInt(matcherFee) * amount / buy.amount.value).toLong, + sellMatcherFee = (BigInt(matcherFee) * amount / sell.amount.value).toLong, + fee = matcherFee, + timestamp = ntpTime.correctedTime() + ) sender.postJson("/transactions/broadcast", tx.json()) @@ -364,22 +355,21 @@ class ExchangeTransactionSuite extends BaseTransactionSuite with NTPTime { val buyerBalance = sender.balanceDetails(buyerAddress).regular val tx = - ExchangeTransaction - .signed( - 3.toByte, - matcher = matcher.privateKey, - order1 = buyNftForWaves, - order2 = sellNftForWaves, - amount = amount, - price = nftWavesPrice, - buyMatcherFee = (BigInt(matcherFee) * amount / sellNftForWaves.amount.value).toLong, - sellMatcherFee = (BigInt(matcherFee) * amount / sellNftForWaves.amount.value).toLong, - fee = matcherFee, - timestamp = ntpTime.correctedTime() - ) - .explicitGet() + TxHelpers.exchange( + version = 3.toByte, + matcher = matcher, + order1 = buyNftForWaves, + order2 = sellNftForWaves, + amount = amount, + price = nftWavesPrice, + buyMatcherFee = (BigInt(matcherFee) * amount / sellNftForWaves.amount.value).toLong, + sellMatcherFee = (BigInt(matcherFee) * amount / sellNftForWaves.amount.value).toLong, + fee = matcherFee, + timestamp = ntpTime.correctedTime() + ) sender.signedBroadcast(tx.json(), waitForTx = true) + nodes.waitForHeightAriseAndTxPresent(tx.id().toString) sender.nftList(sellerAddress, limit = 1) shouldBe empty sender.nftList(buyerAddress, 1).head.assetId shouldBe nftAsset @@ -390,22 +380,21 @@ class ExchangeTransactionSuite extends BaseTransactionSuite with NTPTime { val buyerBalanceAfgerFirstExchange = sender.balanceDetails(buyerAddress).regular val tx2 = - ExchangeTransaction - .signed( - 3.toByte, - matcher = matcher.privateKey, - order1 = buyNftForOtherAsset, - order2 = sellNftForOtherAsset, - amount = amount, - price = nftForAssetPrice, - buyMatcherFee = (BigInt(matcherFee) * amount / buyNftForOtherAsset.amount.value).toLong, - sellMatcherFee = (BigInt(matcherFee) * amount / buyNftForOtherAsset.amount.value).toLong, - fee = matcherFee, - timestamp = ntpTime.correctedTime() - ) - .explicitGet() + TxHelpers.exchange( + version = 3.toByte, + matcher = matcher, + order1 = buyNftForOtherAsset, + order2 = sellNftForOtherAsset, + amount = amount, + price = nftForAssetPrice, + buyMatcherFee = (BigInt(matcherFee) * amount / buyNftForOtherAsset.amount.value).toLong, + sellMatcherFee = (BigInt(matcherFee) * amount / buyNftForOtherAsset.amount.value).toLong, + fee = matcherFee, + timestamp = ntpTime.correctedTime() + ) sender.signedBroadcast(tx2.json(), waitForTx = true) + nodes.waitForHeightAriseAndTxPresent(tx2.id().toString) sender.nftList(buyerAddress, limit = 1) shouldBe empty sender.nftList(sellerAddress, 1, None).head.assetId shouldBe nftAsset @@ -416,11 +405,7 @@ class ExchangeTransactionSuite extends BaseTransactionSuite with NTPTime { } + import NodeConfigs.* override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((BlockchainFeatures.BlockV5.id.toInt, Height(0)))) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + Seq(BiggestMiner.quorum(0), NotMiner).map(_.preactivatedFeatures((BlockchainFeatures.BlockV5))) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/FailedTransactionSuiteLike.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/FailedTransactionSuiteLike.scala index 6e31dc9a03b..2858c4c3da7 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/FailedTransactionSuiteLike.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/FailedTransactionSuiteLike.scala @@ -1,7 +1,5 @@ package com.wavesplatform.it.sync.transactions -import scala.concurrent.duration.* - import com.google.protobuf.ByteString import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.account.KeyPair @@ -9,18 +7,20 @@ import com.wavesplatform.api.grpc.{ApplicationStatus, TransactionsByIdRequest, T import com.wavesplatform.api.http.ApiError.TransactionDoesNotExist import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* -import com.wavesplatform.it.{Node, NodeConfigs} import com.wavesplatform.it.api.TransactionStatus +import com.wavesplatform.it.{Node, NodeConfigs} import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.protobuf.transaction.{PBSignedTransaction, PBTransactions} import com.wavesplatform.state.Height -import com.wavesplatform.transaction.{Asset, TxVersion} import com.wavesplatform.transaction.assets.exchange.{AssetPair, ExchangeTransaction, Order} import com.wavesplatform.transaction.smart.script.ScriptCompiler +import com.wavesplatform.transaction.{Asset, TxHelpers, TxVersion} import com.wavesplatform.utils.ScorexLogging import org.scalatest.matchers.should.Matchers import play.api.libs.json.JsObject +import scala.concurrent.duration.* + trait FailedTransactionSuiteLike[T] extends ScorexLogging { matchers: Matchers => protected def waitForHeightArise(): Unit protected def sender: Node @@ -46,7 +46,7 @@ trait FailedTransactionSuiteLike[T] extends ScorexLogging { matchers: Matchers = } object restApi { - import com.wavesplatform.it.api.SyncHttpApi.{assertApiError, NodeExtSync} + import com.wavesplatform.it.api.SyncHttpApi.{NodeExtSync, assertApiError} /** Checks that transactions contain failed and returns them. */ @@ -64,7 +64,7 @@ trait FailedTransactionSuiteLike[T] extends ScorexLogging { matchers: Matchers = all(failed.flatMap(_.applicationStatus)) shouldBe "script_execution_failed" - val failedIdsByHeight = failed.groupBy(_.height.get).map { case (h, txs) => Height(h) -> txs.map(_.id)} + val failedIdsByHeight = failed.groupBy(_.height.get).map { case (h, txs) => Height(h) -> txs.map(_.id) } failedIdsByHeight.foreach { case (h, ids) => sender.blockAt(h).transactions.map(_.id) should contain allElementsOf ids @@ -282,44 +282,46 @@ object FailedTransactionSuiteLike { sellMatcherFee: Long ): ExchangeTransaction = { val timestamp = System.currentTimeMillis() - val buy = Order.buy( - Order.V4, - buyer, - matcher.publicKey, - assetPair, - 100, - 100, - timestamp, - timestamp + Order.MaxLiveTime / 2, - buyMatcherFee, - Asset.fromString(Some(buyMatcherFeeAsset)) - ).explicitGet() - val sell = Order.sell( - Order.V4, - seller, - matcher.publicKey, - assetPair, - 100, - 100, - timestamp, - timestamp + Order.MaxLiveTime / 2, - sellMatcherFee, - Asset.fromString(Some(sellMatcherFeeAsset)) - ).explicitGet() - ExchangeTransaction - .signed( - TxVersion.V3, - matcher.privateKey, - buy, - sell, - buy.amount.value, - buy.price.value, - buy.matcherFee.value, - sell.matcherFee.value, - fee, - timestamp + val buy = Order + .buy( + Order.V4, + buyer, + matcher.publicKey, + assetPair, + 100, + 100, + timestamp, + timestamp + Order.MaxLiveTime / 2, + buyMatcherFee, + Asset.fromString(Some(buyMatcherFeeAsset)) ) .explicitGet() + val sell = Order + .sell( + Order.V4, + seller, + matcher.publicKey, + assetPair, + 100, + 100, + timestamp, + timestamp + Order.MaxLiveTime / 2, + sellMatcherFee, + Asset.fromString(Some(sellMatcherFeeAsset)) + ) + .explicitGet() + TxHelpers.exchange( + buy, + sell, + matcher, + buy.amount.value, + buy.price.value, + buy.matcherFee.value, + sell.matcherFee.value, + fee, + timestamp, + TxVersion.V3 + ) } val configForMinMicroblockAge: Config = ConfigFactory.parseString(s""" @@ -327,11 +329,6 @@ object FailedTransactionSuiteLike { |waves.miner.max-transactions-in-micro-block = 1 |""".stripMargin) - val Configs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.raw(s"waves.miner.max-transactions-in-micro-block = 50")) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + import NodeConfigs.* + val Configs: Seq[Config] = Seq(BiggestMiner.quorum(0).overrides("waves.miner.max-transactions-in-micro-block = 50"), NotMiner) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/IssueNFTSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/IssueNFTSuite.scala index c215adeea4e..e5444ce998f 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/IssueNFTSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/IssueNFTSuite.scala @@ -2,6 +2,7 @@ package com.wavesplatform.it.sync.transactions import com.typesafe.config.Config import com.wavesplatform.account.KeyPair +import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.it.{Node, NodeConfigs} @@ -17,15 +18,9 @@ class IssueNFTSuite extends BaseTransactionSuite with TableDrivenPropertyChecks val secondNodeIssuer: KeyPair = KeyPair("second_node_issuer".getBytes("UTF-8")) val firstNodeIssuer: KeyPair = KeyPair("first_node_issuer".getBytes("UTF-8")) - override def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.raw("""waves { - | miner.quorum = 0 - | blockchain.custom.functionality.pre-activated-features.13 = 10 - |}""".stripMargin)) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = + Seq(BiggestMiner.quorum(0), NotMiner).map(_.preactivatedFeatures((BlockchainFeatures.ReduceNFTFee, Height(10)))) test("Can't issue NFT before activation") { val assetName = "NFTAsset" @@ -80,7 +75,6 @@ class IssueNFTSuite extends BaseTransactionSuite with TableDrivenPropertyChecks assetDescription, quantity = 1, decimals = 0, - reissuable = true, fee = 0.001.waves, script = None, waitForTx = true diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/IssueTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/IssueTransactionSuite.scala index bed7527af73..93c69c834fa 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/IssueTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/IssueTransactionSuite.scala @@ -2,12 +2,12 @@ package com.wavesplatform.it.sync.transactions import com.wavesplatform.account.{AddressScheme, KeyPair} import com.wavesplatform.api.http.ApiError.{CustomValidationError, InvalidDecimals, InvalidName, NonPositiveAmount} -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.api.IssueTransactionInfo import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.test.* +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.assets.IssueTransaction import org.scalatest.prop.TableDrivenPropertyChecks import play.api.libs.json.{JsNull, JsString, JsValue, Json} @@ -114,20 +114,17 @@ class IssueTransactionSuite extends BaseTransactionSuite with TableDrivenPropert test(s"Try to put incorrect script=$script") { for (v <- issueTxSupportedVersions) { val json = { - val tx = IssueTransaction - .selfSigned( - v, - firstKeyPair, - "1234", - "", - 1, - 2, - false, - None, - issueFee, - System.currentTimeMillis() - ) - .explicitGet() + val tx = TxHelpers.issue( + issuer = firstKeyPair, + amount = 1, + decimals = 2, + name = "1234", + description = "", + fee = issueFee, + script = None, + reissuable = false, + version = v + ) tx.json() ++ Json.obj("script" -> script) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/MassTransferTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/MassTransferTransactionSuite.scala index fd12d0262ce..3724f8141cb 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/MassTransferTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/MassTransferTransactionSuite.scala @@ -2,8 +2,7 @@ package com.wavesplatform.it.sync.transactions import com.google.protobuf.ByteString import com.wavesplatform.account.{Address, AddressScheme, Alias} -import com.wavesplatform.api.http.ApiError.WrongJson -import com.wavesplatform.api.http.requests.{MassTransferRequest, SignedMassTransferRequest} +import com.wavesplatform.api.http.requests.MassTransferRequest import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.crypto @@ -142,23 +141,26 @@ class MassTransferTransactionSuite extends BaseTransactionSuite { fee: Long = calcMassTransferFee(1), timestamp: Long = System.currentTimeMillis, attachment: Array[Byte] = Array.emptyByteArray - ): (SignedMassTransferRequest, Option[ByteStr]) = { + ): (MassTransferRequest, Option[ByteStr]) = { val txEi = for { parsedTransfers <- MassTransferTransaction.parseTransfersList(transfers) - tx <- MassTransferTransaction.selfSigned( - 1.toByte, - sender.keyPair, - Waves, - parsedTransfers, - fee, - timestamp, - ByteStr(attachment) - ) + tx <- MassTransferTransaction + .create( + 1.toByte, + sender.keyPair.publicKey, + Waves, + parsedTransfers, + fee, + timestamp, + ByteStr(attachment), + Proofs.empty + ) + .map(_.signWith(sender.keyPair.privateKey)) } yield tx val (signature, idOpt) = txEi.fold(_ => (Proofs(List(fakeSignature)), None), tx => (tx.proofs, Some(tx.id()))) - val req = SignedMassTransferRequest( + val req = MassTransferRequest( Some(TxVersion.V1), sender.publicKey.toString, None, @@ -172,7 +174,7 @@ class MassTransferTransactionSuite extends BaseTransactionSuite { (req, idOpt) } - def negativeTransferAmountRequest: (SignedMassTransferRequest, Option[ByteStr]) = { + def negativeTransferAmountRequest: (MassTransferRequest, Option[ByteStr]) = { val recipient = secondKeyPair val transfers = List(Transfer(recipient.toAddress.toString, -1)) @@ -191,7 +193,7 @@ class MassTransferTransactionSuite extends BaseTransactionSuite { TxHelpers.massTransferBodyBytes(sender.keyPair, None, mttdTransfers, ByteString.copyFrom(attachment.arr), fee, timestamp, version) ( - SignedMassTransferRequest( + MassTransferRequest( Some(version), sender.publicKey.toString, None, @@ -263,7 +265,10 @@ class MassTransferTransactionSuite extends BaseTransactionSuite { def id(obj: JsObject) = obj.value("id").as[String] val noProof = signedMassTransfer - "proofs" - assertBadRequestAndResponse(sender.postJson("/transactions/broadcast", noProof), s"${WrongJson.WrongJsonDataMessage}.*proofs.*missing") + assertBadRequestAndResponse( + sender.postJson("/transactions/broadcast", noProof), + s"Reason: Transactions from non-scripted accounts must have exactly 1 proof" + ) nodes.foreach(_.ensureTxDoesntExist(id(noProof))) val badProof = signedMassTransfer ++ Json.obj("proofs" -> Seq(fakeSignature.toString)) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/RebroadcastTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/RebroadcastTransactionSuite.scala index 16bbcf24a9e..eb0620a15ce 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/RebroadcastTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/RebroadcastTransactionSuite.scala @@ -4,7 +4,6 @@ import com.typesafe.config.Config import com.typesafe.config.ConfigFactory.parseString import com.wavesplatform.account.Address import com.wavesplatform.api.http.ApiError.CustomValidationError -import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.Node import com.wavesplatform.it.NodeConfigs.* @@ -12,7 +11,7 @@ import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.{BaseTransactionSuite, NodesFromDocker} import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.transfer.TransferTransaction +import com.wavesplatform.transaction.TxHelpers class RebroadcastTransactionSuite extends BaseTransactionSuite with NodesFromDocker { @@ -25,19 +24,15 @@ class RebroadcastTransactionSuite extends BaseTransactionSuite with NodesFromDoc private def nodeBIsNotMiner: Node = nodes.last test("should rebroadcast a transaction if that's allowed in config") { - val tx = TransferTransaction - .selfSigned( - 2.toByte, + val tx = TxHelpers + .transfer( nodeAIsMiner.keyPair, Address.fromString(nodeBIsNotMiner.address).explicitGet(), - Waves, transferAmount, Waves, minFee, - ByteStr.empty, - System.currentTimeMillis() + Waves ) - .explicitGet() .json() val dockerNodeAId = docker.stopContainer(dockerNodes().head) @@ -54,19 +49,15 @@ class RebroadcastTransactionSuite extends BaseTransactionSuite with NodesFromDoc test("should not rebroadcast a transaction if that's not allowed in config") { dockerNodes().foreach(docker.restartNode(_, configWithRebroadcastNotAllowed)) - val tx = TransferTransaction - .selfSigned( - 2.toByte, + val tx = TxHelpers + .transfer( nodeAIsMiner.keyPair, Address.fromString(nodeBIsNotMiner.address).explicitGet(), - Waves, transferAmount, Waves, minFee, - ByteStr.empty, - System.currentTimeMillis() + Waves ) - .explicitGet() .json() val dockerNodeAId = docker.stopContainer(dockerNodes().head) @@ -82,19 +73,15 @@ class RebroadcastTransactionSuite extends BaseTransactionSuite with NodesFromDoc } test("should not broadcast a transaction if there are not enough peers") { - val tx = TransferTransaction - .selfSigned( - 2.toByte, + val tx = TxHelpers + .transfer( nodeAIsMiner.keyPair, Address.fromString(nodeBIsNotMiner.address).explicitGet(), - Waves, transferAmount, Waves, minFee, - ByteStr.empty, - System.currentTimeMillis() + Waves ) - .explicitGet() .json() val testNode = dockerNodes().last diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/ReissueTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/ReissueTransactionSuite.scala index 78f96dc2c36..8e10e3c9783 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/ReissueTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/ReissueTransactionSuite.scala @@ -93,10 +93,6 @@ class ReissueTransactionSuite extends BaseTransactionSuite { } } - override protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0), NotMiner) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SetAssetScriptTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SetAssetScriptTransactionSuite.scala index 4b5807d9fa5..534c1326001 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SetAssetScriptTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SetAssetScriptTransactionSuite.scala @@ -1,6 +1,5 @@ package com.wavesplatform.it.sync.transactions -import org.apache.pekko.http.scaladsl.model.StatusCodes import com.wavesplatform.account.KeyPair import com.wavesplatform.api.http.ApiError.{Mistiming, StateCheckFailed, WrongJson} import com.wavesplatform.common.state.ByteStr @@ -15,9 +14,9 @@ import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.assets.SetAssetScriptTransaction -import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.{Proofs, TxPositiveAmount} +import com.wavesplatform.transaction.{Proofs, TxHelpers, TxPositiveAmount} +import org.apache.pekko.http.scaladsl.model.StatusCodes import play.api.libs.json.* import scala.concurrent.duration.* @@ -238,9 +237,7 @@ class SetAssetScriptTransactionSuite extends BaseTransactionSuite { timestamp: Long = System.currentTimeMillis, assetId: IssuedAsset = IssuedAsset(ByteStr.decodeBase58(assetWScript).get) ): SetAssetScriptTransaction = - SetAssetScriptTransaction - .signed(version = v, sender.keyPair.publicKey, assetId, Some(script), fee, timestamp, sender.keyPair.privateKey) - .explicitGet() + TxHelpers.setAssetScript(sender.keyPair, assetId, script, fee, timestamp, v) val (balance, eff) = miner.accountBalances(firstAddress) @@ -276,16 +273,14 @@ class SetAssetScriptTransactionSuite extends BaseTransactionSuite { test("transaction requires a valid proof") { for (v <- setAssetScrTxSupportedVersions) { val request: JsObject = - SetAssetScriptTransaction - .selfSigned( - v, - firstKeyPair, - IssuedAsset(ByteStr.decodeBase58(assetWScript).get), - Some(script), - setAssetScriptFee, - System.currentTimeMillis() + TxHelpers + .setAssetScript( + acc = firstKeyPair, + asset = IssuedAsset(ByteStr.decodeBase58(assetWScript).get), + script = script, + fee = setAssetScriptFee, + version = v ) - .explicitGet() .json() def id(obj: JsObject) = obj.value("id").as[String] @@ -355,28 +350,23 @@ class SetAssetScriptTransactionSuite extends BaseTransactionSuite { for (v <- setAssetScrTxSupportedVersions) { val assetWithScript = if (v < 2) assetWScript else assetWScript2 - val setScriptTransaction = SetScriptTransaction - .selfSigned( - version = v, - accountA, - Some( - ScriptCompiler - .compile( - s"""|let pkB = base58'${accountB.publicKey}' - |match tx { - | case s: SetAssetScriptTransaction => sigVerify(s.bodyBytes,s.proofs[0],pkB) - | case _ => true - |} - """.stripMargin, - estimator - ) - .explicitGet() - ._1 - ), - setScriptFee + smartFee, - System.currentTimeMillis() - ) - .explicitGet() + val setScriptTransaction = TxHelpers.setScript( + acc = accountA, + script = ScriptCompiler + .compile( + s"""|let pkB = base58'${accountB.publicKey}' + |match tx { + | case s: SetAssetScriptTransaction => sigVerify(s.bodyBytes,s.proofs[0],pkB) + | case _ => true + |} + """.stripMargin, + estimator + ) + .explicitGet() + ._1, + fee = setScriptFee + smartFee, + version = v + ) val setScriptId = sender .signedBroadcast(setScriptTransaction.json()) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SetAssetScriptTxFeatureSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SetAssetScriptTxFeatureSuite.scala index 5a11006bd58..789d99ca2a9 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SetAssetScriptTxFeatureSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SetAssetScriptTxFeatureSuite.scala @@ -1,43 +1,31 @@ package com.wavesplatform.it.sync.transactions import com.typesafe.config.Config +import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.features.{BlockchainFeatureStatus, BlockchainFeatures} -import com.wavesplatform.it.NodeConfigs import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.{issueFee, scriptBase64, setAssetScriptFee, someAssetAmount} -import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.common.utils.EitherExt2.* +import com.wavesplatform.it.{BaseFunSuite, NodeConfigs} import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state.Height import com.wavesplatform.transaction.smart.script.ScriptCompiler -class SetAssetScriptTxFeatureSuite extends BaseTransactionSuite { +class SetAssetScriptTxFeatureSuite extends BaseFunSuite { - private val featureActivationHeight = Height(8) + private val featureActivationHeight = Height(11) private var assetId = "" - override def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.raw(s"""waves { - | blockchain.custom.functionality { - | pre-activated-features = { - | ${BlockchainFeatures.SmartAssets.id} = $featureActivationHeight - | } - | - | } - |}""".stripMargin)) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = + Seq(BiggestMiner.quorum(0).preactivatedFeatures((BlockchainFeatures.SmartAssets, featureActivationHeight))) override def beforeAll(): Unit = { super.beforeAll() assetId = sender .issue( - firstKeyPair, + miner.keyPair, "SetAssetScript", "Test coin for SetAssetScript tests", someAssetAmount, @@ -54,7 +42,7 @@ class SetAssetScriptTxFeatureSuite extends BaseTransactionSuite { test("cannot transact without activated feature") { assertBadRequestAndResponse( - sender.setAssetScript(assetId, firstKeyPair, setAssetScriptFee, Some(scriptBase64)).id, + sender.setAssetScript(assetId, miner.keyPair, setAssetScriptFee, Some(scriptBase64)).id, s"${BlockchainFeatures.SmartAssets.description} feature has not been activated yet" ) } @@ -81,7 +69,7 @@ class SetAssetScriptTxFeatureSuite extends BaseTransactionSuite { val txId = sender .setAssetScript( assetId, - firstKeyPair, + miner.keyPair, setAssetScriptFee, Some(script) ) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SignAndBroadcastApiSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SignAndBroadcastApiSuite.scala index 2b98abfa37a..2edfc32badd 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SignAndBroadcastApiSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SignAndBroadcastApiSuite.scala @@ -8,7 +8,6 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.Base58 import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.crypto -import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite @@ -32,12 +31,8 @@ import play.api.libs.json.* import scala.util.Random class SignAndBroadcastApiSuite extends BaseTransactionSuite with NTPTime with BeforeAndAfterAll { - override protected def nodeConfigs: Seq[Config] = - NodeConfigs - .Builder(Default, 1, Seq.empty) - .overrideBase(_.quorum(0)) - .overrideBase(_.raw(s"waves.blockchain.custom.functionality.min-asset-info-update-interval = 0")) - .buildNonConflicting() + import NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = Seq(BiggestMiner.quorum(0).minAssetInfoUpdateInterval(0)) test("height should always be reported for transactions") { val txId = sender.transfer(firstKeyPair, secondAddress, 1.waves, fee = minFee).id @@ -59,7 +54,7 @@ class SignAndBroadcastApiSuite extends BaseTransactionSuite with NTPTime with Be assertBadRequestAndMessage(sender.postJsonWithApiKey("/transactions/sign", json), expectedMessage, code) for (v <- supportedVersions) { - val json = Json.obj("type" -> CreateAliasTransaction.typeId, "sender" -> firstAddress, "alias" -> "alias", "fee" -> 100000) + val json = Json.obj("type" -> CreateAliasTransaction.typeId, "sender" -> sender.address, "alias" -> "alias", "fee" -> 100000) val js = if (Option(v).isDefined) json ++ Json.obj("version" -> v) else json assertSignBadJson(js - "type", WrongJson.WrongJsonDataMessage) assertSignBadJson(js + ("type" -> JsNumber(-100)), "Bad transaction type") @@ -67,14 +62,14 @@ class SignAndBroadcastApiSuite extends BaseTransactionSuite with NTPTime with Be } val obsoleteTx = - Json.obj("type" -> GenesisTransaction.typeId, "sender" -> firstAddress, "recipient" -> firstAddress, "amount" -> 1, "fee" -> 100000) + Json.obj("type" -> GenesisTransaction.typeId, "sender" -> sender.address, "recipient" -> firstAddress, "amount" -> 1, "fee" -> 100000) assertSignBadJson(obsoleteTx, "transaction type not supported", 501) assertSignBadJson(obsoleteTx + ("type" -> Json.toJson(PaymentTransaction.typeId)), "transaction type not supported", 501) val bigBaseTx = Json.obj( "type" -> TransferTransaction.typeId, - "sender" -> firstAddress, + "sender" -> sender.address, "recipient" -> firstAddress, "amount" -> 1, "fee" -> 100000, @@ -141,7 +136,7 @@ class SignAndBroadcastApiSuite extends BaseTransactionSuite with NTPTime with Be for (j <- List(jsonV1, jsonV2)) { assertBroadcastBadJson(j - "type", WrongJson.WrongJsonDataMessage) assertBroadcastBadJson(j - "type" + ("type" -> Json.toJson(88)), "Bad transaction type") - assertBroadcastBadJson(j - "chainId" + ("chainId" -> Json.toJson(123)), "Wrong chain-id") + assertBroadcastBadJson(j - "chainId" + ("chainId" -> Json.toJson(123)), "Address belongs to another network") assertBroadcastBadJson(j - "alias", WrongJson.WrongJsonDataMessage) } } @@ -365,21 +360,21 @@ class SignAndBroadcastApiSuite extends BaseTransactionSuite with NTPTime with Be } test("/transactions/sign/{signerAddress} should sign a transaction by key of signerAddress") { - val firstAddress = sender.createKeyPairServerSide().toAddress.toString + val firstAddress = sender.createKeyPairServerSide() val json = Json.obj( - "type" -> TransferTransaction.typeId, - "sender" -> firstAddress, - "recipient" -> secondAddress, - "fee" -> minFee, - "amount" -> transferAmount + "type" -> TransferTransaction.typeId, + "senderPublicKey" -> firstAddress.publicKey, + "recipient" -> secondAddress, + "fee" -> minFee, + "amount" -> transferAmount ) val signedRequestResponse = sender.postJsonWithApiKey(s"/transactions/sign/${sender.address}", json) assert(signedRequestResponse.getStatusCode == HttpConstants.ResponseStatusCodes.OK_200) val signedRequestJson = Json.parse(signedRequestResponse.getResponseBody) val signedRequest = signedRequestJson.as[TransferRequest] - assert(PublicKey.fromBase58String(signedRequest.senderPublicKey.get).explicitGet().toAddress.toString == firstAddress) + assert(PublicKey.fromBase58String(signedRequest.senderPublicKey).explicitGet() == firstAddress.publicKey) assert(signedRequest.recipient == secondAddress) assert(signedRequest.fee == minFee) assert(signedRequest.amount == transferAmount) @@ -442,10 +437,10 @@ class SignAndBroadcastApiSuite extends BaseTransactionSuite with NTPTime with Be val amount = math.min(buy.amount.value, sell.amount.value) val tx = if (tver == 1) { - ExchangeTransaction - .signed( - 1.toByte, - matcher = matcher.privateKey, + TxHelpers + .exchange( + version = 1.toByte, + matcher = matcher, order1 = buy, order2 = sell, amount = amount, @@ -455,13 +450,12 @@ class SignAndBroadcastApiSuite extends BaseTransactionSuite with NTPTime with Be fee = mf, timestamp = ts ) - .explicitGet() .json() } else { - ExchangeTransaction - .signed( - 2.toByte, - matcher = matcher.privateKey, + TxHelpers + .exchange( + version = 2.toByte, + matcher = matcher, order1 = buy, order2 = sell, amount = amount, @@ -471,7 +465,6 @@ class SignAndBroadcastApiSuite extends BaseTransactionSuite with NTPTime with Be fee = mf, timestamp = ts ) - .explicitGet() .json() } @@ -504,8 +497,6 @@ class SignAndBroadcastApiSuite extends BaseTransactionSuite with NTPTime with Be val validation = sender.postJson("/debug/validate", body) assert(validation.getStatusCode == HttpConstants.ResponseStatusCodes.OK_200) - val validationTime = (Json.parse(validation.getResponseBody) \ "validationTime").as[Double] - log.debug(s"Validation time of tx is $validationTime ") val rb = sender.postJson("/transactions/broadcast", body) assert(rb.getStatusCode == HttpConstants.ResponseStatusCodes.OK_200) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SponsorshipSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SponsorshipSuite.scala index 219023dd6c6..fc093c9f7ac 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SponsorshipSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/SponsorshipSuite.scala @@ -3,32 +3,31 @@ package com.wavesplatform.it.sync.transactions import com.typesafe.config.Config import com.wavesplatform.account.AddressScheme import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* +import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.TransactionInfo import com.wavesplatform.it.sync.* -import com.wavesplatform.it.{BaseFreeSpec, IntegrationSuiteWithThreeAddresses, NodeConfigs} +import com.wavesplatform.it.{BaseFreeSpec, IntegrationSuiteWithThreeAddresses} import com.wavesplatform.state.Height import com.wavesplatform.state.diffs.FeeValidation import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.IssuedAsset -import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.assets.SponsorFeeTransaction +import com.wavesplatform.transaction.{TxHelpers, TxVersion} import org.scalatest.Assertion import scala.concurrent.duration.* class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddresses { - - override def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .overrideBase(_.preactivatedFeatures((14, Height(1000000)))) - .overrideBase(_.raw("waves.blockchain.custom.functionality.blocks-for-feature-activation=1")) - .overrideBase(_.raw("waves.blockchain.custom.functionality.feature-check-blocks-period=1")) - .withDefault(1) - .withSpecial(1, _.nonMiner) - .buildNonConflicting() + import com.wavesplatform.it.NodeConfigs.* + override protected def nodeConfigs: Seq[Config] = + Seq(Miners.head.quorum(0), NotMiner).map( + _.preactivatedFeatures(BlockchainFeatures.BlockReward -> Height(10000)) + .overrides(s"""waves.blockchain.custom.functionality { + | blocks-for-feature-activation = 1 + | feature-check-blocks-period = 1 + |}""".stripMargin) + ) private def sponsor = firstKeyPair private def alice = secondKeyPair @@ -83,7 +82,6 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres "AssetTxV1", "Created by Sponsorship Suite", sponsorAssetTotal, - decimals = 2, reissuable = false, fee = issueFee, waitForTx = true @@ -95,7 +93,6 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres "AssetTxV2", "Created by Sponsorship Suite", sponsorAssetTotal, - decimals = 2, reissuable = false, fee = issueFee, waitForTx = true @@ -138,16 +135,14 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres "invalid tx timestamp" in { for (v <- sponsorshipTxSupportedVersions) { def invalidTx(timestamp: Long): SponsorFeeTransaction = - SponsorFeeTransaction - .selfSigned( - version = v, - sponsor, - IssuedAsset(ByteStr.decodeBase58(firstSponsorAssetId).get), - Some(SmallFee), - minFee, - timestamp + 1.day.toMillis - ) - .explicitGet() + TxHelpers.sponsor( + asset = IssuedAsset(ByteStr.decodeBase58(firstSponsorAssetId).get), + minSponsoredAssetFee = Some(SmallFee), + sender = sponsor, + fee = minFee, + version = v, + timestamp = timestamp + ) val iTx = invalidTx(timestamp = System.currentTimeMillis + 1.day.toMillis) assertBadRequestAndResponse(sender.broadcastRequest(iTx.json()), "Transaction timestamp .* is more than .*ms in the future") @@ -161,9 +156,14 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres sender.transfer(alice, bobAddress, 10 * Token, SmallFee, Some(firstSponsorAssetId), Some(firstSponsorAssetId)).id val secondTransferTxCustomFeeAlice = // A-8 sender.transfer(alice, bobAddress, 10 * Token, SmallFee, Some(secondSponsorAssetId), Some(secondSponsorAssetId)).id - nodes.waitForHeightArise() - nodes.waitForTransaction(firstTransferTxCustomFeeAlice) - nodes.waitForTransaction(secondTransferTxCustomFeeAlice) + nodes.waitForHeight( + Height( + Math.max( + nodes.waitForTransaction(firstTransferTxCustomFeeAlice).height, + nodes.waitForTransaction(secondTransferTxCustomFeeAlice).height + ) + 1 + ) + ) sender.assertAssetBalance(aliceAddress, firstSponsorAssetId, sponsorAssetTotal / 2 - SmallFee - 10 * Token) sender.assertAssetBalance(aliceAddress, secondSponsorAssetId, sponsorAssetTotal / 2 - SmallFee - 10 * Token) @@ -172,7 +172,7 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres val aliceTxs = sender.transactionsByAddress(aliceAddress, 100) aliceTxs.size shouldBe 5 // not 4, because there was one more transaction in IntegrationSuiteWithThreeAddresses class - aliceTxs.count(tx => tx.sender.contains(aliceAddress) || tx.recipient.contains(aliceAddress)) shouldBe 5 + aliceTxs.count(tx => tx.sender.contains(aliceAddress) || tx.recipient.contains(aliceAddress)) shouldBe 4 aliceTxs.map(_.id) should contain allElementsOf Seq( firstTransferTxToAlice, secondTransferTxToAlice, @@ -182,13 +182,13 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres val bobTxs = sender.transactionsByAddress(bobAddress, 100) bobTxs.size shouldBe 3 - bobTxs.count(tx => tx.sender.contains(bobAddress) || tx.recipient.contains(bobAddress)) shouldBe 3 + bobTxs.count(tx => tx.sender.contains(bobAddress) || tx.recipient.contains(bobAddress)) shouldBe 2 bobTxs.map(_.id) should contain allElementsOf Seq(firstTransferTxCustomFeeAlice, secondTransferTxCustomFeeAlice) } "check transactions by address" in { val minerTxs = sender.transactionsByAddress(miner.address, 100) - minerTxs.size shouldBe 4 + minerTxs.size shouldBe 2 val sponsorTxs = sender.transactionsByAddress(sponsorAddress, 100) // 1 x transfer in IntegrationSuiteWithThreeAddresses @@ -197,7 +197,7 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres // 2 x sponsor here: A-5, A-6 // 2 x transfers with sponsored assets here: A-7, A-8 sponsorTxs.size shouldBe 9 - sponsorTxs.count(tx => tx.sender.contains(sponsorAddress) || tx.recipient.contains(sponsorAddress)) shouldBe 7 // Without A-7, A-8 + sponsorTxs.count(tx => tx.sender.contains(sponsorAddress) || tx.recipient.contains(sponsorAddress)) shouldBe 6 // Without initial transfer, A-7, A-8 sponsorTxs.map(_.id) should contain allElementsOf Seq( firstSponsorAssetId, secondSponsorAssetId, @@ -437,7 +437,6 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres "Another1", "Created by Sponsorship Suite", sponsorAssetTotal, - decimals = 2, fee = issueFee, waitForTx = true ) @@ -449,8 +448,6 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres "Another2", "Created by Sponsorship Suite", sponsorAssetTotal, - decimals = 2, - reissuable = true, fee = issueFee, waitForTx = true ) @@ -516,7 +513,6 @@ class SponsorshipSuite extends BaseFreeSpec with IntegrationSuiteWithThreeAddres "Created by Sponsorship Suite", sponsorAssetTotal, decimals = 8, - reissuable = true, fee = issueFee, waitForTx = true ) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransactionsStatusSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransactionsStatusSuite.scala index 8fe8a64226c..40ac10537e9 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransactionsStatusSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransactionsStatusSuite.scala @@ -2,15 +2,13 @@ package com.wavesplatform.it.sync.transactions import com.wavesplatform.api.http.ApiError.InvalidIds import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.NTPTime import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.{TransactionInfo, TransactionStatus} import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{ProvenTransaction, Transaction} +import com.wavesplatform.transaction.{ProvenTransaction, Transaction, TxHelpers} import play.api.libs.json.* import scala.util.Random @@ -77,19 +75,17 @@ class TransactionsStatusSuite extends BaseTransactionSuite with NTPTime { private def mkTransactions: List[Transaction & ProvenTransaction] = (1001 to 1020).map { amount => - TransferTransaction - .selfSigned( - 2.toByte, - miner.keyPair, - secondKeyPair.toAddress, - Waves, - amount, - Waves, - minFee, - ByteStr.empty, - ntpTime.correctedTime() - ) - .explicitGet() + TxHelpers.transfer( + from = miner.keyPair, + to = secondKeyPair.toAddress, + amount = amount, + asset = Waves, + fee = minFee, + feeAsset = Waves, + attachment = ByteStr.empty, + timestamp = ntpTime.correctedTime(), + version = 2.toByte + ) }.toList private def waitForTransactions(txs: List[Transaction]): List[TransactionInfo] = diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransferNFTSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransferNFTSuite.scala index ec4339a9d5c..d9efc925c0c 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransferNFTSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransferNFTSuite.scala @@ -6,16 +6,16 @@ import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.it.NTPTime import com.wavesplatform.it.api.SyncHttpApi.* import com.wavesplatform.it.api.Transaction -import com.wavesplatform.it.sync.{calcMassTransferFee, setScriptFee, *} +import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.test.* -import com.wavesplatform.transaction.Asset -import com.wavesplatform.transaction.assets.exchange.{AssetPair, ExchangeTransaction, Order} +import com.wavesplatform.transaction.assets.exchange.{AssetPair, Order} import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer +import com.wavesplatform.transaction.{Asset, TxHelpers} class TransferNFTSuite extends BaseTransactionSuite with NTPTime { val assetName = "NFTAsset" @@ -179,20 +179,18 @@ class TransferNFTSuite extends BaseTransactionSuite with NTPTime { ) .explicitGet() - val tx = ExchangeTransaction - .signed( - 2.toByte, - matcher = matcher.privateKey, + val tx = TxHelpers + .exchange( + version = 2.toByte, + matcher = matcher, order1 = buy, order2 = sell, - amount = 1, price = 1.waves, buyMatcherFee = matcherFee, sellMatcherFee = matcherFee, fee = matcherFee, timestamp = ts ) - .explicitGet() .json() sender.signedBroadcast(tx, waitForTx = true) diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransferTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransferTransactionSuite.scala index 41ff9b77e81..8599781db6f 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransferTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/TransferTransactionSuite.scala @@ -9,9 +9,10 @@ import com.wavesplatform.it.sync.* import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.Waves +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.transfer.* import com.wavesplatform.transaction.transfer.TransferTransaction.MaxAttachmentSize -import com.wavesplatform.transaction.{Proofs, TxPositiveAmount, TxVersion, TransactionSignOps} +import com.wavesplatform.transaction.{Proofs, TxPositiveAmount, TxVersion} import org.scalatest.CancelAfterFailure import play.api.libs.json.Json @@ -20,9 +21,7 @@ import scala.concurrent.duration.* class TransferTransactionSuite extends BaseTransactionSuite with CancelAfterFailure { test("transfer with empty string assetId") { - val tx = TransferTransaction - .selfSigned(2.toByte, sender.keyPair, sender.keyPair.toAddress, Waves, 100L, Waves, minFee, ByteStr.empty, System.currentTimeMillis()) - .explicitGet() + val tx = TxHelpers.transfer(from = sender.keyPair, to = sender.keyPair.toAddress, amount = 100L, asset = Waves, fee = minFee, feeAsset = Waves, attachment = ByteStr.empty, version = 2.toByte) val json = tx.json() ++ Json.obj("assetId" -> "", "feeAssetId" -> "") sender.signedBroadcast(json, waitForTx = true) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/UpdateAssetInfoTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/UpdateAssetInfoTransactionSuite.scala index e2c411d463e..5ec4952d032 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/UpdateAssetInfoTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/UpdateAssetInfoTransactionSuite.scala @@ -15,6 +15,7 @@ import com.wavesplatform.lang.directives.values.V4 import com.wavesplatform.lang.v1.compiler.{Terms, TestCompiler} import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.state.Height +import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.assets.IssueTransaction.{MaxAssetDescriptionLength, MaxAssetNameLength, MinAssetNameLength} import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.{TransactionType, TxVersion} @@ -118,9 +119,8 @@ class UpdateAssetInfoTransactionSuite extends BaseTransactionSuite with CancelAf UpdateAssetInfoRequest( TxVersion.V1, AddressScheme.current.chainId, - None, - Some(issuer.publicKey.toString), - assetId, + issuer.publicKey.toString, + IssuedAsset(ByteStr(new Array[Byte](32))), "test", "test", None, diff --git a/node-it/src/test/scala/com/wavesplatform/it/transactions/BaseTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/transactions/BaseTransactionSuite.scala index 6a15fd17ede..b9451e6cfeb 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/transactions/BaseTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/transactions/BaseTransactionSuite.scala @@ -3,7 +3,7 @@ package com.wavesplatform.it.transactions import com.wavesplatform.it.* import org.scalatest.* -trait BaseTransactionSuiteLike extends WaitForHeight2 with IntegrationSuiteWithThreeAddresses with BeforeAndAfterAll with NodesFromDocker { +trait BaseTransactionSuiteLike extends IntegrationSuiteWithThreeAddresses with NodesFromDocker { this: TestSuite & Nodes => } diff --git a/node-it/src/test/scala/com/wavesplatform/test/Signed.scala b/node-it/src/test/scala/com/wavesplatform/test/Signed.scala deleted file mode 100644 index a2a72993c53..00000000000 --- a/node-it/src/test/scala/com/wavesplatform/test/Signed.scala +++ /dev/null @@ -1,24 +0,0 @@ -package com.wavesplatform.test - -import com.wavesplatform.account.{AddressOrAlias, KeyPair} -import com.wavesplatform.common.utils.EitherExt2.* -import com.wavesplatform.lang.v1.compiler.Terms -import com.wavesplatform.transaction.smart.InvokeScriptTransaction -import com.wavesplatform.transaction.{Asset, Proofs, TxTimestamp, TransactionSignOps} - -object Signed { - def invokeScript( - version: Byte, - sender: KeyPair, - dApp: AddressOrAlias, - functionCall: Option[Terms.FUNCTION_CALL], - payments: Seq[InvokeScriptTransaction.Payment], - fee: Long, - feeAssetId: Asset, - timestamp: TxTimestamp - ): InvokeScriptTransaction = - InvokeScriptTransaction - .create(version, sender.publicKey, dApp, functionCall, payments, fee, feeAssetId, timestamp, Proofs.empty, dApp.chainId) - .map(_.signWith(sender.privateKey)) - .explicitGet() -} diff --git a/node/src/main/resources/swagger-ui/openapi.yaml b/node/src/main/resources/swagger-ui/openapi.yaml index 2955e5c51c3..dcb20dd50a6 100644 --- a/node/src/main/resources/swagger-ui/openapi.yaml +++ b/node/src/main/resources/swagger-ui/openapi.yaml @@ -1333,6 +1333,22 @@ paths: examples: largeSignificandblockchainRewards: $ref: '#/components/examples/largeSignificandblockchainRewards' + '/blockchain/finality': + get: + tags: [blockchain] + summary: Finality info + description: Get finalized block, current and next generation periods, and miners committed to generating blocks in both current and next generation periods + operationId: getFinalityInfo + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/FinalityInfo' + application/json;large-significand-format=string: + schema: + $ref: '#/components/schemas/FinalityInfoLSF' '/transactions/status/{id}': get: tags: @@ -3457,6 +3473,10 @@ components: example: DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p Signature: type: string + AmountString: + type: string + pattern: '[0-9]+' + example: 1200 Proof: type: string AssetId: @@ -4504,6 +4524,60 @@ components: type: string xtnBuybackAddress: type: string + GenerationPeriod: + type: object + required: [start, end] + properties: + start: + $ref: '#/components/schemas/Height' + end: + $ref: '#/components/schemas/Height' + FinalityInfoBase: + type: object + required: [ height, finalizedHeight, currentGenerationPeriod, nextGenerationPeriod, nextGenerators ] + properties: + height: + $ref: '#/components/schemas/Height' + finalizedHeight: + $ref: '#/components/schemas/Height' + currentGenerationPeriod: + $ref: '#/components/schemas/GenerationPeriod' + nextGenerationPeriod: + $ref: '#/components/schemas/GenerationPeriod' + nextGenerators: + type: array + items: + $ref: '#/components/schemas/NextGeneratorData' + FinalityInfo: + allOf: + - $ref: '#/components/schemas/FinalityInfoBase' + - type: object + required: [currentGenerators] + properties: + currentGenerators: + type: array + items: + $ref: '#/components/schemas/GeneratorData' + FinalityInfoLSF: + allOf: + - $ref: '#/components/schemas/FinalityInfoBase' + - type: object + required: [ currentGenerators ] + properties: + currentGenerators: + type: array + items: + $ref: '#/components/schemas/GeneratorDataLSF' + NextGeneratorData: + type: object + required: + - address + - transactionId + properties: + address: + $ref: '#/components/schemas/Address' + transactionId: + $ref: '#/components/schemas/TransactionId' GeneratorData: type: object required: @@ -4529,7 +4603,7 @@ components: address: $ref: '#/components/schemas/Address' balance: - type: string + $ref: '#/components/schemas/AmountString' transactionId: $ref: '#/components/schemas/TransactionId' conflictHeight: diff --git a/node/src/main/scala/com/wavesplatform/Application.scala b/node/src/main/scala/com/wavesplatform/Application.scala index 0674edfd3a7..4e1b87f6855 100644 --- a/node/src/main/scala/com/wavesplatform/Application.scala +++ b/node/src/main/scala/com/wavesplatform/Application.scala @@ -492,7 +492,8 @@ class Application(val actorSystem: ActorSystem, val settings: WavesSettings, con blockchainUpdater, routeTimeout ), - RewardApiRoute(blockchainUpdater) + RewardApiRoute(blockchainUpdater), + FinalityApiRoute(blockchainUpdater, extensionContext.blocksApi, extensionContext.generatorsApi) ) val httpService = CompositeHttpService(apiRoutes, settings.restAPISettings) diff --git a/node/src/main/scala/com/wavesplatform/api/common/AddressPortfolio.scala b/node/src/main/scala/com/wavesplatform/api/common/AddressPortfolio.scala index 6c5fa55a69c..7e3705e7a37 100644 --- a/node/src/main/scala/com/wavesplatform/api/common/AddressPortfolio.scala +++ b/node/src/main/scala/com/wavesplatform/api/common/AddressPortfolio.scala @@ -10,16 +10,13 @@ import com.wavesplatform.database.{AddressId, CurrentBalance, DBResource, Key, K import com.wavesplatform.state.{AssetDescription, StateSnapshot} import com.wavesplatform.transaction.Asset import com.wavesplatform.transaction.Asset.IssuedAsset -import com.wavesplatform.utils.ScorexLogging import java.nio.ByteBuffer import scala.collection.immutable.VectorMap import scala.collection.mutable.ArrayBuffer import scala.jdk.CollectionConverters.* -class NFTIterator(addressId: AddressId, maybeAfter: Option[IssuedAsset], resource: DBResource) - extends AbstractIterator[Seq[(IssuedAsset, Long)]] - with ScorexLogging { +class NFTIterator(addressId: AddressId, maybeAfter: Option[IssuedAsset], resource: DBResource) extends AbstractIterator[Seq[(IssuedAsset, Long)]] { private val prefixBytes: Array[Byte] = KeyTag.NftPossession.prefixBytes ++ addressId.toByteArray resource.withSafePrefixIterator { dbIterator => diff --git a/node/src/main/scala/com/wavesplatform/api/common/AddressTransactions.scala b/node/src/main/scala/com/wavesplatform/api/common/AddressTransactions.scala index eb0ca23360a..17996498f6d 100644 --- a/node/src/main/scala/com/wavesplatform/api/common/AddressTransactions.scala +++ b/node/src/main/scala/com/wavesplatform/api/common/AddressTransactions.scala @@ -154,7 +154,7 @@ object AddressTransactions { txs .dropWhile { case (_, txNum, _) => txNum >= maxTxNum } .foreach { case (tp, txNum, size) => - if (types.isEmpty || types(TransactionType(tp))) { + if (types.isEmpty || types(TransactionType.fromId(tp))) { keysBuffer.addOne(Keys.transactionAt(height, txNum, txHandle)) numsBuffer.addOne(txNum) sizesBuffer.addOne(size) @@ -162,7 +162,7 @@ object AddressTransactions { } } else { txs.foreach { case (tp, txNum, size) => - if (types.isEmpty || types(TransactionType(tp))) { + if (types.isEmpty || types(TransactionType.fromId(tp))) { keysBuffer.addOne(Keys.transactionAt(height, txNum, txHandle)) numsBuffer.addOne(txNum) sizesBuffer.addOne(size) diff --git a/node/src/main/scala/com/wavesplatform/api/common/CommonAccountsApi.scala b/node/src/main/scala/com/wavesplatform/api/common/CommonAccountsApi.scala index 7c8e2206212..fa8bfe59254 100644 --- a/node/src/main/scala/com/wavesplatform/api/common/CommonAccountsApi.scala +++ b/node/src/main/scala/com/wavesplatform/api/common/CommonAccountsApi.scala @@ -112,13 +112,15 @@ object CommonAccountsApi { .fold(Array.empty[DataEntry[?]])(_.filter { case (k, _) => pattern.forall(_.matcher(k).matches()) }.values.toArray.sortBy(_.key)) rdb.db.resourceObservable.flatMap { dbResource => - dbResource.get(Keys.addressId(address)).fold(Observable.fromIterable(entriesFromDiff)) { addressId => - Observable - .fromIterator( - Task(new AddressDataIterator(dbResource, addressId, entriesFromDiff, pattern).asScala) - ) - .filterNot(_.isEmpty) - } + dbResource + .get(Keys.addressId(address)) + .fold(Observable.fromIterable(entriesFromDiff)) { addressId => + Observable + .fromIterator( + Task(new AddressDataIterator(dbResource, addressId, entriesFromDiff, pattern).asScala) + ) + } + .filterNot(_.isEmpty) } } diff --git a/node/src/main/scala/com/wavesplatform/api/common/CommonTransactionsApi.scala b/node/src/main/scala/com/wavesplatform/api/common/CommonTransactionsApi.scala index f92f6dead0c..93b721f77a5 100644 --- a/node/src/main/scala/com/wavesplatform/api/common/CommonTransactionsApi.scala +++ b/node/src/main/scala/com/wavesplatform/api/common/CommonTransactionsApi.scala @@ -12,7 +12,7 @@ import com.wavesplatform.mining.BlockChallenger import com.wavesplatform.state.diffs.FeeValidation import com.wavesplatform.state.diffs.FeeValidation.FeeDetails import com.wavesplatform.state.{Blockchain, Height, StateSnapshot, TxMeta} -import com.wavesplatform.transaction.TransactionType.TransactionType +import com.wavesplatform.transaction.TransactionType import com.wavesplatform.transaction.smart.script.trace.TracedResult import com.wavesplatform.transaction.{Asset, CreateAliasTransaction, Transaction} import com.wavesplatform.utx.UtxPool diff --git a/node/src/main/scala/com/wavesplatform/api/http/DebugApiRoute.scala b/node/src/main/scala/com/wavesplatform/api/http/DebugApiRoute.scala index b4b97e8681e..29324cea042 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/DebugApiRoute.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/DebugApiRoute.scala @@ -197,7 +197,7 @@ case class DebugApiRoute( path("validate")(jsonPost[JsObject] { jsv => val startTime = System.nanoTime() - val parsedTransaction = TransactionFactory.fromSignedRequest(jsv) + val parsedTransaction = TransactionFactory.parseRequest(jsv) val tracedSnapshot = for { tx <- TracedResult(parsedTransaction) diff --git a/node/src/main/scala/com/wavesplatform/api/http/FinalityApiRoute.scala b/node/src/main/scala/com/wavesplatform/api/http/FinalityApiRoute.scala new file mode 100644 index 00000000000..cfd4598edeb --- /dev/null +++ b/node/src/main/scala/com/wavesplatform/api/http/FinalityApiRoute.scala @@ -0,0 +1,55 @@ +package com.wavesplatform.api.http + +import com.wavesplatform.api.common.CommonGeneratorsApi.GeneratorEntry +import com.wavesplatform.api.common.{CommonBlocksApi, CommonGeneratorsApi} +import com.wavesplatform.state.{Blockchain, GenerationPeriod, Height} +import org.apache.pekko.http.scaladsl.server.Route +import play.api.libs.json.* + +case class FinalityApiRoute(blockchain: Blockchain, blocksApi: CommonBlocksApi, generatorsApi: CommonGeneratorsApi) extends ApiRoute { + import FinalityApiRoute.given + + override def route: Route = pathPrefix("blockchain" / "finality") { + (get & pathEndOrSingleSlash) { + complete(finalityInfo) + } + } + + private def finalityInfo: JsObject = { + val currentHeight = Height(blockchain.height) + val currentPeriod = blockchain.generationPeriodOf(currentHeight) + Json.obj( + "height" -> currentHeight, + "finalizedHeight" -> blocksApi.currentFinalizedHeight, + "currentGenerationPeriod" -> currentPeriod, + "currentGenerators" -> generatorsApi.generators(currentHeight), + "nextGenerationPeriod" -> currentPeriod.map(_.next), + "nextGenerators" -> currentPeriod.fold(Seq.empty)(p => + generatorsApi + .generators(p.next.start) + .map(ge => + Json.obj( + "address" -> ge.address, + "transactionId" -> ge.commitTxnId + ) + ) + ) + ) + } +} + +object FinalityApiRoute { + given Writes[GenerationPeriod] = (gp: GenerationPeriod) => + Json.obj( + "start" -> gp.start, + "end" -> gp.end + ) + + given Writes[GeneratorEntry] = (ge: GeneratorEntry) => + Json.obj( + "address" -> ge.address, + "transactionId" -> ge.commitTxnId, + "balance" -> ge.balance, + "conflictHeight" -> ge.conflictHeight + ) +} diff --git a/node/src/main/scala/com/wavesplatform/api/http/TransactionsApiRoute.scala b/node/src/main/scala/com/wavesplatform/api/http/TransactionsApiRoute.scala index 83124c00444..6201e594546 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/TransactionsApiRoute.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/TransactionsApiRoute.scala @@ -187,16 +187,18 @@ case class TransactionsApiRoute( def sign: Route = (pathPrefix("sign") & withAuth) { pathEndOrSingleSlash(jsonPost[JsObject] { jsv => - mkTxFactory.parseRequestAndSign((jsv \ "sender").as[String], jsv) + TransactionFactory.parseRequestAndSign(jsv, wallet, None, blockchain.currentGenerationPeriod.map(_.next.start.toInt)) }) ~ signWithSigner } def signWithSigner: Route = path(AddrSegment) { address => - jsonPost[JsObject](mkTxFactory.parseRequestAndSign(address.toString, _)) + jsonPost[JsObject]( + TransactionFactory.parseRequestAndSign(_, wallet, Some(address.toString), blockchain.currentGenerationPeriod.map(_.next.start.toInt)) + ) } def signedBroadcast: Route = path("broadcast") { - broadcast[JsValue](TransactionFactory.fromSignedRequest) + broadcast[JsObject](jsv => TransactionFactory.parseRequest(jsv)) } def merkleProof: Route = path("merkleProof") { @@ -250,8 +252,6 @@ case class TransactionsApiRoute( .take(limitParam) .mapEval(txMetaEnriched(address, _)) } - - private def mkTxFactory = TransactionFactory(wallet, time, blockchain.currentGenerationPeriod) } object TransactionsApiRoute { diff --git a/node/src/main/scala/com/wavesplatform/api/http/package.scala b/node/src/main/scala/com/wavesplatform/api/http/package.scala index 08f2d922139..b67287c21a6 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/package.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/package.scala @@ -4,9 +4,6 @@ import cats.syntax.either.* import com.typesafe.scalalogging.Logger import com.wavesplatform.account.{Address, PublicKey} import com.wavesplatform.api.http.ApiError.{InvalidAssetId, InvalidBlockId, InvalidPublicKey, InvalidSignature, InvalidTransactionId, WrongJson} -import com.wavesplatform.api.http.requests.* -import com.wavesplatform.api.http.requests.DataRequest.* -import com.wavesplatform.api.http.requests.SponsorFeeRequest.* import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.Base58 import com.wavesplatform.crypto @@ -15,6 +12,7 @@ import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.TxValidationError.GenericError import monix.eval.Coeval import monix.execution.Scheduler +import org.apache.pekko import org.apache.pekko.http.scaladsl.marshalling.ToResponseMarshallable import org.apache.pekko.http.scaladsl.model.StatusCodes import org.apache.pekko.http.scaladsl.server.* @@ -59,8 +57,6 @@ package object http { def createTransaction(senderPk: String, jsv: JsObject)( txToResponse: Transaction => ToResponseMarshallable ): ToResponseMarshallable = { - val typeId = (jsv \ "type").as[Byte] - (jsv \ "version").validateOpt[Byte](using versionReads) match { case JsError(errors) => WrongJson(None, errors) case JsSuccess(value, _) => @@ -70,25 +66,7 @@ package object http { PublicKey .fromBase58String(senderPk) .flatMap { senderPk => - TransactionType(typeId) match { - case TransactionType.Transfer => txJson.as[TransferRequest].toTxFrom(senderPk) - case TransactionType.CreateAlias => txJson.as[CreateAliasRequest].toTxFrom(senderPk) - case TransactionType.Lease => txJson.as[LeaseRequest].toTxFrom(senderPk) - case TransactionType.LeaseCancel => txJson.as[LeaseCancelRequest].toTxFrom(senderPk) - case TransactionType.Exchange => txJson.as[ExchangeRequest].toTxFrom(senderPk) - case TransactionType.Issue => txJson.as[IssueRequest].toTxFrom(senderPk) - case TransactionType.Reissue => txJson.as[ReissueRequest].toTxFrom(senderPk) - case TransactionType.Burn => txJson.as[BurnRequest].toTxFrom(senderPk) - case TransactionType.MassTransfer => TransactionFactory.massTransferAsset(txJson.as[MassTransferRequest], senderPk) - case TransactionType.Data => TransactionFactory.data(txJson.as[DataRequest], senderPk) - case TransactionType.InvokeScript => TransactionFactory.invokeScript(txJson.as[InvokeScriptRequest], senderPk) - case TransactionType.SetScript => TransactionFactory.setScript(txJson.as[SetScriptRequest], senderPk) - case TransactionType.SetAssetScript => TransactionFactory.setAssetScript(txJson.as[SetAssetScriptRequest], senderPk) - case TransactionType.SponsorFee => TransactionFactory.sponsor(txJson.as[SponsorFeeRequest], senderPk) - case TransactionType.UpdateAssetInfo => txJson.as[UpdateAssetInfoRequest].toTxFrom(senderPk) - case TransactionType.InvokeExpression => TransactionFactory.invokeExpression(txJson.as[InvokeExpressionRequest], senderPk) - case other => throw new IllegalArgumentException(s"Unsupported transaction type: $other") - } + TransactionFactory.parseRequest(txJson ++ Json.obj("senderPublicKey" -> senderPk.toString)) } .fold(ApiError.fromValidationError, txToResponse) } @@ -97,7 +75,7 @@ package object http { def parseOrCreateTransaction(jsv: JsObject)( txToResponse: Transaction => ToResponseMarshallable ): ToResponseMarshallable = { - val result = TransactionFactory.fromSignedRequest(jsv) + val result = TransactionFactory.parseRequest(jsv) if (result.isRight) { result.fold(ApiError.fromValidationError, txToResponse) } else { diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/BurnRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/BurnRequest.scala index 1bcb6e386be..dc91fad47b2 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/BurnRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/BurnRequest.scala @@ -11,8 +11,7 @@ import play.api.libs.json.* case class BurnRequest( version: Option[Byte], - sender: Option[String], - senderPublicKey: Option[String], + senderPublicKey: String, asset: IssuedAsset, quantity: Long, fee: Long, @@ -20,12 +19,13 @@ case class BurnRequest( signature: Option[ByteStr], proofs: Option[Proofs] ) extends TxBroadcastRequest[BurnTransaction] { - def toTxFrom(sender: PublicKey): Either[ValidationError, BurnTransaction] = + def toTx: Either[ValidationError, BurnTransaction] = for { validProofs <- toProofs(signature, proofs) + validSender <- PublicKey.fromBase58String(senderPublicKey) tx <- BurnTransaction.create( version.getOrElse(defaultVersion), - sender, + validSender, asset, quantity, fee, @@ -37,10 +37,9 @@ case class BurnRequest( object BurnRequest { import com.wavesplatform.utils.byteStrFormat - implicit val jsonFormat: Format[BurnRequest] = Format( + given Format[BurnRequest] = Format( ((JsPath \ "version").readNullable[Byte] and - (JsPath \ "sender").readNullable[String] and - (JsPath \ "senderPublicKey").readNullable[String] and + (JsPath \ "senderPublicKey").read[String] and (JsPath \ "assetId").read[IssuedAsset] and (JsPath \ "amount").read[Long].orElse((JsPath \ "quantity").read[Long]) and (JsPath \ "fee").read[Long] and diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/CommitToGenerationRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/CommitToGenerationRequest.scala index 1075828151d..822be43c85b 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/CommitToGenerationRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/CommitToGenerationRequest.scala @@ -2,7 +2,7 @@ package com.wavesplatform.api.http.requests import com.wavesplatform.account.* import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.crypto.bls.{BlsKeyPair, BlsPublicKey, BlsSignature} +import com.wavesplatform.crypto.bls.{BlsPublicKey, BlsSignature} import com.wavesplatform.lang.ValidationError import com.wavesplatform.state.Height import com.wavesplatform.state.diffs.FeeValidation.{FeeConstants, FeeUnit} @@ -10,78 +10,36 @@ import com.wavesplatform.transaction.{CommitToGenerationTransaction, Proofs, Tra import play.api.libs.json.* object CommitToGenerationRequest { - given OFormat[CommitToGenerationRequest] = Json.format - given OFormat[SignedCommitToGenerationRequest] = Json.format + given OFormat[CommitToGenerationRequest] = Json.format } -/** @param sender Address - */ case class CommitToGenerationRequest( version: Option[TxVersion] = None, - sender: Option[String], - endorserPublicKey: Option[ByteStr] = None, - generationPeriodStart: Option[Height] = None, + senderPublicKey: String, + endorserPublicKey: ByteStr, + generationPeriodStart: Height, timestamp: Option[Long] = None, fee: Option[Long] = None, - commitmentSignature: Option[ByteStr] = None, - chainId: Option[Byte] = None -) { - def toTxFrom( - senderPk: PublicKey, - defaultEndorserKp: => BlsKeyPair, - defaultGenerationPeriodStart: Height, - defaultTimestamp: => Long - ): Either[ValidationError, CommitToGenerationTransaction] = { - val exactGenerationPeriodStart = generationPeriodStart.getOrElse(defaultGenerationPeriodStart) + commitmentSignature: ByteStr, + chainId: Byte = AddressScheme.current.chainId, + proofs: Proofs = Proofs.empty +) extends TxBroadcastRequest[CommitToGenerationTransaction] { + def toTx: Either[ValidationError, CommitToGenerationTransaction] = { for { - commitmentSignature <- commitmentSignature match { - case Some(r) => BlsSignature(r) - case None => Right(CommitToGenerationTransaction.mkPopSignature(defaultEndorserKp, exactGenerationPeriodStart)) - } - endorserPublicKey <- endorserPublicKey match { - case Some(endorserPublicKey) => BlsPublicKey(endorserPublicKey) - case None => Right(defaultEndorserKp.publicKey) - } + blsSignature <- BlsSignature(commitmentSignature) + blsPk <- BlsPublicKey(endorserPublicKey) + senderPk <- PublicKey.fromBase58String(senderPublicKey) tx <- CommitToGenerationTransaction.create( version.getOrElse(1.toByte), - senderPk, // sender is address, we need a public key - endorserPublicKey, - exactGenerationPeriodStart, + senderPk, + blsPk, + generationPeriodStart, timestamp.getOrElse(defaultTimestamp), fee.getOrElse(FeeConstants(TransactionType.CommitToGeneration) * FeeUnit), - commitmentSignature, - Proofs.empty, - chainId.getOrElse(AddressScheme.current.chainId) + blsSignature, + proofs, + chainId ) } yield tx } } - -case class SignedCommitToGenerationRequest( - version: Option[TxVersion], - senderPublicKey: String, - endorserPublicKey: ByteStr, - generationPeriodStart: Int, - timestamp: Long, - fee: Long, - commitmentSignature: ByteStr, - proofs: Proofs -) { - def toTx: Either[ValidationError, CommitToGenerationTransaction] = - for { - _senderPk <- PublicKey.fromBase58String(senderPublicKey) - sig <- BlsSignature(commitmentSignature) - endorserPk <- BlsPublicKey(endorserPublicKey) - t <- CommitToGenerationTransaction.create( - version.getOrElse(1.toByte), - _senderPk, - endorserPk, - Height(generationPeriodStart), - timestamp, - fee, - sig, - proofs, - AddressScheme.current.chainId - ) - } yield t -} diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/CreateAliasRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/CreateAliasRequest.scala index 828a5c65825..19ab467775d 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/CreateAliasRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/CreateAliasRequest.scala @@ -1,6 +1,6 @@ package com.wavesplatform.api.http.requests -import com.wavesplatform.account.PublicKey +import com.wavesplatform.account.{AddressScheme, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.{CreateAliasTransaction, Proofs, TxTimestamp, TxVersion} @@ -8,21 +8,22 @@ import play.api.libs.json.{Format, Json} case class CreateAliasRequest( alias: String, - version: Option[TxVersion] = None, - sender: Option[String] = None, - senderPublicKey: Option[String] = None, + version: TxVersion = 1.toByte, + senderPublicKey: String, fee: Option[Long] = None, timestamp: Option[TxTimestamp] = None, signature: Option[ByteStr] = None, - proofs: Option[Proofs] = None + proofs: Option[Proofs] = None, + chainId: Byte = AddressScheme.current.chainId ) extends TxBroadcastRequest[CreateAliasTransaction] { - def toTxFrom(sender: PublicKey): Either[ValidationError, CreateAliasTransaction] = + def toTx: Either[ValidationError, CreateAliasTransaction] = for { validProofs <- toProofs(signature, proofs) - tx <- CreateAliasTransaction.create(version.getOrElse(1.toByte), sender, alias, fee.getOrElse(0L), timestamp.getOrElse(0L), validProofs) + validSender <- PublicKey.fromBase58String(senderPublicKey) + tx <- CreateAliasTransaction.create(version, validSender, alias, fee.getOrElse(0L), timestamp.getOrElse(0L), validProofs, chainId) } yield tx } object CreateAliasRequest { - implicit val jsonFormat: Format[CreateAliasRequest] = Json.format + given Format[CreateAliasRequest] = Json.format } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/DataRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/DataRequest.scala index 5ad3e6f66cb..e7f4377739b 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/DataRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/DataRequest.scala @@ -1,31 +1,31 @@ package com.wavesplatform.api.http.requests -import com.wavesplatform.account.PublicKey +import com.wavesplatform.account.{AddressScheme, PublicKey} +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.state.DataEntry import com.wavesplatform.transaction.{DataTransaction, Proofs} import play.api.libs.json.{Format, Json} -object DataRequest { - implicit val unsignedDataRequestReads: Format[DataRequest] = Json.format -} - case class DataRequest( version: Byte, - sender: String, + senderPublicKey: String, data: List[DataEntry[?]], fee: Long, - timestamp: Option[Long] = None -) - -case class SignedDataRequest(version: Byte, senderPublicKey: String, data: List[DataEntry[?]], fee: Long, timestamp: Long, proofs: Proofs) { + timestamp: Long, + proofs: Option[Proofs], + signature: Option[ByteStr], + chainId: Byte = AddressScheme.current.chainId +) extends TxBroadcastRequest[DataTransaction] { def toTx: Either[ValidationError, DataTransaction] = for { - _sender <- PublicKey.fromBase58String(senderPublicKey) - t <- DataTransaction.create(version, _sender, data, fee, timestamp, proofs) - } yield t + validProofs <- toProofs(signature, proofs) + validSender <- PublicKey.fromBase58String(senderPublicKey) + tx <- DataTransaction.create(version, validSender, data, fee, timestamp, validProofs, chainId) + } yield tx + } -object SignedDataRequest { - implicit val signedDataRequestReads: Format[SignedDataRequest] = Json.format +object DataRequest { + given Format[DataRequest] = Json.format } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/ExchangeRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/ExchangeRequest.scala index 470bdfe489a..4c9dc1ad165 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/ExchangeRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/ExchangeRequest.scala @@ -1,6 +1,5 @@ package com.wavesplatform.api.http.requests -import com.wavesplatform.account.PublicKey import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.assets.exchange.{ExchangeTransaction, Order} @@ -16,13 +15,12 @@ case class ExchangeRequest( sellMatcherFee: Long, version: Option[TxVersion] = None, sender: Option[String] = None, - senderPublicKey: Option[String] = None, fee: Option[Long] = None, timestamp: Option[TxTimestamp] = None, signature: Option[ByteStr] = None, proofs: Option[Proofs] = None ) extends TxBroadcastRequest[ExchangeTransaction] { - def toTxFrom(sender: PublicKey): Either[ValidationError, ExchangeTransaction] = + def toTx: Either[ValidationError, ExchangeTransaction] = for { validProofs <- toProofs(signature, proofs) tx <- ExchangeTransaction.create( @@ -41,5 +39,5 @@ case class ExchangeRequest( } object ExchangeRequest { - implicit val jsonFormat: Format[ExchangeRequest] = Json.format + given Format[ExchangeRequest] = Json.format } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/InvokeExpressionRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/InvokeExpressionRequest.scala index 24d9ba55551..b7edf1fc002 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/InvokeExpressionRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/InvokeExpressionRequest.scala @@ -10,15 +10,6 @@ import com.wavesplatform.transaction.smart.InvokeExpressionTransaction import play.api.libs.json.* case class InvokeExpressionRequest( - version: Option[Byte], - sender: String, - fee: Long, - feeAssetId: Option[String], - expression: String, - timestamp: Option[Long] = None -) - -case class SignedInvokeExpressionRequest( version: Option[Byte], senderPublicKey: String, fee: Long, @@ -26,7 +17,7 @@ case class SignedInvokeExpressionRequest( expression: String, timestamp: Long, proofs: Proofs -) { +) extends TxBroadcastRequest[InvokeExpressionTransaction] { def toTx: Either[ValidationError, InvokeExpressionTransaction] = for { _sender <- PublicKey.fromBase58String(senderPublicKey) @@ -48,6 +39,5 @@ case class SignedInvokeExpressionRequest( } object InvokeExpressionRequest { - implicit val unsignedInvokeExpressionRequestReads: Reads[InvokeExpressionRequest] = Json.reads[InvokeExpressionRequest] - implicit val signedInvokeExpressionRequestReads: Reads[SignedInvokeExpressionRequest] = Json.reads[SignedInvokeExpressionRequest] + given Reads[InvokeExpressionRequest] = Json.reads } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/InvokeScriptRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/InvokeScriptRequest.scala index 270ea7661cb..55c7c7118ad 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/InvokeScriptRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/InvokeScriptRequest.scala @@ -70,8 +70,7 @@ object InvokeScriptRequest { } yield FunctionCallPart(funcName, args) } - implicit val unsignedInvokeScriptRequestReads: Reads[InvokeScriptRequest] = Json.reads[InvokeScriptRequest] - implicit val signedInvokeScriptRequestReads: Reads[SignedInvokeScriptRequest] = Json.reads[SignedInvokeScriptRequest] + implicit val unsignedInvokeScriptRequestReads: Reads[InvokeScriptRequest] = Json.reads[InvokeScriptRequest] def buildFunctionCall(fc: FunctionCallPart): FUNCTION_CALL = FUNCTION_CALL(FunctionHeader.User(fc.function), fc.args) @@ -79,19 +78,7 @@ object InvokeScriptRequest { case class InvokeScriptRequest( chainId: Option[Byte], - version: Option[Byte], - sender: String, - fee: Long, - feeAssetId: Option[String], - call: Option[InvokeScriptRequest.FunctionCallPart], - payment: Seq[InvokeScriptTransaction.Payment], - dApp: String, - timestamp: Option[Long] = None -) - -case class SignedInvokeScriptRequest( - chainId: Option[Byte], - version: Option[Byte], + version: Byte = 2.toByte, senderPublicKey: String, fee: Long, feeAssetId: Option[Asset], @@ -99,14 +86,14 @@ case class SignedInvokeScriptRequest( call: Option[InvokeScriptRequest.FunctionCallPart], payment: Option[Seq[InvokeScriptTransaction.Payment]], timestamp: Long, - proofs: Proofs -) { + proofs: Proofs = Proofs.empty +) extends TxBroadcastRequest[InvokeScriptTransaction] { def toTx: Either[ValidationError, InvokeScriptTransaction] = for { - _sender <- PublicKey.fromBase58String(senderPublicKey) _dappAddress <- AddressOrAlias.fromString(dApp) + _sender <- PublicKey.fromBase58String(senderPublicKey) t <- InvokeScriptTransaction.create( - version.getOrElse(2.toByte), + version, _sender, _dappAddress, call.map(InvokeScriptRequest.buildFunctionCall).filterNot(_ == InvokeTransaction.DefaultCall), diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/IssueRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/IssueRequest.scala index b30e73e8c46..93a541b8934 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/IssueRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/IssueRequest.scala @@ -1,6 +1,6 @@ package com.wavesplatform.api.http.requests -import com.wavesplatform.account.PublicKey +import com.wavesplatform.account.{AddressScheme, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.script.Script @@ -9,9 +9,8 @@ import com.wavesplatform.transaction.{Proofs, TxVersion} import play.api.libs.json.{Format, Json} case class IssueRequest( - version: Option[Byte], - sender: Option[String], - senderPublicKey: Option[String], + version: Byte = TxVersion.V3, + senderPublicKey: String, name: String, description: String, quantity: Long, @@ -21,20 +20,20 @@ case class IssueRequest( fee: Long, timestamp: Option[Long], signature: Option[ByteStr], - proofs: Option[Proofs] + proofs: Option[Proofs], + chainId: Byte = AddressScheme.current.chainId ) extends TxBroadcastRequest[IssueTransaction] { - def toTxFrom(sender: PublicKey): Either[ValidationError, IssueTransaction] = { - val actualVersion = version.getOrElse(TxVersion.V3) - + def toTx: Either[ValidationError, IssueTransaction] = { for { validProofs <- toProofs(signature, proofs) + validSender <- PublicKey.fromBase58String(senderPublicKey) validScript <- script match { case None => Right(None) case Some(script) => Script.fromBase64String(script).map(Some(_)) } tx <- IssueTransaction.create( - actualVersion, - sender, + version, + validSender, name, description, quantity, @@ -43,12 +42,13 @@ case class IssueRequest( validScript, fee, timestamp.getOrElse(defaultTimestamp), - validProofs + validProofs, + chainId ) } yield tx } } object IssueRequest { - implicit val jsonFormat: Format[IssueRequest] = Json.format + given Format[IssueRequest] = Json.format } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/LeaseCancelRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/LeaseCancelRequest.scala index 1460858a0c0..855d3dcec4d 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/LeaseCancelRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/LeaseCancelRequest.scala @@ -1,6 +1,6 @@ package com.wavesplatform.api.http.requests -import com.wavesplatform.account.PublicKey +import com.wavesplatform.account.{AddressScheme, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.Proofs @@ -10,21 +10,22 @@ import play.api.libs.json.* case class LeaseCancelRequest( version: Option[Byte], - sender: Option[String], - senderPublicKey: Option[String], + senderPublicKey: String, leaseId: String, fee: Long, timestamp: Option[Long], signature: Option[ByteStr], - proofs: Option[Proofs] + proofs: Option[Proofs], + chainId: Byte ) extends TxBroadcastRequest[LeaseCancelTransaction] { - def toTxFrom(sender: PublicKey): Either[ValidationError, LeaseCancelTransaction] = + def toTx: Either[ValidationError, LeaseCancelTransaction] = for { validProofs <- toProofs(signature, proofs) validLeaseId <- parseBase58(leaseId, "invalid.leaseTx", DigestStringLength) + validSender <- PublicKey.fromBase58String(senderPublicKey) tx <- LeaseCancelTransaction.create( version.getOrElse(1.toByte), - sender, + validSender, validLeaseId, fee, timestamp.getOrElse(0L), @@ -35,15 +36,15 @@ case class LeaseCancelRequest( object LeaseCancelRequest { import com.wavesplatform.utils.byteStrFormat - implicit val jsonFormat: Format[LeaseCancelRequest] = Format( + given Format[LeaseCancelRequest] = Format( ((JsPath \ "version").readNullable[Byte] and - (JsPath \ "sender").readNullable[String] and - (JsPath \ "senderPublicKey").readNullable[String] and + (JsPath \ "senderPublicKey").read[String] and (JsPath \ "leaseId").read[String].orElse((JsPath \ "txId").read[String]) and (JsPath \ "fee").read[Long] and (JsPath \ "timestamp").readNullable[Long] and (JsPath \ "signature").readNullable[ByteStr] and - (JsPath \ "proofs").readNullable[Proofs])(LeaseCancelRequest.apply), + (JsPath \ "proofs").readNullable[Proofs] and + (JsPath \ "chainId").readWithDefault(AddressScheme.current.chainId))(LeaseCancelRequest.apply), Json.writes[LeaseCancelRequest] ) } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/LeaseRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/LeaseRequest.scala index ab78fcc201b..d8e737a81e8 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/LeaseRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/LeaseRequest.scala @@ -9,8 +9,7 @@ import play.api.libs.json.{Format, Json} case class LeaseRequest( version: Option[Byte], - sender: Option[String], - senderPublicKey: Option[String], + senderPublicKey: String, recipient: String, amount: Long, fee: Long, @@ -18,13 +17,14 @@ case class LeaseRequest( signature: Option[ByteStr], proofs: Option[Proofs] ) extends TxBroadcastRequest[LeaseTransaction] { - def toTxFrom(sender: PublicKey): Either[ValidationError, LeaseTransaction] = + def toTx: Either[ValidationError, LeaseTransaction] = for { validRecipient <- AddressOrAlias.fromString(recipient) validProofs <- toProofs(signature, proofs) + validSender <- PublicKey.fromBase58String(senderPublicKey) tx <- LeaseTransaction.create( version.getOrElse(1.toByte), - sender, + validSender, validRecipient, amount, fee, @@ -35,5 +35,5 @@ case class LeaseRequest( } object LeaseRequest { - implicit val jsonFormat: Format[LeaseRequest] = Json.format + given Format[LeaseRequest] = Json.format } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/MassTransferRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/MassTransferRequest.scala index 691016061db..ab0f63a8cc4 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/MassTransferRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/MassTransferRequest.scala @@ -1,19 +1,53 @@ package com.wavesplatform.api.http.requests +import com.wavesplatform.account.PublicKey import com.wavesplatform.common.state.ByteStr +import com.wavesplatform.lang.ValidationError +import com.wavesplatform.transaction.transfer.* import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer -import play.api.libs.json.{Json, OFormat} +import com.wavesplatform.transaction.{Asset, Proofs} +import play.api.libs.functional.syntax.* +import play.api.libs.json.* + +object MassTransferRequest { + given Format[MassTransferRequest] = Format( + ( + (JsPath \ "version").readNullable[Byte] and + (JsPath \ "senderPublicKey").read[String] and + (JsPath \ "assetId").readNullable[Asset] and + (JsPath \ "transfers").read[List[Transfer]] and + (JsPath \ "fee").read[Long] and + (JsPath \ "timestamp").read[Long] and + (JsPath \ "attachment").readWithDefault(ByteStr.empty) and + (JsPath \ "proofs").readWithDefault(Proofs.empty) + )(MassTransferRequest.apply), + Json.writes[MassTransferRequest].transform((jsobj: JsObject) => jsobj + ("type" -> JsNumber(MassTransferTransaction.typeId.toInt))) + ) +} case class MassTransferRequest( version: Option[Byte], - assetId: Option[String], - sender: String, + senderPublicKey: String, + assetId: Option[Asset], transfers: List[Transfer], fee: Long, - attachment: Option[ByteStr] = None, - timestamp: Option[Long] = None -) - -object MassTransferRequest { - implicit val jsonFormat: OFormat[MassTransferRequest] = Json.format[MassTransferRequest] + timestamp: Long, + attachment: ByteStr = ByteStr.empty, + proofs: Proofs +) extends TxBroadcastRequest[MassTransferTransaction] { + def toTx: Either[ValidationError, MassTransferTransaction] = + for { + _sender <- PublicKey.fromBase58String(senderPublicKey) + _transfers <- MassTransferTransaction.parseTransfersList(transfers) + t <- MassTransferTransaction.create( + version.getOrElse(1.toByte), + _sender, + assetId.getOrElse(Asset.Waves), + _transfers, + fee, + timestamp, + attachment, + proofs + ) + } yield t } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/ReissueRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/ReissueRequest.scala index 7869a0b7470..2c92177e3cc 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/ReissueRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/ReissueRequest.scala @@ -10,8 +10,7 @@ import play.api.libs.json.{Format, Json} case class ReissueRequest( version: Option[Byte], - sender: Option[String], - senderPublicKey: Option[String], + senderPublicKey: String, assetId: IssuedAsset, quantity: Long, reissuable: Boolean, @@ -20,12 +19,13 @@ case class ReissueRequest( signature: Option[ByteStr], proofs: Option[Proofs] ) extends TxBroadcastRequest[ReissueTransaction] { - def toTxFrom(sender: PublicKey): Either[ValidationError, ReissueTransaction] = + def toTx: Either[ValidationError, ReissueTransaction] = for { validProofs <- toProofs(signature, proofs) + validSender <- PublicKey.fromBase58String(senderPublicKey) tx <- ReissueTransaction.create( version.getOrElse(defaultVersion), - sender, + validSender, assetId, quantity, reissuable, @@ -37,5 +37,5 @@ case class ReissueRequest( } object ReissueRequest { - implicit val jsonFormat: Format[ReissueRequest] = Json.format + given Format[ReissueRequest] = Json.format } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/SetAssetScriptRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/SetAssetScriptRequest.scala index 6461206f4f4..4e732c48a4f 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/SetAssetScriptRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/SetAssetScriptRequest.scala @@ -1,20 +1,42 @@ package com.wavesplatform.api.http.requests +import com.wavesplatform.account.PublicKey +import com.wavesplatform.lang.ValidationError +import com.wavesplatform.lang.script.Script +import com.wavesplatform.transaction.Asset.IssuedAsset +import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.assets.SetAssetScriptTransaction -import play.api.libs.json.{Format, JsNumber, JsObject, Json} +import play.api.libs.functional.syntax.* +import play.api.libs.json.{JsPath, Reads} + +object SetAssetScriptRequest { + given Reads[SetAssetScriptRequest] = ( + (JsPath \ "version").readNullable[Byte] and + (JsPath \ "senderPublicKey").read[String] and + (JsPath \ "assetId").read[IssuedAsset] and + (JsPath \ "script").readNullable[String] and + (JsPath \ "fee").read[Long] and + (JsPath \ "timestamp").read[Long] and + (JsPath \ "proofs").read[Proofs] + )(SetAssetScriptRequest.apply) +} case class SetAssetScriptRequest( version: Option[Byte], - sender: String, - assetId: String, + senderPublicKey: String, + assetId: IssuedAsset, script: Option[String], fee: Long, - timestamp: Option[Long] = None -) {} - -object SetAssetScriptRequest { - implicit val jsonFormat: Format[SetAssetScriptRequest] = Json.format - implicit class SetAssetScriptRequestExt(val self: SetAssetScriptRequest) extends AnyVal { - def toJsObject: JsObject = Json.toJson(self).as[JsObject] + ("type" -> JsNumber(SetAssetScriptTransaction.typeId.toInt)) - } + timestamp: Long, + proofs: Proofs +) extends TxBroadcastRequest[SetAssetScriptTransaction] { + def toTx: Either[ValidationError, SetAssetScriptTransaction] = + for { + _sender <- PublicKey.fromBase58String(senderPublicKey) + _script <- script match { + case None | Some("") => Right(None) + case Some(s) => Script.fromBase64String(s).map(Some(_)) + } + t <- SetAssetScriptTransaction.create(version.getOrElse(1.toByte), _sender, assetId, _script, fee, timestamp, proofs) + } yield t } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/SetScriptRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/SetScriptRequest.scala index 7608b1cc759..609bae0f462 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/SetScriptRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/SetScriptRequest.scala @@ -1,13 +1,42 @@ package com.wavesplatform.api.http.requests +import com.wavesplatform.account.PublicKey +import com.wavesplatform.lang.ValidationError +import com.wavesplatform.lang.script.Script +import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.smart.SetScriptTransaction -import play.api.libs.json.{Format, JsNumber, JsObject, Json} - -case class SetScriptRequest(version: Option[Byte], sender: String, script: Option[String], fee: Long, timestamp: Option[Long] = None) {} +import play.api.libs.functional.syntax.* +import play.api.libs.json.* object SetScriptRequest { - implicit val jsonFormat: Format[SetScriptRequest] = Json.format - implicit class SetScriptRequestExt(val self: SetScriptRequest) extends AnyVal { - def toJsObject: JsObject = Json.toJson(self).as[JsObject] + ("type" -> JsNumber(SetScriptTransaction.typeId.toInt)) - } + given Reads[SetScriptRequest] = ( + (JsPath \ "version").readNullable[Byte] and + (JsPath \ "senderPublicKey").read[String] and + (JsPath \ "script").readNullable[String] and + (JsPath \ "fee").read[Long] and + (JsPath \ "timestamp").read[Long] and + (JsPath \ "proofs").readWithDefault(Proofs.empty) + )(SetScriptRequest.apply) + + implicit val signedSetScriptRequestWrites: OWrites[SetScriptRequest] = + Json.writes[SetScriptRequest].transform((request: JsObject) => request + ("version" -> JsNumber(1))) +} + +case class SetScriptRequest( + version: Option[Byte], + senderPublicKey: String, + script: Option[String], + fee: Long, + timestamp: Long, + proofs: Proofs +) extends TxBroadcastRequest[SetScriptTransaction] { + def toTx: Either[ValidationError, SetScriptTransaction] = + for { + _sender <- PublicKey.fromBase58String(senderPublicKey) + _script <- script match { + case None | Some("") => Right(None) + case Some(s) => Script.fromBase64String(s).map(Some(_)) + } + t <- SetScriptTransaction.create(version.getOrElse(1.toByte), _sender, _script, fee, timestamp, proofs) + } yield t } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/SignedMassTransferRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/SignedMassTransferRequest.scala deleted file mode 100644 index f7b21b70eab..00000000000 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/SignedMassTransferRequest.scala +++ /dev/null @@ -1,53 +0,0 @@ -package com.wavesplatform.api.http.requests - -import com.wavesplatform.account.PublicKey -import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.lang.ValidationError -import com.wavesplatform.transaction.{Asset, Proofs} -import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer -import com.wavesplatform.transaction.transfer.* -import play.api.libs.functional.syntax.* -import play.api.libs.json.* - -object SignedMassTransferRequest { - implicit val jsonFormat: Format[SignedMassTransferRequest] = Format( - ( - (JsPath \ "version").readNullable[Byte] and - (JsPath \ "senderPublicKey").read[String] and - (JsPath \ "assetId").readNullable[Asset] and - (JsPath \ "transfers").read[List[Transfer]] and - (JsPath \ "fee").read[Long] and - (JsPath \ "timestamp").read[Long] and - (JsPath \ "attachment").readWithDefault(ByteStr.empty) and - (JsPath \ "proofs").read[Proofs] - )(SignedMassTransferRequest.apply), - Json.writes[SignedMassTransferRequest].transform((jsobj: JsObject) => jsobj + ("type" -> JsNumber(MassTransferTransaction.typeId.toInt))) - ) -} - -case class SignedMassTransferRequest( - version: Option[Byte], - senderPublicKey: String, - assetId: Option[Asset], - transfers: List[Transfer], - fee: Long, - timestamp: Long, - attachment: ByteStr, - proofs: Proofs -) { - def toTx: Either[ValidationError, MassTransferTransaction] = - for { - _sender <- PublicKey.fromBase58String(senderPublicKey) - _transfers <- MassTransferTransaction.parseTransfersList(transfers) - t <- MassTransferTransaction.create( - version.getOrElse(1.toByte), - _sender, - assetId.getOrElse(Asset.Waves), - _transfers, - fee, - timestamp, - attachment, - proofs - ) - } yield t -} diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/SignedSetAssetScriptRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/SignedSetAssetScriptRequest.scala deleted file mode 100644 index 5bffcb620bd..00000000000 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/SignedSetAssetScriptRequest.scala +++ /dev/null @@ -1,42 +0,0 @@ -package com.wavesplatform.api.http.requests - -import com.wavesplatform.account.PublicKey -import com.wavesplatform.lang.ValidationError -import com.wavesplatform.lang.script.Script -import com.wavesplatform.transaction.Asset.IssuedAsset -import com.wavesplatform.transaction.Proofs -import com.wavesplatform.transaction.assets.SetAssetScriptTransaction -import play.api.libs.functional.syntax.* -import play.api.libs.json.{JsPath, Reads} - -object SignedSetAssetScriptRequest { - implicit val signedSetAssetScriptRequestReads: Reads[SignedSetAssetScriptRequest] = ( - (JsPath \ "version").readNullable[Byte] and - (JsPath \ "senderPublicKey").read[String] and - (JsPath \ "assetId").read[IssuedAsset] and - (JsPath \ "script").readNullable[String] and - (JsPath \ "fee").read[Long] and - (JsPath \ "timestamp").read[Long] and - (JsPath \ "proofs").read[Proofs] - )(SignedSetAssetScriptRequest.apply) -} - -case class SignedSetAssetScriptRequest( - version: Option[Byte], - senderPublicKey: String, - assetId: IssuedAsset, - script: Option[String], - fee: Long, - timestamp: Long, - proofs: Proofs -) { - def toTx: Either[ValidationError, SetAssetScriptTransaction] = - for { - _sender <- PublicKey.fromBase58String(senderPublicKey) - _script <- script match { - case None | Some("") => Right(None) - case Some(s) => Script.fromBase64String(s).map(Some(_)) - } - t <- SetAssetScriptTransaction.create(version.getOrElse(1.toByte), _sender, assetId, _script, fee, timestamp, proofs) - } yield t -} diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/SignedSetScriptRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/SignedSetScriptRequest.scala deleted file mode 100644 index d97238fc087..00000000000 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/SignedSetScriptRequest.scala +++ /dev/null @@ -1,42 +0,0 @@ -package com.wavesplatform.api.http.requests - -import com.wavesplatform.account.PublicKey -import com.wavesplatform.lang.ValidationError -import com.wavesplatform.lang.script.Script -import com.wavesplatform.transaction.Proofs -import com.wavesplatform.transaction.smart.SetScriptTransaction -import play.api.libs.functional.syntax.* -import play.api.libs.json.* - -object SignedSetScriptRequest { - implicit val signedSetScriptRequestReads: Reads[SignedSetScriptRequest] = ( - (JsPath \ "version").readNullable[Byte] and - (JsPath \ "senderPublicKey").read[String] and - (JsPath \ "script").readNullable[String] and - (JsPath \ "fee").read[Long] and - (JsPath \ "timestamp").read[Long] and - (JsPath \ "proofs").read[Proofs] - )(SignedSetScriptRequest.apply) - - implicit val signedSetScriptRequestWrites: OWrites[SignedSetScriptRequest] = - Json.writes[SignedSetScriptRequest].transform((request: JsObject) => request + ("version" -> JsNumber(1))) -} - -case class SignedSetScriptRequest( - version: Option[Byte], - senderPublicKey: String, - script: Option[String], - fee: Long, - timestamp: Long, - proofs: Proofs -) { - def toTx: Either[ValidationError, SetScriptTransaction] = - for { - _sender <- PublicKey.fromBase58String(senderPublicKey) - _script <- script match { - case None | Some("") => Right(None) - case Some(s) => Script.fromBase64String(s).map(Some(_)) - } - t <- SetScriptTransaction.create(version.getOrElse(1.toByte), _sender, _script, fee, timestamp, proofs) - } yield t -} diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/SignedUpdateAssetInfoRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/SignedUpdateAssetInfoRequest.scala deleted file mode 100644 index 76aa968c826..00000000000 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/SignedUpdateAssetInfoRequest.scala +++ /dev/null @@ -1,39 +0,0 @@ -package com.wavesplatform.api.http.requests - -import cats.instances.option.* -import cats.syntax.traverse.* -import com.wavesplatform.account.PublicKey -import com.wavesplatform.lang.ValidationError -import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.assets.UpdateAssetInfoTransaction -import com.wavesplatform.transaction.{AssetIdStringLength, Proofs, TxTimestamp, TxVersion} -import play.api.libs.json.{Format, Json} - -case class SignedUpdateAssetInfoRequest( - version: TxVersion, - chainId: Byte, - senderPublicKey: String, - assetId: IssuedAsset, - name: String, - description: String, - timestamp: TxTimestamp, - fee: Long, - feeAssetId: Option[String], - proofs: Proofs -) { - - def toTx: Either[ValidationError, UpdateAssetInfoTransaction] = - for { - _sender <- PublicKey.fromBase58String(senderPublicKey) - _feeAssetId <- feeAssetId - .traverse(parseBase58(_, "invalid.assetId", AssetIdStringLength).map(IssuedAsset(_))) - .map(_ getOrElse Waves) - tx <- UpdateAssetInfoTransaction - .create(version, _sender, assetId.id, name, description, timestamp, fee, _feeAssetId, proofs, chainId) - } yield tx - -} - -object SignedUpdateAssetInfoRequest { - implicit val format: Format[SignedUpdateAssetInfoRequest] = Json.format -} diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/SponsorFeeRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/SponsorFeeRequest.scala index 62104e7ff8f..fcc066f5f52 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/SponsorFeeRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/SponsorFeeRequest.scala @@ -1,38 +1,29 @@ package com.wavesplatform.api.http.requests -import com.wavesplatform.account.PublicKey +import com.wavesplatform.account.{AddressScheme, PublicKey} import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.Asset.IssuedAsset -import com.wavesplatform.transaction.assets.SponsorFeeTransaction import com.wavesplatform.transaction.Proofs +import com.wavesplatform.transaction.assets.SponsorFeeTransaction import play.api.libs.json.{Format, Json} object SponsorFeeRequest { - implicit val unsignedSponsorRequestFormat: Format[SponsorFeeRequest] = Json.format - implicit val signedSponsorRequestFormat: Format[SignedSponsorFeeRequest] = Json.format + given Format[SponsorFeeRequest] = Json.format } case class SponsorFeeRequest( - version: Option[Byte], - sender: String, - assetId: String, - minSponsoredAssetFee: Option[Long], - fee: Long, - timestamp: Option[Long] = None -) - -case class SignedSponsorFeeRequest( - version: Option[Byte], + version: Byte = 1.toByte, senderPublicKey: String, assetId: IssuedAsset, minSponsoredAssetFee: Option[Long], fee: Long, timestamp: Long, - proofs: Proofs -) { + proofs: Proofs = Proofs.empty, + chainId: Byte = AddressScheme.current.chainId +) extends TxBroadcastRequest[SponsorFeeTransaction] { def toTx: Either[ValidationError, SponsorFeeTransaction] = for { - _sender <- PublicKey.fromBase58String(senderPublicKey) - t <- SponsorFeeTransaction.create(version.getOrElse(1.toByte), _sender, assetId, minSponsoredAssetFee.filterNot(_ == 0), fee, timestamp, proofs) + validSender <- PublicKey.fromBase58String(senderPublicKey) + t <- SponsorFeeTransaction.create(version, validSender, assetId, minSponsoredAssetFee.filterNot(_ == 0), fee, timestamp, proofs, chainId) } yield t } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/TransferRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/TransferRequest.scala index 8e71299358c..3f2683d571a 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/TransferRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/TransferRequest.scala @@ -8,9 +8,8 @@ import com.wavesplatform.transaction.{Asset, Proofs} import play.api.libs.json.* case class TransferRequest( - version: Option[Byte], - sender: Option[String], - senderPublicKey: Option[String], + version: Byte = 1.toByte, + senderPublicKey: String, recipient: String, assetId: Option[Asset], amount: Long, @@ -21,13 +20,14 @@ case class TransferRequest( signature: Option[ByteStr] = None, proofs: Option[Proofs] = None ) extends TxBroadcastRequest[TransferTransaction] { - def toTxFrom(sender: PublicKey): Either[ValidationError, TransferTransaction] = + def toTx: Either[ValidationError, TransferTransaction] = for { validRecipient <- AddressOrAlias.fromString(recipient) validProofs <- toProofs(signature, proofs) + validSender <- PublicKey.fromBase58String(senderPublicKey) tx <- TransferTransaction.create( - version.getOrElse(1.toByte), - sender, + version, + validSender, validRecipient, assetId.getOrElse(Asset.Waves), amount, @@ -41,5 +41,5 @@ case class TransferRequest( } object TransferRequest { - implicit val jsonFormat: Format[TransferRequest] = Json.format + given Format[TransferRequest] = Json.format } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/TxBroadcastRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/TxBroadcastRequest.scala index 13bcbe1e528..3aca4c7de66 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/TxBroadcastRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/TxBroadcastRequest.scala @@ -1,22 +1,8 @@ package com.wavesplatform.api.http.requests -import com.wavesplatform.account.PublicKey import com.wavesplatform.lang.ValidationError -import com.wavesplatform.transaction.Transaction -import com.wavesplatform.transaction.TxValidationError.GenericError +import com.wavesplatform.transaction.{ProvenTransaction, Transaction} -trait TxBroadcastRequest[A <: Transaction] { - def sender: Option[String] - def senderPublicKey: Option[String] - - def toTxFrom(sender: PublicKey): Either[ValidationError, A] - - def toTx: Either[ValidationError, A] = - for { - sender <- senderPublicKey match { - case Some(key) => PublicKey.fromBase58String(key) - case None => Left(GenericError("invalid.senderPublicKey")) - } - tx <- toTxFrom(sender) - } yield tx +trait TxBroadcastRequest[+T <: Transaction & ProvenTransaction] { + def toTx: Either[ValidationError, T] } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/UpdateAssetInfoRequest.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/UpdateAssetInfoRequest.scala index 59e9774f0cb..0a22b0cc717 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/UpdateAssetInfoRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/UpdateAssetInfoRequest.scala @@ -12,9 +12,8 @@ import play.api.libs.json.{Json, OFormat} case class UpdateAssetInfoRequest( version: TxVersion, chainId: Byte, - sender: Option[String], - senderPublicKey: Option[String], - assetId: String, + senderPublicKey: String, + assetId: IssuedAsset, name: String, description: String, timestamp: Option[TxTimestamp], @@ -22,17 +21,17 @@ case class UpdateAssetInfoRequest( feeAssetId: Option[String], proofs: Option[Proofs] ) extends TxBroadcastRequest[UpdateAssetInfoTransaction] { - override def toTxFrom(sender: PublicKey): Either[ValidationError, UpdateAssetInfoTransaction] = + override def toTx: Either[ValidationError, UpdateAssetInfoTransaction] = for { - _assetId <- parseBase58(assetId, "invalid.assetId", AssetIdStringLength) _feeAssetId <- feeAssetId .traverse(parseBase58(_, "invalid.assetId", AssetIdStringLength).map(IssuedAsset(_))) .map(_ getOrElse Waves) + _sender <- PublicKey.fromBase58String(senderPublicKey) tx <- UpdateAssetInfoTransaction - .create(version, sender, _assetId, name, description, timestamp.getOrElse(0L), fee, _feeAssetId, proofs.getOrElse(Proofs.empty), chainId) + .create(version, _sender, assetId, name, description, timestamp.getOrElse(0L), fee, _feeAssetId, proofs.getOrElse(Proofs.empty), chainId) } yield tx } object UpdateAssetInfoRequest { - implicit val jsonFormat: OFormat[UpdateAssetInfoRequest] = Json.format[UpdateAssetInfoRequest] + given OFormat[UpdateAssetInfoRequest] = Json.format[UpdateAssetInfoRequest] } diff --git a/node/src/main/scala/com/wavesplatform/api/http/requests/package.scala b/node/src/main/scala/com/wavesplatform/api/http/requests/package.scala index 27727e48e12..89d62aa0df0 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/package.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/package.scala @@ -85,5 +85,5 @@ package object requests { implicit val byteStrFormat: Format[ByteStr] = com.wavesplatform.utils.byteStrFormat private[requests] def defaultVersion = TxVersion.V1 - private[requests] def defaultTimestamp = 0L + private[requests] def defaultTimestamp = System.currentTimeMillis() } diff --git a/node/src/main/scala/com/wavesplatform/api/http/utils/Evaluation.scala b/node/src/main/scala/com/wavesplatform/api/http/utils/Evaluation.scala index 59f9b6061cb..466f8cfac4c 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/utils/Evaluation.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/utils/Evaluation.scala @@ -15,7 +15,7 @@ import com.wavesplatform.lang.v1.evaluator.ContractEvaluator.Invocation import com.wavesplatform.state.diffs.FeeValidation.{FeeConstants, ScriptExtraFee} import com.wavesplatform.state.diffs.invoke.InvokeScriptTransactionLike import com.wavesplatform.state.{AccountScriptInfo, Blockchain} -import com.wavesplatform.transaction.TransactionType.{InvokeScript, TransactionType} +import com.wavesplatform.transaction.TransactionType.InvokeScript import com.wavesplatform.transaction.TxValidationError.GenericError import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.{Asset, TransactionType} diff --git a/node/src/main/scala/com/wavesplatform/features/api/FinalityStatus.scala b/node/src/main/scala/com/wavesplatform/features/api/FinalityStatus.scala new file mode 100644 index 00000000000..d97cc6a2d4b --- /dev/null +++ b/node/src/main/scala/com/wavesplatform/features/api/FinalityStatus.scala @@ -0,0 +1,33 @@ +package com.wavesplatform.features.api + +import com.wavesplatform.state.{GenerationPeriod, Height} +import play.api.libs.json.* +import play.api.libs.functional.syntax._ + +case class FinalityStatus( + height: Height, + finalizedHeight: Height, + currentGenerationPeriod: Option[GenerationPeriod], + nextGenerationPeriod: Option[GenerationPeriod] +) + +object FinalityStatus { + def parse(activationHeight: Option[Height]): Reads[FinalityStatus] = + Reads { json => + for { + height <- (json \ "height").validate[Height] + finalizedHeight <- (json \ "finalizedHeight").validate[Height] + currentGenerationPeriod <- readGenerationPeriod(activationHeight, json, "currentGenerationPeriod") + nextGenerationPeriod <- readGenerationPeriod(activationHeight, json, "nextGenerationPeriod") + } yield FinalityStatus(height, finalizedHeight, currentGenerationPeriod, nextGenerationPeriod) + + } + + private def readGenerationPeriod(activationHeight: Option[Height], json: JsValue, fieldName: String) = + activationHeight.fold(JsError())(h => (json \ fieldName).validateOpt[GenerationPeriod](using generationPeriodReads(h))) + + private def generationPeriodReads(activationHeight: Height): Reads[GenerationPeriod] = + ( + (__ \ "start").read[Height] and (__ \ "end").read[Height] + )((start, end) => GenerationPeriod(activationHeight, start, end - start)) +} diff --git a/node/src/main/scala/com/wavesplatform/protobuf/transaction/PBTransactions.scala b/node/src/main/scala/com/wavesplatform/protobuf/transaction/PBTransactions.scala index 56658695bcc..b81f1a470bd 100644 --- a/node/src/main/scala/com/wavesplatform/protobuf/transaction/PBTransactions.scala +++ b/node/src/main/scala/com/wavesplatform/protobuf/transaction/PBTransactions.scala @@ -316,7 +316,7 @@ object PBTransactions { UpdateAssetInfoTransaction.create( version.toByte, sender.toPublicKey, - assetId.toByteStr, + IssuedAsset(assetId.toByteStr), name, description, timestamp, diff --git a/node/src/main/scala/com/wavesplatform/settings/BlockchainSettings.scala b/node/src/main/scala/com/wavesplatform/settings/BlockchainSettings.scala index bf0869e0737..15c1bb51bd1 100644 --- a/node/src/main/scala/com/wavesplatform/settings/BlockchainSettings.scala +++ b/node/src/main/scala/com/wavesplatform/settings/BlockchainSettings.scala @@ -82,7 +82,7 @@ case class FunctionalitySettings( paymentsCheckHeight: Int = 0, unitsRegistryAddress: Option[String] = None, maxValidEndorsers: Int = 5, - generationPeriodLength: Int = 1001 + generationPeriodLength: Int = 1000 ) { val allowLeasedBalanceTransferUntilHeight: Int = blockVersion3AfterHeight val allowTemporaryNegativeUntil: Long = lastTimeBasedForkParameter diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/FeeValidation.scala b/node/src/main/scala/com/wavesplatform/state/diffs/FeeValidation.scala index 3dc43f7612d..3148c9acb71 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/FeeValidation.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/FeeValidation.scala @@ -24,7 +24,7 @@ object FeeValidation { val NFTMultiplier = 0.001 val BlockV5Multiplier = 0.001 - val FeeConstants: Map[TransactionType.TransactionType, Long] = Map( + val FeeConstants: Map[TransactionType, Long] = Map( TransactionType.Genesis -> 0, TransactionType.Payment -> 1, TransactionType.Issue -> 1000, @@ -62,7 +62,7 @@ object FeeValidation { } } - private def notEnoughFeeError(txType: TransactionType.TransactionType, feeDetails: FeeDetails, feeAmount: Long): ValidationError = { + private def notEnoughFeeError(txType: TransactionType, feeDetails: FeeDetails, feeAmount: Long): ValidationError = { val actualFee = s"$feeAmount in ${feeDetails.asset.fold("WAVES")(_.id.toString)}" val requiredFee = s"${feeDetails.minFeeInWaves} WAVES${feeDetails.asset.fold("")(id => s" or ${feeDetails.minFeeInAsset} ${id.id.toString}")}" diff --git a/node/src/main/scala/com/wavesplatform/transaction/CommitToGenerationTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/CommitToGenerationTransaction.scala index de123b9ea04..a9ec5b2ed16 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/CommitToGenerationTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/CommitToGenerationTransaction.scala @@ -1,6 +1,7 @@ package com.wavesplatform.transaction import com.wavesplatform.account.* +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto import com.wavesplatform.crypto.bls.{BlsKeyPair, BlsPublicKey, BlsSignature} import com.wavesplatform.lang.ValidationError @@ -27,6 +28,11 @@ final case class CommitToGenerationTransaction( with TxWithFee.InWaves with FastHashId with PBSince.V1 { + + override type T = CommitToGenerationTransaction + + override def addProof(proof: ByteStr): CommitToGenerationTransaction = copy(proofs = proofs.add(proof)) + override val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(PBTransactionSerializer.bodyBytes(this)) override val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(PBTransactionSerializer.bytes(this)) override val json: Coeval[JsObject] = diff --git a/node/src/main/scala/com/wavesplatform/transaction/CreateAliasTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/CreateAliasTransaction.scala index 17664d0e09d..35b04552d10 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/CreateAliasTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/CreateAliasTransaction.scala @@ -22,11 +22,14 @@ final case class CreateAliasTransaction( timestamp: TxTimestamp, proofs: Proofs, chainId: Byte -) extends Transaction(TransactionType.CreateAlias) - with SigProofsSwitch - with Versioned.ToV3 - with TxWithFee.InWaves - with PBSince.V3 { +) extends Transaction(TransactionType.CreateAlias), + ProvenTransaction, + HasSignature, + Versioned.ToV3, + TxWithFee.InWaves, + PBSince.V3 { + + type T = CreateAliasTransaction lazy val alias: Alias = Alias.createWithChainId(aliasName, chainId, Some(chainId)).explicitGet() @@ -34,6 +37,8 @@ final case class CreateAliasTransaction( override val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(CreateAliasTxSerializer.toBytes(this)) override val json: Coeval[JsObject] = Coeval.evalOnce(CreateAliasTxSerializer.toJson(this)) + override def addProof(proof: ByteStr): CreateAliasTransaction = copy(proofs = proofs.add(proof)) + override val id: Coeval[ByteStr] = Coeval.evalOnce { ByteStr(crypto.fastHash(version match { case TxVersion.V1 | TxVersion.V2 => Bytes.concat(Array(tpe.id.toByte), alias.bytes) @@ -49,9 +54,6 @@ object CreateAliasTransaction extends TransactionParser { implicit val validator: TxValidator[CreateAliasTransaction] = CreateAliasTxValidator - implicit def sign(tx: CreateAliasTransaction, privateKey: PrivateKey): CreateAliasTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - override def parseBytes(bytes: Array[TxVersion]): Try[CreateAliasTransaction] = CreateAliasTxSerializer.parseBytes(bytes) @@ -61,7 +63,7 @@ object CreateAliasTransaction extends TransactionParser { aliasName: String, fee: Long, timestamp: TxTimestamp, - proofs: Proofs, + proofs: Proofs = Proofs.empty, chainId: Byte = AddressScheme.current.chainId ): Either[ValidationError, TransactionT] = { for { @@ -69,25 +71,4 @@ object CreateAliasTransaction extends TransactionParser { tx <- CreateAliasTransaction(version, sender, aliasName, fee, timestamp, proofs, chainId).validatedEither } yield tx } - - def signed( - version: TxVersion, - sender: PublicKey, - alias: String, - fee: Long, - timestamp: TxTimestamp, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, TransactionT] = - create(version, sender, alias, fee, timestamp, Nil, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - aliasName: String, - fee: Long, - timestamp: TxTimestamp, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, TransactionT] = - signed(version, sender.publicKey, aliasName, fee, timestamp, sender.privateKey, chainId) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/DataTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/DataTransaction.scala index a8b60db756c..f2c0dc9c463 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/DataTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/DataTransaction.scala @@ -1,7 +1,7 @@ package com.wavesplatform.transaction -import com.wavesplatform.account.{AddressScheme, KeyPair, PrivateKey, PublicKey} -import com.wavesplatform.crypto +import com.wavesplatform.account.{AddressScheme, PublicKey} +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.protobuf.transaction.PBTransactions import com.wavesplatform.state.* @@ -27,6 +27,8 @@ case class DataTransaction( with TxWithFee.InWaves with FastHashId with PBSince.V2 { + override type T = DataTransaction + override def addProof(proof: ByteStr): DataTransaction = copy(proofs = this.proofs.add(proof)) override val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(DataTxSerializer.bodyBytes(this)) override val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(DataTxSerializer.toBytes(this)) @@ -47,9 +49,6 @@ object DataTransaction extends TransactionParser { implicit val validator: TxValidator[DataTransaction] = DataTxValidator - implicit def sign(tx: DataTransaction, privateKey: PrivateKey): DataTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - override def parseBytes(bytes: Array[TxVersion]): Try[DataTransaction] = DataTxSerializer.parseBytes(bytes) @@ -59,32 +58,11 @@ object DataTransaction extends TransactionParser { data: Seq[DataEntry[?]], fee: Long, timestamp: TxTimestamp, - proofs: Proofs, + proofs: Proofs = Proofs.empty, chainId: Byte = AddressScheme.current.chainId ): Either[ValidationError, DataTransaction] = for { fee <- TxPositiveAmount(fee)(TxValidationError.InsufficientFee) tx <- DataTransaction(version, sender, data, fee, timestamp, proofs, chainId).validatedEither } yield tx - - def signed( - version: TxVersion, - sender: PublicKey, - data: Seq[DataEntry[?]], - fee: Long, - timestamp: TxTimestamp, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, DataTransaction] = - create(version, sender, data, fee, timestamp, Proofs.empty, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - data: Seq[DataEntry[?]], - fee: Long, - timestamp: TxTimestamp, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, DataTransaction] = - signed(version, sender.publicKey, data, fee, timestamp, sender.privateKey, chainId) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/EthereumTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/EthereumTransaction.scala index 39bc2f15436..ff1fc3030c4 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/EthereumTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/EthereumTransaction.scala @@ -12,7 +12,7 @@ import com.wavesplatform.protobuf.transaction.PBTransactions import com.wavesplatform.state.Blockchain import com.wavesplatform.state.diffs.invoke.InvokeScriptTransactionLike import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.TransactionType.TransactionType +import com.wavesplatform.transaction.TransactionType import com.wavesplatform.transaction.TxValidationError.GenericError import com.wavesplatform.transaction.serialization.impl.BaseTxJson import com.wavesplatform.transaction.smart.InvokeScriptTransaction diff --git a/node/src/main/scala/com/wavesplatform/transaction/HasSignature.scala b/node/src/main/scala/com/wavesplatform/transaction/HasSignature.scala new file mode 100644 index 00000000000..bc22f2c5e80 --- /dev/null +++ b/node/src/main/scala/com/wavesplatform/transaction/HasSignature.scala @@ -0,0 +1,10 @@ +package com.wavesplatform.transaction + +import com.wavesplatform.common.state.ByteStr + +trait HasSignature { self: Proven & Versioned => + def usesLegacySignature: Boolean = + self.version == Transaction.V1 + + def signature: ByteStr = self.proofs.toSignature +} diff --git a/node/src/main/scala/com/wavesplatform/transaction/PaymentTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/PaymentTransaction.scala index 84f3cafeb19..afe2175329e 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/PaymentTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/PaymentTransaction.scala @@ -23,6 +23,8 @@ case class PaymentTransaction( ) extends Transaction(TransactionType.Payment) with ProvenTransaction with TxWithFee.InWaves { + override type T = PaymentTransaction + override def addProof(proof: ByteStr): PaymentTransaction = copy(signature = proof) val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(PaymentTxSerializer.bodyBytes(this)) diff --git a/node/src/main/scala/com/wavesplatform/transaction/Proofs.scala b/node/src/main/scala/com/wavesplatform/transaction/Proofs.scala index 73b30ec87f1..840dea8db21 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/Proofs.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/Proofs.scala @@ -16,6 +16,7 @@ case class Proofs(proofs: Seq[ByteStr]) { val base58: Coeval[Seq[String]] = Coeval.evalOnce(proofs.map(p => Base58.encode(p.arr))) def toSignature: ByteStr = proofs.headOption.getOrElse(ByteStr.empty) override def toString: String = s"Proofs(${proofs.mkString(", ")})" + def add(proof: ByteStr): Proofs = Proofs(proofs :+ proof) } object Proofs { diff --git a/node/src/main/scala/com/wavesplatform/transaction/ProvenTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/ProvenTransaction.scala index 0357e4e2b39..4d3bcc457c9 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/ProvenTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/ProvenTransaction.scala @@ -1,5 +1,16 @@ package com.wavesplatform.transaction +import com.wavesplatform.account.PrivateKey +import com.wavesplatform.common.state.ByteStr +import com.wavesplatform.crypto + trait ProvenTransaction extends Proven { this: Transaction => + type T <: Transaction + def addProof(proof: ByteStr): T +} +object ProvenTransaction { + extension (p: ProvenTransaction) { + def signWith(privateKey: PrivateKey): p.T = p.addProof(crypto.sign(privateKey, p.bodyBytes())) + } } diff --git a/node/src/main/scala/com/wavesplatform/transaction/SigProofsSwitch.scala b/node/src/main/scala/com/wavesplatform/transaction/SigProofsSwitch.scala deleted file mode 100644 index ddd20a1be53..00000000000 --- a/node/src/main/scala/com/wavesplatform/transaction/SigProofsSwitch.scala +++ /dev/null @@ -1,6 +0,0 @@ -package com.wavesplatform.transaction - -trait SigProofsSwitch extends ProvenTransaction { self: Transaction & Versioned => - def usesLegacySignature: Boolean = - self.version == Transaction.V1 -} diff --git a/node/src/main/scala/com/wavesplatform/transaction/Transaction.scala b/node/src/main/scala/com/wavesplatform/transaction/Transaction.scala index dc75953451b..ef712f38f29 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/Transaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/Transaction.scala @@ -13,7 +13,7 @@ trait TransactionBase { def chainId: Byte def id: Coeval[ByteStr] def checkedAssets: Seq[IssuedAsset] - val tpe: TransactionType.TransactionType + val tpe: TransactionType } object TransactionBase { @@ -24,7 +24,7 @@ object TransactionBase { } } -abstract class Transaction(val tpe: TransactionType.TransactionType, val checkedAssets: Seq[IssuedAsset] = Nil) extends TransactionBase { +abstract class Transaction(val tpe: TransactionType, val checkedAssets: Seq[IssuedAsset] = Nil) extends TransactionBase { def bytesSize: Int = bytes().length lazy val protoSize: Coeval[Int] = Coeval(PBTransactions.protobuf(this).serializedSize) val bodyBytes: Coeval[Array[Byte]] @@ -42,7 +42,7 @@ abstract class Transaction(val tpe: TransactionType.TransactionType, val checked } object Transaction { - type Type = TransactionType.TransactionType + type Type = TransactionType val V1: TxVersion = TxVersion.V1 val V2: TxVersion = TxVersion.V2 diff --git a/node/src/main/scala/com/wavesplatform/transaction/TransactionFactory.scala b/node/src/main/scala/com/wavesplatform/transaction/TransactionFactory.scala index 9e088b85f91..f42a35aa558 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/TransactionFactory.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/TransactionFactory.scala @@ -2,467 +2,99 @@ package com.wavesplatform.transaction import com.wavesplatform.account.* import com.wavesplatform.api.http.requests.* -import com.wavesplatform.api.http.requests.CommitToGenerationRequest.given -import com.wavesplatform.api.http.requests.DataRequest.* -import com.wavesplatform.api.http.requests.InvokeExpressionRequest.* -import com.wavesplatform.api.http.requests.SponsorFeeRequest.* -import com.wavesplatform.api.http.versionReads -import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto.bls.BlsKeyPair import com.wavesplatform.lang.ValidationError -import com.wavesplatform.lang.script.Script -import com.wavesplatform.lang.script.v1.ExprScript -import com.wavesplatform.state.GenerationPeriod -import com.wavesplatform.transaction.Asset.IssuedAsset +import com.wavesplatform.state.Height import com.wavesplatform.transaction.TxValidationError.* -import com.wavesplatform.transaction.assets.* -import com.wavesplatform.transaction.assets.exchange.* -import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} -import com.wavesplatform.transaction.smart.{InvokeExpressionTransaction, InvokeScriptTransaction, SetScriptTransaction} -import com.wavesplatform.transaction.transfer.* -import com.wavesplatform.utils.Time import com.wavesplatform.wallet.Wallet -import play.api.libs.json.{JsObject, JsValue} +import play.api.libs.json.* -class TransactionFactory(wallet: Wallet, time: Time, currentPeriod: Option[GenerationPeriod]) { - def transferAsset(request: TransferRequest): Either[ValidationError, TransferTransaction] = - for { - _ <- Either.cond(request.sender.nonEmpty, (), GenericError("invalid.sender")) - tx <- transferAsset(request, request.sender.get) - } yield tx - - def transferAsset(request: TransferRequest, signerAddress: String): Either[ValidationError, TransferTransaction] = - for { - _ <- Either.cond(request.sender.isDefined, (), GenericError("invalid.sender")) - sender <- wallet.findPrivateKey(request.sender.get) - tx <- request.copy(timestamp = request.timestamp.orElse(Some(time.getTimestamp()))).toTxFrom(sender.publicKey) - signer <- if (request.sender.get == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - signedTx = tx.signWith(signer.privateKey) - } yield signedTx - - def massTransferAsset(request: MassTransferRequest): Either[ValidationError, MassTransferTransaction] = - massTransferAsset(request, request.sender) - - def massTransferAsset(request: MassTransferRequest, signerAddress: String): Either[ValidationError, MassTransferTransaction] = - for { - sender <- wallet.findPrivateKey(request.sender) - signer <- if (request.sender == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - transfers <- MassTransferTransaction.parseTransfersList(request.transfers) - tx <- MassTransferTransaction.signed( - request.version.getOrElse(1.toByte), - sender.publicKey, - Asset.fromCompatId(request.assetId.map(s => ByteStr.decodeBase58(s).get)), - transfers, - request.fee, - request.timestamp.getOrElse(time.getTimestamp()), - request.attachment.getOrElse(ByteStr.empty), - signer.privateKey - ) - } yield tx - - def setScript(request: SetScriptRequest): Either[ValidationError, SetScriptTransaction] = setScript(request, request.sender) - - def setScript(request: SetScriptRequest, signerAddress: String): Either[ValidationError, SetScriptTransaction] = - for { - sender <- wallet.findPrivateKey(request.sender) - signer <- if (request.sender == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - script <- request.script match { - case None | Some("") => Right(None) - case Some(s) => Script.fromBase64String(s).map(Some(_)) - } - tx <- SetScriptTransaction.signed( - request.version.getOrElse(1.toByte), - sender.publicKey, - script, - request.fee, - request.timestamp.getOrElse(time.getTimestamp()), - signer.privateKey - ) - } yield tx - - def setAssetScript(request: SetAssetScriptRequest, signerAddress: String): Either[ValidationError, SetAssetScriptTransaction] = - for { - sender <- wallet.findPrivateKey(request.sender) - signer <- if (request.sender == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - script <- request.script match { - case None | Some("") => Right(None) - case Some(s) => Script.fromBase64String(s).map(Some(_)) - } - tx <- SetAssetScriptTransaction.signed( - request.version.getOrElse(1.toByte), - sender.publicKey, - IssuedAsset(ByteStr.decodeBase58(request.assetId).get), - script, - request.fee, - request.timestamp.getOrElse(time.getTimestamp()), - signer.privateKey - ) - } yield tx - - def lease(request: LeaseRequest): Either[ValidationError, LeaseTransaction] = - for { - _ <- Either.cond(request.sender.nonEmpty, (), GenericError("invalid.sender")) - tx <- lease(request, request.sender.get) - } yield tx - - def lease(request: LeaseRequest, signerAddress: String): Either[ValidationError, LeaseTransaction] = - for { - _ <- Either.cond(request.sender.isDefined, (), GenericError("invalid.sender")) - sender <- wallet.findPrivateKey(request.sender.get) - tx <- request.copy(timestamp = request.timestamp.orElse(Some(time.getTimestamp()))).toTxFrom(sender.publicKey) - signer <- if (request.sender.get == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - signedTx = tx.signWith(signer.privateKey) - } yield signedTx - - def leaseCancel(request: LeaseCancelRequest): Either[ValidationError, LeaseCancelTransaction] = - for { - _ <- Either.cond(request.sender.nonEmpty, (), GenericError("invalid.sender")) - tx <- leaseCancel(request, request.sender.get) - } yield tx - - def leaseCancel(request: LeaseCancelRequest, signerAddress: String): Either[ValidationError, LeaseCancelTransaction] = - for { - _ <- Either.cond(request.sender.isDefined, (), GenericError("invalid.sender")) - sender <- wallet.findPrivateKey(request.sender.get) - tx <- request.copy(timestamp = request.timestamp.orElse(Some(time.getTimestamp()))).toTxFrom(sender.publicKey) - signer <- if (request.sender.get == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - signedTx = tx.signWith(signer.privateKey) - } yield signedTx - - def createAlias(request: CreateAliasRequest): Either[ValidationError, CreateAliasTransaction] = - for { - _ <- Either.cond(request.sender.nonEmpty, (), GenericError("invalid.sender")) - tx <- createAlias(request, request.sender.get) - } yield tx - - def createAlias(request: CreateAliasRequest, signerAddress: String): Either[ValidationError, CreateAliasTransaction] = - for { - _ <- Either.cond(request.sender.isDefined, (), GenericError("invalid.sender")) - sender <- wallet.findPrivateKey(request.sender.get) - tx <- request.copy(timestamp = request.timestamp.orElse(Some(time.getTimestamp()))).toTxFrom(sender.publicKey) - signer <- if (request.sender.get == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - signedTx = tx.signWith(signer.privateKey) - } yield signedTx - - def exchange(request: ExchangeRequest): Either[ValidationError, ExchangeTransaction] = - for { - _ <- Either.cond(request.sender.nonEmpty, (), GenericError("invalid.sender")) - tx <- exchange(request, request.sender.get) - } yield tx - - def exchange(request: ExchangeRequest, signerAddress: String): Either[ValidationError, ExchangeTransaction] = - for { - _ <- Either.cond(request.sender.isDefined, (), GenericError("invalid.sender")) - sender <- wallet.findPrivateKey(request.sender.get) - tx <- request.copy(timestamp = request.timestamp.orElse(Some(time.getTimestamp()))).toTxFrom(sender.publicKey) - signer <- if (request.sender.get == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - signedTx = tx.signWith(signer.privateKey) - } yield signedTx - - def issue(request: IssueRequest): Either[ValidationError, IssueTransaction] = - for { - _ <- Either.cond(request.sender.nonEmpty, (), GenericError("invalid.sender")) - tx <- issue(request, request.sender.get) - } yield tx - - def issue(request: IssueRequest, signerAddress: String): Either[ValidationError, IssueTransaction] = - for { - _ <- Either.cond(request.sender.isDefined, (), GenericError("invalid.sender")) - sender <- wallet.findPrivateKey(request.sender.get) - tx <- request.copy(timestamp = request.timestamp.orElse(Some(time.getTimestamp()))).toTxFrom(sender.publicKey) - signer <- if (request.sender.get == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - signedTx = tx.signWith(signer.privateKey) - } yield signedTx - - def reissue(request: ReissueRequest): Either[ValidationError, ReissueTransaction] = - for { - _ <- Either.cond(request.sender.nonEmpty, (), GenericError("invalid.sender")) - tx <- reissue(request, request.sender.get) - } yield tx - - def reissue(request: ReissueRequest, signerAddress: String): Either[ValidationError, ReissueTransaction] = - for { - _ <- Either.cond(request.sender.isDefined, (), GenericError("invalid.sender")) - sender <- wallet.findPrivateKey(request.sender.get) - tx <- request.copy(timestamp = request.timestamp.orElse(Some(time.getTimestamp()))).toTxFrom(sender.publicKey) - signer <- if (request.sender.get == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - signedTx = tx.signWith(signer.privateKey) - } yield signedTx - - def burn(request: BurnRequest): Either[ValidationError, BurnTransaction] = - for { - _ <- Either.cond(request.sender.nonEmpty, (), GenericError("invalid.sender")) - tx <- burn(request, request.sender.get) - } yield tx - - def burn(request: BurnRequest, signerAddress: String): Either[ValidationError, BurnTransaction] = - for { - _ <- Either.cond(request.sender.isDefined, (), GenericError("invalid.sender")) - sender <- wallet.findPrivateKey(request.sender.get) - tx <- request.copy(timestamp = request.timestamp.orElse(Some(time.getTimestamp()))).toTxFrom(sender.publicKey) - signer <- if (request.sender.get == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - signedTx = tx.signWith(signer.privateKey) - } yield signedTx - - def data(request: DataRequest): Either[ValidationError, DataTransaction] = data(request, request.sender) - - def data(request: DataRequest, signerAddress: String): Either[ValidationError, DataTransaction] = - for { - sender <- wallet.findPrivateKey(request.sender) - signer <- if (request.sender == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - tx <- DataTransaction.signed( - request.version, - sender.publicKey, - request.data, - request.fee, - request.timestamp.getOrElse(time.getTimestamp()), - signer.privateKey - ) - } yield tx - - def invokeScript(request: InvokeScriptRequest): Either[ValidationError, InvokeScriptTransaction] = - invokeScript(request, request.sender) - - def invokeScript(request: InvokeScriptRequest, signerAddress: String): Either[ValidationError, InvokeScriptTransaction] = - for { - sender <- wallet.findPrivateKey(request.sender) - signer <- if (request.sender == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - contract <- AddressOrAlias.fromString(request.dApp) +object TransactionFactory { + def parseRequestAndSign(request: JsObject, signer: KeyPair, generationPeriodStart: => Option[Int]): Either[ValidationError, Transaction] = { + val overrides = Json.newBuilder + if (!request.keys.contains("senderPublicKey")) { + overrides += "senderPublicKey" -> signer.publicKey + } - tx <- InvokeScriptTransaction - .create( - request.version.getOrElse(1.toByte), - sender.publicKey, - contract, - request.call.map(fCallPart => InvokeScriptRequest.buildFunctionCall(fCallPart)), - request.payment, - request.fee, - Asset.fromCompatId(request.feeAssetId.map(s => ByteStr.decodeBase58(s).get)), - request.timestamp.getOrElse(time.getTimestamp()), - Proofs.empty, - request.chainId.getOrElse(AddressScheme.current.chainId) + val extendedRequest = if ((request \ "type").as[Int] == TransactionType.CommitToGeneration.id) { + for { + periodStart <- ((request \ "generationPeriodStart").asOpt[Int] orElse generationPeriodStart) + .toRight(GenericError("missing generation period start")) + } yield { + val endorserKP = BlsKeyPair(signer.privateKey) + overrides ++= Seq( + "commitmentSignature" -> CommitToGenerationTransaction.mkPopSignature(endorserKP, Height(periodStart)).base58, + "generationPeriodStart" -> periodStart, + "endorserPublicKey" -> endorserKP.publicKey.base58 ) - .map(_.signWith(signer.privateKey)) - } yield tx - - def sponsor(request: SponsorFeeRequest): Either[ValidationError, SponsorFeeTransaction] = sponsor(request, request.sender) - - def sponsor(request: SponsorFeeRequest, signerAddress: String): Either[ValidationError, SponsorFeeTransaction] = - for { - sender <- wallet.findPrivateKey(request.sender) - signer <- if (request.sender == signerAddress) Right(sender) else wallet.findPrivateKey(signerAddress) - assetId <- ByteStr - .decodeBase58(request.assetId) - .toEither - .map(IssuedAsset(_)) - .left - .map(_ => GenericError(s"Wrong Base58 string: ${request.assetId}")) - tx <- SponsorFeeTransaction.signed( - request.version.getOrElse(1.toByte), - sender.publicKey, - assetId, - request.minSponsoredAssetFee, - request.fee, - request.timestamp.getOrElse(time.getTimestamp()), - signer.privateKey - ) - } yield tx - - def updateAssetInfo(request: UpdateAssetInfoRequest, signerAddress: String): Either[ValidationError, UpdateAssetInfoTransaction] = - for { - sender <- request.sender match { - case Some(sender) => wallet.findPrivateKey(sender) - case None => Left(GenericError("invalid.sender")) + overrides.result() } - signer <- if (request.sender.contains(signerAddress)) Right(sender) else wallet.findPrivateKey(signerAddress) - tx <- request.copy(timestamp = request.timestamp.orElse(Some(time.getTimestamp()))).toTxFrom(sender.publicKey) - } yield { - tx.signWith(signer.privateKey) - } + } else Right(overrides.result()) - def commitToGeneration(request: CommitToGenerationRequest, signerAddress: String): Either[ValidationError, CommitToGenerationTransaction] = { for { - currentPeriod <- currentPeriod.toRight(ActivationError("DeterministicFinality is not yet activated")) - defaultPeriod = currentPeriod.next - sender <- request.sender match { - case Some(sender) => wallet.findPrivateKey(sender) - case None => Left(GenericError("invalid.sender")) - } - signer <- wallet.findPrivateKey(signerAddress) - tx <- request.toTxFrom(sender.publicKey, BlsKeyPair(signer.privateKey), defaultPeriod.start, time.getTimestamp()) + req <- extendedRequest + tx <- parseRequest(req ++ request) } yield tx.signWith(signer.privateKey) } - def parseRequestAndSign(signerAddress: String, jsv: JsObject): Either[ValidationError, Transaction] = { - import play.api.libs.json.* - - val typeId = (jsv \ "type").as[Byte] - (jsv \ "version").validateOpt[Byte](using versionReads) match { - case JsError(errors) => - Left(GenericError(s"Wrong JSON: ${errors.mkString(", ")}")) - case JsSuccess(value, _) => - val version = value getOrElse (1: Byte) - val txJson = jsv ++ Json.obj("version" -> version) - - try { - (TransactionType(typeId): @unchecked) match { - case TransactionType.Transfer => transferAsset(txJson.as[TransferRequest], signerAddress) - case TransactionType.CreateAlias => createAlias(txJson.as[CreateAliasRequest], signerAddress) - case TransactionType.Lease => lease(txJson.as[LeaseRequest], signerAddress) - case TransactionType.LeaseCancel => leaseCancel(txJson.as[LeaseCancelRequest], signerAddress) - case TransactionType.Issue => issue(txJson.as[IssueRequest], signerAddress) - case TransactionType.Reissue => reissue(txJson.as[ReissueRequest], signerAddress) - case TransactionType.Burn => burn(txJson.as[BurnRequest], signerAddress) - case TransactionType.MassTransfer => massTransferAsset(txJson.as[MassTransferRequest], signerAddress) - case TransactionType.Data => data(txJson.as[DataRequest], signerAddress) - case TransactionType.InvokeScript => invokeScript(txJson.as[InvokeScriptRequest], signerAddress) - case TransactionType.SetScript => setScript(txJson.as[SetScriptRequest], signerAddress) - case TransactionType.SetAssetScript => setAssetScript(txJson.as[SetAssetScriptRequest], signerAddress) - case TransactionType.SponsorFee => sponsor(txJson.as[SponsorFeeRequest], signerAddress) - case TransactionType.UpdateAssetInfo => updateAssetInfo(txJson.as[UpdateAssetInfoRequest], signerAddress) - case TransactionType.CommitToGeneration => commitToGeneration(txJson.as[CommitToGenerationRequest], signerAddress) - } - } catch { - case _: NoSuchElementException => Left(UnsupportedTypeAndVersion(typeId, version)) - case _: MatchError => Left(UnsupportedTransactionType) - } - } - } -} - -object TransactionFactory { - def massTransferAsset(request: MassTransferRequest, sender: PublicKey): Either[ValidationError, MassTransferTransaction] = - for { - transfers <- MassTransferTransaction.parseTransfersList(request.transfers) - tx <- MassTransferTransaction.create( - request.version.getOrElse(1.toByte), - sender, - Asset.fromCompatId(request.assetId.map(s => ByteStr.decodeBase58(s).get)), - transfers, - request.fee, - 0, - request.attachment.getOrElse(ByteStr.empty), - Proofs.empty - ) - } yield tx - - def setScript(request: SetScriptRequest, sender: PublicKey): Either[ValidationError, SetScriptTransaction] = - for { - script <- request.script match { - case None | Some("") => Right(None) - case Some(s) => Script.fromBase64String(s).map(Some(_)) - } - tx <- SetScriptTransaction.create(request.version.getOrElse(1.toByte), sender, script, request.fee, 0, Proofs.empty) - } yield tx - - def setAssetScript(request: SetAssetScriptRequest, sender: PublicKey): Either[ValidationError, SetAssetScriptTransaction] = - for { - script <- request.script match { - case None | Some("") => Right(None) - case Some(s) => Script.fromBase64String(s).map(Some(_)) + def parseRequestAndSign( + request: JsObject, + wallet: Wallet, + signer: Option[String | KeyPair], + generationPeriodStart: => Option[Int] + ): Either[ValidationError, Transaction] = + signer + .fold((request \ "sender").asOpt[String].toRight(GenericError("invalid.sender")).flatMap(wallet.findPrivateKey)) { + case signerAddress: String => wallet.findPrivateKey(signerAddress) + case signerKP: KeyPair => Right(signerKP) } - tx <- SetAssetScriptTransaction.create( - request.version.getOrElse(1.toByte), - sender, - IssuedAsset(ByteStr.decodeBase58(request.assetId).get), - script, - request.fee, - request.timestamp.getOrElse(0), - Proofs.empty - ) - } yield tx - - def data(request: DataRequest, sender: PublicKey): Either[ValidationError, DataTransaction] = - DataTransaction.create(request.version, sender, request.data, request.fee, request.timestamp.getOrElse(0), Proofs.empty) - - def invokeScript(request: InvokeScriptRequest, sender: PublicKey): Either[ValidationError, InvokeScriptTransaction] = - for { - addressOrAlias <- AddressOrAlias.fromString(request.dApp) - fcOpt = request.call.map(fCallPart => InvokeScriptRequest.buildFunctionCall(fCallPart)) - tx <- InvokeScriptTransaction.create( - request.version.getOrElse(1.toByte), - sender, - addressOrAlias, - fcOpt, - request.payment, - request.fee, - Asset.fromCompatId(request.feeAssetId.map(s => ByteStr.decodeBase58(s).get)), - request.timestamp.getOrElse(0), - Proofs.empty, - request.chainId.getOrElse(AddressScheme.current.chainId) - ) - - } yield tx + .flatMap(signer => parseRequestAndSign(request, signer, generationPeriodStart)) - def invokeExpression(request: InvokeExpressionRequest, sender: PublicKey): Either[ValidationError, InvokeExpressionTransaction] = - for { - expression <- Script.fromBase64String(request.expression).flatMap { - case e: ExprScript => Right(e) - case _ => Left(GenericError("Unexpected expression type for InvokeExpression")) - } - tx <- InvokeExpressionTransaction.create( - request.version.getOrElse(1.toByte), - sender, - expression, - request.fee, - Asset.fromCompatId(request.feeAssetId.map(s => ByteStr.decodeBase58(s).get)), - request.timestamp.getOrElse(0), - Proofs.empty - ) - } yield tx + def parseRequest(request: JsObject): Either[ValidationError, Transaction & ProvenTransaction] = { + val overrides = Json.newBuilder + if (!request.keys.contains("timestamp")) { + overrides += "timestamp" -> System.currentTimeMillis() + } + if (!request.keys.contains("version")) { + overrides += "version" -> 1 + } - def sponsor(request: SponsorFeeRequest, sender: PublicKey): Either[ValidationError, SponsorFeeTransaction] = - for { - assetId <- ByteStr - .decodeBase58(request.assetId) - .toEither - .map(IssuedAsset(_)) - .left - .map(_ => GenericError(s"Wrong Base58 string: ${request.assetId}")) - tx <- SponsorFeeTransaction.create( - request.version.getOrElse(1.toByte), - sender, - assetId, - request.minSponsoredAssetFee, - request.fee, - request.timestamp.getOrElse(0), - Proofs.empty - ) - } yield tx + val jsv = overrides.result() ++ request - def fromSignedRequest(jsv: JsValue): Either[ValidationError, Transaction] = { - import InvokeScriptRequest.* - val chainId = (jsv \ "chainId").asOpt[Byte] val typeId = (jsv \ "type").as[Byte] - val version = (jsv \ "version").asOpt[Byte](using versionReads).getOrElse(1.toByte) + val version = (jsv \ "version").as[Byte] + + try { + import TransactionType.* + import cats.syntax.either.* + val req = TransactionType.fromId(typeId) match { + case Transfer => jsv.as[TransferRequest].asRight + case CreateAlias => jsv.as[CreateAliasRequest].asRight + case Lease => jsv.as[LeaseRequest].asRight + case LeaseCancel => jsv.as[LeaseCancelRequest].asRight + case Issue => jsv.as[IssueRequest].asRight + case Reissue => jsv.as[ReissueRequest].asRight + case Burn => jsv.as[BurnRequest].asRight + case MassTransfer => jsv.as[MassTransferRequest].asRight + case Data => jsv.as[DataRequest].asRight + case InvokeScript => jsv.as[InvokeScriptRequest].asRight + case SetScript => jsv.as[SetScriptRequest].asRight + case SetAssetScript => jsv.as[SetAssetScriptRequest].asRight + case SponsorFee => jsv.as[SponsorFeeRequest].asRight + case UpdateAssetInfo => jsv.as[UpdateAssetInfoRequest].asRight + case CommitToGeneration => jsv.as[CommitToGenerationRequest].asRight + case Exchange => jsv.as[ExchangeRequest].asRight + case InvokeExpression => jsv.as[InvokeExpressionRequest].asRight + case Genesis | Payment | Ethereum | InvokeExpression => + UnsupportedTransactionType.asLeft[TxBroadcastRequest[Transaction & ProvenTransaction]] + } - val pf: PartialFunction[TransactionType.TransactionType, Either[ValidationError, Transaction]] = { - case TransactionType.Transfer => jsv.as[TransferRequest].toTx - case TransactionType.CreateAlias => jsv.as[CreateAliasRequest].toTx - case TransactionType.Lease => jsv.as[LeaseRequest].toTx - case TransactionType.LeaseCancel => jsv.as[LeaseCancelRequest].toTx - case TransactionType.Issue => jsv.as[IssueRequest].toTx - case TransactionType.Reissue => jsv.as[ReissueRequest].toTx - case TransactionType.Burn => jsv.as[BurnRequest].toTx - case TransactionType.MassTransfer => jsv.as[SignedMassTransferRequest].toTx - case TransactionType.Data => jsv.as[SignedDataRequest].toTx - case TransactionType.InvokeScript => jsv.as[SignedInvokeScriptRequest].toTx - case TransactionType.SetScript => jsv.as[SignedSetScriptRequest].toTx - case TransactionType.SetAssetScript => jsv.as[SignedSetAssetScriptRequest].toTx - case TransactionType.SponsorFee => jsv.as[SignedSponsorFeeRequest].toTx - case TransactionType.Exchange => jsv.as[ExchangeRequest].toTx - case TransactionType.UpdateAssetInfo => jsv.as[SignedUpdateAssetInfoRequest].toTx - case TransactionType.InvokeExpression => jsv.as[SignedInvokeExpressionRequest].toTx - case TransactionType.CommitToGeneration => jsv.as[SignedCommitToGenerationRequest].toTx + for { + r <- req + tx <- r.toTx + } yield tx + } catch { + case _: MatchError | _: NoSuchElementException => Left(UnsupportedTypeAndVersion(typeId, version)) } - - if (chainId.exists(_ != AddressScheme.current.chainId)) { - Left(WrongChain(AddressScheme.current.chainId, chainId.get)) - } else - try pf(TransactionType(typeId)) - catch { - case _: NoSuchElementException => Left(UnsupportedTypeAndVersion(typeId, version)) - case _: MatchError => Left(UnsupportedTransactionType) - } } } diff --git a/node/src/main/scala/com/wavesplatform/transaction/TransactionType.scala b/node/src/main/scala/com/wavesplatform/transaction/TransactionType.scala index 17235bdb813..41fa85de7e6 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/TransactionType.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/TransactionType.scala @@ -1,13 +1,14 @@ package com.wavesplatform.transaction -object TransactionType extends Enumeration(1) { - type TransactionType = Value +enum TransactionType { + def id: Int = ordinal + 1 + def transactionName: String = s"${this.toString}Transaction" - // Add new transactions before InvokeExpression - val Genesis, Payment, Issue, Transfer, Reissue, Burn, Exchange, Lease, LeaseCancel, CreateAlias, MassTransfer, Data, SetScript, SponsorFee, - SetAssetScript, InvokeScript, UpdateAssetInfo, Ethereum, CommitToGeneration, InvokeExpression = Value + case Genesis, Payment, Issue, Transfer, Reissue, Burn, Exchange, Lease, LeaseCancel, CreateAlias, MassTransfer, Data, SetScript, SponsorFee, + SetAssetScript, InvokeScript, UpdateAssetInfo, Ethereum, CommitToGeneration, InvokeExpression - implicit class ValueExt(val tpe: TransactionType) extends AnyVal { - def transactionName: String = s"${tpe}Transaction" - } +} + +object TransactionType { + def fromId(id: Byte): TransactionType = TransactionType.fromOrdinal(id - 1) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/assets/BurnTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/assets/BurnTransaction.scala index fe73ec31ef8..41d47533bc3 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/assets/BurnTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/assets/BurnTransaction.scala @@ -1,10 +1,10 @@ package com.wavesplatform.transaction.assets -import com.wavesplatform.account.{AddressScheme, KeyPair, PrivateKey, PublicKey} -import com.wavesplatform.crypto +import com.wavesplatform.account.{AddressScheme, PublicKey} +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError -import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.* +import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.serialization.impl.BurnTxSerializer import com.wavesplatform.transaction.validation.TxValidator import com.wavesplatform.transaction.validation.impl.BurnTxValidator @@ -25,14 +25,18 @@ final case class BurnTransaction( ) extends Transaction(TransactionType.Burn, Seq(asset)) with ProvenTransaction with Versioned.ToV3 - with SigProofsSwitch + with HasSignature with TxWithFee.InWaves with FastHashId with PBSince.V3 { + type T = BurnTransaction + override val bodyBytes: Coeval[Array[Byte]] = BurnTxSerializer.bodyBytes(this) override val bytes: Coeval[Array[Byte]] = BurnTxSerializer.toBytes(this) override val json: Coeval[JsObject] = BurnTxSerializer.toJson(this) + + override def addProof(proof: ByteStr): BurnTransaction = copy(proofs = this.proofs.add(proof)) } object BurnTransaction extends TransactionParser { @@ -41,9 +45,6 @@ object BurnTransaction extends TransactionParser { implicit val validator: TxValidator[BurnTransaction] = BurnTxValidator - implicit def sign(tx: BurnTransaction, privateKey: PrivateKey): BurnTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - val serializer = BurnTxSerializer override def parseBytes(bytes: Array[TxVersion]): Try[BurnTransaction] = @@ -56,7 +57,7 @@ object BurnTransaction extends TransactionParser { quantity: Long, fee: Long, timestamp: Long, - proofs: Proofs, + proofs: Proofs = Proofs.empty, chainId: Byte = AddressScheme.current.chainId ): Either[ValidationError, BurnTransaction] = for { @@ -64,28 +65,4 @@ object BurnTransaction extends TransactionParser { fee <- TxPositiveAmount(fee)(TxValidationError.InsufficientFee) tx <- BurnTransaction(version, sender, asset, quantity, fee, timestamp, proofs, chainId).validatedEither } yield tx - - def signed( - version: TxVersion, - sender: PublicKey, - asset: IssuedAsset, - quantity: Long, - fee: Long, - timestamp: Long, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, BurnTransaction] = - create(version, sender, asset, quantity, fee, timestamp, Proofs.empty, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - asset: IssuedAsset, - quantity: Long, - fee: Long, - timestamp: Long, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, BurnTransaction] = { - signed(version, sender.publicKey, asset, quantity, fee, timestamp, sender.privateKey, chainId) - } } diff --git a/node/src/main/scala/com/wavesplatform/transaction/assets/IssueTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/assets/IssueTransaction.scala index b52c3744a5a..272487ef4cf 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/assets/IssueTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/assets/IssueTransaction.scala @@ -1,13 +1,13 @@ package com.wavesplatform.transaction.assets import com.google.protobuf.ByteString -import com.wavesplatform.account.{AddressScheme, KeyPair, PrivateKey, PublicKey} +import com.wavesplatform.account.{AddressScheme, PrivateKey, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.script.Script -import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.* +import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.serialization.impl.IssueTxSerializer import com.wavesplatform.transaction.validation.TxValidator import com.wavesplatform.transaction.validation.impl.IssueTxValidator @@ -33,13 +33,17 @@ case class IssueTransaction( with Versioned.ToV3 with ProvenTransaction with FastHashId - with SigProofsSwitch + with HasSignature with TxWithFee.InWaves with PBSince.V3 { + override type T = IssueTransaction + override val bodyBytes: Coeval[Array[TxType]] = Coeval.evalOnce(IssueTxSerializer.bodyBytes(this)) override val bytes: Coeval[Array[TxType]] = Coeval.evalOnce(IssueTxSerializer.toBytes(this)) override val json: Coeval[JsObject] = Coeval.evalOnce(IssueTxSerializer.toJson(this)) + + override def addProof(proof: ByteStr): IssueTransaction = copy(proofs = this.proofs.add(proof)) } object IssueTransaction extends TransactionParser { @@ -67,7 +71,7 @@ object IssueTransaction extends TransactionParser { script: Option[Script], fee: Long, timestamp: Long, - proofs: Proofs, + proofs: Proofs = Proofs.empty, chainId: Byte = AddressScheme.current.chainId ): Either[ValidationError, IssueTransaction] = for { @@ -90,37 +94,6 @@ object IssueTransaction extends TransactionParser { ).validatedEither } yield tx - def signed( - version: TxVersion, - sender: PublicKey, - name: String, - description: String, - quantity: Long, - decimals: Byte, - reissuable: Boolean, - script: Option[Script], - fee: Long, - timestamp: Long, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, IssueTransaction] = - create(version, sender, name, description, quantity, decimals, reissuable, script, fee, timestamp, Proofs.empty, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - name: String, - description: String, - quantity: Long, - decimals: Byte, - reissuable: Boolean, - script: Option[Script], - fee: Long, - timestamp: Long, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, IssueTransaction] = - signed(version, sender.publicKey, name, description, quantity, decimals, reissuable, script, fee, timestamp, sender.privateKey, chainId) - override def parseBytes(bytes: Array[TxType]): Try[IssueTransaction] = IssueTxSerializer.parseBytes(bytes) implicit class IssueTransactionExt(private val tx: IssueTransaction) extends AnyVal { diff --git a/node/src/main/scala/com/wavesplatform/transaction/assets/ReissueTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/assets/ReissueTransaction.scala index 9e6012f48b7..be292f27484 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/assets/ReissueTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/assets/ReissueTransaction.scala @@ -1,10 +1,11 @@ package com.wavesplatform.transaction.assets -import com.wavesplatform.account.{AddressScheme, KeyPair, PrivateKey, PublicKey} +import com.wavesplatform.account.{AddressScheme, PrivateKey, PublicKey} +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto import com.wavesplatform.lang.ValidationError -import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.* +import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.serialization.impl.ReissueTxSerializer import com.wavesplatform.transaction.validation.TxValidator import com.wavesplatform.transaction.validation.impl.ReissueTxValidator @@ -26,14 +27,17 @@ case class ReissueTransaction( ) extends Transaction(TransactionType.Reissue, Seq(asset)) with Versioned.ToV3 with ProvenTransaction - with SigProofsSwitch + with HasSignature with TxWithFee.InWaves with FastHashId with PBSince.V3 { + override type T = ReissueTransaction override val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(ReissueTxSerializer.bodyBytes(this)) override val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(ReissueTxSerializer.toBytes(this)) override val json: Coeval[JsObject] = Coeval.evalOnce(ReissueTxSerializer.toJson(this)) + + override def addProof(proof: ByteStr): ReissueTransaction = copy(proofs = this.proofs.add(proof)) } object ReissueTransaction extends TransactionParser { @@ -56,7 +60,7 @@ object ReissueTransaction extends TransactionParser { reissuable: Boolean, fee: Long, timestamp: Long, - proofs: Proofs, + proofs: Proofs = Proofs.empty, chainId: Byte = AddressScheme.current.chainId ): Either[ValidationError, ReissueTransaction] = for { @@ -64,29 +68,4 @@ object ReissueTransaction extends TransactionParser { quantity <- TxPositiveAmount(quantity)(TxValidationError.NonPositiveAmount(quantity, "assets")) tx <- ReissueTransaction(version, sender, asset, quantity, reissuable, fee, timestamp, proofs, chainId).validatedEither } yield tx - - def signed( - version: TxVersion, - sender: PublicKey, - asset: IssuedAsset, - quantity: Long, - reissuable: Boolean, - fee: Long, - timestamp: Long, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, ReissueTransaction] = - create(version, sender, asset, quantity, reissuable, fee, timestamp, Nil, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - asset: IssuedAsset, - quantity: Long, - reissuable: Boolean, - fee: Long, - timestamp: Long, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, ReissueTransaction] = - signed(version, sender.publicKey, asset, quantity, reissuable, fee, timestamp, sender.privateKey, chainId) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/assets/SetAssetScriptTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/assets/SetAssetScriptTransaction.scala index c445da9fe97..d3e3c061669 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/assets/SetAssetScriptTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/assets/SetAssetScriptTransaction.scala @@ -1,7 +1,7 @@ package com.wavesplatform.transaction.assets import com.wavesplatform.account.* -import com.wavesplatform.crypto +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.script.Script import com.wavesplatform.transaction.* @@ -29,6 +29,8 @@ case class SetAssetScriptTransaction( with TxWithFee.InWaves with FastHashId with PBSince.V2 { + override type T = SetAssetScriptTransaction + override def addProof(proof: ByteStr): SetAssetScriptTransaction = copy(proofs = this.proofs.add(proof)) override val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(SetAssetScriptTxSerializer.bodyBytes(this)) override val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(SetAssetScriptTxSerializer.toBytes(this)) @@ -41,9 +43,6 @@ object SetAssetScriptTransaction extends TransactionParser { implicit val validator: TxValidator[SetAssetScriptTransaction] = SetAssetScriptTxValidator - implicit def sign(tx: SetAssetScriptTransaction, privateKey: PrivateKey): SetAssetScriptTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - val serializer = SetAssetScriptTxSerializer override def parseBytes(bytes: Array[TxVersion]): Try[SetAssetScriptTransaction] = @@ -63,27 +62,4 @@ object SetAssetScriptTransaction extends TransactionParser { fee <- TxPositiveAmount(fee)(TxValidationError.InsufficientFee) tx <- SetAssetScriptTransaction(version, sender, assetId, script, fee, timestamp, proofs, chainId).validatedEither } yield tx - - def signed( - version: TxVersion, - sender: PublicKey, - asset: IssuedAsset, - script: Option[Script], - fee: Long, - timestamp: TxTimestamp, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, SetAssetScriptTransaction] = - create(version, sender, asset, script, fee, timestamp, Proofs.empty, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - asset: IssuedAsset, - script: Option[Script], - fee: Long, - timestamp: TxTimestamp, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, SetAssetScriptTransaction] = - signed(version, sender.publicKey, asset, script, fee, timestamp, sender.privateKey, chainId) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/assets/SponsorFeeTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/assets/SponsorFeeTransaction.scala index a3c0cbf6e03..cb714395ae2 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/assets/SponsorFeeTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/assets/SponsorFeeTransaction.scala @@ -1,8 +1,8 @@ package com.wavesplatform.transaction.assets import cats.syntax.traverse.* -import com.wavesplatform.account.{AddressScheme, KeyPair, PrivateKey, PublicKey} -import com.wavesplatform.crypto +import com.wavesplatform.account.{AddressScheme, PublicKey} +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.TxValidationError.NegativeMinFee @@ -30,6 +30,8 @@ case class SponsorFeeTransaction( with TxWithFee.InWaves with FastHashId with PBSince.V2 { + override type T = SponsorFeeTransaction + override def addProof(proof: ByteStr): SponsorFeeTransaction = copy(proofs = this.proofs.add(proof)) val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(SponsorFeeTxSerializer.bodyBytes(this)) override val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(SponsorFeeTxSerializer.toBytes(this)) @@ -42,9 +44,6 @@ object SponsorFeeTransaction extends TransactionParser { implicit val validator: TxValidator[SponsorFeeTransaction] = SponsorFeeTxValidator - implicit def sign(tx: SponsorFeeTransaction, privateKey: PrivateKey): SponsorFeeTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - override def parseBytes(bytes: Array[TxVersion]): Try[SponsorFeeTransaction] = SponsorFeeTxSerializer.parseBytes(bytes) @@ -63,27 +62,4 @@ object SponsorFeeTransaction extends TransactionParser { minSponsoredAssetFee <- minSponsoredAssetFee.traverse(fee => TxPositiveAmount(fee)(NegativeMinFee(fee, "asset"))) tx <- SponsorFeeTransaction(version, sender, asset, minSponsoredAssetFee, fee, timestamp, proofs, chainId).validatedEither } yield tx - - def signed( - version: TxVersion, - sender: PublicKey, - asset: IssuedAsset, - minSponsoredAssetFee: Option[Long], - fee: Long, - timestamp: TxTimestamp, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, SponsorFeeTransaction] = - create(version, sender, asset, minSponsoredAssetFee, fee, timestamp, Proofs.empty, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - asset: IssuedAsset, - minSponsoredAssetFee: Option[Long], - fee: Long, - timestamp: TxTimestamp, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, SponsorFeeTransaction] = - signed(version, sender.publicKey, asset, minSponsoredAssetFee, fee, timestamp, sender.privateKey, chainId) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/assets/UpdateAssetInfoTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/assets/UpdateAssetInfoTransaction.scala index 75dc0c047d5..3300261ebcd 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/assets/UpdateAssetInfoTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/assets/UpdateAssetInfoTransaction.scala @@ -1,8 +1,7 @@ package com.wavesplatform.transaction.assets -import com.wavesplatform.account.{AddressScheme, KeyPair, PrivateKey, PublicKey} +import com.wavesplatform.account.{AddressScheme, PublicKey} import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.crypto import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.* import com.wavesplatform.transaction.Asset.IssuedAsset @@ -30,6 +29,8 @@ case class UpdateAssetInfoTransaction( with FastHashId with ProvenTransaction with PBSince.V1 { self => + override type T = UpdateAssetInfoTransaction + override def addProof(proof: ByteStr): UpdateAssetInfoTransaction = copy(proofs = this.proofs.add(proof)) override def assetFee: (Asset, Long) = (feeAsset, feeAmount.value) @@ -51,15 +52,12 @@ object UpdateAssetInfoTransaction extends TransactionParser { type TransactionT = UpdateAssetInfoTransaction override val typeId: TxType = 17: Byte - implicit def sign(tx: UpdateAssetInfoTransaction, privateKey: PrivateKey): UpdateAssetInfoTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - implicit val validator: TxValidator[UpdateAssetInfoTransaction] = UpdateAssetInfoTxValidator def create( version: Byte, sender: PublicKey, - assetId: ByteStr, + assetId: IssuedAsset, name: String, description: String, timestamp: TxTimestamp, @@ -73,7 +71,7 @@ object UpdateAssetInfoTransaction extends TransactionParser { tx <- UpdateAssetInfoTransaction( version, sender, - IssuedAsset(assetId), + assetId, name, description, timestamp, @@ -84,20 +82,6 @@ object UpdateAssetInfoTransaction extends TransactionParser { ).validatedEither } yield tx - def selfSigned( - version: Byte, - sender: KeyPair, - assetId: ByteStr, - name: String, - description: String, - timestamp: TxTimestamp, - feeAmount: Long, - feeAsset: Asset, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, UpdateAssetInfoTransaction] = - create(version, sender.publicKey, assetId, name, description, timestamp, feeAmount, feeAsset, Proofs.empty, chainId) - .map(_.signWith(sender.privateKey)) - override def parseBytes(bytes: Array[Byte]): Try[UpdateAssetInfoTransaction] = PBTransactionSerializer .parseBytes(bytes) diff --git a/node/src/main/scala/com/wavesplatform/transaction/assets/exchange/ExchangeTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/assets/exchange/ExchangeTransaction.scala index 37e221117c2..d2e305d80fb 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/assets/exchange/ExchangeTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/assets/exchange/ExchangeTransaction.scala @@ -1,6 +1,7 @@ package com.wavesplatform.transaction.assets.exchange import com.wavesplatform.account.{AddressScheme, PrivateKey, PublicKey} +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.* @@ -26,13 +27,17 @@ case class ExchangeTransaction( timestamp: Long, proofs: Proofs, chainId: Byte -) extends Transaction(TransactionType.Exchange, order1.assetPair.checkedAssets) - with Versioned.ToV3 - with ProvenTransaction - with TxWithFee.InWaves - with FastHashId - with SigProofsSwitch - with PBSince.V3 { +) extends Transaction(TransactionType.Exchange, order1.assetPair.checkedAssets), + ProvenTransaction, + HasSignature, + Versioned.ToV3, + TxWithFee.InWaves, + FastHashId, + PBSince.V3 { + + override type T = ExchangeTransaction + + override def addProof(proof: ByteStr): ExchangeTransaction = copy(proofs = proofs.add(proof)) val (buyOrder, sellOrder) = if (order1.orderType == OrderType.BUY) (order1, order2) else (order2, order1) @@ -98,19 +103,4 @@ object ExchangeTransaction extends TransactionParser { chainId ).validatedEither } yield tx - - def signed( - version: TxVersion, - matcher: PrivateKey, - order1: Order, - order2: Order, - amount: Long, - price: Long, - buyMatcherFee: Long, - sellMatcherFee: Long, - fee: Long, - timestamp: Long, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, ExchangeTransaction] = - create(version, order1, order2, amount, price, buyMatcherFee, sellMatcherFee, fee, timestamp, Proofs.empty, chainId).map(_.signWith(matcher)) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/assets/exchange/Order.scala b/node/src/main/scala/com/wavesplatform/transaction/assets/exchange/Order.scala index b583e46a8a9..1a94f6174e6 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/assets/exchange/Order.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/assets/exchange/Order.scala @@ -153,7 +153,7 @@ object Order { price <- TxOrderPrice(price)(GenericError(s"Order validation error: ${TxOrderPrice.errMsg}")) matcherFee <- TxMatcherFee(matcherFee)(GenericError(s"Order validation error: ${TxMatcherFee.errMsg}")) } yield { - Order( + val o = Order( version, OrderAuthentication(sender.publicKey), matcher, @@ -168,7 +168,7 @@ object Order { priceMode = priceMode, attachment = attachment ) - .signWith(sender.privateKey) + o.withProofs(Proofs(crypto.sign(sender.privateKey, o.bodyBytes()))) } def buy( diff --git a/node/src/main/scala/com/wavesplatform/transaction/lease/LeaseCancelTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/lease/LeaseCancelTransaction.scala index 70607f6eaee..6727d34de9c 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/lease/LeaseCancelTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/lease/LeaseCancelTransaction.scala @@ -1,8 +1,7 @@ package com.wavesplatform.transaction.lease -import com.wavesplatform.account.{AddressScheme, KeyPair, PrivateKey, PublicKey} +import com.wavesplatform.account.{AddressScheme, PublicKey} import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.crypto import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.* import com.wavesplatform.transaction.serialization.impl.LeaseCancelTxSerializer @@ -21,15 +20,20 @@ final case class LeaseCancelTransaction( timestamp: TxTimestamp, proofs: Proofs, chainId: Byte -) extends Transaction(TransactionType.LeaseCancel) - with SigProofsSwitch - with Versioned.ToV3 - with TxWithFee.InWaves - with FastHashId - with PBSince.V3 { +) extends Transaction(TransactionType.LeaseCancel), + ProvenTransaction, + HasSignature, + Versioned.ToV3, + TxWithFee.InWaves, + FastHashId, + PBSince.V3 { + override type T = LeaseCancelTransaction + override val bodyBytes: Coeval[Array[TxVersion]] = Coeval.evalOnce(LeaseCancelTxSerializer.bodyBytes(this)) override val bytes: Coeval[Array[TxVersion]] = Coeval.evalOnce(LeaseCancelTxSerializer.toBytes(this)) override val json: Coeval[JsObject] = Coeval.evalOnce(LeaseCancelTxSerializer.toJson(this)) + + override def addProof(proof: ByteStr): LeaseCancelTransaction = copy(proofs = this.proofs.add(proof)) } object LeaseCancelTransaction extends TransactionParser { @@ -39,9 +43,6 @@ object LeaseCancelTransaction extends TransactionParser { implicit val validator: TxValidator[LeaseCancelTransaction] = LeaseCancelTxValidator - implicit def sign(tx: LeaseCancelTransaction, privateKey: PrivateKey): LeaseCancelTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - override def parseBytes(bytes: Array[Byte]): Try[LeaseCancelTransaction] = LeaseCancelTxSerializer.parseBytes(bytes) @@ -58,25 +59,4 @@ object LeaseCancelTransaction extends TransactionParser { fee <- TxPositiveAmount(fee)(TxValidationError.InsufficientFee) tx <- LeaseCancelTransaction(version, sender, leaseId, fee, timestamp, proofs, chainId).validatedEither } yield tx - - def signed( - version: TxVersion, - sender: PublicKey, - leaseId: ByteStr, - fee: Long, - timestamp: TxTimestamp, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, TransactionT] = - create(version, sender, leaseId, fee, timestamp, Nil, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - leaseId: ByteStr, - fee: Long, - timestamp: TxTimestamp, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, TransactionT] = - signed(version, sender.publicKey, leaseId, fee, timestamp, sender.privateKey, chainId).map(_.signWith(sender.privateKey)) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/lease/LeaseTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/lease/LeaseTransaction.scala index aea45ea0107..ddf6207c31b 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/lease/LeaseTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/lease/LeaseTransaction.scala @@ -1,7 +1,7 @@ package com.wavesplatform.transaction.lease -import com.wavesplatform.account.{AddressOrAlias, KeyPair, PrivateKey, PublicKey} -import com.wavesplatform.crypto +import com.wavesplatform.account.{AddressOrAlias, PublicKey} +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.* import com.wavesplatform.transaction.serialization.impl.LeaseTxSerializer @@ -21,15 +21,20 @@ final case class LeaseTransaction( timestamp: TxTimestamp, proofs: Proofs, chainId: Byte -) extends Transaction(TransactionType.Lease) - with SigProofsSwitch - with Versioned.ToV3 - with TxWithFee.InWaves - with FastHashId - with PBSince.V3 { +) extends Transaction(TransactionType.Lease), + ProvenTransaction, + HasSignature, + Versioned.ToV3, + TxWithFee.InWaves, + FastHashId, + PBSince.V3 { + type T = LeaseTransaction + override val bodyBytes: Coeval[Array[TxVersion]] = Coeval.evalOnce(LeaseTxSerializer.bodyBytes(this)) override val bytes: Coeval[Array[TxVersion]] = Coeval.evalOnce(LeaseTxSerializer.toBytes(this)) override val json: Coeval[JsObject] = Coeval.evalOnce(LeaseTxSerializer.toJson(this)) + + override def addProof(proof: ByteStr): LeaseTransaction = copy(proofs = this.proofs.add(proof)) } object LeaseTransaction extends TransactionParser { @@ -39,9 +44,6 @@ object LeaseTransaction extends TransactionParser { implicit val validator: TxValidator[LeaseTransaction] = LeaseTxValidator - implicit def sign(tx: LeaseTransaction, privateKey: PrivateKey): LeaseTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - override def parseBytes(bytes: Array[TxVersion]): Try[LeaseTransaction] = LeaseTxSerializer.parseBytes(bytes) @@ -61,25 +63,4 @@ object LeaseTransaction extends TransactionParser { } yield tx } - - def signed( - version: TxVersion, - sender: PublicKey, - recipient: AddressOrAlias, - amount: Long, - fee: Long, - timestamp: TxTimestamp, - signer: PrivateKey - ): Either[ValidationError, TransactionT] = - create(version, sender, recipient, amount, fee, timestamp, Nil).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - recipient: AddressOrAlias, - amount: Long, - fee: Long, - timestamp: TxTimestamp - ): Either[ValidationError, TransactionT] = - signed(version, sender.publicKey, recipient, amount, fee, timestamp, sender.privateKey) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/package.scala b/node/src/main/scala/com/wavesplatform/transaction/package.scala index 3e1a3ddf993..d07feebd3ad 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/package.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/package.scala @@ -1,7 +1,6 @@ package com.wavesplatform import cats.data.ValidatedNel -import com.wavesplatform.account.PrivateKey import com.wavesplatform.block.{Block, BlockSnapshot, MicroBlock} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError @@ -97,10 +96,6 @@ package object transaction { def validatedEither(implicit validator: TxValidator[T]): Either[ValidationError, T] = this.validatedNel.toEither.left.map(_.head) } - implicit class TransactionSignOps[T](val tx: T) extends AnyVal { - def signWith(privateKey: PrivateKey)(implicit sign: (T, PrivateKey) => T): T = sign(tx, privateKey) - } - object ERC20Address { def apply(bs: ByteStr): ERC20Address = { require(bs.arr.length == 20, "ERC20 token address length must be 20 bytes") diff --git a/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/BaseTxJson.scala b/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/BaseTxJson.scala index 4c7731e7a5e..b199985075b 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/BaseTxJson.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/BaseTxJson.scala @@ -1,6 +1,6 @@ package com.wavesplatform.transaction.serialization.impl -import com.wavesplatform.transaction.{EthereumTransaction, PBSince, ProvenTransaction, SigProofsSwitch, Transaction, Versioned} +import com.wavesplatform.transaction.{EthereumTransaction, PBSince, ProvenTransaction, HasSignature, Transaction, Versioned} import play.api.libs.json.{JsArray, JsObject, JsString, Json} object BaseTxJson { @@ -27,8 +27,8 @@ object BaseTxJson { "proofs" -> JsArray(p.proofs.proofs.map(p => JsString(p.toString))) ) ++ (tx match { // Compatibility - case s: SigProofsSwitch if s.usesLegacySignature => Json.obj("signature" -> s.signature.toString) - case _ => Json.obj() + case s: HasSignature if s.usesLegacySignature => Json.obj("signature" -> s.signature.toString) + case _ => Json.obj() }) case _ => JsObject.empty }) diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/InvokeExpressionTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/InvokeExpressionTransaction.scala index 96414f793ef..100de9b8c8b 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/InvokeExpressionTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/InvokeExpressionTransaction.scala @@ -2,7 +2,6 @@ package com.wavesplatform.transaction.smart import com.wavesplatform.account.* import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.crypto import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.v1.compiler.Terms @@ -24,10 +23,11 @@ case class InvokeExpressionTransaction( override val timestamp: TxTimestamp, proofs: Proofs, chainId: Byte -) extends Transaction(TransactionType.InvokeExpression, Nil) - with InvokeTransaction - with Versioned.ConstV1 - with PBSince.V1 { +) extends Transaction(TransactionType.InvokeExpression, Nil), + InvokeTransaction, + Versioned.ConstV1, + PBSince.V1 { + override type T = InvokeExpressionTransaction lazy val expressionBytes: ByteStr = expression.bytes.value() @@ -38,6 +38,9 @@ case class InvokeExpressionTransaction( override val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(PBTransactionSerializer.bodyBytes(this)) override val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(PBTransactionSerializer.bytes(this)) + + override def addProof(proof: ByteStr): InvokeExpressionTransaction = copy(proofs = this.proofs.add(proof)) + override val json: Coeval[JsObject] = Coeval.evalOnce( BaseTxJson.toJson(this) ++ Json.obj( @@ -52,9 +55,6 @@ object InvokeExpressionTransaction extends TransactionParser { override val typeId: TxType = 18: Byte - implicit def sign(tx: InvokeExpressionTransaction, privateKey: PrivateKey): InvokeExpressionTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - implicit val validator: TxValidator[InvokeExpressionTransaction] = InvokeExpressionTxValidator override def parseBytes(bytes: Array[TxType]): Try[InvokeExpressionTransaction] = @@ -88,15 +88,4 @@ object InvokeExpressionTransaction extends TransactionParser { chainId ).validatedEither } yield tx - - def selfSigned( - version: Byte, - sender: KeyPair, - expression: ExprScript, - feeAmount: Long, - feeAsset: Asset, - timestamp: TxTimestamp - ): Either[ValidationError, InvokeExpressionTransaction] = - create(version, sender.publicKey, expression, feeAmount, feeAsset, timestamp, Proofs.empty) - .map(_.signWith(sender.privateKey)) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/InvokeScriptTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/InvokeScriptTransaction.scala index e848fa972d5..3ede490e4c6 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/InvokeScriptTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/InvokeScriptTransaction.scala @@ -1,7 +1,7 @@ package com.wavesplatform.transaction.smart import com.wavesplatform.account.* -import com.wavesplatform.crypto +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.v1.compiler.Terms.FUNCTION_CALL import com.wavesplatform.state.diffs.invoke.{InvokeScriptLike, InvokeScriptTransactionLike} @@ -31,6 +31,8 @@ case class InvokeScriptTransaction( with Versioned.ToV2 with PBSince.V2 { + override type T = InvokeScriptTransaction + override def root: InvokeScriptTransactionLike = this override val funcCall: FUNCTION_CALL = funcCallOpt.getOrElse(InvokeTransaction.DefaultCall) def senderAddress: Address = sender.toAddress @@ -38,6 +40,8 @@ case class InvokeScriptTransaction( val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(InvokeScriptTxSerializer.bodyBytes(this)) val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(InvokeScriptTxSerializer.toBytes(this)) val json: Coeval[JsObject] = Coeval.evalOnce(InvokeScriptTxSerializer.toJson(this)) + + override def addProof(proof: ByteStr): InvokeScriptTransaction = copy(proofs = this.proofs.add(proof)) } object InvokeScriptTransaction extends TransactionParser { @@ -47,9 +51,6 @@ object InvokeScriptTransaction extends TransactionParser { implicit val validator: TxValidator[InvokeScriptTransaction] = InvokeScriptTxValidator - implicit def sign(tx: InvokeScriptTransaction, privateKey: PrivateKey): InvokeScriptTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - override def parseBytes(bytes: Array[Byte]): Try[InvokeScriptTransaction] = InvokeScriptTxSerializer.parseBytes(bytes) @@ -67,8 +68,8 @@ object InvokeScriptTransaction extends TransactionParser { fee: Long, feeAssetId: Asset, timestamp: TxTimestamp, - proofs: Proofs, - chainId: Byte + proofs: Proofs = Proofs.empty, + chainId: Byte = AddressScheme.current.chainId ): Either[ValidationError, InvokeScriptTransaction] = for { fee <- TxPositiveAmount(fee)(TxValidationError.InsufficientFee) diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/SetScriptTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/SetScriptTransaction.scala index 8f21e7ac3b3..cbe81512025 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/SetScriptTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/SetScriptTransaction.scala @@ -1,7 +1,7 @@ package com.wavesplatform.transaction.smart import com.wavesplatform.account.* -import com.wavesplatform.crypto +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.script.Script import com.wavesplatform.transaction.* @@ -27,6 +27,8 @@ case class SetScriptTransaction( with TxWithFee.InWaves with FastHashId with PBSince.V2 { + override type T = SetScriptTransaction + override def addProof(proof: ByteStr): SetScriptTransaction = copy(proofs = this.proofs.add(proof)) val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(SetScriptTxSerializer.bodyBytes(this)) override val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(SetScriptTxSerializer.toBytes(this)) @@ -40,9 +42,6 @@ object SetScriptTransaction extends TransactionParser { implicit val validator: TxValidator[SetScriptTransaction] = SetScriptTxValidator - implicit def sign(tx: SetScriptTransaction, privateKey: PrivateKey): SetScriptTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - override def parseBytes(bytes: Array[TxVersion]): Try[SetScriptTransaction] = SetScriptTxSerializer.parseBytes(bytes) @@ -59,25 +58,4 @@ object SetScriptTransaction extends TransactionParser { fee <- TxPositiveAmount(fee)(TxValidationError.InsufficientFee) tx <- SetScriptTransaction(version, sender, script, fee, timestamp, proofs, chainId).validatedEither } yield tx - - def signed( - version: TxVersion, - sender: PublicKey, - script: Option[Script], - fee: Long, - timestamp: TxTimestamp, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, SetScriptTransaction] = - create(version, sender, script, fee, timestamp, Proofs.empty, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - script: Option[Script], - fee: Long, - timestamp: TxTimestamp, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, SetScriptTransaction] = - signed(version, sender.publicKey, script, fee, timestamp, sender.privateKey, chainId) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/Verifier.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/Verifier.scala index dec313d1899..ac80e277cda 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/Verifier.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/Verifier.scala @@ -59,7 +59,7 @@ object Verifier extends ScorexLogging { if (limitedExecution) ContractLimits.FailFreeInvokeComplexity else Int.MaxValue, enableExecutionLog ) - case (sps: SigProofsSwitch, Some(_)) if sps.usesLegacySignature => + case (hs: HasSignature, Some(_)) if hs.usesLegacySignature => Left(GenericError("Can't process transaction with signature from scripted account")) case (_: PaymentTransaction, Some(_)) => Left(GenericError("Can't process transaction with signature from scripted account")) diff --git a/node/src/main/scala/com/wavesplatform/transaction/transfer/MassTransferTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/transfer/MassTransferTransaction.scala index f1cf5c1b8b5..ed898c49b9f 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/transfer/MassTransferTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/transfer/MassTransferTransaction.scala @@ -4,7 +4,6 @@ import cats.instances.list.* import cats.syntax.traverse.* import com.wavesplatform.account.* import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.crypto import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} @@ -34,17 +33,20 @@ case class MassTransferTransaction( case Waves => Seq() case a: IssuedAsset => Seq(a) } - ) - with ProvenTransaction - with Versioned.ToV2 - with TxWithFee.InWaves - with FastHashId - with PBSince.V2 { + ), + ProvenTransaction, + Versioned.ToV2, + TxWithFee.InWaves, + FastHashId, + PBSince.V2 { + override type T = MassTransferTransaction override val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(MassTransferTxSerializer.bodyBytes(this)) override val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(MassTransferTxSerializer.toBytes(this)) override val json: Coeval[JsObject] = Coeval.evalOnce(MassTransferTxSerializer.toJson(this)) + override def addProof(proof: ByteStr): MassTransferTransaction = copy(proofs = this.proofs.add(proof)) + def compactJson(recipient: Address, aliases: Set[Alias]): JsObject = json() ++ Json.obj( "transfers" -> MassTransferTxSerializer.transfersJson(transfers.filter { t => @@ -65,9 +67,6 @@ object MassTransferTransaction extends TransactionParser { implicit val validator: TxValidator[MassTransferTransaction] = MassTransferTxValidator - implicit def sign(tx: MassTransferTransaction, privateKey: PrivateKey): MassTransferTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - override def parseBytes(bytes: Array[Byte]): Try[MassTransferTransaction] = MassTransferTxSerializer.parseBytes(bytes) @@ -98,31 +97,6 @@ object MassTransferTransaction extends TransactionParser { tx <- MassTransferTransaction(version, sender, assetId, transfers, fee, timestamp, attachment, proofs, chainId).validatedEither } yield tx - def signed( - version: TxVersion, - sender: PublicKey, - assetId: Asset, - transfers: Seq[ParsedTransfer], - fee: Long, - timestamp: TxTimestamp, - attachment: ByteStr, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, MassTransferTransaction] = - create(version, sender, assetId, transfers, fee, timestamp, attachment, Proofs.empty, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - assetId: Asset, - transfers: Seq[ParsedTransfer], - fee: Long, - timestamp: TxTimestamp, - attachment: ByteStr, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, MassTransferTransaction] = - signed(version, sender.publicKey, assetId, transfers, fee, timestamp, attachment, sender.privateKey, chainId) - def parseTransfersList(transfers: List[Transfer]): Validation[List[ParsedTransfer]] = transfers.traverse { case Transfer(recipient, amount) => for { diff --git a/node/src/main/scala/com/wavesplatform/transaction/transfer/TransferTransaction.scala b/node/src/main/scala/com/wavesplatform/transaction/transfer/TransferTransaction.scala index b67c2aae32c..35df34a5503 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/transfer/TransferTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/transfer/TransferTransaction.scala @@ -2,7 +2,6 @@ package com.wavesplatform.transaction.transfer import com.wavesplatform.account.* import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.crypto import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} @@ -33,17 +32,21 @@ case class TransferTransaction( case Waves => Seq() case a: IssuedAsset => Seq(a) } - ) - with TransferTransactionLike - with Versioned.ToV3 - with FastHashId - with SigProofsSwitch - with TxWithFee.InCustomAsset - with PBSince.V3 { + ), + ProvenTransaction, + TransferTransactionLike, + Versioned.ToV3, + FastHashId, + HasSignature, + TxWithFee.InCustomAsset, + PBSince.V3 { + override type T = TransferTransaction val bodyBytes: Coeval[TxByteArray] = Coeval.evalOnce(TransferTxSerializer.bodyBytes(this)) val bytes: Coeval[TxByteArray] = Coeval.evalOnce(TransferTxSerializer.toBytes(this)) final val json: Coeval[JsObject] = Coeval.evalOnce(TransferTxSerializer.toJson(this)) + + override def addProof(proof: ByteStr): TransferTransaction = copy(proofs = this.proofs.add(proof)) } trait TransferTransactionLike extends TransactionBase with Authorized { @@ -64,9 +67,6 @@ object TransferTransaction extends TransactionParser { implicit val validator: TxValidator[TransferTransaction] = TransferTxValidator - implicit def sign(tx: TransferTransaction, privateKey: PrivateKey): TransferTransaction = - tx.copy(proofs = Proofs(crypto.sign(privateKey, tx.bodyBytes()))) - override def parseBytes(bytes: TxByteArray): Try[TransferTransaction] = TransferTxSerializer.parseBytes(bytes) def create( @@ -87,33 +87,4 @@ object TransferTransaction extends TransactionParser { fee <- TxPositiveAmount(fee)(TxValidationError.InsufficientFee) tx <- TransferTransaction(version, sender, recipient, asset, amount, feeAsset, fee, attachment, timestamp, proofs, chainId).validatedEither } yield tx - - def signed( - version: TxVersion, - sender: PublicKey, - recipient: AddressOrAlias, - asset: Asset, - amount: Long, - feeAsset: Asset, - fee: Long, - attachment: ByteStr, - timestamp: TxTimestamp, - signer: PrivateKey, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, TransferTransaction] = - create(version, sender, recipient, asset, amount, feeAsset, fee, attachment, timestamp, Proofs.empty, chainId).map(_.signWith(signer)) - - def selfSigned( - version: TxVersion, - sender: KeyPair, - recipient: AddressOrAlias, - asset: Asset, - amount: Long, - feeAsset: Asset, - fee: Long, - attachment: ByteStr, - timestamp: TxTimestamp, - chainId: Byte = AddressScheme.current.chainId - ): Either[ValidationError, TransferTransaction] = - signed(version, sender.publicKey, recipient, asset, amount, feeAsset, fee, attachment, timestamp, sender.privateKey, chainId) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/utils/Signed.scala b/node/src/main/scala/com/wavesplatform/transaction/utils/Signed.scala deleted file mode 100644 index 0610a207cde..00000000000 --- a/node/src/main/scala/com/wavesplatform/transaction/utils/Signed.scala +++ /dev/null @@ -1,55 +0,0 @@ -package com.wavesplatform.transaction.utils - -import com.wavesplatform.account.{AddressOrAlias, KeyPair} -import com.wavesplatform.common.utils.EitherExt2.* -import com.wavesplatform.lang.script.Script -import com.wavesplatform.lang.v1.compiler.Terms -import com.wavesplatform.transaction.assets.IssueTransaction -import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} -import com.wavesplatform.transaction.{Asset, Proofs, TxTimestamp, TransactionSignOps} - -object Signed { - def invokeScript( - version: Byte, - sender: KeyPair, - dApp: AddressOrAlias, - functionCall: Option[Terms.FUNCTION_CALL], - payments: Seq[InvokeScriptTransaction.Payment], - fee: Long, - feeAssetId: Asset, - timestamp: TxTimestamp - ): InvokeScriptTransaction = - InvokeScriptTransaction - .create(version, sender.publicKey, dApp, functionCall, payments, fee, feeAssetId, timestamp, Proofs.empty, dApp.chainId) - .map(_.signWith(sender.privateKey)) - .explicitGet() - - def issue( - version: Byte, - sender: KeyPair, - name: String, - description: String, - quantity: Long, - decimals: Byte, - reissuable: Boolean, - script: Option[Script], - fee: Long, - timestamp: TxTimestamp - ): IssueTransaction = - IssueTransaction - .create(version, sender.publicKey, name, description, quantity, decimals, reissuable, script, fee, timestamp, Proofs.empty) - .map(_.signWith(sender.privateKey)) - .explicitGet() - - def setScript( - version: Byte, - sender: KeyPair, - script: Option[Script], - fee: Long, - timestamp: TxTimestamp - ): SetScriptTransaction = - SetScriptTransaction - .create(version, sender.publicKey, script, fee, timestamp, Proofs.empty) - .map(_.signWith(sender.privateKey)) - .explicitGet() -} diff --git a/node/src/main/scala/com/wavesplatform/utils/UtilApp.scala b/node/src/main/scala/com/wavesplatform/utils/UtilApp.scala index 9c5a1bacada..1535f2e6607 100644 --- a/node/src/main/scala/com/wavesplatform/utils/UtilApp.scala +++ b/node/src/main/scala/com/wavesplatform/utils/UtilApp.scala @@ -1,20 +1,19 @@ package com.wavesplatform.utils import com.google.common.io.ByteStreams -import com.wavesplatform.account.{KeyPair, PrivateKey, PublicKey} -import com.wavesplatform.api.http.requests.* +import com.wavesplatform.account.{KeyPair, PKKeyPair, PrivateKey, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.explicitGet import com.wavesplatform.common.utils.{Base58, Base64, FastBase58} +import com.wavesplatform.crypto.bls.{BlsKeyPair, BlsSignature} import com.wavesplatform.crypto.{P256Curve, Sha256} -import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.features.EstimatorProvider.* +import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.script.{Script, ScriptReader} import com.wavesplatform.settings.{WalletSettings, WavesSettings} -import com.wavesplatform.state.{GenerationPeriod, Height} -import com.wavesplatform.transaction.TxValidationError.GenericError +import com.wavesplatform.state.Height +import com.wavesplatform.transaction.TransactionFactory import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.{Transaction, TransactionFactory, TransactionSignOps, TransactionType} import com.wavesplatform.wallet.Wallet import com.wavesplatform.{Application, Version} import play.api.libs.json.{JsObject, Json} @@ -25,16 +24,14 @@ import java.nio.charset.StandardCharsets import java.nio.file.{Files, Paths} import java.util import scala.annotation.nowarn +import scala.util.Random -//noinspection ScalaStyle -// TODO: Consider remove implemented methods from REST API object UtilApp { enum Mode { - case CompileScript, DecompileScript, SignBytes, VerifySignature, CreateKeyPair, Hash, SerializeTx, SignTx, SignTxWithSk, SmokeTest + case CompileScript, DecompileScript, SignBytes, VerifySignature, CreateKeyPair, Hash, SerializeTx, SignTx, SmokeTest } case class CompileOptions(assetScript: Boolean = false) - case class SignOptions(privateKey: PrivateKey = null.asInstanceOf[PrivateKey]) case class VerifyOptions(publicKey: PublicKey = null.asInstanceOf[PublicKey], signature: ByteStr = ByteStr.empty, checkWeakPk: Boolean = false) case class HashOptions(mode: String = "fast") case class SignTxOptions(signerAddress: String = "", currentHeight: Height = Height(1), finalityActivationHeight: Option[Height] = None) @@ -54,26 +51,33 @@ object UtilApp { inFormat: String = "plain", outFormat: String = "plain", compileOptions: CompileOptions = CompileOptions(), - signOptions: SignOptions = SignOptions(), + signOptions: String | KeyPair = "", verifyOptions: VerifyOptions = VerifyOptions(), hashOptions: HashOptions = HashOptions(), - signTxOptions: SignTxOptions = SignTxOptions(), keyPairOptions: KeyPairOptions = KeyPairOptions() ) + private def maybeFindKeyPair(cmd: Command): Either[ValidationError, KeyPair] = { + // we need to load application config to properly set chain ID + val walletSettings = Application.loadApplicationConfig(cmd.configFile.map(new File(_))).walletSettings + cmd.signOptions match { + case signerAddress: String => Wallet(walletSettings).findPrivateKey(signerAddress) + case kp: KeyPair => Right(kp) + } + } + def main(args: Array[String]): Unit = { OParser.parse(commandParser, args, Command()).foreach { cmd => val inBytes = IO.readInput(cmd) val result = cmd.mode match { case Mode.CompileScript => Actions.doCompile(Application.loadApplicationConfig(cmd.configFile.map(new File(_))))(cmd, inBytes) case Mode.DecompileScript => Actions.doDecompile(inBytes) - case Mode.SignBytes => Actions.doSign(cmd, inBytes) + case Mode.SignBytes => maybeFindKeyPair(cmd).flatMap(Actions.doSign(_, inBytes)) case Mode.VerifySignature => Actions.doVerify(cmd, inBytes) case Mode.CreateKeyPair => Actions.doCreateKeyPair(cmd, inBytes) case Mode.Hash => Actions.doHash(cmd, inBytes) case Mode.SerializeTx => Actions.doSerializeTx(inBytes) - case Mode.SignTx => Actions.doSignTx(new NodeState(cmd))(cmd, inBytes) - case Mode.SignTxWithSk => Actions.doSignTxWithSK(cmd, inBytes) + case Mode.SignTx => maybeFindKeyPair(cmd).flatMap(Actions.doSignTx(_, inBytes)) case Mode.SmokeTest => Actions.doSmokeTest() } @@ -149,7 +153,7 @@ object UtilApp { opt[String]('k', "private-key") .text("Private key for signing") .required() - .action((s, c) => c.copy(signOptions = c.signOptions.copy(privateKey = PrivateKey(Base58.decode(s))))) + .action((s, c) => c.copy(signOptions = PKKeyPair(PrivateKey(Base58.decode(s))))) ) .text("Sign bytes with provided private key") .action((_, c) => c.copy(mode = Mode.SignBytes)), @@ -196,24 +200,16 @@ object UtilApp { opt[String]("signer-address") .abbr("sa") .text("Signer address (requires corresponding key in wallet.dat)") - .action((a, c) => c.copy(signTxOptions = c.signTxOptions.copy(signerAddress = a))), - opt[Int]('h', "current-height") - .text("Current height, required for signing CommitToGeneration transaction") - .optional() - .action((h, c) => c.copy(signTxOptions = c.signTxOptions.copy(currentHeight = Height(h)))), - opt[Int]('f', "finality-activation-height") - .text("Finality activation height, required for signing CommitToGeneration transaction. From preActivatedFeatures setting by default") - .optional() - .action((h, c) => c.copy(signTxOptions = c.signTxOptions.copy(finalityActivationHeight = Some(Height(h))))) + .action((a, c) => c.copy(signOptions = a)) ), cmd("sign-with-sk") .text("Sign JSON transaction with private key") - .action((_, c) => c.copy(mode = Mode.SignTxWithSk)) + .action((_, c) => c.copy(mode = Mode.SignTx)) .children( opt[String]("private-key") .abbr("sk") .text("Private key") - .action((a, c) => c.copy(signOptions = c.signOptions.copy(privateKey = PrivateKey(Base58.decode(a))))) + .action((a, c) => c.copy(signOptions = PKKeyPair(PrivateKey(Base58.decode(a))))) ) ), cmd("smoke").action((_, c) => c.copy(mode = Mode.SmokeTest, inputData = Input.Str(""))), @@ -225,13 +221,6 @@ object UtilApp { ) } - // noinspection TypeAnnotation - private final class NodeState(c: Command) { - lazy val settings = Application.loadApplicationConfig(c.configFile.map(new File(_))) - lazy val wallet = Wallet(settings.walletSettings) - lazy val time = new NTP(settings.ntpServer) - } - private object Actions { type ActionResult = Either[String, Array[Byte]] @@ -251,8 +240,8 @@ object UtilApp { } } - def doSign(c: Command, data: Array[Byte]): ActionResult = - Right(com.wavesplatform.crypto.sign(c.signOptions.privateKey, data).arr) + def doSign(keyPair: KeyPair, data: Array[Byte]): ActionResult = + Right(com.wavesplatform.crypto.sign(keyPair.privateKey, data).arr) def doVerify(c: Command, data: Array[Byte]): ActionResult = Either.cond( @@ -291,66 +280,20 @@ object UtilApp { case m => Left(s"Invalid hashing mode: $m") } - def doSerializeTx(data: Array[Byte]): ActionResult = { - val jsv = Json.parse(data) + def doSerializeTx(data: Array[Byte]): ActionResult = TransactionFactory - .fromSignedRequest(jsv) + .parseRequest(Json.parse(data).as[JsObject]) .left .map(_.toString) .map(_.bytes()) - } - def doSignTx(ns: NodeState)(c: Command, data: Array[Byte]): ActionResult = { - val unsignedTx = Json.parse(data).as[JsObject] - - val currentPeriod = for { - finalityActivationHeight <- c.signTxOptions.finalityActivationHeight - .orElse( - ns.settings.blockchainSettings.functionalitySettings.preActivatedFeatures - .get(BlockchainFeatures.DeterministicFinality.id) - .map(Height.apply) - ) - currentPeriod <- GenerationPeriod.from(c.signTxOptions.currentHeight, finalityActivationHeight, ns.settings) - } yield currentPeriod - - val signedTx = for { - tpe <- (unsignedTx \ "type").validate[Int].asEither.left.map { _ => s"Can't parse as transaction request: $unsignedTx" } - currentPeriod <- - if (tpe == TransactionType.CommitToGeneration.id) - currentPeriod.toRight("Finality activation height is required for signing CommitToGeneration transaction") - else Right(GenerationPeriod(Height(1), Height(1), 1)) - factory = TransactionFactory(ns.wallet, ns.time, Some(currentPeriod)) - signedTx <- factory.parseRequestAndSign(c.signTxOptions.signerAddress, unsignedTx) - } yield signedTx - - signedTx.left.map(_.toString).map(tx => Json.toBytes(tx.json())) - } - - def doSignTxWithSK(c: Command, data: Array[Byte]): ActionResult = { + def doSignTx(signerKeyPair: KeyPair, data: Array[Byte]): ActionResult = { import cats.syntax.either.* - import com.wavesplatform.api.http.requests.InvokeScriptRequest.signedInvokeScriptRequestReads - import com.wavesplatform.api.http.requests.SponsorFeeRequest.signedSponsorRequestFormat - import com.wavesplatform.transaction.TransactionType.* - - val json = Json.parse(data) - (TransactionType((json \ "type").as[Int]) match { - case Issue => json.as[IssueRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case Transfer => json.as[TransferRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case Reissue => json.as[ReissueRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case Burn => json.as[BurnRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case Exchange => json.as[ExchangeRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case Lease => json.as[LeaseRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case LeaseCancel => json.as[LeaseCancelRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case CreateAlias => json.as[CreateAliasRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case MassTransfer => json.as[SignedMassTransferRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case Data => json.as[SignedDataRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case SetScript => json.as[SignedSetScriptRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case SponsorFee => json.as[SignedSponsorFeeRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case SetAssetScript => json.as[SignedSetAssetScriptRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case InvokeScript => json.as[SignedInvokeScriptRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case UpdateAssetInfo => json.as[SignedUpdateAssetInfoRequest].toTx.map(_.signWith(c.signOptions.privateKey)) - case other => GenericError(s"Signing $other is not supported").asLeft[Transaction] - }).leftMap(_.toString).map(_.json().toString().getBytes()) + + TransactionFactory + .parseRequestAndSign(Json.parse(data).as[JsObject], signerKeyPair, None) + .leftMap(_.toString) + .map(_.json().toString().getBytes()) } def doSmokeTest(): ActionResult = { @@ -362,6 +305,20 @@ object UtilApp { val publicKey = Base64.decode("KdU/1vG5aM0TC1WRHYmV8ByD6oabSRj7vHVvqIWYn0h60Ihc/FT/NvVgBTMG8rnVnEF+AeojruMo22LjhGDo7A==") require(util.Arrays.equals(hash, Sha256.hash(message)), "hash mismatch") require(P256Curve.verify(message, signature, publicKey).explicitGet(), "invalid signature") + + val blsSK1bs = new Array[Byte](32) + Random.nextBytes(blsSK1bs) + val blsSK1 = BlsKeyPair(PrivateKey(blsSK1bs)) + val blsSig1 = blsSK1.sign(message) + + val blsSK2bs = new Array[Byte](32) + Random.nextBytes(blsSK2bs) + val blsSK2 = BlsKeyPair(PrivateKey(blsSK2bs)) + val blsSig2 = blsSK2.sign(message) + + val aggSig = BlsSignature.agg(Seq(blsSig1, blsSig2)).explicitGet() + aggSig.verifyAgg(message, Seq(blsSK1.publicKey, blsSK2.publicKey)).explicitGet() + Right(Array.emptyByteArray) } } diff --git a/node/testkit/src/main/scala/com/wavesplatform/TransactionGen.scala b/node/testkit/src/main/scala/com/wavesplatform/TransactionGen.scala index 990d81da456..bfc1956f951 100644 --- a/node/testkit/src/main/scala/com/wavesplatform/TransactionGen.scala +++ b/node/testkit/src/main/scala/com/wavesplatform/TransactionGen.scala @@ -21,7 +21,6 @@ import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeExpressionTransaction, InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.transfer.* import com.wavesplatform.transaction.utils.EthConverters.* -import com.wavesplatform.transaction.utils.Signed import org.scalacheck.Gen.{alphaLowerChar, alphaUpperChar, frequency, numChar} import org.scalacheck.{Arbitrary, Gen} import org.scalatest.Suite @@ -140,9 +139,9 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su script1 <- scriptGen script2 <- scriptGen issue = IssueTransaction - .selfSigned( + .create( TxVersion.V2, - sender, + sender.publicKey, new String(assetName), new String(description), quantity, @@ -152,9 +151,19 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su iFee, timestamp ) + .map(_.signWith(sender.privateKey)) .explicitGet() setAssetScript = SetAssetScriptTransaction - .selfSigned(1.toByte, sender, IssuedAsset(issue.id()), Some(script2), 1 * Constants.UnitsInWave + ScriptExtraFee, timestamp) + .create( + 1.toByte, + sender.publicKey, + IssuedAsset(issue.id()), + Some(script2), + 1 * Constants.UnitsInWave + ScriptExtraFee, + timestamp, + Proofs.empty + ) + .map(_.signWith(sender.privateKey)) .explicitGet() } yield (issue, setAssetScript) @@ -169,7 +178,10 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su fee <- smallFeeGen timestamp <- timestampGen script <- Gen.option(contractOrExpr) - } yield SetScriptTransaction.selfSigned(1.toByte, sender, script, fee, timestamp).explicitGet() + } yield SetScriptTransaction + .create(1.toByte, sender.publicKey, script, fee, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() private val leaseParamGen = for { sender <- accountGen @@ -180,14 +192,26 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su } yield (sender, amount, fee, timestamp, recipient) def createLease(sender: KeyPair, amount: Long, fee: Long, timestamp: Long, recipient: AddressOrAlias): Gen[LeaseTransaction] = { - val v1 = LeaseTransaction.selfSigned(1.toByte, sender, recipient, amount, fee, timestamp).explicitGet() - val v2 = LeaseTransaction.selfSigned(2.toByte, sender, recipient, amount, fee, timestamp).explicitGet() + val v1 = LeaseTransaction + .create(1.toByte, sender.publicKey, recipient, amount, fee, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() + val v2 = LeaseTransaction + .create(2.toByte, sender.publicKey, recipient, amount, fee, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() Gen.oneOf(v1, v2) } def createLeaseCancel(sender: KeyPair, leaseId: ByteStr, cancelFee: Long, timestamp: Long): Gen[LeaseCancelTransaction] = { - val v1 = LeaseCancelTransaction.selfSigned(1.toByte, sender, leaseId, cancelFee, timestamp + 1).explicitGet() - val v2 = LeaseCancelTransaction.selfSigned(2.toByte, sender, leaseId, cancelFee, timestamp + 1).explicitGet() + val v1 = LeaseCancelTransaction + .create(1.toByte, sender.publicKey, leaseId, cancelFee, timestamp + 1, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() + val v2 = LeaseCancelTransaction + .create(2.toByte, sender.publicKey, leaseId, cancelFee, timestamp + 1, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() Gen.oneOf(v1, v2) } val leaseAndCancelGen: Gen[(LeaseTransaction, LeaseCancelTransaction)] = for { @@ -231,23 +255,35 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su def transferGeneratorP(sender: KeyPair, recipient: AddressOrAlias, assetId: Asset, feeAssetId: Asset): Gen[TransferTransaction] = for { (_, _, _, amount, timestamp, _, feeAmount, attachment) <- transferParamGen - } yield TransferTransaction.selfSigned(1.toByte, sender, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp).explicitGet() + } yield TransferTransaction + .create(1.toByte, sender.publicKey, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() def versionedTransferGeneratorP(sender: KeyPair, recipient: AddressOrAlias, assetId: Asset, feeAssetId: Asset): Gen[TransferTransaction] = for { (_, _, _, amount, timestamp, _, feeAmount, attachment) <- transferParamGen - } yield TransferTransaction.selfSigned(2.toByte, sender, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp).explicitGet() + } yield TransferTransaction + .create(2.toByte, sender.publicKey, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() def transferGeneratorP(timestamp: Long, sender: KeyPair, recipient: AddressOrAlias, maxAmount: Long): Gen[TransferTransaction] = for { amount <- Gen.choose(1L, maxAmount) (_, _, _, _, _, _, feeAmount, attachment) <- transferParamGen - } yield TransferTransaction.selfSigned(1.toByte, sender, recipient, Waves, amount, Waves, feeAmount, attachment, timestamp).explicitGet() + } yield TransferTransaction + .create(1.toByte, sender.publicKey, recipient, Waves, amount, Waves, feeAmount, attachment, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() def transferGeneratorP(timestamp: Long, sender: KeyPair, recipient: AddressOrAlias, assetId: Asset, feeAssetId: Asset): Gen[TransferTransaction] = for { (_, _, _, amount, _, _, feeAmount, attachment) <- transferParamGen - } yield TransferTransaction.selfSigned(1.toByte, sender, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp).explicitGet() + } yield TransferTransaction + .create(1.toByte, sender.publicKey, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() def wavesTransferGeneratorP(sender: KeyPair, recipient: AddressOrAlias): Gen[TransferTransaction] = transferGeneratorP(sender, recipient, Waves, Waves) @@ -262,17 +298,23 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su fee: Long, timestamp: Long ): Either[ValidationError, TransferTransaction] = - TransferTransaction.selfSigned(1.toByte, sender, recipient, Waves, amount, Waves, fee, ByteStr.empty, timestamp) + TransferTransaction + .create(1.toByte, sender.publicKey, recipient, Waves, amount, Waves, fee, ByteStr.empty, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) val transferV1Gen: Gen[TransferTransaction] = (for { (assetId, sender, recipient, amount, timestamp, feeAssetId, feeAmount, attachment) <- transferParamGen - } yield TransferTransaction.selfSigned(1.toByte, sender, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp).explicitGet()) + } yield TransferTransaction + .create(1.toByte, sender.publicKey, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet()) .label("transferTransaction") val transferV2Gen: Gen[TransferTransaction] = (for { (assetId, sender, recipient, amount, timestamp, feeAssetId, feeAmount, attachment) <- transferParamGen } yield TransferTransaction - .selfSigned(2.toByte, sender, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp) + .create(2.toByte, sender.publicKey, recipient, assetId, amount, feeAssetId, feeAmount, attachment, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) .explicitGet( )) .label("VersionedTransferTransaction") @@ -283,16 +325,22 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su sender <- accountGen alias: Alias <- aliasGen tx <- Gen.oneOf( - CreateAliasTransaction.selfSigned(Transaction.V1, sender, alias.name, MinIssueFee, timestamp).explicitGet(), - CreateAliasTransaction.selfSigned(Transaction.V2, sender, alias.name, MinIssueFee, timestamp).explicitGet() + CreateAliasTransaction + .create(Transaction.V1, sender.publicKey, alias.name, MinIssueFee, timestamp) + .map(_.signWith(sender.privateKey)) + .explicitGet(), + CreateAliasTransaction + .create(Transaction.V2, sender.publicKey, alias.name, MinIssueFee, timestamp) + .map(_.signWith(sender.privateKey)) + .explicitGet() ) } yield tx def createAliasGen(sender: KeyPair, alias: Alias, fee: Long, timestamp: Long): Gen[CreateAliasTransaction] = for { tx <- Gen.oneOf( - CreateAliasTransaction.selfSigned(Transaction.V1, sender, alias.name, fee, timestamp).explicitGet(), - CreateAliasTransaction.selfSigned(Transaction.V2, sender, alias.name, fee, timestamp).explicitGet() + CreateAliasTransaction.create(Transaction.V1, sender.publicKey, alias.name, fee, timestamp).map(_.signWith(sender.privateKey)).explicitGet(), + CreateAliasTransaction.create(Transaction.V2, sender.publicKey, alias.name, fee, timestamp).map(_.signWith(sender.privateKey)).explicitGet() ) } yield tx @@ -313,7 +361,19 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su timestamp: Long ): Gen[IssueTransaction] = IssueTransaction - .selfSigned(TxVersion.V1, issuer, new String(nameBytes), new String(descriptionBytes), quantity, decimals, reissuable, None, fee, timestamp) + .create( + TxVersion.V1, + issuer.publicKey, + new String(nameBytes), + new String(descriptionBytes), + quantity, + decimals, + reissuable, + None, + fee, + timestamp + ) + .map(_.signWith(issuer.privateKey)) .explicitGet() def createReissue( @@ -326,8 +386,14 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su ): Gen[ReissueTransaction] = { for { tx <- Gen.oneOf( - ReissueTransaction.selfSigned(1.toByte, reissuer, assetId, quantity, reissuable, fee, timestamp).explicitGet(), - ReissueTransaction.selfSigned(2.toByte, reissuer, assetId, quantity, reissuable, fee, timestamp).explicitGet() + ReissueTransaction + .create(1.toByte, reissuer.publicKey, assetId, quantity, reissuable, fee, timestamp) + .map(_.signWith(reissuer.privateKey)) + .explicitGet(), + ReissueTransaction + .create(2.toByte, reissuer.publicKey, assetId, quantity, reissuable, fee, timestamp) + .map(_.signWith(reissuer.privateKey)) + .explicitGet() ) } yield tx } @@ -335,8 +401,8 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su def createBurn(burner: KeyPair, assetId: IssuedAsset, amount: Long, fee: Long, timestamp: Long): Gen[BurnTransaction] = { for { tx <- Gen.oneOf( - BurnTransaction.selfSigned(1.toByte, burner, assetId, amount, fee, timestamp).explicitGet(), - BurnTransaction.selfSigned(2.toByte, burner, assetId, amount, fee, timestamp).explicitGet() + BurnTransaction.create(1.toByte, burner.publicKey, assetId, amount, fee, timestamp).map(_.signWith(burner.privateKey)).explicitGet(), + BurnTransaction.create(2.toByte, burner.publicKey, assetId, amount, fee, timestamp).map(_.signWith(burner.privateKey)).explicitGet() ) } yield tx } @@ -376,9 +442,9 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su for { (_, assetName, description, quantity, decimals, reissuable, iFee, timestamp) <- issueParamGen issue = IssueTransaction - .selfSigned( + .create( TxVersion.V1, - sender, + sender.publicKey, new String(assetName), new String(description), quantity, @@ -388,6 +454,7 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su iFee, timestamp ) + .map(_.signWith(sender.privateKey)) .explicitGet() minFee <- smallFeeGen minFee1 <- smallFeeGen @@ -395,9 +462,18 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su fee = (if (reducedFee) 0.001 * Constants.UnitsInWave else 1 * Constants.UnitsInWave.toDouble).toLong } yield ( issue, - SponsorFeeTransaction.selfSigned(1.toByte, sender, assetId, Some(minFee), fee, timestamp).explicitGet(), - SponsorFeeTransaction.selfSigned(1.toByte, sender, assetId, Some(minFee1), fee, timestamp).explicitGet(), - SponsorFeeTransaction.selfSigned(1.toByte, sender, assetId, None, fee, timestamp).explicitGet() + SponsorFeeTransaction + .create(1.toByte, sender.publicKey, assetId, Some(minFee), fee, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet(), + SponsorFeeTransaction + .create(1.toByte, sender.publicKey, assetId, Some(minFee1), fee, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet(), + SponsorFeeTransaction + .create(1.toByte, sender.publicKey, assetId, None, fee, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() ) val sponsorFeeGen: Gen[SponsorFeeTransaction] = for { @@ -424,7 +500,10 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su fc <- funcCallGen fee <- smallFeeGen timestamp <- timestampGen - } yield Signed.invokeScript(1.toByte, sender, dappAddress.toAddress, Some(fc), payments, fee, Waves, timestamp) + } yield InvokeScriptTransaction + .create(1.toByte, sender.publicKey, dappAddress.toAddress, Some(fc), payments, fee, Waves, timestamp) + .map(_.signWith(sender.privateKey)) + .explicitGet() val paymentListGen: Gen[Seq[Payment]] = for { @@ -456,30 +535,53 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su val orderV1Gen: Gen[Order] = for { (sender, matcher, pair, orderType, price, amount, timestamp, expiration, matcherFee) <- orderParamGen - } yield Order.selfSigned(1.toByte, sender, matcher.publicKey, pair, orderType, price, amount, timestamp, expiration, matcherFee).explicitGet() + } yield TxHelpers.order( + orderType = orderType, + amountAsset = pair.amountAsset, + priceAsset = pair.priceAsset, + amount = price, + price = amount, + fee = matcherFee, + sender = sender, + matcher = matcher, + timestamp = timestamp, + expiration = expiration, + version = 1.toByte + ) val orderV2Gen: Gen[Order] = for { (sender, matcher, pair, orderType, amount, price, timestamp, expiration, matcherFee) <- orderParamGen - } yield Order.selfSigned(2.toByte, sender, matcher.publicKey, pair, orderType, amount, price, timestamp, expiration, matcherFee).explicitGet() + } yield TxHelpers.order( + orderType = orderType, + amountAsset = pair.amountAsset, + priceAsset = pair.priceAsset, + amount = amount, + price = price, + fee = matcherFee, + sender = sender, + matcher = matcher, + timestamp = timestamp, + expiration = expiration, + version = 2.toByte + ) val orderV3Gen: Gen[Order] = for { (sender, matcher, pair, orderType, price, amount, timestamp, expiration, matcherFee) <- orderParamGen matcherFeeAssetId <- assetIdGen - } yield Order - .selfSigned( - 3.toByte, - sender, - matcher.publicKey, - pair, - orderType, - amount, - price, - timestamp, - expiration, - matcherFee, - Asset.fromCompatId(matcherFeeAssetId) - ) - .explicitGet() + } yield TxHelpers.order( + orderType = orderType, + amountAsset = pair.amountAsset, + priceAsset = pair.priceAsset, + feeAsset = Asset.fromCompatId(matcherFeeAssetId), + amount = amount, + price = price, + fee = matcherFee, + sender = sender, + matcher = matcher, + timestamp = timestamp, + expiration = expiration, + version = 3.toByte + ) val orderGen: Gen[Order] = Gen.oneOf(orderV1Gen, orderV2Gen, orderV3Gen) @@ -490,7 +592,19 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su timestamp <- Arbitrary.arbitrary[Long] expiration <- Arbitrary.arbitrary[Long] matcherFee <- Arbitrary.arbitrary[Long] - } yield Order.selfSigned(1: Byte, sender, matcher.publicKey, pair, orderType, amount, price, timestamp, expiration, matcherFee).explicitGet() + } yield TxHelpers.order( + orderType = orderType, + amountAsset = pair.amountAsset, + priceAsset = pair.priceAsset, + amount = amount, + price = price, + fee = matcherFee, + sender = sender, + matcher = matcher, + timestamp = timestamp, + expiration = expiration, + version = 1.toByte + ) val exchangeTransactionGen: Gen[ExchangeTransaction] = for { sender1 <- accountGen @@ -551,7 +665,8 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su val sellFee = (BigInt(matcherFee) * BigInt(matchedAmount) / BigInt(amount2)).longValue val trans = ExchangeTransaction - .signed(1.toByte, matcher.privateKey, o1, o2, matchedAmount, price, buyFee, sellFee, (buyFee + sellFee) / 2, expiration - 100) + .create(1.toByte, o1, o2, matchedAmount, price, buyFee, sellFee, (buyFee + sellFee) / 2, expiration - 100) + .map(_.signWith(matcher.privateKey)) .explicitGet() trans @@ -600,7 +715,8 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su val o2 = mkO2(seller, matcher.publicKey, assetPair, amount2, price, timestamp, expiration, matcherFee) ExchangeTransaction - .signed(2.toByte, matcher.privateKey, o1, o2, matchedAmount, price, buyFee, sellFee, (buyFee + sellFee) / 2, expiration - 100) + .create(2.toByte, o1, o2, matchedAmount, price, buyFee, sellFee, (buyFee + sellFee) / 2, expiration - 100) + .map(_.signWith(matcher.privateKey)) .explicitGet() } } @@ -694,7 +810,10 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su uniq = data.foldRight(List.empty[DataEntry[?]]) { (e, es) => if (es.exists(_.key == e.key)) es else e :: es } - } yield DataTransaction.selfSigned(if (withDeleteEntry) 2.toByte else 1.toByte, sender, uniq, 15000000, timestamp).explicitGet()) + } yield DataTransaction + .create(if (withDeleteEntry) 2.toByte else 1.toByte, sender.publicKey, uniq, 15000000, timestamp) + .map(_.signWith(sender.privateKey)) + .explicitGet()) .label("DataTransaction") def issueV2TransactionGen( @@ -712,11 +831,15 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { su quantity = quantityParam.getOrElse(generatedQuantity) fee = feeParam.getOrElse(generatedFee) } yield IssueTransaction - .selfSigned(TxVersion.V2, sender, new String(assetName), new String(description), quantity, decimals, reissuable, script, fee, timestamp) + .create(TxVersion.V2, sender.publicKey, new String(assetName), new String(description), quantity, decimals, reissuable, script, fee, timestamp) + .map(_.signWith(sender.privateKey)) .explicitGet() def invokeExpressionTransactionGen(sender: KeyPair, script: ExprScript, feeAmount: Long): Gen[InvokeExpressionTransaction] = - InvokeExpressionTransaction.selfSigned(1, sender, script, feeAmount, Waves, ntpTime.getTimestamp()).explicitGet() + InvokeExpressionTransaction + .create(1, sender.publicKey, script, feeAmount, Waves, ntpTime.getTimestamp(), Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() } trait TransactionGen extends TransactionGenBase { suite: Suite => } diff --git a/node/testkit/src/main/scala/com/wavesplatform/transaction/TxHelpers.scala b/node/testkit/src/main/scala/com/wavesplatform/transaction/TxHelpers.scala index b89114c8fbe..f0e40c66964 100644 --- a/node/testkit/src/main/scala/com/wavesplatform/transaction/TxHelpers.scala +++ b/node/testkit/src/main/scala/com/wavesplatform/transaction/TxHelpers.scala @@ -31,7 +31,6 @@ import com.wavesplatform.transaction.smart.{InvokeExpressionTransaction, InvokeS import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTransfer import com.wavesplatform.transaction.transfer.{MassTransferTransaction, TransferTransaction} import com.wavesplatform.transaction.utils.EthConverters.* -import com.wavesplatform.transaction.utils.Signed import monix.execution.atomic.AtomicLong import org.web3j.crypto.ECKeyPair @@ -85,7 +84,10 @@ object TxHelpers { version: Byte = TxVersion.V2, chainId: Byte = AddressScheme.current.chainId ): TransferTransaction = - TransferTransaction.selfSigned(version, from, to, asset, amount, feeAsset, fee, attachment, timestamp, chainId).explicitGet() + TransferTransaction + .create(version, from.publicKey, to, asset, amount, feeAsset, fee, attachment, timestamp, Proofs.empty, chainId) + .map(_.signWith(from.privateKey)) + .explicitGet() def transferUnsigned( from: KeyPair = defaultSigner, @@ -120,16 +122,18 @@ object TxHelpers { chainId: Byte = AddressScheme.current.chainId ): MassTransferTransaction = MassTransferTransaction - .selfSigned( + .create( version, - from, + from.publicKey, asset, to.map { case (r, a) => MassTransferTransaction.ParsedTransfer(r, TxNonNegativeAmount.unsafeFrom(a)) }, fee, timestamp, ByteStr.empty, + Proofs.empty, chainId ) + .map(_.signWith(from.privateKey)) .explicitGet() def issue( @@ -146,7 +150,8 @@ object TxHelpers { chainId: Byte = AddressScheme.current.chainId ): IssueTransaction = IssueTransaction - .selfSigned(version, issuer, name, description, amount, decimals, reissuable, script, fee, timestamp, chainId) + .create(version, issuer.publicKey, name, description, amount, decimals, reissuable, script, fee, timestamp, chainId = chainId) + .map(_.signWith(issuer.privateKey)) .explicitGet() def reissue( @@ -156,20 +161,31 @@ object TxHelpers { reissuable: Boolean = true, fee: Long = TestValues.fee, version: TxVersion = TxVersion.V2, - chainId: Byte = AddressScheme.current.chainId + chainId: Byte = AddressScheme.current.chainId, + timestamp: TxTimestamp = timestamp ): ReissueTransaction = ReissueTransaction - .selfSigned(version, sender, asset, amount, reissuable = reissuable, fee, timestamp, chainId) + .create(version, sender.publicKey, asset, amount, reissuable = reissuable, fee, timestamp, chainId = chainId) + .map(_.signWith(sender.privateKey)) .explicitGet() def dataEntry(account: KeyPair, value: DataEntry[?]): DataTransaction = - DataTransaction.selfSigned(TxVersion.V1, account, Seq(value), TestValues.fee * 3, timestamp).explicitGet() + DataTransaction + .create(TxVersion.V1, account.publicKey, Seq(value), TestValues.fee * 3, timestamp) + .map(_.signWith(account.privateKey)) + .explicitGet() def dataSingle(account: KeyPair = defaultSigner, key: String = "test", value: String = "test", fee: Long = TestValues.fee): DataTransaction = data(account, Seq(StringDataEntry(key, value)), fee) - def data(account: KeyPair, entries: Seq[DataEntry[?]], fee: Long = TestValues.fee * 3, version: TxVersion = TxVersion.V1): DataTransaction = - DataTransaction.selfSigned(version, account, entries, fee, timestamp).explicitGet() + def data( + account: KeyPair, + entries: Seq[DataEntry[?]], + fee: Long = TestValues.fee * 3, + version: TxVersion = TxVersion.V1, + timestamp: TxTimestamp = timestamp + ): DataTransaction = + DataTransaction.create(version, account.publicKey, entries, fee, timestamp).map(_.signWith(account.privateKey)).explicitGet() def dataV2( account: KeyPair, @@ -177,10 +193,13 @@ object TxHelpers { fee: Long = TestValues.fee * 3, chainId: Byte = AddressScheme.current.chainId ): DataTransaction = - DataTransaction.selfSigned(TxVersion.V2, account, entries, fee, timestamp, chainId).explicitGet() + DataTransaction + .create(TxVersion.V2, account.publicKey, entries, fee, timestamp, chainId = chainId) + .map(_.signWith(account.privateKey)) + .explicitGet() def dataWithMultipleEntries(account: KeyPair, entries: Seq[DataEntry[?]]): DataTransaction = - DataTransaction.selfSigned(TxVersion.V1, account, entries, TestValues.fee * 3, timestamp).explicitGet() + DataTransaction.create(TxVersion.V1, account.publicKey, entries, TestValues.fee * 3, timestamp).map(_.signWith(account.privateKey)).explicitGet() def burn( asset: IssuedAsset, @@ -188,9 +207,13 @@ object TxHelpers { sender: KeyPair = defaultSigner, fee: Long = TestValues.fee, version: TxVersion = TxVersion.V3, - chainId: Byte = AddressScheme.current.chainId + chainId: Byte = AddressScheme.current.chainId, + timestamp: TxTimestamp = timestamp ): BurnTransaction = - BurnTransaction.selfSigned(version, sender, asset, amount, fee, timestamp, chainId).explicitGet() + BurnTransaction + .create(version, sender.publicKey, asset, amount, fee, timestamp, chainId = chainId) + .map(_.signWith(sender.privateKey)) + .explicitGet() def updateAssetInfo( assetId: ByteStr, @@ -202,7 +225,10 @@ object TxHelpers { version: TxVersion = TxVersion.V1, chainId: Byte = AddressScheme.current.chainId ): UpdateAssetInfoTransaction = - UpdateAssetInfoTransaction.selfSigned(version, sender, assetId, name, desc, timestamp, fee, feeAsset, chainId).explicitGet() + UpdateAssetInfoTransaction + .create(version, sender.publicKey, IssuedAsset(assetId), name, desc, timestamp, fee, feeAsset, Proofs.empty, chainId) + .map(_.signWith(sender.privateKey)) + .explicitGet() def orderV3(orderType: OrderType, asset: Asset, feeAsset: Asset = Waves): Order = { order(orderType, asset, Waves, feeAsset) @@ -262,9 +288,8 @@ object TxHelpers { chainId: Byte ): ExchangeTransaction = ExchangeTransaction - .signed( + .create( version, - matcher.privateKey, order1, order2, order1.amount.value, @@ -273,8 +298,9 @@ object TxHelpers { order2.matcherFee.value, fee, timestamp, - chainId + chainId = chainId ) + .map(_.signWith(matcher.privateKey)) .explicitGet() def exchange( @@ -291,9 +317,8 @@ object TxHelpers { chainId: Byte = AddressScheme.current.chainId ): ExchangeTransaction = ExchangeTransaction - .signed( + .create( version, - matcher = matcher.privateKey, order1 = order1, order2 = order2, amount = amount, @@ -304,6 +329,7 @@ object TxHelpers { timestamp = timestamp, chainId = chainId ) + .map(_.signWith(matcher.privateKey)) .explicitGet() def script(scriptText: String): Script = { @@ -370,7 +396,10 @@ object TxHelpers { chainId: Byte = AddressScheme.current.chainId, timestamp: TxTimestamp = timestamp ): SetScriptTransaction = { - SetScriptTransaction.selfSigned(version, acc, Some(script), fee, timestamp, chainId).explicitGet() + SetScriptTransaction + .create(version, acc.publicKey, Some(script), fee, timestamp, Proofs.empty, chainId) + .map(_.signWith(acc.privateKey)) + .explicitGet() } def removeScript( @@ -380,7 +409,7 @@ object TxHelpers { chainId: Byte = AddressScheme.current.chainId, timestamp: TxTimestamp = timestamp ): SetScriptTransaction = { - SetScriptTransaction.selfSigned(version, acc, None, fee, timestamp, chainId).explicitGet() + SetScriptTransaction.create(version, acc.publicKey, None, fee, timestamp, Proofs.empty, chainId).map(_.signWith(acc.privateKey)).explicitGet() } def setAssetScript( @@ -392,7 +421,10 @@ object TxHelpers { version: TxVersion = TxVersion.V1, chainId: Byte = AddressScheme.current.chainId ): SetAssetScriptTransaction = { - SetAssetScriptTransaction.selfSigned(version, acc, asset, Some(script), fee, timestamp, chainId).explicitGet() + SetAssetScriptTransaction + .create(version, acc.publicKey, asset, Some(script), fee, timestamp, Proofs.empty, chainId) + .map(_.signWith(acc.privateKey)) + .explicitGet() } def invoke( @@ -405,18 +437,33 @@ object TxHelpers { feeAssetId: Asset = Waves, version: TxVersion = TxVersion.V2, timestamp: TxTimestamp = timestamp - ): InvokeScriptTransaction = { - val fc = func.map(name => functionCall(name, args*)) - Signed.invokeScript(version, invoker, dApp, fc, payments, fee, feeAssetId, timestamp) - } + ): InvokeScriptTransaction = + InvokeScriptTransaction + .create( + version, + invoker.publicKey, + dApp, + func.map(name => functionCall(name, args*)), + payments, + fee, + feeAssetId, + timestamp, + chainId = dApp.chainId + ) + .map(_.signWith(invoker.privateKey)) + .explicitGet() def invokeExpression( expression: ExprScript, sender: KeyPair = defaultSigner, fee: Long = TestValues.fee, - feeAssetId: Asset = Waves + feeAssetId: Asset = Waves, + version: TxVersion = TxVersion.V1 ): InvokeExpressionTransaction = - InvokeExpressionTransaction.selfSigned(TxVersion.V1, sender, expression, fee, feeAssetId, timestamp).explicitGet() + InvokeExpressionTransaction + .create(version, sender.publicKey, expression, fee, feeAssetId, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() def functionCall(func: String, args: EXPR*): FUNCTION_CALL = { FUNCTION_CALL(FunctionHeader.User(func), args.toList) @@ -430,7 +477,10 @@ object TxHelpers { timestamp: TxTimestamp = timestamp, version: TxVersion = TxVersion.V2 ): LeaseTransaction = { - LeaseTransaction.selfSigned(version, sender, recipient, amount, fee, timestamp).explicitGet() + LeaseTransaction + .create(version, sender.publicKey, recipient, amount, fee, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() } def leaseCancel( @@ -441,7 +491,10 @@ object TxHelpers { version: TxVersion = TxVersion.V2, chainId: Byte = AddressScheme.current.chainId ): LeaseCancelTransaction = { - LeaseCancelTransaction.selfSigned(version, sender, leaseId, fee, timestamp, chainId).explicitGet() + LeaseCancelTransaction + .create(version, sender.publicKey, leaseId, fee, timestamp, Proofs.empty, chainId) + .map(_.signWith(sender.privateKey)) + .explicitGet() } def sponsor( @@ -450,9 +503,13 @@ object TxHelpers { sender: KeyPair = defaultSigner, fee: Long = 1.waves, version: TxVersion = TxVersion.V1, - chainId: Byte = AddressScheme.current.chainId + chainId: Byte = AddressScheme.current.chainId, + timestamp: TxTimestamp = timestamp ): SponsorFeeTransaction = { - SponsorFeeTransaction.selfSigned(version, sender, asset, minSponsoredAssetFee, fee, timestamp, chainId).explicitGet() + SponsorFeeTransaction + .create(version, sender.publicKey, asset, minSponsoredAssetFee, fee, timestamp, Proofs.empty, chainId) + .map(_.signWith(sender.privateKey)) + .explicitGet() } def createAlias( @@ -460,9 +517,10 @@ object TxHelpers { sender: KeyPair = defaultSigner, fee: Long = TestValues.fee, version: TxVersion = TxVersion.V2, - chainId: Byte = AddressScheme.current.chainId + chainId: Byte = AddressScheme.current.chainId, + timestamp: TxTimestamp = timestamp ): CreateAliasTransaction = { - CreateAliasTransaction.selfSigned(version, sender, name, fee, timestamp, chainId).explicitGet() + CreateAliasTransaction.create(version, sender.publicKey, name, fee, timestamp, chainId = chainId).map(_.signWith(sender.privateKey)).explicitGet() } def commitToGeneration( diff --git a/node/tests/src/test/scala/com/wavesplatform/BlocksTransactionsHelpers.scala b/node/tests/src/test/scala/com/wavesplatform/BlocksTransactionsHelpers.scala index 984987b8d45..5d9991969b1 100644 --- a/node/tests/src/test/scala/com/wavesplatform/BlocksTransactionsHelpers.scala +++ b/node/tests/src/test/scala/com/wavesplatform/BlocksTransactionsHelpers.scala @@ -13,9 +13,7 @@ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} -import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.utils.Signed -import com.wavesplatform.transaction.{DataTransaction, Transaction, TxVersion} +import com.wavesplatform.transaction.{DataTransaction, Transaction, TxHelpers, TxVersion} import org.scalacheck.Gen trait BlocksTransactionsHelpers { self: TransactionGen => @@ -30,7 +28,7 @@ trait BlocksTransactionsHelpers { self: TransactionGen => ): Gen[Transaction] = for { timestamp <- timestamp - } yield TransferTransaction.selfSigned(1.toByte, from, to, Waves, amount, Waves, FeeAmount, ByteStr.empty, timestamp).explicitGet() + } yield TxHelpers.transfer(from, to, amount, Waves, FeeAmount, Waves, ByteStr.empty, timestamp, 1.toByte) def transferV2( from: KeyPair, @@ -40,7 +38,7 @@ trait BlocksTransactionsHelpers { self: TransactionGen => ): Gen[Transaction] = for { timestamp <- timestamp - } yield TransferTransaction.selfSigned(2.toByte, from, to, Waves, amount, Waves, FeeAmount, ByteStr.empty, timestamp).explicitGet() + } yield TxHelpers.transfer(from, to, amount, Waves, FeeAmount, Waves, ByteStr.empty, timestamp, 2.toByte) def transferAsset( asset: IssuedAsset, @@ -51,7 +49,7 @@ trait BlocksTransactionsHelpers { self: TransactionGen => ): Gen[Transaction] = for { timestamp <- timestamp - } yield TransferTransaction.selfSigned(1.toByte, from, to, asset, amount, Waves, FeeAmount, ByteStr.empty, timestamp).explicitGet() + } yield TxHelpers.transfer(from, to, amount, asset, FeeAmount, Waves, ByteStr.empty, timestamp, 1.toByte) def lease( from: KeyPair, @@ -61,40 +59,39 @@ trait BlocksTransactionsHelpers { self: TransactionGen => ): Gen[LeaseTransaction] = for { timestamp <- timestamp - } yield LeaseTransaction.selfSigned(1.toByte, from, to, amount, FeeAmount, timestamp).explicitGet() + } yield TxHelpers.lease(from, to, amount, FeeAmount, timestamp, 1.toByte) def leaseCancel(from: KeyPair, leaseId: ByteStr, timestamp: Gen[Long] = timestampGen): Gen[LeaseCancelTransaction] = for { timestamp <- timestamp - } yield LeaseCancelTransaction.selfSigned(1.toByte, from, leaseId, FeeAmount, timestamp).explicitGet() + } yield TxHelpers.leaseCancel(leaseId, from, FeeAmount, timestamp, 1.toByte) def data(from: KeyPair, dataKey: String, timestamp: Gen[Long] = timestampGen): Gen[DataTransaction] = for { timestamp <- timestamp - } yield DataTransaction.selfSigned(1.toByte, from, List(StringDataEntry(dataKey, Gen.numStr.sample.get)), FeeAmount, timestamp).explicitGet() + } yield TxHelpers.data(from, List(StringDataEntry(dataKey, Gen.numStr.sample.get)), FeeAmount, timestamp = timestamp) def nftIssue(from: KeyPair, timestamp: Gen[Long] = timestampGen): Gen[IssueTransaction] = for { timestamp <- timestamp - } yield IssueTransaction - .selfSigned( - TxVersion.V1, + } yield TxHelpers + .issue( from, + 1, + 0.toByte, "test", "", - 1, - 0, - reissuable = false, - script = None, 100000000L, - timestamp + None, + false, + timestamp, + TxVersion.V1 ) - .explicitGet() def setScript(from: KeyPair, script: Script, timestamp: Gen[Long] = timestampGen): Gen[SetScriptTransaction] = for { timestamp <- timestamp - } yield SetScriptTransaction.selfSigned(1.toByte, from, Some(script), FeeAmount, timestamp).explicitGet() + } yield TxHelpers.setScript(from, script, FeeAmount, 1.toByte, timestamp = timestamp) def invokeScript( from: KeyPair, @@ -105,7 +102,7 @@ trait BlocksTransactionsHelpers { self: TransactionGen => ): Gen[InvokeScriptTransaction] = for { timestamp <- timestamp - } yield Signed.invokeScript(1.toByte, from, dapp, Some(call), payments, FeeAmount * 2, Waves, timestamp) + } yield TxHelpers.invoke(dapp, Some(call.function.funcName), call.args, payments, from, FeeAmount * 2, Waves, 1.toByte, timestamp) } object UnsafeBlocks { diff --git a/node/tests/src/test/scala/com/wavesplatform/RxScheduler.scala b/node/tests/src/test/scala/com/wavesplatform/RxScheduler.scala index cc1f9d2d2ef..791f4554fcb 100644 --- a/node/tests/src/test/scala/com/wavesplatform/RxScheduler.scala +++ b/node/tests/src/test/scala/com/wavesplatform/RxScheduler.scala @@ -7,6 +7,7 @@ import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.crypto.* import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.transaction.Asset.Waves +import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.transfer.* import monix.execution.schedulers.SchedulerService import monix.execution.{Ack, Scheduler} @@ -38,7 +39,7 @@ trait RxScheduler extends BeforeAndAfterAll { suite: Suite => def block(id: Int): Block = TestBlock.create(Seq.empty).block.copy(signature = byteStr(id)) def microBlock(total: Int, prev: Int): MicroBlock = { - val tx = TransferTransaction.selfSigned(1.toByte, signer, signer.toAddress, Waves, 1, Waves, 1, ByteStr.empty, 1).explicitGet() + val tx = TransferTransaction.create(1.toByte, signer.publicKey, signer.toAddress, Waves, 1, Waves, 1, ByteStr.empty, 1, Proofs.empty).map(_.signWith(signer.privateKey)).explicitGet() MicroBlock.buildAndSign(3.toByte, signer, Seq(tx), byteStr(prev), byteStr(total), None, None).explicitGet() } diff --git a/node/tests/src/test/scala/com/wavesplatform/api/common/CommonAccountApiSpec.scala b/node/tests/src/test/scala/com/wavesplatform/api/common/CommonAccountApiSpec.scala index 0a356565c5e..c1e18d956ec 100644 --- a/node/tests/src/test/scala/com/wavesplatform/api/common/CommonAccountApiSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/api/common/CommonAccountApiSpec.scala @@ -9,12 +9,12 @@ import com.wavesplatform.lang.directives.values.V5 import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.lang.v1.traits.domain.{Lease, Recipient} import com.wavesplatform.settings.TestFunctionalitySettings -import com.wavesplatform.state.{DataEntry, EmptyDataEntry, StringDataEntry, diffs, Height, TransactionId} +import com.wavesplatform.state.{DataEntry, EmptyDataEntry, Height, StringDataEntry, TransactionId, diffs} import com.wavesplatform.test.DomainPresets.RideV4 -import com.wavesplatform.test.FreeSpec +import com.wavesplatform.test.* import com.wavesplatform.transaction.TxHelpers.data import com.wavesplatform.transaction.TxVersion.V2 -import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction, TxHelpers} +import com.wavesplatform.transaction.{GenesisTransaction, TxHelpers} import com.wavesplatform.{BlocksTransactionsHelpers, history} import monix.execution.Scheduler.Implicits.global @@ -61,9 +61,9 @@ class CommonAccountApiSpec extends FreeSpec with WithDomain with BlocksTransacti ts = System.currentTimeMillis() fee <- smallFeeGen genesis = GenesisTransaction.create(acc.toAddress, diffs.ENOUGH_AMT, ts).explicitGet() - data1 = DataTransaction.selfSigned(1.toByte, acc, Seq(entry1), fee, ts).explicitGet() - data2 = DataTransaction.selfSigned(1.toByte, acc, Seq(entry2), fee, ts).explicitGet() - data3 = DataTransaction.selfSigned(1.toByte, acc, Seq(entry3), fee, ts).explicitGet() + data1 = TxHelpers.data(acc, Seq(entry1), fee) + data2 = TxHelpers.data(acc, Seq(entry2), fee) + data3 = TxHelpers.data(acc, Seq(entry3), fee) (block1, mbs1) = UnsafeBlocks.unsafeChainBaseAndMicro(history.randomSig, Seq(genesis), Seq(Seq(data1)), acc, 3, ts) (block2, mbs2) = UnsafeBlocks.unsafeChainBaseAndMicro(mbs1.last.totalResBlockSig, Seq(data2), Seq(Seq(data3)), acc, 3, ts) } yield (acc, block1, mbs1.head, block2, mbs2.head) @@ -83,6 +83,20 @@ class CommonAccountApiSpec extends FreeSpec with WithDomain with BlocksTransacti } } } + + val fundSource = TxHelpers.signer(1003) + val dataSender = TxHelpers.signer(1004) + "filters entries created and deleted in liquid block" in withDomain(DomainPresets.RideV4, Seq(fundSource -> 100.waves)) { d => + def dataList() = d.accountsApi.dataStream(dataSender.toAddress, None).toListL.runSyncUnsafe() + + val e1 = StringDataEntry("k1", "v1") + val e2 = StringDataEntry("k2", "v2") + d.appendKeyBlock() + d.appendMicroBlock(TxHelpers.transfer(fundSource, dataSender.toAddress, 1.waves), TxHelpers.data(dataSender, Seq(e1, e2))) + dataList() shouldBe Seq(e1, e2) + d.appendMicroBlock(TxHelpers.data(dataSender, Seq(EmptyDataEntry("k1"), EmptyDataEntry("k2")), version = 2.toByte)) + dataList() shouldBe empty + } } "Waves distribution" - { diff --git a/node/tests/src/test/scala/com/wavesplatform/api/eth/EthRpcRouteSpec.scala b/node/tests/src/test/scala/com/wavesplatform/api/eth/EthRpcRouteSpec.scala index a3252cb946f..2d007f79aed 100644 --- a/node/tests/src/test/scala/com/wavesplatform/api/eth/EthRpcRouteSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/api/eth/EthRpcRouteSpec.scala @@ -14,8 +14,7 @@ import com.wavesplatform.test.node.{randomAddress, randomKeyPair} import com.wavesplatform.transaction.TxHelpers.issue import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.utils.EthConverters.* -import com.wavesplatform.transaction.utils.Signed -import com.wavesplatform.transaction.{Asset, EthTxGenerator, GenesisTransaction, TxHelpers} +import com.wavesplatform.transaction.{Asset, EthTxGenerator, GenesisTransaction, TxHelpers, TxVersion} import com.wavesplatform.utils.EthEncoding.toHexString import com.wavesplatform.utils.{EthEncoding, EthHelpers} import play.api.libs.json.* @@ -70,22 +69,22 @@ class EthRpcRouteSpec extends RouteSpec("/eth") with WithDomain with EthHelpers val testKP = randomKeyPair() d.appendBlock( GenesisTransaction.create(testKP.toAddress, 1.waves, ntpTime.getTimestamp()).explicitGet(), - Signed.setScript( - 2.toByte, + TxHelpers.setScript( testKP, - Some(TestCompiler(V5).compileContract("""{-# STDLIB_VERSION 4 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-# SCRIPT_TYPE ACCOUNT #-} - | - |@Callable(inv) - |func foo() = { - | [ - | BinaryEntry("leaseId", base64'AAA') - | ] - |} - |""".stripMargin)), + TestCompiler(V5).compileContract("""{-# STDLIB_VERSION 4 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-# SCRIPT_TYPE ACCOUNT #-} + | + |@Callable(inv) + |func foo() = { + | [ + | BinaryEntry("leaseId", base64'AAA') + | ] + |} + |""".stripMargin), 0.01.waves, - ntpTime.getTimestamp() + version = TxVersion.V2, + timestamp = ntpTime.getTimestamp() ) ) routeTest(d, "eth_getCode", testKP.toAddress.toEthAddress)(result shouldBe "0xff") @@ -110,7 +109,7 @@ class EthRpcRouteSpec extends RouteSpec("/eth") with WithDomain with EthHelpers "eth_call" - { "asset calls" in withDomain() { d => val randomKP = randomKeyPair() - val issueTransaction = Signed.issue(2.toByte, randomKP, "TEST", "test asset", 100000, 2, false, None, 1.waves, ntpTime.getTimestamp()) + val issueTransaction = TxHelpers.issue(randomKP, 100000, 2, "TEST", "test asset", 1.waves, None, false, ntpTime.getTimestamp(), TxVersion.V2) d.appendBlock( GenesisTransaction.create(randomKP.toAddress, 5.waves, ntpTime.getTimestamp()).explicitGet(), @@ -225,31 +224,31 @@ class EthRpcRouteSpec extends RouteSpec("/eth") with WithDomain with EthHelpers ) { d => val randomKP = randomKeyPair() val invoker = randomKeyPair() - val issue1 = Signed.issue(2.toByte, randomKP, "TEST1", "test asset", 100000, 2, true, None, 1.waves, ntpTime.getTimestamp()) - val issue2 = Signed.issue(2.toByte, randomKP, "NFT1", "test asset", 1, 0, false, None, 0.001.waves, ntpTime.getTimestamp()) + val issue1 = TxHelpers.issue(randomKP,100000, 2, "TEST1", "test asset", 1.waves, None, true, version = 2.toByte) + val issue2 = TxHelpers.issue(randomKP,1, 0, "NFT1", "test asset", 0.001.waves, None, false, version = 2.toByte) d.appendBlock( GenesisTransaction.create(randomKP.toAddress, 5.waves, ntpTime.getTimestamp()).explicitGet(), GenesisTransaction.create(invoker.toAddress, 5.waves, ntpTime.getTimestamp()).explicitGet() ) - val invoke = Signed.invokeScript( - 2.toByte, - invoker, + val invoke = TxHelpers.invoke( randomKP.toAddress, None, + Seq.empty, Seq(InvokeScriptTransaction.Payment(1.waves, Asset.Waves)), + invoker, 1.005.waves, Asset.Waves, + 2.toByte, ntpTime.getTimestamp() ) d.appendBlock( issue1, issue2, - Signed.setScript( - 2.toByte, + TxHelpers.setScript( randomKP, - Some(TestCompiler(V5).compileContract("""{-# STDLIB_VERSION 4 #-} + TestCompiler(V5).compileContract("""{-# STDLIB_VERSION 4 #-} |{-# CONTENT_TYPE DAPP #-} |{-# SCRIPT_TYPE ACCOUNT #-} | @@ -261,9 +260,9 @@ class EthRpcRouteSpec extends RouteSpec("/eth") with WithDomain with EthHelpers | BinaryEntry("assetId", calculateAssetId(issue)) | ] |} - |""".stripMargin)), + |""".stripMargin), 0.01.waves, - ntpTime.getTimestamp() + timestamp = ntpTime.getTimestamp() ), invoke ) @@ -326,15 +325,15 @@ class EthRpcRouteSpec extends RouteSpec("/eth") with WithDomain with EthHelpers } "absence of id" in withDomain() { d => - Post(routePath(""), Json.obj("method" -> "eth_chainId")) - .~>(new EthRpcRoute(d.blockchain, d.commonApi.transactions, ntpTime).route) - .~>(check{ responseAs[JsObject] shouldBe Json.obj("id" -> null, "jsonrpc" -> "2.0", "result" -> "0x54") }) + Post(routePath(""), Json.obj("method" -> "eth_chainId")) + .~>(new EthRpcRoute(d.blockchain, d.commonApi.transactions, ntpTime).route) + .~>(check { responseAs[JsObject] shouldBe Json.obj("id" -> null, "jsonrpc" -> "2.0", "result" -> "0x54") }) } "absence of method" in withDomain() { d => - Post(routePath(""), Json.obj()) - .~>(new EthRpcRoute(d.blockchain, d.commonApi.transactions, ntpTime).route) - .~>(check { responseAs[JsObject] shouldBe Json.obj() }) + Post(routePath(""), Json.obj()) + .~>(new EthRpcRoute(d.blockchain, d.commonApi.transactions, ntpTime).route) + .~>(check { responseAs[JsObject] shouldBe Json.obj() }) } def resultJson: JsObject = (responseAs[JsObject] \ "result").as[JsObject] diff --git a/node/tests/src/test/scala/com/wavesplatform/api/http/requests/RequestsSpec.scala b/node/tests/src/test/scala/com/wavesplatform/api/http/requests/RequestsSpec.scala index a72e2c04bcb..43a5c3abf3f 100644 --- a/node/tests/src/test/scala/com/wavesplatform/api/http/requests/RequestsSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/api/http/requests/RequestsSpec.scala @@ -34,9 +34,9 @@ class RequestsSpec extends FreeSpec with OptionValues { "accepts proofs for version >= 2" in { Seq(2, 3).foreach { version => forAll(transferRequestGen(version)) { - case (sender, json) => + case (_, json) => val request = json.as[TransferRequest] - val tx = request.toTxFrom(sender.publicKey).explicitGet() + val tx = request.toTx.explicitGet() request.proofs.value should be(tx.proofs) } diff --git a/node/tests/src/test/scala/com/wavesplatform/consensus/nxt/TransactionsOrderingSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/consensus/nxt/TransactionsOrderingSpecification.scala index 76e48192c64..5e8de93d477 100644 --- a/node/tests/src/test/scala/com/wavesplatform/consensus/nxt/TransactionsOrderingSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/consensus/nxt/TransactionsOrderingSpecification.scala @@ -5,7 +5,7 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.consensus.TransactionsOrdering import com.wavesplatform.test.PropSpec -import com.wavesplatform.transaction.Asset +import com.wavesplatform.transaction.{Asset, TxHelpers} import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer.* @@ -16,71 +16,56 @@ class TransactionsOrderingSpecification extends PropSpec { private val kp: KeyPair = KeyPair(ByteStr(new Array[Byte](32))) property("TransactionsOrdering.InBlock should sort correctly") { val correctSeq = Seq( - TransferTransaction - .selfSigned( - 1.toByte, + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 125L, + Waves, ByteStr.empty, 1 - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 124L, + Waves, ByteStr.empty, 2 - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 124L, + Waves, ByteStr.empty, 1 - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, - Asset.fromCompatId(Some(ByteStr.empty)), + Waves, 124L, + Asset.fromCompatId(Some(ByteStr.empty)), ByteStr.empty, 2 - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, - Asset.fromCompatId(Some(ByteStr.empty)), + Waves, 124L, + Asset.fromCompatId(Some(ByteStr.empty)), ByteStr.empty, 1 ) - .explicitGet() ) val sorted = Random.shuffle(correctSeq).sorted(using TransactionsOrdering.InBlock) @@ -90,71 +75,56 @@ class TransactionsOrderingSpecification extends PropSpec { property("TransactionsOrdering.InUTXPool should sort correctly") { val correctSeq = Seq( - TransferTransaction - .selfSigned( - 1.toByte, + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 124L, + Waves, ByteStr.empty, 1 - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 123L, + Waves, ByteStr.empty, 1 - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 123L, + Waves, ByteStr.empty, 2 - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, - Asset.fromCompatId(Some(ByteStr.empty)), + Waves, 124L, + Asset.fromCompatId(Some(ByteStr.empty)), ByteStr.empty, 1 - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, - Asset.fromCompatId(Some(ByteStr.empty)), + Waves, 124L, + Asset.fromCompatId(Some(ByteStr.empty)), ByteStr.empty, 2 ) - .explicitGet() ) val sorted = Random.shuffle(correctSeq).sorted(using TransactionsOrdering.InUTXPool(Set.empty)) @@ -164,32 +134,26 @@ class TransactionsOrderingSpecification extends PropSpec { property("TransactionsOrdering.InBlock should sort txs by decreasing block timestamp") { val correctSeq = Seq( - TransferTransaction - .selfSigned( - 1.toByte, + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 1, + Waves, ByteStr.empty, 124L - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( kp, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 1, + Waves, ByteStr.empty, 123L ) - .explicitGet() ) Random.shuffle(correctSeq).sorted(using TransactionsOrdering.InBlock) shouldBe correctSeq @@ -198,32 +162,26 @@ class TransactionsOrderingSpecification extends PropSpec { property("TransactionsOrdering.InUTXPool should sort txs by ascending block timestamp taking into consideration whitelisted senders") { val whitelisted = KeyPair(Array.fill(32)(1: Byte)) val correctSeq = Seq( - TransferTransaction - .selfSigned( - 1.toByte, + TxHelpers.transfer( whitelisted, Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 2, + Waves, ByteStr.empty, 123L - ) - .explicitGet(), - TransferTransaction - .selfSigned( - 1.toByte, + ), + TxHelpers.transfer( KeyPair(Array.fill(32)(0: Byte)), Address.fromString("3MydsP4UeQdGwBq7yDbMvf9MzfB2pxFoUKU").explicitGet(), - Waves, 100000, Waves, 2, + Waves, ByteStr.empty, 124L ) - .explicitGet() ) Random.shuffle(correctSeq).sorted(using TransactionsOrdering.InUTXPool(Set(whitelisted.toAddress.toString))) shouldBe correctSeq } diff --git a/node/tests/src/test/scala/com/wavesplatform/database/RocksDBWriterSpec.scala b/node/tests/src/test/scala/com/wavesplatform/database/RocksDBWriterSpec.scala index 31446bef2b5..3b444fa3d93 100644 --- a/node/tests/src/test/scala/com/wavesplatform/database/RocksDBWriterSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/database/RocksDBWriterSpec.scala @@ -20,7 +20,7 @@ import com.wavesplatform.test.* import com.wavesplatform.test.DomainPresets.* import com.wavesplatform.transaction.TxValidationError.AliasDoesNotExist import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.{TxHelpers, TxPositiveAmount} +import com.wavesplatform.transaction.{Proofs, TxHelpers, TxPositiveAmount} import org.rocksdb.{ReadOptions, RocksIterator} import scala.util.{Random, Using} @@ -92,7 +92,7 @@ class RocksDBWriterSpec extends FreeSpec with WithDomain { d.blockchain.hasAccountScript(scriptOwner.toAddress) shouldBe true // removing account script - d.appendBlock(SetScriptTransaction.selfSigned(1.toByte, scriptOwner, None, 0.014.waves, ntpNow).explicitGet()) + d.appendBlock(SetScriptTransaction.create(1.toByte, scriptOwner.publicKey, None, 0.014.waves, ntpNow, Proofs.empty).map(_.signWith(scriptOwner.privateKey)).explicitGet()) d.blockchain.hasAccountScript(scriptOwner.toAddress) shouldBe false d.appendBlock() diff --git a/node/tests/src/test/scala/com/wavesplatform/db/ScriptCacheTest.scala b/node/tests/src/test/scala/com/wavesplatform/db/ScriptCacheTest.scala index 260fd24e71c..794c83172f6 100644 --- a/node/tests/src/test/scala/com/wavesplatform/db/ScriptCacheTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/db/ScriptCacheTest.scala @@ -12,9 +12,8 @@ import com.wavesplatform.settings.{TestFunctionalitySettings, WavesSettings, loa import com.wavesplatform.state.* import com.wavesplatform.state.utils.TestRocksDB import com.wavesplatform.test.FreeSpec -import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.{BlockchainUpdater, GenesisTransaction} +import com.wavesplatform.transaction.{BlockchainUpdater, GenesisTransaction, TxHelpers} import com.wavesplatform.utils.Time import org.scalacheck.Gen @@ -54,9 +53,7 @@ class ScriptCacheTest extends FreeSpec with WithNewDBForEachTest { val setScriptTxs = (accounts zip scripts) .map { case (account, (script, _)) => - SetScriptTransaction - .selfSigned(1.toByte, account, Some(script), FEE, ts + accounts.length + accounts.indexOf(account) + 1) - .explicitGet() + TxHelpers.setScript(account, script, FEE, timestamp = ts + accounts.length + accounts.indexOf(account) + 1) } val genesisBlock = TestBlock.create(genesisTxs).block @@ -107,9 +104,7 @@ class ScriptCacheTest extends FreeSpec with WithNewDBForEachTest { val lastBlockHeader = bcu.lastBlockHeader.get - val newScriptTx = SetScriptTransaction - .selfSigned(1.toByte, account, None, FEE, lastBlockHeader.header.timestamp + 1) - .explicitGet() + val newScriptTx = TxHelpers.removeScript(account, FEE, timestamp = lastBlockHeader.header.timestamp + 1) val blockWithEmptyScriptTx = TestBlock .create( diff --git a/node/tests/src/test/scala/com/wavesplatform/features/RideV6FailRejectTest.scala b/node/tests/src/test/scala/com/wavesplatform/features/RideV6FailRejectTest.scala index e20fe526d55..1d8ff993595 100644 --- a/node/tests/src/test/scala/com/wavesplatform/features/RideV6FailRejectTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/features/RideV6FailRejectTest.scala @@ -18,7 +18,7 @@ import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.utils.EthConverters.* -import com.wavesplatform.transaction.{EthTxGenerator, EthereumTransaction, Transaction, TxHelpers, TxVersion, TransactionSignOps} +import com.wavesplatform.transaction.{EthTxGenerator, EthereumTransaction, Transaction, TxHelpers, TxVersion} import org.scalatest.{EitherValues, OptionValues} import java.nio.charset.StandardCharsets @@ -310,7 +310,7 @@ class RideV6FailRejectTest extends FreeSpec with WithDomain with OptionValues wi s"NODE-546 If an invoke writes an empty $entryType key to the state", "Data entry key should not be empty", mkDAppFunc(entry), - invokeTx = aliceInvokeTx.copy(version = TxVersion.V1).signWith(invoker.privateKey) + invokeTx = TxHelpers.invoke(dApp = aliceAddr, invoker = invoker, func = Some("foo"), fee = 3.waves, version = TxVersion.V1) ) } ++ dataEntries.map { case (entryType, entry) => diff --git a/node/tests/src/test/scala/com/wavesplatform/history/BlockRewardSpec.scala b/node/tests/src/test/scala/com/wavesplatform/history/BlockRewardSpec.scala index 99f64ee95e3..750b0421e1b 100644 --- a/node/tests/src/test/scala/com/wavesplatform/history/BlockRewardSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/history/BlockRewardSpec.scala @@ -20,7 +20,6 @@ import com.wavesplatform.state.{BlockRewardCalculator, Blockchain, GenesisBlockH import com.wavesplatform.test.* import com.wavesplatform.test.DomainPresets.{RideV6, WavesSettingsOps, BlockRewardDistribution as BlockRewardDistributionSettings} import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{GenesisTransaction, TxHelpers} import org.scalacheck.Gen import org.scalactic.source.Position @@ -232,32 +231,29 @@ class BlockRewardSpec extends FreeSpec with WithDomain { "Miner receives reward and fees" - { val ngEmptyScenario = for { (sourceAddress, issuer, miner1, miner2, genesisBlock) <- genesis - tx1 = TransferTransaction - .selfSigned( - 1.toByte, + tx1 = TxHelpers.transfer( + issuer, + sourceAddress.toAddress, + 10 * Constants.UnitsInWave, + Waves, + OneTotalFee, + Waves, + ByteStr.empty, + ntpTime.getTimestamp(), + 1.toByte + ) + tx2 = TxHelpers + .transfer( issuer, sourceAddress.toAddress, - Waves, 10 * Constants.UnitsInWave, Waves, OneTotalFee, - ByteStr.empty, - ntpTime.getTimestamp() - ) - .explicitGet() - tx2 = TransferTransaction - .selfSigned( - 1.toByte, - issuer, - sourceAddress.toAddress, Waves, - 10 * Constants.UnitsInWave, - Waves, - OneTotalFee, ByteStr.empty, - ntpTime.getTimestamp() + ntpTime.getTimestamp(), + 1.toByte ) - .explicitGet() b2 = mkEmptyBlock(genesisBlock.id(), miner1) b3 = mkEmptyBlock(b2.id(), miner1) b4 = TestBlock.create(ntpNow, b3.id(), Seq(tx1), miner1).block @@ -306,19 +302,17 @@ class BlockRewardSpec extends FreeSpec with WithDomain { val betterBlockScenario = for { (sourceAddress, issuer, miner, _, genesisBlock) <- genesis - tx = TransferTransaction - .selfSigned( - 1.toByte, - issuer, - sourceAddress.toAddress, - Waves, - 10 * Constants.UnitsInWave, - Waves, - OneTotalFee, - ByteStr.empty, - ntpTime.getTimestamp() - ) - .explicitGet() + tx = TxHelpers.transfer( + issuer, + sourceAddress.toAddress, + 10 * Constants.UnitsInWave, + Waves, + OneTotalFee, + Waves, + ByteStr.empty, + ntpTime.getTimestamp(), + 1.toByte + ) b2 = mkEmptyBlock(genesisBlock.id(), miner) b3 = mkEmptyBlock(b2.id(), miner) b4 = mkEmptyBlock(b3.id(), miner) diff --git a/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBurnTest.scala b/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBurnTest.scala index 96135d3d55f..344bd5cf504 100644 --- a/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBurnTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBurnTest.scala @@ -9,7 +9,7 @@ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.test.* import com.wavesplatform.transaction.assets.{BurnTransaction, IssueTransaction, ReissueTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{Asset, GenesisTransaction, TxVersion} +import com.wavesplatform.transaction.{Asset, GenesisTransaction, TxHelpers, TxVersion} import org.scalacheck.Gen class BlockchainUpdaterBurnTest extends PropSpec with DomainScenarioDrivenPropertyCheck { @@ -25,78 +25,82 @@ class BlockchainUpdaterBurnTest extends PropSpec with DomainScenarioDrivenProper alice <- accountGen (_, assetName, description, quantity, decimals, _, _, _) <- issueParamGen genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet() - masterToAlice: TransferTransaction = TransferTransaction - .selfSigned(1.toByte, master, alice.toAddress, Asset.Waves, 3 * Waves, Asset.Waves, transferAssetWavesFee, ByteStr.empty, ts + 1) - .explicitGet() - issue: IssueTransaction = IssueTransaction - .selfSigned( - TxVersion.V1, - alice, - new String(assetName), - new String(description), - quantity, - decimals, - false, - script = None, - Waves, - ts + 100 - ) - .explicitGet() - burn: BurnTransaction = BurnTransaction.selfSigned(1.toByte, alice, issue.asset, quantity / 2, Waves, ts + 200).explicitGet() - reissue: ReissueTransaction = ReissueTransaction - .selfSigned(1.toByte, alice, issue.asset, burn.quantity.value, true, Waves, ts + 300) - .explicitGet() + masterToAlice: TransferTransaction = TxHelpers.transfer( + master, + alice.toAddress, + 3 * Waves, + Asset.Waves, + transferAssetWavesFee, + Asset.Waves, + ByteStr.empty, + ts + 1, + TxVersion.V1 + ) + issue: IssueTransaction = TxHelpers.issue( + alice, + quantity, + decimals, + new String(assetName), + new String(description), + reissuable = false, + script = None, + timestamp = ts + ) + burn: BurnTransaction = TxHelpers.burn(issue.asset, quantity / 2, alice, version = TxVersion.V1, timestamp = ts) + reissue: ReissueTransaction = TxHelpers.reissue(issue.asset, alice, burn.quantity.value, version = TxVersion.V1, timestamp = ts) } yield (ts, genesis, masterToAlice, issue, burn, reissue) val localBlockchainSettings: BlockchainSettings = DefaultBlockchainSettings.copy( functionalitySettings = DefaultBlockchainSettings.functionalitySettings - .copy(featureCheckBlocksPeriod = 1, blocksForFeatureActivation = 1, preActivatedFeatures = Map(BlockchainFeatures.NG.id -> 0, BlockchainFeatures.DataTransaction.id -> 0)) + .copy( + featureCheckBlocksPeriod = 1, + blocksForFeatureActivation = 1, + preActivatedFeatures = Map(BlockchainFeatures.NG.id -> 0, BlockchainFeatures.DataTransaction.id -> 0) + ) ) val localWavesSettings: WavesSettings = settings.copy(blockchainSettings = localBlockchainSettings) property("issue -> burn -> reissue in sequential blocks works correctly") { - scenario(preconditions, localWavesSettings) { - case (domain, (ts, genesis, masterToAlice, issue, burn, reissue)) => - val block0 = customBuildBlockOfTxs(randomSig, Seq(genesis), defaultSigner, 1.toByte, ts) - val block1 = customBuildBlockOfTxs(block0.id(), Seq(masterToAlice), defaultSigner, TxVersion.V1, ts + 150) - val block2 = customBuildBlockOfTxs(block1.id(), Seq(issue), defaultSigner, TxVersion.V1, ts + 250) - val block3 = customBuildBlockOfTxs(block2.id(), Seq(burn), defaultSigner, TxVersion.V1, ts + 350) - val block4 = customBuildBlockOfTxs(block3.id(), Seq(reissue), defaultSigner, TxVersion.V1, ts + 450) + scenario(preconditions, localWavesSettings) { case (domain, (ts, genesis, masterToAlice, issue, burn, reissue)) => + val block0 = customBuildBlockOfTxs(randomSig, Seq(genesis), defaultSigner, 1.toByte, ts) + val block1 = customBuildBlockOfTxs(block0.id(), Seq(masterToAlice), defaultSigner, TxVersion.V1, ts + 150) + val block2 = customBuildBlockOfTxs(block1.id(), Seq(issue), defaultSigner, TxVersion.V1, ts + 250) + val block3 = customBuildBlockOfTxs(block2.id(), Seq(burn), defaultSigner, TxVersion.V1, ts + 350) + val block4 = customBuildBlockOfTxs(block3.id(), Seq(reissue), defaultSigner, TxVersion.V1, ts + 450) - domain.appendBlock(block0) - domain.appendBlock(block1) + domain.appendBlock(block0) + domain.appendBlock(block1) - domain.appendBlock(block2) - val assetDescription1 = domain.blockchainUpdater.assetDescription(issue.asset).get - assetDescription1.reissuable should be(false) - assetDescription1.totalVolume should be(issue.quantity.value) + domain.appendBlock(block2) + val assetDescription1 = domain.blockchainUpdater.assetDescription(issue.asset).get + assetDescription1.reissuable should be(false) + assetDescription1.totalVolume should be(issue.quantity.value) - domain.appendBlock(block3) - val assetDescription2 = domain.blockchainUpdater.assetDescription(issue.asset).get - assetDescription2.reissuable should be(false) - assetDescription2.totalVolume should be(issue.quantity.value - burn.quantity.value) + domain.appendBlock(block3) + val assetDescription2 = domain.blockchainUpdater.assetDescription(issue.asset).get + assetDescription2.reissuable should be(false) + assetDescription2.totalVolume should be(issue.quantity.value - burn.quantity.value) - domain.blockchainUpdater.processBlock(block4) should produce("Asset is not reissuable") + domain.blockchainUpdater.processBlock(block4) should produce("Asset is not reissuable") } } property("issue -> burn -> reissue in micro blocks works correctly") { - scenario(preconditions, localWavesSettings) { - case (domain, (ts, genesis, masterToAlice, issue, burn, reissue)) => - val block0 = customBuildBlockOfTxs(randomSig, Seq(genesis), defaultSigner, TxVersion.V1, ts) - val block1 = customBuildBlockOfTxs(block0.id(), Seq(masterToAlice), defaultSigner, TxVersion.V1, ts + 150) - val block2 = customBuildBlockOfTxs(block1.id(), Seq(issue), defaultSigner, TxVersion.V1, ts + 250) - val block3 = customBuildBlockOfTxs(block2.id(), Seq(burn, reissue), defaultSigner, TxVersion.V1, ts + 350) + scenario(preconditions, localWavesSettings) { case (domain, (ts, genesis, masterToAlice, issue, burn, reissue)) => + val block0 = customBuildBlockOfTxs(randomSig, Seq(genesis), defaultSigner, TxVersion.V1, ts) + val block1 = customBuildBlockOfTxs(block0.id(), Seq(masterToAlice), defaultSigner, TxVersion.V1, ts + 150) + val block2 = customBuildBlockOfTxs(block1.id(), Seq(issue), defaultSigner, TxVersion.V1, ts + 250) + val block3 = customBuildBlockOfTxs(block2.id(), Seq(burn, reissue), defaultSigner, TxVersion.V1, ts + 350) - domain.appendBlock(block0) - domain.appendBlock(block1) + domain.appendBlock(block0) + domain.appendBlock(block1) - domain.appendBlock(block2) - val assetDescription1 = domain.blockchainUpdater.assetDescription(issue.asset).get - assetDescription1.reissuable should be(false) - assetDescription1.totalVolume should be(issue.quantity.value) + domain.appendBlock(block2) + val assetDescription1 = domain.blockchainUpdater.assetDescription(issue.asset).get + assetDescription1.reissuable should be(false) + assetDescription1.totalVolume should be(issue.quantity.value) - domain.blockchainUpdater.processBlock(block3) should produce("Asset is not reissuable") + domain.blockchainUpdater.processBlock(block3) should produce("Asset is not reissuable") } } } diff --git a/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterNFTTest.scala b/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterNFTTest.scala index c257d6e16d3..f63010f1b68 100644 --- a/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterNFTTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterNFTTest.scala @@ -13,14 +13,16 @@ import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms.FUNCTION_CALL import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state.diffs -import com.wavesplatform.test.PropSpec +import com.wavesplatform.test.{NumericExt, PropSpec} import com.wavesplatform.transaction.Asset.IssuedAsset -import com.wavesplatform.transaction.GenesisTransaction +import com.wavesplatform.transaction.{GenesisTransaction, TxHelpers} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalacheck.Gen import org.scalatest.* +import scala.concurrent.duration.* +import monix.execution.Scheduler.Implicits.global class BlockchainUpdaterNFTTest extends PropSpec with DomainScenarioDrivenPropertyCheck with BlocksTransactionsHelpers { @@ -102,6 +104,28 @@ class BlockchainUpdaterNFTTest extends PropSpec with DomainScenarioDrivenPropert } } + property("liquid block test") { + val sender = TxHelpers.signer(1004) + val issuer = TxHelpers.signer(1005) + val recipient = TxHelpers.signer(1006) + val r2 = TxHelpers.address(1007) + import DomainPresets.* + withDomain(RideV4.addFeatures(BlockchainFeatures.ReduceNFTFee), Seq(sender -> 10.waves)) { d => + val issueNFT = TxHelpers.issue(issuer, 1, 0, "AAAA", "", 0.001.waves, reissuable = false) + d.appendBlock( + TxHelpers.transfer(sender, issuer.toAddress, 1.waves), + TxHelpers.transfer(sender, recipient.toAddress, 1.waves), + issueNFT, + TxHelpers.transfer(issuer, recipient.toAddress, 1, issueNFT.asset, 0.001.waves), + TxHelpers.transfer(recipient, r2, 1, issueNFT.asset, 0.001.waves) + ) + + d.accountsApi.nftList(issuer.toAddress, None).headL.runSyncUnsafe(5.seconds) shouldBe empty + d.accountsApi.nftList(recipient.toAddress, None).headL.runSyncUnsafe(5.seconds) shouldBe empty + d.accountsApi.nftList(r2, None).headL.runSyncUnsafe(5.seconds).map(_._1) shouldBe Seq(issueNFT.asset) + } + } + private object Preconditions { import UnsafeBlocks.* diff --git a/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterSponsoredFeeBlockTest.scala b/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterSponsoredFeeBlockTest.scala index 98a93d3ce7b..5d85cceaf58 100644 --- a/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterSponsoredFeeBlockTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/history/BlockchainUpdaterSponsoredFeeBlockTest.scala @@ -11,7 +11,7 @@ import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.assets.{IssueTransaction, SponsorFeeTransaction} import com.wavesplatform.transaction.transfer.* -import com.wavesplatform.transaction.{Asset, GenesisTransaction} +import com.wavesplatform.transaction.{Asset, GenesisTransaction, TxHelpers, TxVersion} import org.scalacheck.Gen class BlockchainUpdaterSponsoredFeeBlockTest extends PropSpec with DomainScenarioDrivenPropertyCheck { @@ -33,58 +33,51 @@ class BlockchainUpdaterSponsoredFeeBlockTest extends PropSpec with DomainScenari (feeAsset, sponsorTx, _, _) <- sponsorFeeCancelSponsorFeeGen(alice) wavesFee = Sponsorship.toWaves(sponsorTx.minSponsoredAssetFee.get.value, sponsorTx.minSponsoredAssetFee.get.value) genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet() - masterToAlice: TransferTransaction = TransferTransaction - .selfSigned( - 1.toByte, - master, - alice.toAddress, - Waves, - feeAsset.fee.value + sponsorTx.fee.value + transferAssetWavesFee + wavesFee, - Waves, - transferAssetWavesFee, - ByteStr.empty, - ts + 1 - ) - .explicitGet() - aliceToBob: TransferTransaction = TransferTransaction - .selfSigned( - 1.toByte, - alice, - bob.toAddress, - Asset.fromCompatId(Some(feeAsset.id())), - feeAsset.quantity.value / 2, - Waves, - transferAssetWavesFee, - ByteStr.empty, - ts + 2 - ) - .explicitGet() - bobToMaster: TransferTransaction = TransferTransaction - .selfSigned( - 1.toByte, + masterToAlice: TransferTransaction = TxHelpers.transfer( + master, + alice.toAddress, + feeAsset.fee.value + sponsorTx.fee.value + transferAssetWavesFee + wavesFee, + Waves, + transferAssetWavesFee, + Waves, + ByteStr.empty, + ts + 1, + TxVersion.V1 + ) + aliceToBob: TransferTransaction = TxHelpers.transfer( + alice, + bob.toAddress, + feeAsset.quantity.value / 2, + Asset.fromCompatId(Some(feeAsset.id())), + transferAssetWavesFee, + Waves, + ByteStr.empty, + ts + 2, + TxVersion.V1 + ) + bobToMaster: TransferTransaction = TxHelpers.transfer( + bob, + master.toAddress, + amtTx, + Asset.fromCompatId(Some(feeAsset.id())), + sponsorTx.minSponsoredAssetFee.get.value, + Asset.fromCompatId(Some(feeAsset.id())), + ByteStr.empty, + ts + 3, + TxVersion.V1 + ) + bobToMaster2: TransferTransaction = TxHelpers + .transfer( bob, master.toAddress, - Asset.fromCompatId(Some(feeAsset.id())), amtTx, Asset.fromCompatId(Some(feeAsset.id())), sponsorTx.minSponsoredAssetFee.get.value, - ByteStr.empty, - ts + 3 - ) - .explicitGet() - bobToMaster2: TransferTransaction = TransferTransaction - .selfSigned( - 1.toByte, - bob, - master.toAddress, Asset.fromCompatId(Some(feeAsset.id())), - amtTx, - Asset.fromCompatId(Some(feeAsset.id())), - sponsorTx.minSponsoredAssetFee.get.value, ByteStr.empty, - ts + 4 + ts + 4, + TxVersion.V1 ) - .explicitGet() } yield (genesis, masterToAlice, feeAsset, sponsorTx, aliceToBob, bobToMaster, bobToMaster2) val SponsoredFeeActivatedAt0BlockchainSettings: BlockchainSettings = DefaultBlockchainSettings.copy( diff --git a/node/tests/src/test/scala/com/wavesplatform/http/AssetsRouteSpec.scala b/node/tests/src/test/scala/com/wavesplatform/http/AssetsRouteSpec.scala index 66486f7d02b..3b9f309641e 100644 --- a/node/tests/src/test/scala/com/wavesplatform/http/AssetsRouteSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/http/AssetsRouteSpec.scala @@ -1,7 +1,5 @@ package com.wavesplatform.http -import org.apache.pekko.http.scaladsl.model.{ContentTypes, FormData, HttpEntity, StatusCodes} -import org.apache.pekko.http.scaladsl.server.Route import com.google.protobuf.ByteString import com.wavesplatform.TestWallet import com.wavesplatform.account.KeyPair @@ -25,13 +23,13 @@ import com.wavesplatform.state.{AssetDescription, AssetScriptInfo, BinaryDataEnt import com.wavesplatform.test.* import com.wavesplatform.test.DomainPresets.* import com.wavesplatform.transaction.Asset.IssuedAsset +import com.wavesplatform.transaction.EthTxGenerator.Arg import com.wavesplatform.transaction.TxHelpers.* import com.wavesplatform.transaction.assets.IssueTransaction -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.transfer.MassTransferTransaction -import com.wavesplatform.transaction.EthTxGenerator.Arg -import com.wavesplatform.transaction.{AssetIdLength, EthTxGenerator, GenesisTransaction, Transaction, TxHelpers, TxNonNegativeAmount, TxVersion} +import com.wavesplatform.transaction.{AssetIdLength, EthTxGenerator, GenesisTransaction, Transaction, TxHelpers, TxVersion} import com.wavesplatform.utils.SharedSchedulerMixin +import org.apache.pekko.http.scaladsl.model.{ContentTypes, FormData, HttpEntity, StatusCodes} +import org.apache.pekko.http.scaladsl.server.Route import org.scalatest.concurrent.Eventually import play.api.libs.json.* import play.api.libs.json.Json.JsValueWrapper @@ -72,44 +70,40 @@ class AssetsRouteSpec } private def setScriptTransaction(sender: KeyPair) = - SetScriptTransaction - .selfSigned( - TxVersion.V2, + TxHelpers + .setScript( sender, - Some(TestCompiler(V6).compileContract(""" - |{-# STDLIB_VERSION 6 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-# SCRIPT_TYPE ACCOUNT #-} - | - |@Callable(inv) - |func issue(name: String, description: String, amount: Int, decimals: Int, isReissuable: Boolean) = { - | let t = Issue(name, description, amount, decimals, isReissuable) - | [ - | t, - | BinaryEntry("assetId", calculateAssetId(t)) - | ] - |} - |""".stripMargin)), + TestCompiler(V6).compileContract(""" + |{-# STDLIB_VERSION 6 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-# SCRIPT_TYPE ACCOUNT #-} + | + |@Callable(inv) + |func issue(name: String, description: String, amount: Int, decimals: Int, isReissuable: Boolean) = { + | let t = Issue(name, description, amount, decimals, isReissuable) + | [ + | t, + | BinaryEntry("assetId", calculateAssetId(t)) + | ] + |} + |""".stripMargin), 0.01.waves, - ntpTime.getTimestamp() + timestamp = ntpTime.getTimestamp() ) - .explicitGet() private def issueTransaction(name: Option[String] = None, script: Option[Script] = None, quantity: Option[Long] = None): IssueTransaction = - IssueTransaction - .selfSigned( - version = TxVersion.V2, - sender = defaultSigner, - name = name.getOrElse(assetDesc.name.toStringUtf8), - description = assetDesc.description.toStringUtf8, - quantity = quantity.getOrElse(assetDesc.totalVolume.toLong), - decimals = assetDesc.decimals.toByte, - reissuable = assetDesc.reissuable, - script = script, - fee = 1.waves, - timestamp = TxHelpers.timestamp - ) - .explicitGet() + TxHelpers.issue( + defaultSigner, + quantity.getOrElse(assetDesc.totalVolume.toLong), + assetDesc.decimals.toByte, + name.getOrElse(assetDesc.name.toStringUtf8), + assetDesc.description.toStringUtf8, + 1.waves, + script, + assetDesc.reissuable, + TxHelpers.timestamp, + TxVersion.V2 + ) private val assetDesc = AssetDescription( TransactionId(ByteStr.empty), @@ -286,7 +280,7 @@ class AssetsRouteSpec checkDetails(route, issues(i), issues(i).id().toString, assetDesc.copy(sequenceInBlock = i)) } - d.appendBlock((7 to 10).map(issues) *) + d.appendBlock((7 to 10).map(issues)*) (1 to 6).foreach { i => checkDetails(route, issues(i), issues(i).id().toString, assetDesc.copy(sequenceInBlock = i)) } @@ -301,29 +295,25 @@ class AssetsRouteSpec d.appendBlock(TxHelpers.genesis(issuer.toAddress, 10.waves)) val recipients = testWallet.generateNewAccounts(5) val transfers = recipients.zipWithIndex.map { case (kp, i) => - MassTransferTransaction.ParsedTransfer(kp.toAddress, TxNonNegativeAmount.unsafeFrom((i + 1) * 10000)) + kp.toAddress -> ((i + 1) * 10000L) } d.appendBlock( issueTransaction, - MassTransferTransaction - .selfSigned( - 2.toByte, - issuer, - issueTransaction.asset, - transfers, - 0.01.waves, - ntpTime.getTimestamp(), - ByteStr.empty - ) - .explicitGet() + TxHelpers.massTransfer( + issuer, + transfers, + issueTransaction.asset, + 0.01.waves, + timestamp = ntpTime.getTimestamp() + ) ) d.appendBlock() Get(routePath(s"/${issueTransaction.id()}/distribution/2/limit/$MaxAddressesPerRequest")) ~> route ~> check { val response = responseAs[JsObject] (response \ "items").as[JsObject] shouldBe Json.obj( - (transfers.map(pt => pt.address.toString -> (pt.amount.value: JsValueWrapper)) :+ - issuer.toAddress.toString -> (issueTransaction.quantity.value - transfers.map(_.amount.value).sum: JsValueWrapper))* + transfers.map(pt => pt._1.toString -> (pt._2: JsValueWrapper)) :+ + issuer.toAddress.toString -> (issueTransaction.quantity.value - transfers.map(_._2).sum: JsValueWrapper) * ) } @@ -513,7 +503,7 @@ class AssetsRouteSpec } d.appendBlock(TxHelpers.genesis(issuer.toAddress, 100.waves)) val nonNFT = TxHelpers.issue(issuer, 100, 2.toByte) - d.appendBlock((nfts :+ nonNFT)*) + d.appendBlock(nfts :+ nonNFT *) Get(routePath(s"/balance/${issuer.toAddress}/${nonNFT.id()}")) ~> route ~> check { val balance = responseAs[JsObject] diff --git a/node/tests/src/test/scala/com/wavesplatform/http/ProtoVersionTransactionsSpec.scala b/node/tests/src/test/scala/com/wavesplatform/http/ProtoVersionTransactionsSpec.scala index bf2d500108d..fab6ef23a82 100644 --- a/node/tests/src/test/scala/com/wavesplatform/http/ProtoVersionTransactionsSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/http/ProtoVersionTransactionsSpec.scala @@ -49,7 +49,7 @@ class ProtoVersionTransactionsSpec private val script = TxHelpers.script("true") private val route: Route = - TransactionsApiRoute( + Route.seal(TransactionsApiRoute( restAPISettings, domain.transactionsApi, domain.wallet, @@ -59,7 +59,7 @@ class ProtoVersionTransactionsSpec DummyTransactionPublisher.accepting, domain.testTime, new RouteTimeout(60.seconds)(using sharedScheduler) - ).route + ).route) "Proto transactions should be able to broadcast " - { "CreateAliasTransaction" in { @@ -191,9 +191,7 @@ class ProtoVersionTransactionsSpec .explicitGet() val exchangeTx = - ExchangeTransaction - .signed(TxVersion.V3, account.privateKey, buyOrder, sellOrder, 100, 100, MinFee * 3, MinFee * 3, MinFee * 3, now) - .explicitGet() + TxHelpers.exchange(buyOrder, sellOrder, account, 100, 100, MinFee * 3, MinFee * 3, MinFee * 3, now, TxVersion.V3) val base64Str = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(exchangeTx))) Post(routePath("/broadcast"), exchangeTx.json()) ~> ApiKeyHeader ~> route ~> check { @@ -404,7 +402,7 @@ class ProtoVersionTransactionsSpec .create( TxVersion.V1, account.publicKey, - asset.id, + asset, "Test", "Test", ntpNow, diff --git a/node/tests/src/test/scala/com/wavesplatform/http/SpentComplexitySpec.scala b/node/tests/src/test/scala/com/wavesplatform/http/SpentComplexitySpec.scala index 7273950ffd9..46b864f0f2c 100644 --- a/node/tests/src/test/scala/com/wavesplatform/http/SpentComplexitySpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/http/SpentComplexitySpec.scala @@ -2,18 +2,15 @@ package com.wavesplatform.http import com.wavesplatform.api.http.{ApiMarshallers, RouteTimeout, TransactionsApiRoute} import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.db.WithDomain import com.wavesplatform.db.WithState.AddrWithBalance import com.wavesplatform.history.Domain import com.wavesplatform.lang.directives.values.V5 import com.wavesplatform.lang.v1.compiler.TestCompiler -import com.wavesplatform.transaction.Asset import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.assets.IssueTransaction -import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} -import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.utils.Signed +import com.wavesplatform.transaction.smart.InvokeScriptTransaction +import com.wavesplatform.transaction.{Asset, TxHelpers} import com.wavesplatform.utils.SharedSchedulerMixin import com.wavesplatform.{BlockGen, TestWallet} import org.scalatest.OptionValues @@ -82,11 +79,10 @@ class SpentComplexitySpec "Invocation" - { "does not count verifier complexity when InvokeScript is sent from smart account" in withDomain(settings, Seq(AddrWithBalance(sender.toAddress, 10_000_00000000L))) { d => - val invokeTx = Signed - .invokeScript(2.toByte, sender, sender.toAddress, None, Seq.empty, 90_0000L, Asset.Waves, ntpTime.getTimestamp()) + val invokeTx = TxHelpers.invoke(sender.toAddress, None, Seq.empty, Seq.empty, sender, 90_0000L, Asset.Waves, 2.toByte, ntpTime.getTimestamp()) d.appendBlock( - SetScriptTransaction.selfSigned(2.toByte, sender, Some(contract), 100_0000L, ntpTime.getTimestamp()).explicitGet(), + TxHelpers.setScript(sender, contract, 100_0000L, 2.toByte, timestamp = ntpTime.getTimestamp()), invokeTx ) @@ -99,30 +95,27 @@ class SpentComplexitySpec val recipient = testWallet.generateNewAccount().get withDomain(settings, Seq(AddrWithBalance(sender.toAddress, 10_000_00000000L), AddrWithBalance(recipient.toAddress, 10_00000000L))) { d => - val issue = IssueTransaction - .selfSigned(2.toByte, sender, "TEST", "", 1000_00L, 2.toByte, false, Some(assetScript), 1_00000000L, ntpTime.getTimestamp()) - .explicitGet() - - val transferAsset = TransferTransaction - .selfSigned(2.toByte, sender, recipient.toAddress, issue.asset, 50_00L, Waves, 90_0000L, ByteStr.empty, ntpTime.getTimestamp()) - .explicitGet() - - val invokeTx = Signed - .invokeScript( - 2.toByte, - recipient, - sender.toAddress, - None, - Seq(InvokeScriptTransaction.Payment(50_00L, issue.asset)), - 90_0000L, - Asset.Waves, - ntpTime.getTimestamp() - ) + val issue = TxHelpers.issue(sender, 1000_00L, 2.toByte, "TEST", "", 1_00000000L, Some(assetScript), false, ntpTime.getTimestamp(), 2.toByte) + + val transferAsset = TxHelpers + .transfer(sender, recipient.toAddress, 50_00L, issue.asset, 90_0000L, Waves, timestamp = ntpTime.getTimestamp(), version = 2.toByte) + + val invokeTx = TxHelpers.invoke( + sender.toAddress, + None, + Seq.empty, + Seq(InvokeScriptTransaction.Payment(50_00L, issue.asset)), + recipient, + 90_0000L, + Asset.Waves, + 2.toByte, + ntpTime.getTimestamp() + ) d.appendBlock( issue, transferAsset, - SetScriptTransaction.selfSigned(2.toByte, sender, Some(contract), 100_0000L, ntpTime.getTimestamp()).explicitGet(), + TxHelpers.setScript(sender, contract, 100_0000L, 2.toByte, timestamp = ntpTime.getTimestamp()), invokeTx ) @@ -137,17 +130,13 @@ class SpentComplexitySpec val recipient = testWallet.generateNewAccount().get withDomain(settings, Seq(AddrWithBalance(sender.toAddress, 10_000_00000000L), AddrWithBalance(recipient.toAddress, 10_00000000L))) { d => - val issue = IssueTransaction - .selfSigned(2.toByte, sender, "TEST", "", 1000_00L, 2.toByte, false, Some(assetScript), 1_00000000L, ntpTime.getTimestamp()) - .explicitGet() + val issue = TxHelpers.issue(sender, 1000_00L, 2.toByte, "TEST", "", 1_00000000L, Some(assetScript), false, ntpTime.getTimestamp(), 2.toByte) - val transferAsset = TransferTransaction - .selfSigned(2.toByte, sender, recipient.toAddress, issue.asset, 50_00L, Waves, 90_0000L, ByteStr.empty, ntpTime.getTimestamp()) - .explicitGet() + val transferAsset = + TxHelpers.transfer(sender, recipient.toAddress, 50_00L, issue.asset, 90_0000L, Waves, ByteStr.empty, ntpTime.getTimestamp(), 2.toByte) - val returnFrom = TransferTransaction - .selfSigned(2.toByte, recipient, sender.toAddress, issue.asset, 49_00L, Waves, 90_0000L, ByteStr.empty, ntpTime.getTimestamp()) - .explicitGet() + val returnFrom = + TxHelpers.transfer(recipient, sender.toAddress, 49_00L, issue.asset, 90_0000L, Waves, ByteStr.empty, ntpTime.getTimestamp(), 2.toByte) d.appendBlock( issue, diff --git a/node/tests/src/test/scala/com/wavesplatform/http/TransactionBroadcastSpec.scala b/node/tests/src/test/scala/com/wavesplatform/http/TransactionBroadcastSpec.scala index 4b4aa8cc9c7..dd86084dd77 100644 --- a/node/tests/src/test/scala/com/wavesplatform/http/TransactionBroadcastSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/http/TransactionBroadcastSpec.scala @@ -23,7 +23,6 @@ import com.wavesplatform.transaction.{ AssetIdLength, Proofs, Transaction, - TransactionSignOps, TxExchangeAmount, TxHelpers, TxMatcherFee, diff --git a/node/tests/src/test/scala/com/wavesplatform/http/TransactionsRouteSpec.scala b/node/tests/src/test/scala/com/wavesplatform/http/TransactionsRouteSpec.scala index 0cf66ea5ddf..b05f16dee87 100644 --- a/node/tests/src/test/scala/com/wavesplatform/http/TransactionsRouteSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/http/TransactionsRouteSpec.scala @@ -29,8 +29,7 @@ import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.trace.AccountVerifierTrace import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.utils.EthConverters.* -import com.wavesplatform.transaction.utils.Signed -import com.wavesplatform.transaction.{Asset, AssetIdLength, EthTxGenerator, TransactionSignOps, TxHelpers, TxVersion} +import com.wavesplatform.transaction.{Asset, AssetIdLength, EthTxGenerator, TxHelpers, TxVersion} import com.wavesplatform.utils.{EthEncoding, EthHelpers, SharedSchedulerMixin} import com.wavesplatform.{BlockGen, TestValues, crypto} import org.apache.pekko.http.scaladsl.model.* @@ -896,15 +895,12 @@ class TransactionsRouteSpec val seed = new Array[Byte](32) Random.nextBytes(seed) val sender: KeyPair = KeyPair(seed) - val ist = Signed.invokeScript( - TxVersion.V1, - sender, - sender.toAddress, - None, - Seq.empty, - 500000L, - Asset.Waves, - testTime.getTimestamp() + val ist = TxHelpers.invoke( + dApp = sender.toAddress, + invoker = sender, + fee = 500000L, + version = TxVersion.V1, + timestamp = testTime.getTimestamp() ) f(sender, ist) } @@ -986,8 +982,13 @@ class TransactionsRouteSpec lease ) - val invoke = Signed - .invokeScript(2.toByte, sender, sender.toAddress, None, Seq.empty, 0.005.waves, Asset.Waves, ntpTime.getTimestamp()) + val invoke = TxHelpers.invoke( + dApp = sender.toAddress, + invoker = sender, + fee = 0.005.waves, + version = 2.toByte, + timestamp = ntpTime.getTimestamp() + ) Post(routePath("/broadcast?trace=true"), invoke.json()) ~> route ~> check { val dappTrace = (responseAs[JsObject] \ "trace").as[Seq[JsObject]].find(jsObject => (jsObject \ "type").as[String] == "dApp").get diff --git a/node/tests/src/test/scala/com/wavesplatform/lagonaki/unit/MicroBlockSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/lagonaki/unit/MicroBlockSpecification.scala index 1f43968dec7..015a19e7570 100644 --- a/node/tests/src/test/scala/com/wavesplatform/lagonaki/unit/MicroBlockSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/lagonaki/unit/MicroBlockSpecification.scala @@ -33,10 +33,10 @@ class MicroBlockSpecification extends FunSuite { val ts = System.currentTimeMillis() - 5000 val tr: TransferTransaction = - TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, Waves, 5, Waves, 2, ByteStr.empty, ts + 1).explicitGet() + TxHelpers.transfer(from = sender, to = gen.toAddress, amount = 5, asset = Waves, fee = 2, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts + 1, version = 1.toByte) val assetId = IssuedAsset(ByteStr(Array.fill(AssetIdLength)(Random.nextInt(100).toByte))) val tr2: TransferTransaction = - TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, assetId, 5, Waves, 2, ByteStr.empty, ts + 2).explicitGet() + TxHelpers.transfer(from = sender, to = gen.toAddress, amount = 5, asset = assetId, fee = 2, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts + 2, version = 1.toByte) val transactions = Seq(tr, tr2) @@ -58,10 +58,10 @@ class MicroBlockSpecification extends FunSuite { test("MicroBlock with txs bytes/parse roundtrip, with finalizationVoting") { val ts = System.currentTimeMillis() - 5000 val tr: TransferTransaction = - TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, Waves, 5, Waves, 2, ByteStr.empty, ts + 1).explicitGet() + TxHelpers.transfer(from = sender, to = gen.toAddress, amount = 5, asset = Waves, fee = 2, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts + 1, version = 1.toByte) val assetId = IssuedAsset(ByteStr(Array.fill(AssetIdLength)(Random.nextInt(100).toByte))) val tr2: TransferTransaction = - TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, assetId, 5, Waves, 2, ByteStr.empty, ts + 2).explicitGet() + TxHelpers.transfer(from = sender, to = gen.toAddress, amount = 5, asset = assetId, fee = 2, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts + 2, version = 1.toByte) val transactions = Seq(tr, tr2) @@ -198,7 +198,7 @@ class MicroBlockSpecification extends FunSuite { test("MicroBlock cannot contain more than Miner.MaxTransactionsPerMicroblock") { val transaction = - TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, Waves, 5, Waves, 1000, ByteStr.empty, System.currentTimeMillis()).explicitGet() + TxHelpers.transfer(from = sender, to = gen.toAddress, amount = 5, asset = Waves, fee = 1000, feeAsset = Waves, attachment = ByteStr.empty, timestamp = System.currentTimeMillis(), version = 1.toByte) val transactions = Seq.fill(Miner.MaxTransactionsPerMicroblock + 1)(transaction) val eitherBlockOrError = MicroBlock.buildAndSign(3.toByte, sender, transactions, prevResBlockSig, totalResBlockSig, None, None) diff --git a/node/tests/src/test/scala/com/wavesplatform/mining/BlockV5Test.scala b/node/tests/src/test/scala/com/wavesplatform/mining/BlockV5Test.scala index dfb84254457..269cc6804ee 100644 --- a/node/tests/src/test/scala/com/wavesplatform/mining/BlockV5Test.scala +++ b/node/tests/src/test/scala/com/wavesplatform/mining/BlockV5Test.scala @@ -17,7 +17,6 @@ import com.wavesplatform.state.BlockchainUpdaterImpl.BlockApplyResult.Applied import com.wavesplatform.state.{Blockchain, BlockchainUpdaterImpl, NG, diffs} import com.wavesplatform.test.{FlatSpec, *} import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{BlockchainUpdater, GenesisTransaction, Transaction, TxHelpers, TxVersion} import com.wavesplatform.utils.Time import com.wavesplatform.{BlocksTransactionsHelpers, crypto, protobuf} @@ -337,9 +336,17 @@ class BlockV5Test extends FlatSpec with WithMiner with OptionValues with EitherV } private def createTx(sender: KeyPair, recipient: AddressOrAlias): Transaction = - TransferTransaction - .selfSigned(TxVersion.V1, sender, recipient, Waves, 10 * Constants.UnitsInWave, Waves, 100000, ByteStr.empty, ntpTime.getTimestamp()) - .explicitGet() + TxHelpers.transfer( + from = sender, + to = recipient, + amount = 10 * Constants.UnitsInWave, + asset = Waves, + fee = 100000, + feeAsset = Waves, + attachment = ByteStr.empty, + timestamp = ntpTime.getTimestamp(), + version = TxVersion.V1 + ) private val updaterScenario = for { (miner1, miner2, b1) <- genesis diff --git a/node/tests/src/test/scala/com/wavesplatform/mining/MicroBlockMinerSpec.scala b/node/tests/src/test/scala/com/wavesplatform/mining/MicroBlockMinerSpec.scala index 2db5cda1e56..4fb1b4fc0d1 100644 --- a/node/tests/src/test/scala/com/wavesplatform/mining/MicroBlockMinerSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/mining/MicroBlockMinerSpec.scala @@ -14,8 +14,8 @@ import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state.{Blockchain, EndorsementStorage, StateSnapshot} import com.wavesplatform.test.DomainPresets.RideV6 import com.wavesplatform.test.FlatSpec -import com.wavesplatform.transaction.TxHelpers.{defaultAddress, defaultSigner, secondAddress, transfer} -import com.wavesplatform.transaction.{CreateAliasTransaction, Transaction, TxVersion} +import com.wavesplatform.transaction.TxHelpers.{createAlias, defaultAddress, defaultSigner, secondAddress, transfer} +import com.wavesplatform.transaction.{Transaction, TxVersion} import com.wavesplatform.utils.Schedulers import com.wavesplatform.utx.{UtxPool, UtxPoolImpl, UtxPriorityPool} import monix.execution.Scheduler @@ -58,9 +58,7 @@ class MicroBlockMinerSpec extends FlatSpec with WithDomain { ) import Scheduler.Implicits.global val startTime = System.nanoTime() - val tx = CreateAliasTransaction - .selfSigned(TxVersion.V1, acc, "test" + Random.nextInt(), TestValues.fee, TestValues.timestamp) - .explicitGet() + val tx = createAlias(name = "test" + Random.nextInt(), sender = acc, fee = TestValues.fee, version = TxVersion.V1) utxPool.putIfNew(tx).resultE.explicitGet() val result = task.runSyncUnsafe() result match { diff --git a/node/tests/src/test/scala/com/wavesplatform/mining/MinerAccountScriptRestrictionsTest.scala b/node/tests/src/test/scala/com/wavesplatform/mining/MinerAccountScriptRestrictionsTest.scala index 85d3d7965bd..bd4df5e3221 100644 --- a/node/tests/src/test/scala/com/wavesplatform/mining/MinerAccountScriptRestrictionsTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/mining/MinerAccountScriptRestrictionsTest.scala @@ -88,8 +88,6 @@ class MinerAccountScriptRestrictionsTest extends PropSpec with WithDomain { private def errMsgBeforeRideV6 = s"Account(${minerAcc.toAddress}) is scripted and not allowed to forge blocks" - private def ts: Long = System.currentTimeMillis() - private def withMiner(d: Domain)(f: (MinerImpl, Appender, Scheduler) => Unit): Unit = { val defaultSettings = WavesSettings.default() val wavesSettings = defaultSettings.copy(minerSettings = defaultSettings.minerSettings.copy(quorum = 0)) @@ -140,7 +138,7 @@ class MinerAccountScriptRestrictionsTest extends PropSpec with WithDomain { } private def setScript(script: Script): SetScriptTransaction = - SetScriptTransaction.selfSigned(TxVersion.V2, minerAcc, Some(script), 0.01.waves, ts).explicitGet() + TxHelpers.setScript(acc = minerAcc, script = script, fee = 0.01.waves, version = TxVersion.V2) private def verifierScriptStr: String = s""" diff --git a/node/tests/src/test/scala/com/wavesplatform/mining/MiningWithRewardSuite.scala b/node/tests/src/test/scala/com/wavesplatform/mining/MiningWithRewardSuite.scala index e8f3c478204..bb4c128d570 100644 --- a/node/tests/src/test/scala/com/wavesplatform/mining/MiningWithRewardSuite.scala +++ b/node/tests/src/test/scala/com/wavesplatform/mining/MiningWithRewardSuite.scala @@ -15,8 +15,7 @@ import com.wavesplatform.settings.* import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.{BlockEndorser, Blockchain, BlockchainUpdaterImpl, EndorsementStorage, NG} import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{BlockchainUpdater, GenesisTransaction, Transaction} +import com.wavesplatform.transaction.{BlockchainUpdater, GenesisTransaction, Transaction, TxHelpers} import com.wavesplatform.utx.UtxPoolImpl import com.wavesplatform.wallet.Wallet import com.wavesplatform.{TransactionGen, WithNewDBForEachTest} @@ -73,20 +72,14 @@ class MiningWithRewardSuite extends AsyncFlatSpec with Matchers with WithNewDBFo val bps: Seq[BlockProducer] = Seq((ts, reference, account) => { val recipient1 = createAccount.toAddress val recipient2 = createAccount.toAddress - val tx1 = TransferTransaction - .selfSigned(2.toByte, account, recipient1, Waves, 10 * Constants.UnitsInWave, Waves, 400000, ByteStr.empty, ts) - .explicitGet() - val tx2 = TransferTransaction - .selfSigned(2.toByte, account, recipient2, Waves, 5 * Constants.UnitsInWave, Waves, 400000, ByteStr.empty, ts) - .explicitGet() + val tx1 = TxHelpers.transfer(from = account, to = recipient1, amount = 10 * Constants.UnitsInWave, asset = Waves, fee = 400000, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts, version = 2.toByte) + val tx2 = TxHelpers.transfer(from = account, to = recipient2, amount = 5 * Constants.UnitsInWave, asset = Waves, fee = 400000, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts, version = 2.toByte) TestBlock.create(time = ts, ref = reference, txs = Seq(tx1, tx2), version = Block.NgBlockVersion).block }) val txs: Seq[TransactionProducer] = Seq((ts, account) => { val recipient1 = createAccount.toAddress - TransferTransaction - .selfSigned(2.toByte, account, recipient1, Waves, 10 * Constants.UnitsInWave, Waves, 400000, ByteStr.empty, ts) - .explicitGet() + TxHelpers.transfer(from = account, to = recipient1, amount = 10 * Constants.UnitsInWave, asset = Waves, fee = 400000, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts, version = 2.toByte) }) withEnv(bps, txs) { case Env(_, account, miner, blockchain) => diff --git a/node/tests/src/test/scala/com/wavesplatform/mining/ScriptComplexityMiningConstraintSuite.scala b/node/tests/src/test/scala/com/wavesplatform/mining/ScriptComplexityMiningConstraintSuite.scala index 2a5b7569019..dd05206250e 100644 --- a/node/tests/src/test/scala/com/wavesplatform/mining/ScriptComplexityMiningConstraintSuite.scala +++ b/node/tests/src/test/scala/com/wavesplatform/mining/ScriptComplexityMiningConstraintSuite.scala @@ -10,7 +10,7 @@ import com.wavesplatform.state.diffs.TransactionDiffer import com.wavesplatform.state.{AccountScriptInfo, Height} import com.wavesplatform.test.FlatSpec import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.{Asset, DataTransaction, Transaction, TxVersion} +import com.wavesplatform.transaction.{Asset, DataTransaction, Transaction, TxHelpers, TxVersion} import com.wavesplatform.utils.EmptyBlockchain import org.scalacheck.Gen @@ -59,8 +59,8 @@ class ScriptComplexityMiningConstraintSuite extends FlatSpec { for { acc1 <- accountGen acc2 <- accountGen - tx1 = DataTransaction.selfSigned(TxVersion.V1, acc1, Nil, 1000000, System.currentTimeMillis()).explicitGet() - tx2 = DataTransaction.selfSigned(TxVersion.V1, acc2, Nil, 1000000, System.currentTimeMillis()).explicitGet() - tx3 = DataTransaction.selfSigned(TxVersion.V1, acc2, Nil, 1000000, System.currentTimeMillis()).explicitGet() + tx1 = TxHelpers.data(account = acc1, entries = Nil, fee = 1000000, version = TxVersion.V1) + tx2 = TxHelpers.data(account = acc2, entries = Nil, fee = 1000000, version = TxVersion.V1) + tx3 = TxHelpers.data(account = acc2, entries = Nil, fee = 1000000, version = TxVersion.V1) } yield (acc1, acc2, tx1, tx2, tx3) } diff --git a/node/tests/src/test/scala/com/wavesplatform/network/BasicMessagesRepoSpec.scala b/node/tests/src/test/scala/com/wavesplatform/network/BasicMessagesRepoSpec.scala index c97750579fa..f773233977b 100644 --- a/node/tests/src/test/scala/com/wavesplatform/network/BasicMessagesRepoSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/network/BasicMessagesRepoSpec.scala @@ -1,17 +1,15 @@ package com.wavesplatform.network -import java.io.ByteArrayOutputStream - import com.google.protobuf.{ByteString, CodedOutputStream, WireFormat} import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.mining.MiningConstraints import com.wavesplatform.protobuf.block.* import com.wavesplatform.protobuf.transaction.* import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.IssuedAsset -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.{DataTransaction, Proofs, TxVersion} +import com.wavesplatform.transaction.{DataTransaction, Proofs, TxHelpers, TxVersion} + +import java.io.ByteArrayOutputStream class BasicMessagesRepoSpec extends FreeSpec { "PBBlockSpec max length" in { @@ -52,15 +50,11 @@ class BasicMessagesRepoSpec extends FreeSpec { val minPossibleTransactionSize = PBTransactions .protobuf( - SetScriptTransaction - .selfSigned( - TxVersion.V2, - accountGen.sample.get, - None, - 1L, - 0L - ) - .explicitGet() + TxHelpers.removeScript( + accountGen.sample.get, + fee = 1L, + version = TxVersion.V2 + ) ) .serializedSize diff --git a/node/tests/src/test/scala/com/wavesplatform/network/LegacyFrameCodecSpec.scala b/node/tests/src/test/scala/com/wavesplatform/network/LegacyFrameCodecSpec.scala index cf7e85654a1..8340345c38d 100644 --- a/node/tests/src/test/scala/com/wavesplatform/network/LegacyFrameCodecSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/network/LegacyFrameCodecSpec.scala @@ -2,11 +2,10 @@ package com.wavesplatform.network import java.net.InetSocketAddress -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.network.message.{MessageSpec, Message as ScorexMessage} import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.assets.UpdateAssetInfoTransaction +import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.{TestValues, crypto} import io.netty.buffer.Unpooled.wrappedBuffer import io.netty.buffer.{ByteBuf, Unpooled} @@ -85,9 +84,7 @@ class LegacyFrameCodecSpec extends FreeSpec { } "should pack update asset info in PB message" in { - val tx = UpdateAssetInfoTransaction - .selfSigned(1, TestValues.keyPair, TestValues.asset.id, "bomz", "", System.currentTimeMillis(), TestValues.fee, Waves) - .explicitGet() + val tx = TxHelpers.updateAssetInfo(TestValues.asset.id, "bomz", "", TestValues.keyPair, TestValues.fee, Waves) RawBytes.fromTransaction(tx) shouldBe RawBytes(PBTransactionSpec.messageCode, PBTransactionSpec.serializeData(tx)) } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/BlockchainUpdaterImplSpec.scala b/node/tests/src/test/scala/com/wavesplatform/state/BlockchainUpdaterImplSpec.scala index c26d9eba155..2a671527db2 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/BlockchainUpdaterImplSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/BlockchainUpdaterImplSpec.scala @@ -16,10 +16,8 @@ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.TxValidationError.BlockAppendError -import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.utils.Signed import com.wavesplatform.transaction.{Transaction, TxHelpers, TxVersion} import com.wavesplatform.utils.{Schedulers, SystemTime, Time} import com.wavesplatform.{EitherMatchers, NTPTime} @@ -274,11 +272,11 @@ class BlockchainUpdaterImplSpec extends FreeSpec with EitherMatchers with WithDo ._1 d.appendBlock( - SetScriptTransaction.selfSigned(2.toByte, dapp, Some(script), 500_0000L, ntpTime.getTimestamp()).explicitGet() + TxHelpers.setScript(acc = dapp, script = script, fee = 500_0000L, version = 2.toByte, timestamp = ntpTime.getTimestamp()) ) val invoke = - Signed.invokeScript(3.toByte, sender, dapp.toAddress, None, Seq.empty, 50_0000L, Waves, ntpTime.getTimestamp()) + TxHelpers.invoke(dApp = dapp.toAddress, invoker = sender, fee = 50_0000L, version = 3.toByte, timestamp = ntpTime.getTimestamp()) d.appendBlock(d.createBlock(Seq(invoke))) } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/RollbackSpec.scala b/node/tests/src/test/scala/com/wavesplatform/state/RollbackSpec.scala index 2bd85c958c5..0e63a1748af 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/RollbackSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/RollbackSpec.scala @@ -20,14 +20,13 @@ import com.wavesplatform.lang.v1.compiler.Terms.TRUE import com.wavesplatform.lang.v1.compiler.{Terms, TestCompiler} import com.wavesplatform.lang.v1.traits.domain.Lease import com.wavesplatform.settings.{TestFunctionalitySettings, WavesSettings} +import com.wavesplatform.state.{Height, TransactionId} import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxHelpers.* import com.wavesplatform.transaction.TxValidationError.AliasDoesNotExist -import com.wavesplatform.transaction.lease.LeaseTransaction import com.wavesplatform.transaction.smart.{InvokeTransaction, SetScriptTransaction} -import com.wavesplatform.transaction.transfer.* -import com.wavesplatform.transaction.{Transaction, TxHelpers, TxPositiveAmount, TxVersion} +import com.wavesplatform.transaction.{Proofs, Transaction, TxHelpers, TxPositiveAmount, TxVersion} import monix.execution.Scheduler.Implicits.global import org.scalatest.{Assertion, Assertions} @@ -260,9 +259,17 @@ class RollbackSpec extends FreeSpec with WithDomain { nextTs, d.lastBlockId, Seq( - TransferTransaction - .selfSigned(1.toByte, sender, recipient.toAddress, IssuedAsset(issueTransaction.id()), assetAmount, Waves, 1, ByteStr.empty, nextTs) - .explicitGet() + TxHelpers.transfer( + from = sender, + to = recipient.toAddress, + amount = assetAmount, + asset = IssuedAsset(issueTransaction.id()), + fee = 1, + feeAsset = Waves, + attachment = ByteStr.empty, + timestamp = nextTs, + version = 1.toByte + ) ) ) .block @@ -845,9 +852,13 @@ class RollbackSpec extends FreeSpec with WithDomain { val leaseAmount = smallFeeGen.sample.get val leaseTx = - LeaseTransaction - .selfSigned(2.toByte, leaseSender, leaseRecipientAddress.toAddress, leaseAmount, setScript.fee.value, nextTs) - .explicitGet() + TxHelpers.lease( + sender = leaseSender, + recipient = leaseRecipientAddress.toAddress, + amount = leaseAmount, + fee = setScript.fee.value, + version = 2.toByte + ) val leaseId = leaseTx.id() d.appendBlock(setScript, leaseTx) @@ -941,7 +952,12 @@ class RollbackSpec extends FreeSpec with WithDomain { .create( nextTs, blockWithScriptId, - Seq(SetScriptTransaction.selfSigned(1.toByte, sender, None, 800000, nextTs).explicitGet()) + Seq( + SetScriptTransaction + .create(1.toByte, sender.publicKey, None, 800000, nextTs, Proofs.empty) + .map(_.signWith(sender.privateKey)) + .explicitGet() + ) ) .block ) @@ -1124,9 +1140,9 @@ class RollbackSpec extends FreeSpec with WithDomain { def leases(address: Address) = d.accountsApi.activeLeases(address).toListL.runSyncUnsafe() val leaseTxs = Seq.fill(5)(lease(defaultSigner, secondAddress)) ++ Seq.fill(5)(lease(secondSigner, defaultAddress)) - val info = leaseTxs.map { tx => - LeaseInfo(tx.id(), TransactionId(tx.id()), tx.sender.toAddress, tx.recipient.asInstanceOf[Address], tx.amount.value, Height(2), Active) - } + val info = leaseTxs.map {tx => + LeaseInfo(tx.id(), TransactionId(tx.id()), tx.sender.toAddress, tx.recipient.asInstanceOf[Address], tx.amount.value, Height(2), Active) + } val b1 = d.appendBlock(leaseTxs*) leases(defaultAddress) should contain theSameElementsAs info diff --git a/node/tests/src/test/scala/com/wavesplatform/state/TransactionsByAddressSpec.scala b/node/tests/src/test/scala/com/wavesplatform/state/TransactionsByAddressSpec.scala index 07753a0d399..885e3cfc5ae 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/TransactionsByAddressSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/TransactionsByAddressSpec.scala @@ -122,7 +122,7 @@ class TransactionsByAddressSpec extends FreeSpec with BlockGen with WithDomain { val txs = Future { d.addressTransactions(defaultAddress).map(_._2.tpe) } d.blockchain.bestLiquidSnapshot.synchronized(d.appendKeyBlock()) startRead.unlock() - Await.result(txs, 1.minute).map(_.tpe) shouldBe List(TransactionType.Issue) + Await.result(txs, 1.minute) shouldBe List(TransactionType.Issue) } } } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/AssetTransactionsDiffTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/AssetTransactionsDiffTest.scala index ad155079b62..da5b93ac49f 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/AssetTransactionsDiffTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/AssetTransactionsDiffTest.scala @@ -460,9 +460,9 @@ class AssetTransactionsDiffTest extends PropSpec with BlocksTransactionsHelpers val genesis = GenesisTransaction.create(sender.toAddress, ENOUGH_AMT, t).explicitGet() def issue(script: Script) = - IssueTransaction.selfSigned(2.toByte, sender, "name", "", ENOUGH_AMT, 0, true, Some(script), 100000000, t).explicitGet() + TxHelpers.issue(issuer = sender, amount = ENOUGH_AMT, decimals = 0, name = "name", description = "", reissuable = true, script = Some(script), fee = 100000000, version = 2.toByte) def setAssetScript(asset: IssuedAsset) = - SetAssetScriptTransaction.selfSigned(2.toByte, sender, asset, Some(testScript), 100000000, t).explicitGet() + TxHelpers.setAssetScript(sender, asset, testScript, fee = 100000000, version = TxVersion.V2) def settings(checkNegative: Boolean = false, checkSumOverflow: Boolean = false): FunctionalitySettings = { TestFunctionalitySettings @@ -499,20 +499,17 @@ class AssetTransactionsDiffTest extends PropSpec with BlocksTransactionsHelpers val ts: Long = System.currentTimeMillis() def issue(script: Option[Script]): IssueTransaction = - IssueTransaction - .selfSigned( - version = TxVersion.V2, - sender = issuer, - name = "test", - description = "desc", - quantity = 1, - decimals = 0, - reissuable = true, - script = script, - fee = 1.waves, - timestamp = ts - ) - .explicitGet() + TxHelpers.issue( + issuer = issuer, + amount = 1, + decimals = 0, + name = "test", + description = "desc", + reissuable = true, + script = script, + fee = 1.waves, + version = TxVersion.V2 + ) withDomain(DomainPresets.RideV5) { d => val genesis = GenesisTransaction.create(issuer.toAddress, ENOUGH_AMT, ts).explicitGet() diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiffTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiffTest.scala index 09746e45763..77fe255b1a3 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiffTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiffTest.scala @@ -1358,20 +1358,18 @@ class ExchangeTransactionDiffTest extends PropSpec with Inside with WithDomain w ) .explicitGet() - ExchangeTransaction - .signed( - TxVersion.V3, - matcher.privateKey, - buyOrder, - sellOrder, - 1L, - 1L, - TestValues.fee, - TestValues.fee, - TestValues.fee, - ntpTime.correctedTime() - ) - .explicitGet() + TxHelpers.exchange( + buyOrder, + sellOrder, + matcher, + 1L, + 1L, + TestValues.fee, + TestValues.fee, + TestValues.fee, + ntpTime.correctedTime(), + TxVersion.V3 + ) } def generateAndAppendTx(orderVersion: TxVersion, mode: OrderPriceMode, settings: WavesSettings = DomainPresets.RideV5): Unit = { @@ -1590,14 +1588,16 @@ class ExchangeTransactionDiffTest extends PropSpec with Inside with WithDomain w buyMatcherFee = fee, sellMatcherFee = fee, fee = TxPositiveAmount.unsafeFrom(fee), - order1 = tx.order1.copy(version = Order.V4, matcherFee = TxMatcherFee.unsafeFrom(fee)).signWith(buyer.privateKey), - order2 = tx.order2.copy(version = Order.V4, matcherFee = TxMatcherFee.unsafeFrom(fee)).signWith(seller.privateKey) + order1 = { val o = tx.order1.copy(version = Order.V4, matcherFee = TxMatcherFee.unsafeFrom(fee)); o.withProofs(Proofs(crypto.sign(buyer.privateKey, o.bodyBytes()))) }, + order2 = { val o = tx.order2.copy(version = Order.V4, matcherFee = TxMatcherFee.unsafeFrom(fee)); o.withProofs(Proofs(crypto.sign(seller.privateKey, o.bodyBytes()))) }, + proofs = Proofs.empty ) .signWith(matcher.privateKey) val reversed = fixed .copy( order1 = fixed.order2, - order2 = fixed.order1 + order2 = fixed.order1, + proofs = Proofs.empty ) .signWith(matcher.privateKey) @@ -1664,10 +1664,11 @@ class ExchangeTransactionDiffTest extends PropSpec with Inside with WithDomain w val exchange = tx .copy( amount = TxExchangeAmount.unsafeFrom(amount), - order1 = tx.buyOrder.copy(amount = TxExchangeAmount.unsafeFrom(sellAmount)).signWith(buyer.privateKey), - order2 = tx.sellOrder.copy(amount = TxExchangeAmount.unsafeFrom(buyAmount)).signWith(seller.privateKey), + order1 = { val o = tx.buyOrder.copy(amount = TxExchangeAmount.unsafeFrom(sellAmount)); o.withProofs(Proofs(crypto.sign(buyer.privateKey, o.bodyBytes()))) }, + order2 = { val o = tx.sellOrder.copy(amount = TxExchangeAmount.unsafeFrom(buyAmount)); o.withProofs(Proofs(crypto.sign(seller.privateKey, o.bodyBytes()))) }, buyMatcherFee = (BigInt(tx.fee.value) * amount / buyAmount).toLong, - sellMatcherFee = (BigInt(tx.fee.value) * amount / sellAmount).toLong + sellMatcherFee = (BigInt(tx.fee.value) * amount / sellAmount).toLong, + proofs = Proofs.empty ) .signWith(matcher.privateKey) @@ -1857,42 +1858,39 @@ class ExchangeTransactionDiffTest extends PropSpec with Inside with WithDomain w val sellMatcherFee = Long.MinValue - buyMatcherFee + exchangeFee val sender = testWallet.generateNewAccount().get - def mkIssueTx = IssueTransaction.selfSigned(2.toByte, sender, "IA_01", "", 100, 2, true, None, issueFee, ntpTime.getTimestamp()).explicitGet() + def mkIssueTx = TxHelpers.issue(issuer = sender, amount = 100, decimals = 2, name = "IA_01", description = "", fee = issueFee, script = None, reissuable = true, timestamp = ntpTime.getTimestamp(), version = 2.toByte) val priceAsset = mkIssueTx val amountAsset = mkIssueTx val assetPair = AssetPair(priceAsset.asset, amountAsset.asset) def mkOrder(orderType: OrderType): Order = - Order - .selfSigned( - 3.toByte, - sender, - sender.publicKey, - assetPair, - orderType, - 1, - 1, - ntpTime.getTimestamp(), - ntpTime.getTimestamp() + 100000, - 100 - ) - .explicitGet() + TxHelpers.order( + orderType = orderType, + amountAsset = assetPair.amountAsset, + priceAsset = assetPair.priceAsset, + amount = 1, + price = 1, + fee = 100, + sender = sender, + matcher = sender, + timestamp = ntpTime.getTimestamp(), + expiration = ntpTime.getTimestamp() + 100000, + version = 3.toByte + ) def mkExchangeTx: ExchangeTransaction = - ExchangeTransaction - .signed( - 2.toByte, - sender.privateKey, - mkOrder(OrderType.BUY), - mkOrder(OrderType.SELL), - 1, - 1, - buyMatcherFee, - sellMatcherFee, - exchangeFee, - ntpTime.getTimestamp() - ) - .explicitGet() + TxHelpers.exchange( + mkOrder(OrderType.BUY), + mkOrder(OrderType.SELL), + sender, + 1, + 1, + buyMatcherFee, + sellMatcherFee, + exchangeFee, + ntpTime.getTimestamp(), + 2.toByte + ) withDomain(DomainPresets.RideV5) { d => d.appendBlock( diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiffTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiffTest.scala index 77ba2769f96..3b9b45a56a3 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiffTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiffTest.scala @@ -28,7 +28,7 @@ import com.wavesplatform.settings.{FunctionalitySettings, TestFunctionalitySetti import com.wavesplatform.test.* import com.wavesplatform.transaction.TxValidationError.GenericError import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.{GenesisTransaction, TxHelpers, TxVersion} +import com.wavesplatform.transaction.{GenesisTransaction, Proofs, TxHelpers, TxVersion} import monix.eval.Coeval import org.scalatest.Assertion @@ -390,7 +390,7 @@ class SetScriptTransactionDiffTest extends PropSpec with WithDomain { property("free call is prohibited") { val freeCall = TestCompiler(V6).compileFreeCall("[]") val account = accountGen.sample.get - SetScriptTransaction.selfSigned(1.toByte, account, Some(freeCall), MinIssueFee, System.currentTimeMillis()) shouldBe Left( + SetScriptTransaction.create(1.toByte, account.publicKey, Some(freeCall), MinIssueFee, System.currentTimeMillis(), Proofs.empty) shouldBe Left( GenericError("Script type for Set Script Transaction should not be CALL") ) } @@ -542,12 +542,13 @@ class SetScriptTransactionDiffTest extends PropSpec with WithDomain { val compileVersion = if (version == V6) V5 else version val script = ContractScriptImpl(version, TestCompiler(compileVersion).compile(expr).explicitGet()) - val tx = SetScriptTransaction.selfSigned( + val tx = SetScriptTransaction.create( TxVersion.V1, - accountGen.sample.get, + accountGen.sample.get.publicKey, Some(script), 100000000, - 1526287561757L + 1526287561757L, + Proofs.empty ) if (version == V6) { @@ -624,15 +625,15 @@ class SetScriptTransactionDiffTest extends PropSpec with WithDomain { val genesis = GenesisTransaction.create(dApp.toAddress, ENOUGH_AMT, ts).explicitGet() val scriptWithInvoke = TestCompiler(V5).compileContract(dAppVerifier("invoke")) - val setScriptWithInvoke = SetScriptTransaction.selfSigned(TxVersion.V2, dApp, Some(scriptWithInvoke), fee, ts).explicitGet() + val setScriptWithInvoke = TxHelpers.setScript(dApp, scriptWithInvoke, fee, TxVersion.V2) val scriptWithReentrantInvoke = TestCompiler(V5).compileContract(dAppVerifier("reentrantInvoke")) - val setScriptWithReentrantInvoke = SetScriptTransaction.selfSigned(TxVersion.V2, dApp, Some(scriptWithReentrantInvoke), fee, ts).explicitGet() + val setScriptWithReentrantInvoke = TxHelpers.setScript(dApp, scriptWithReentrantInvoke, fee, TxVersion.V2) val setScriptWithInvokeRec = - SetScriptTransaction.selfSigned(TxVersion.V2, dApp, Some(dAppVerifierRec(FunctionIds.CALLDAPP)), fee, ts).explicitGet() + TxHelpers.setScript(dApp, dAppVerifierRec(FunctionIds.CALLDAPP), fee, TxVersion.V2) val setScriptWithReentrantInvokeRec = - SetScriptTransaction.selfSigned(TxVersion.V2, dApp, Some(dAppVerifierRec(FunctionIds.CALLDAPPREENTRANT)), fee, ts).explicitGet() + TxHelpers.setScript(dApp, dAppVerifierRec(FunctionIds.CALLDAPPREENTRANT), fee, TxVersion.V2) d.appendBlock(genesis) d.appendBlockE(setScriptWithInvoke) should produce("DApp-to-dApp invocations are not allowed from verifier") @@ -662,9 +663,9 @@ class SetScriptTransactionDiffTest extends PropSpec with WithDomain { val genesis = GenesisTransaction.create(smartAcc.toAddress, ENOUGH_AMT, ts).explicitGet() val setScriptWithInvoke = - SetScriptTransaction.selfSigned(TxVersion.V2, smartAcc, Some(getScriptWithSyncCall("invoke")), 0.01.waves, ts).explicitGet() + TxHelpers.setScript(smartAcc, getScriptWithSyncCall("invoke"), 0.01.waves, TxVersion.V2) val setScriptWithReentrantInvoke = - SetScriptTransaction.selfSigned(TxVersion.V2, smartAcc, Some(getScriptWithSyncCall("reentrantInvoke")), 0.01.waves, ts).explicitGet() + TxHelpers.setScript(smartAcc, getScriptWithSyncCall("reentrantInvoke"), 0.01.waves, TxVersion.V2) d.appendBlock(genesis) d.appendBlockE(setScriptWithInvoke) should produce("function 'Native(1020)' not found") diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/DAppListArgTypesTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/DAppListArgTypesTest.scala index cb562c98224..0cc14ba850d 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/DAppListArgTypesTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/DAppListArgTypesTest.scala @@ -8,7 +8,6 @@ import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.contract.DApp.{CallableAnnotation, CallableFunction} import com.wavesplatform.lang.directives.values.{V3, V4} import com.wavesplatform.lang.script.{ContractScript, Script} -import com.wavesplatform.lang.v1.FunctionHeader.User import com.wavesplatform.lang.v1.compiler.Terms.{CONST_STRING, *} import com.wavesplatform.lang.v1.compiler.{TestCompiler, Types} import com.wavesplatform.lang.v1.evaluator.ctx.impl.GlobalValNames @@ -18,8 +17,6 @@ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.TxHelpers -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.utils.Signed import org.scalatest.Inside class DAppListArgTypesTest extends PropSpec with WithDomain with Inside { @@ -32,10 +29,9 @@ class DAppListArgTypesTest extends PropSpec with WithDomain with Inside { val invoker = RandomKeyPair() val dApp = RandomKeyPair() val fee = ciFee().sample.get - val call = Some(FUNCTION_CALL(User("f"), args)) val genesis = Seq(invoker, dApp).map(acc => TxHelpers.genesis(acc.toAddress, ENOUGH_AMT)) - val setDApp = SetScriptTransaction.selfSigned(1.toByte, dApp, Some(dAppScript), 0.01.waves, ts).explicitGet() - val ci = () => Signed.invokeScript(1.toByte, invoker, dApp.toAddress, call, Nil, fee, Waves, ts) + val setDApp = TxHelpers.setScript(dApp, dAppScript, 0.01.waves, 1.toByte) + val ci = () => TxHelpers.invoke(dApp.toAddress, Some("f"), args, Nil, invoker, fee, Waves, 1.toByte, ts) (genesis :+ setDApp, ci, dApp.toAddress) } @@ -127,7 +123,7 @@ class DAppListArgTypesTest extends PropSpec with WithDomain with Inside { assert(forbidAfterActivation = true, rideList(rideList().head)) } - property("NODE-799. list of object as callable argument is forbidden by serialization") { + property("NODE-799. list of object as callable argument is forbidden by serialization") { val (_, invoke, _) = preconditions(dApp, rideList(CaseObj(Types.UNIT, Map()))) (the[Throwable] thrownBy invoke()).getMessage should include("Serialization of value Unit is unsupported") } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/IllegalAddressChainIdTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/IllegalAddressChainIdTest.scala index ae8014a70f0..6b07389813b 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/IllegalAddressChainIdTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/IllegalAddressChainIdTest.scala @@ -1,14 +1,10 @@ package com.wavesplatform.state.diffs.ci -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.db.WithDomain import com.wavesplatform.lang.directives.values.V5 import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.test.* -import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.utils.Signed import com.wavesplatform.transaction.{TxHelpers, TxVersion} class IllegalAddressChainIdTest extends PropSpec with WithDomain { @@ -33,8 +29,8 @@ class IllegalAddressChainIdTest extends PropSpec with WithDomain { val invoker = RandomKeyPair() val gTx1 = TxHelpers.genesis(master.toAddress, ENOUGH_AMT, TxHelpers.timestamp) val gTx2 = TxHelpers.genesis(invoker.toAddress, ENOUGH_AMT, TxHelpers.timestamp) - val ssTx = SetScriptTransaction.selfSigned(1.toByte, master, Some(contract(bigComplexity)), 0.01.waves, TxHelpers.timestamp).explicitGet() - val invokeTx = Signed.invokeScript(TxVersion.V3, invoker, master.toAddress, None, Nil, 0.005.waves, Waves, TxHelpers.timestamp) + val ssTx = TxHelpers.setScript(master, contract(bigComplexity), 0.01.waves, 1.toByte) + val invokeTx = TxHelpers.invoke(master.toAddress, invoker = invoker, fee = 0.005.waves, version = TxVersion.V3, timestamp = TxHelpers.timestamp) (Seq(gTx1, gTx2, ssTx), invokeTx) } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeValidationTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeValidationTest.scala index fc10661ff1f..afb39b34006 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeValidationTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeValidationTest.scala @@ -5,7 +5,8 @@ import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.db.WithDomain import com.wavesplatform.db.WithState.AddrWithBalance import com.wavesplatform.lang.directives.values.V5 -import com.wavesplatform.lang.v1.compiler.Terms.{ARR, CONST_LONG} +import com.wavesplatform.lang.v1.FunctionHeader.User +import com.wavesplatform.lang.v1.compiler.Terms.{ARR, CONST_LONG, FUNCTION_CALL} import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.protobuf.transaction.PBTransactions import com.wavesplatform.state.diffs.ENOUGH_AMT @@ -15,6 +16,7 @@ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.TxHelpers.* import com.wavesplatform.transaction.TxVersion.{V1, V2} +import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment class InvokeValidationTest extends PropSpec with WithDomain { @@ -114,14 +116,37 @@ class InvokeValidationTest extends PropSpec with WithDomain { property("invoke tx size limit is 5 Kb") { def array(size: Int): ARR = ARR(Vector.fill(size)(CONST_LONG(1)), 0, false).explicitGet() - val txV1 = invoke(defaultAddress, Some("f"), Seq(array(557)), version = V1) - def tooBigTxV1 = invoke(defaultAddress, Some("f"), Seq(array(558)), version = V1) + val txV1 = invoke(defaultAddress, Some("f"), Seq(array(557)), version = V1) + def tooBigTxV1 = InvokeScriptTransaction.create( + 1.toByte, + defaultSigner.publicKey, + defaultAddress, + Some(FUNCTION_CALL(User("f"), List(array(559)))), + Seq.empty, + 1, + Waves, + 1, + Proofs.empty, + defaultAddress.chainId + ).explicitGet() + txV1.copy(proofs = Proofs.empty).bytes().length shouldBe 5114 - (the[Exception] thrownBy tooBigTxV1).getMessage shouldBe "GenericError(InvokeScriptTransaction bytes length = 5123 exceeds limit = 5120)" + (the[Exception] thrownBy tooBigTxV1).getMessage shouldBe "GenericError(InvokeScriptTransaction bytes length = 5132 exceeds limit = 5120)" val txV2 = invoke(defaultAddress, Some("f"), Seq(array(564)), version = V2) - def tooBigTxV2 = invoke(defaultAddress, Some("f"), Seq(array(565)), version = V2) + def tooBigTxV2 = InvokeScriptTransaction.create( + 2.toByte, + defaultSigner.publicKey, + defaultAddress, + Some(FUNCTION_CALL(User("f"), List(array(566)))), + Seq.empty, + 1, + Waves, + 1, + Proofs.empty, + defaultAddress.chainId + ).explicitGet() PBTransactions.toPBInvokeScriptData(txV2.dApp, txV2.funcCallOpt, txV2.payments).toByteArray.length shouldBe 5120 - (the[Exception] thrownBy tooBigTxV2).getMessage shouldBe "GenericError(InvokeScriptTransaction bytes length = 5129 exceeds limit = 5120)" + (the[Exception] thrownBy tooBigTxV2).getMessage shouldBe "GenericError(InvokeScriptTransaction bytes length = 5138 exceeds limit = 5120)" } } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/package.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/package.scala index 1c66719b1ec..ea656e3287e 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/package.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/package.scala @@ -7,9 +7,8 @@ import com.wavesplatform.lang.script.ContractScript.ContractScriptImpl import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.v1.compiler.Terms.{BLOCK, FUNCTION_CALL, LET} import com.wavesplatform.state.diffs.FeeValidation.* -import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.{TransactionType, TxVersion} import com.wavesplatform.transaction.smart.{InvokeExpressionTransaction, SetScriptTransaction} +import com.wavesplatform.transaction.{TransactionType, TxHelpers} import org.scalacheck.Gen package object ci { @@ -36,19 +35,14 @@ package object ci { callables.head.u.body ) { c => val callable = callables.find(_.u.name == c.function.funcName).get.u - (callable.args zip c.args).foldLeft(callable.body) { - case (resultExpr, (argName, arg)) => BLOCK(LET(argName, arg), resultExpr) + (callable.args zip c.args).foldLeft(callable.body) { case (resultExpr, (argName, arg)) => + BLOCK(LET(argName, arg), resultExpr) } } - InvokeExpressionTransaction - .selfSigned( - TxVersion.V1, - invoker, - ExprScript(V5, expression, isFreeCall = true).explicitGet(), - fee.getOrElse(ciFee(freeCall = true).sample.get), - Waves, - setScript.timestamp - ) - .explicitGet() + TxHelpers.invokeExpression( + ExprScript(V5, expression, isFreeCall = true).explicitGet(), + invoker, + fee.getOrElse(ciFee(freeCall = true).sample.get) + ) } } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/InvokeScriptTransactionCrosscontractInvokeDiffTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/InvokeScriptTransactionCrosscontractInvokeDiffTest.scala index 252a8d11021..4755bdcc095 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/InvokeScriptTransactionCrosscontractInvokeDiffTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/InvokeScriptTransactionCrosscontractInvokeDiffTest.scala @@ -13,26 +13,21 @@ import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.{Terms, TestCompiler} import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.settings.TestFunctionalitySettings -import com.wavesplatform.state.{IntegerDataEntry, StringDataEntry} import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.diffs.ci.ciFee +import com.wavesplatform.state.{IntegerDataEntry, StringDataEntry} import com.wavesplatform.test.* -import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction, TxVersion} import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.assets.IssueTransaction +import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment -import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.utils.Signed +import com.wavesplatform.transaction.{GenesisTransaction, TxHelpers, TxVersion} import org.scalatest.EitherValues -class InvokeScriptTransactionCrosscontractInvokeDiffTest - extends PropSpec - with WithState - with DBCacheSettings - with EitherValues { +class InvokeScriptTransactionCrosscontractInvokeDiffTest extends PropSpec with WithState with DBCacheSettings with EitherValues { - private val fsWithV5 = TestFunctionalitySettings.Enabled.copy(preActivatedFeatures = Map( + private val fsWithV5 = TestFunctionalitySettings.Enabled.copy(preActivatedFeatures = + Map( BlockchainFeatures.SmartAccounts.id -> 0, BlockchainFeatures.SmartAssets.id -> 0, BlockchainFeatures.Ride4DApps.id -> 0, @@ -40,7 +35,8 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest BlockchainFeatures.DataTransaction.id -> 0, BlockchainFeatures.BlockV5.id -> 0, BlockchainFeatures.SynchronousCalls.id -> 0 - )) + ) + ) property("Crosscontract call - internal invoke state update") { @@ -48,49 +44,51 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest val (invokeEntry2Key, invokeEntry2NewVal) = ("entry2", 100500) val invokeEntry3Key = "entry3" - def contractMain(otherAcc: Address): Script = TestCompiler(V5).compileContract(s""" - |{-# STDLIB_VERSION 5 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-#SCRIPT_TYPE ACCOUNT#-} - | - | @Callable(i) - | func foo() = { - | let nextDAppAddr = Address(base58'$otherAcc') - | - | strict invEntry3BeforeIsDefined = isDefined(getString(nextDAppAddr, "$invokeEntry3Key")) - | - | strict invResult = invoke(nextDAppAddr, "bar", [], []) - | - | let invEntry1ValIsOK = getIntegerValue(nextDAppAddr, "$invokeEntry1Key") == $invokeEntry1Val - | let invEntry2IsNotString = isDefined(getString(nextDAppAddr, "$invokeEntry2Key")) == false - | let invEntry2ValIsOK = getIntegerValue(nextDAppAddr, "$invokeEntry2Key") == $invokeEntry2NewVal - | let invEntry3AfterIsDeleted = isDefined(getString(nextDAppAddr, "$invokeEntry3Key")) == false - | - | - | if invEntry1ValIsOK && invEntry2IsNotString && invEntry2ValIsOK && invEntry3BeforeIsDefined && invEntry3AfterIsDeleted - | then - | ([], unit) - | else - | throw("Internal invoke state update error") - | } - |""".stripMargin) + def contractMain(otherAcc: Address): Script = TestCompiler(V5).compileContract( + s""" + |{-# STDLIB_VERSION 5 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-#SCRIPT_TYPE ACCOUNT#-} + | + | @Callable(i) + | func foo() = { + | let nextDAppAddr = Address(base58'$otherAcc') + | + | strict invEntry3BeforeIsDefined = isDefined(getString(nextDAppAddr, "$invokeEntry3Key")) + | + | strict invResult = invoke(nextDAppAddr, "bar", [], []) + | + | let invEntry1ValIsOK = getIntegerValue(nextDAppAddr, "$invokeEntry1Key") == $invokeEntry1Val + | let invEntry2IsNotString = isDefined(getString(nextDAppAddr, "$invokeEntry2Key")) == false + | let invEntry2ValIsOK = getIntegerValue(nextDAppAddr, "$invokeEntry2Key") == $invokeEntry2NewVal + | let invEntry3AfterIsDeleted = isDefined(getString(nextDAppAddr, "$invokeEntry3Key")) == false + | + | + | if invEntry1ValIsOK && invEntry2IsNotString && invEntry2ValIsOK && invEntry3BeforeIsDefined && invEntry3AfterIsDeleted + | then + | ([], unit) + | else + | throw("Internal invoke state update error") + | } + |""".stripMargin + ) def contractSecond(): Script = TestCompiler(V5).compileContract(s""" - |{-# STDLIB_VERSION 5 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-#SCRIPT_TYPE ACCOUNT#-} - | - | @Callable(i) - | func bar() = { - | ( - | [IntegerEntry("$invokeEntry1Key", $invokeEntry1Val), - | IntegerEntry("$invokeEntry2Key", $invokeEntry2NewVal), - | DeleteEntry("$invokeEntry3Key") - | ], - | unit - | ) - | } - |""".stripMargin) + |{-# STDLIB_VERSION 5 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-#SCRIPT_TYPE ACCOUNT#-} + | + | @Callable(i) + | func bar() = { + | ( + | [IntegerEntry("$invokeEntry1Key", $invokeEntry1Val), + | IntegerEntry("$invokeEntry2Key", $invokeEntry2NewVal), + | DeleteEntry("$invokeEntry3Key") + | ], + | unit + | ) + | } + |""".stripMargin) val scenario = for { @@ -105,37 +103,31 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest scriptMain = Some(contractMain(secondAcc.toAddress)) scriptSecond = Some(contractSecond()) - ssTxMain = SetScriptTransaction.selfSigned(1.toByte, mainAcc, scriptMain, fee, ts + 5).explicitGet() - ssTxSecond = SetScriptTransaction.selfSigned(1.toByte, secondAcc, scriptSecond, fee, ts + 5).explicitGet() + ssTxMain = TxHelpers.setScript(mainAcc, scriptMain.get, fee, 1.toByte) + ssTxSecond = TxHelpers.setScript(secondAcc, scriptSecond.get, fee, 1.toByte) dataEntry = StringDataEntry(invokeEntry2Key, "strData") - dataTxSecond = DataTransaction.selfSigned(1.toByte, secondAcc, Seq(dataEntry), fee, ts + 6).explicitGet() + dataTxSecond = TxHelpers.data(secondAcc, Seq(dataEntry), fee) dataEntry2 = StringDataEntry(invokeEntry3Key, "deleted entry") - dataTxSecond2 = DataTransaction.selfSigned(1.toByte, secondAcc, Seq(dataEntry2), fee, ts + 6).explicitGet() + dataTxSecond2 = TxHelpers.data(secondAcc, Seq(dataEntry2), fee) fc = Terms.FUNCTION_CALL(FunctionHeader.User("foo"), List.empty) payments = List(Payment(10L, Waves)) - invokeTx = Signed.invokeScript( - TxVersion.V3, - invoker, - mainAcc.toAddress, - Some(fc), - payments, - fee, - Waves, - ts + 10) + invokeTx = InvokeScriptTransaction + .create(TxVersion.V3, invoker.publicKey, mainAcc.toAddress, Some(fc), payments, fee, Waves, ts + 10) + .map(_.signWith(invoker.privateKey)) + .explicitGet() } yield (Seq(gTx1, gTx2, gTx3, ssTxMain, ssTxSecond, dataTxSecond, dataTxSecond2), invokeTx, secondAcc.toAddress) - forAll(scenario) { - case (genesisTxs, invokeTx, secondDApp) => - assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { - case (snapshot, bc) => - snapshot.errorMessage(invokeTx.id()) shouldBe None + forAll(scenario) { case (genesisTxs, invokeTx, secondDApp) => + assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { + case (snapshot, bc) => + snapshot.errorMessage(invokeTx.id()) shouldBe None - bc.accountData(secondDApp, invokeEntry1Key) shouldBe Some(IntegerDataEntry(invokeEntry1Key, invokeEntry1Val)) - bc.accountData(secondDApp, invokeEntry2Key) shouldBe Some(IntegerDataEntry(invokeEntry2Key, invokeEntry2NewVal)) - } + bc.accountData(secondDApp, invokeEntry1Key) shouldBe Some(IntegerDataEntry(invokeEntry1Key, invokeEntry1Val)) + bc.accountData(secondDApp, invokeEntry2Key) shouldBe Some(IntegerDataEntry(invokeEntry2Key, invokeEntry2NewVal)) + } } } @@ -145,42 +137,44 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest val (invokeEntry2Key, invokeEntry2NewVal) = ("entry2", 100500) val invokeEntry3Key = "entry3" - val contractMain = TestCompiler(V5).compileContract(s""" - |{-# STDLIB_VERSION 5 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-#SCRIPT_TYPE ACCOUNT#-} - | - | @Callable(i) - | func foo() = { - | - | strict invEntry3BeforeIsDefined = isDefined(getString(this, "$invokeEntry3Key")) - | - | strict invResult = invoke(this, "bar", [], []) - | - | let invEntry1ValIsOK = getIntegerValue(this, "$invokeEntry1Key") == $invokeEntry1Val - | let invEntry2IsNotString = isDefined(getString(this, "$invokeEntry2Key")) == false - | let invEntry2ValIsOK = getIntegerValue(this, "$invokeEntry2Key") == $invokeEntry2NewVal - | let invEntry3AfterIsDeleted = isDefined(getString(this, "$invokeEntry3Key")) == false - | - | - | if invEntry1ValIsOK && invEntry2IsNotString && invEntry2ValIsOK && invEntry3BeforeIsDefined && invEntry3AfterIsDeleted - | then - | ([], unit) - | else - | throw("Internal invoke state update error") - | } - | - | @Callable(i) - | func bar() = { - | ( - | [IntegerEntry("$invokeEntry1Key", $invokeEntry1Val), - | IntegerEntry("$invokeEntry2Key", $invokeEntry2NewVal), - | DeleteEntry("$invokeEntry3Key") - | ], - | unit - | ) - | } - |""".stripMargin) + val contractMain = TestCompiler(V5).compileContract( + s""" + |{-# STDLIB_VERSION 5 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-#SCRIPT_TYPE ACCOUNT#-} + | + | @Callable(i) + | func foo() = { + | + | strict invEntry3BeforeIsDefined = isDefined(getString(this, "$invokeEntry3Key")) + | + | strict invResult = invoke(this, "bar", [], []) + | + | let invEntry1ValIsOK = getIntegerValue(this, "$invokeEntry1Key") == $invokeEntry1Val + | let invEntry2IsNotString = isDefined(getString(this, "$invokeEntry2Key")) == false + | let invEntry2ValIsOK = getIntegerValue(this, "$invokeEntry2Key") == $invokeEntry2NewVal + | let invEntry3AfterIsDeleted = isDefined(getString(this, "$invokeEntry3Key")) == false + | + | + | if invEntry1ValIsOK && invEntry2IsNotString && invEntry2ValIsOK && invEntry3BeforeIsDefined && invEntry3AfterIsDeleted + | then + | ([], unit) + | else + | throw("Internal invoke state update error") + | } + | + | @Callable(i) + | func bar() = { + | ( + | [IntegerEntry("$invokeEntry1Key", $invokeEntry1Val), + | IntegerEntry("$invokeEntry2Key", $invokeEntry2NewVal), + | DeleteEntry("$invokeEntry3Key") + | ], + | unit + | ) + | } + |""".stripMargin + ) val scenario = for { @@ -191,36 +185,30 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest gTx1 = GenesisTransaction.create(mainAcc.toAddress, ENOUGH_AMT, ts).explicitGet() gTx2 = GenesisTransaction.create(invoker.toAddress, ENOUGH_AMT, ts).explicitGet() - ssTxMain = SetScriptTransaction.selfSigned(1.toByte, mainAcc, Some(contractMain), fee, ts + 5).explicitGet() + ssTxMain = TxHelpers.setScript(mainAcc, contractMain, fee, 1.toByte) dataEntry = StringDataEntry(invokeEntry2Key, "strData") - dataTxMain = DataTransaction.selfSigned(1.toByte, mainAcc, Seq(dataEntry), fee, ts + 6).explicitGet() + dataTxMain = TxHelpers.data(mainAcc, Seq(dataEntry), fee) dataEntry2 = StringDataEntry(invokeEntry3Key, "deleted entry") - dataTxMain2 = DataTransaction.selfSigned(1.toByte, mainAcc, Seq(dataEntry2), fee, ts + 6).explicitGet() + dataTxMain2 = TxHelpers.data(mainAcc, Seq(dataEntry2), fee) fc = Terms.FUNCTION_CALL(FunctionHeader.User("foo"), List.empty) payments = List(Payment(10L, Waves)) - invokeTx = Signed.invokeScript( - TxVersion.V3, - invoker, - mainAcc.toAddress, - Some(fc), - payments, - fee, - Waves, - ts + 10) + invokeTx = InvokeScriptTransaction + .create(TxVersion.V3, invoker.publicKey, mainAcc.toAddress, Some(fc), payments, fee, Waves, ts + 10) + .map(_.signWith(invoker.privateKey)) + .explicitGet() } yield (Seq(gTx1, gTx2, ssTxMain, dataTxMain, dataTxMain2), invokeTx, mainAcc.toAddress) - forAll(scenario) { - case (genesisTxs, invokeTx, mainDApp) => - assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { - case (snapshot, bc) => - snapshot.errorMessage(invokeTx.id()) shouldBe None + forAll(scenario) { case (genesisTxs, invokeTx, mainDApp) => + assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { + case (snapshot, bc) => + snapshot.errorMessage(invokeTx.id()) shouldBe None - bc.accountData(mainDApp, invokeEntry1Key) shouldBe Some(IntegerDataEntry(invokeEntry1Key, invokeEntry1Val)) - bc.accountData(mainDApp, invokeEntry2Key) shouldBe Some(IntegerDataEntry(invokeEntry2Key, invokeEntry2NewVal)) - } + bc.accountData(mainDApp, invokeEntry1Key) shouldBe Some(IntegerDataEntry(invokeEntry1Key, invokeEntry1Val)) + bc.accountData(mainDApp, invokeEntry2Key) shouldBe Some(IntegerDataEntry(invokeEntry2Key, invokeEntry2NewVal)) + } } } @@ -254,75 +242,77 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest ScriptCompiler.compile(script, ScriptEstimatorV3.latest).explicitGet()._1 } - def contractMain(secondAcc: Address, thirdAcc: Address, paymentAsset: ByteStr): Script = TestCompiler(V5).compileContract(s""" - |{-# STDLIB_VERSION 5 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-#SCRIPT_TYPE ACCOUNT#-} - | - | @Callable(i) - | func foo() = { - | let secondDAppAddr = Address(base58'$secondAcc') - | let thirdDAppAddr = Address(base58'$thirdAcc') - | - | strict invBarResult = invoke(secondDAppAddr, "bar", [], []) - | - | let thirdDAppDataEntryIsOK = getIntegerValue(thirdDAppAddr, "$invokeEntry1Key") == $invokeEntry1Val - | - | strict invAnotherBazResult = invoke( - | thirdDAppAddr, - | "anotherBaz", - | [], - | [AttachedPayment(base58'$paymentAsset', $paymentAssetAmount)]) - | - | if thirdDAppDataEntryIsOK - | then - | ([], unit) - | else - | throw("Internal invoke chain state update error") - | } - |""".stripMargin) - - def contractSecond(thirdAcc: Address, transferAsset: ByteStr): Script = TestCompiler(V5).compileContract(s""" - |{-# STDLIB_VERSION 5 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-#SCRIPT_TYPE ACCOUNT#-} - | - | @Callable(i) - | func bar() = { - | let thirdDAppAddr = Address(base58'$thirdAcc') - | - | strict invBazResult = invoke(thirdDAppAddr, "baz", [], []) - | - | let thirdDAppDataEntryIsOK = getIntegerValue(thirdDAppAddr, "$invokeEntry1Key") == $invokeEntry1Val - | - | if thirdDAppDataEntryIsOK - | then - | ([ScriptTransfer(thirdDAppAddr, $transferAssetAmount, base58'$transferAsset')], unit) - | else - | throw("Internal invoke chain state update error") - | } - |""".stripMargin) + def contractMain(secondAcc: Address, thirdAcc: Address, paymentAsset: ByteStr): Script = + TestCompiler(V5).compileContract(s""" + |{-# STDLIB_VERSION 5 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-#SCRIPT_TYPE ACCOUNT#-} + | + | @Callable(i) + | func foo() = { + | let secondDAppAddr = Address(base58'$secondAcc') + | let thirdDAppAddr = Address(base58'$thirdAcc') + | + | strict invBarResult = invoke(secondDAppAddr, "bar", [], []) + | + | let thirdDAppDataEntryIsOK = getIntegerValue(thirdDAppAddr, "$invokeEntry1Key") == $invokeEntry1Val + | + | strict invAnotherBazResult = invoke( + | thirdDAppAddr, + | "anotherBaz", + | [], + | [AttachedPayment(base58'$paymentAsset', $paymentAssetAmount)]) + | + | if thirdDAppDataEntryIsOK + | then + | ([], unit) + | else + | throw("Internal invoke chain state update error") + | } + |""".stripMargin) + + def contractSecond(thirdAcc: Address, transferAsset: ByteStr): Script = + TestCompiler(V5).compileContract(s""" + |{-# STDLIB_VERSION 5 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-#SCRIPT_TYPE ACCOUNT#-} + | + | @Callable(i) + | func bar() = { + | let thirdDAppAddr = Address(base58'$thirdAcc') + | + | strict invBazResult = invoke(thirdDAppAddr, "baz", [], []) + | + | let thirdDAppDataEntryIsOK = getIntegerValue(thirdDAppAddr, "$invokeEntry1Key") == $invokeEntry1Val + | + | if thirdDAppDataEntryIsOK + | then + | ([ScriptTransfer(thirdDAppAddr, $transferAssetAmount, base58'$transferAsset')], unit) + | else + | throw("Internal invoke chain state update error") + | } + |""".stripMargin) val contractThird = TestCompiler(V5).compileContract(s""" - |{-# STDLIB_VERSION 5 #-} - |{-# CONTENT_TYPE DAPP #-} - |{-#SCRIPT_TYPE ACCOUNT#-} - | - | @Callable(i) - | func baz() = { - | ( - | [ - | IntegerEntry("$invokeEntry1Key", $invokeEntry1Val) - | ], - | unit - | ) - | } - | - | @Callable(i) - | func anotherBaz() = { - | ([], unit) - | } - |""".stripMargin) + |{-# STDLIB_VERSION 5 #-} + |{-# CONTENT_TYPE DAPP #-} + |{-#SCRIPT_TYPE ACCOUNT#-} + | + | @Callable(i) + | func baz() = { + | ( + | [ + | IntegerEntry("$invokeEntry1Key", $invokeEntry1Val) + | ], + | unit + | ) + | } + | + | @Callable(i) + | func anotherBaz() = { + | ([], unit) + | } + |""".stripMargin) val scenario = for { @@ -333,34 +323,28 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest ts <- timestampGen fee <- ciFee(1) - paymentIssue = IssueTransaction - .selfSigned( - 2.toByte, - mainAcc, - "Payment asset", - "", - ENOUGH_AMT, - 8, - reissuable = true, - Some(paymentAssetScript(thirdAcc.toAddress)), - fee, - ts + 1 - ) - .explicitGet() - transferIssue = IssueTransaction - .selfSigned( - 2.toByte, - secondAcc, - "Transfer asset", - "", - ENOUGH_AMT, - 8, - reissuable = true, - Some(transferAssetScript(thirdAcc.toAddress)), - fee, - ts + 2 - ) - .explicitGet() + paymentIssue = TxHelpers.issue( + issuer = mainAcc, + amount = ENOUGH_AMT, + decimals = 8, + name = "Payment asset", + description = "", + reissuable = true, + script = Some(paymentAssetScript(thirdAcc.toAddress)), + fee = fee, + version = 2.toByte + ) + transferIssue = TxHelpers.issue( + issuer = secondAcc, + amount = ENOUGH_AMT, + decimals = 8, + name = "Transfer asset", + description = "", + reissuable = true, + script = Some(transferAssetScript(thirdAcc.toAddress)), + fee = fee, + version = 2.toByte + ) gTx1 = GenesisTransaction.create(mainAcc.toAddress, ENOUGH_AMT, ts).explicitGet() gTx2 = GenesisTransaction.create(invoker.toAddress, ENOUGH_AMT, ts).explicitGet() @@ -370,21 +354,16 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest scriptMain = Some(contractMain(secondAcc.toAddress, thirdAcc.toAddress, paymentIssue.id())) scriptSecond = Some(contractSecond(thirdAcc.toAddress, transferIssue.id())) scriptThird = Some(contractThird) - ssTxMain = SetScriptTransaction.selfSigned(1.toByte, mainAcc, scriptMain, fee, ts + 5).explicitGet() - ssTxSecond = SetScriptTransaction.selfSigned(1.toByte, secondAcc, scriptSecond, fee, ts + 5).explicitGet() - ssTxThird = SetScriptTransaction.selfSigned(1.toByte, thirdAcc, scriptThird, fee, ts + 5).explicitGet() + ssTxMain = TxHelpers.setScript(mainAcc, scriptMain.get, fee, 1.toByte) + ssTxSecond = TxHelpers.setScript(secondAcc, scriptSecond.get, fee, 1.toByte) + ssTxThird = TxHelpers.setScript(thirdAcc, scriptThird.get, fee, 1.toByte) fc = Terms.FUNCTION_CALL(FunctionHeader.User("foo"), List.empty) payments = List(Payment(10L, Waves)) - invokeTx = Signed.invokeScript( - TxVersion.V3, - invoker, - mainAcc.toAddress, - Some(fc), - payments, - fee * 100, - Waves, - ts + 10) + invokeTx = InvokeScriptTransaction + .create(TxVersion.V3, invoker.publicKey, mainAcc.toAddress, Some(fc), payments, fee * 100, Waves, ts + 10) + .map(_.signWith(invoker.privateKey)) + .explicitGet() } yield ( Seq(gTx1, gTx2, gTx3, gTx4, ssTxMain, ssTxSecond, ssTxThird, paymentIssue, transferIssue), invokeTx, @@ -393,15 +372,14 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest paymentIssue.id() ) - forAll(scenario) { - case (genesisTxs, invokeTx, thirdAcc, transferAsset, paymentAsset) => - assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { - case (snapshot, bc) => - snapshot.errorMessage(invokeTx.id()) shouldBe None + forAll(scenario) { case (genesisTxs, invokeTx, thirdAcc, transferAsset, paymentAsset) => + assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { + case (snapshot, bc) => + snapshot.errorMessage(invokeTx.id()) shouldBe None - bc.balance(thirdAcc, IssuedAsset(transferAsset)) shouldBe transferAssetAmount - bc.balance(thirdAcc, IssuedAsset(paymentAsset)) shouldBe paymentAssetAmount - } + bc.balance(thirdAcc, IssuedAsset(transferAsset)) shouldBe transferAssetAmount + bc.balance(thirdAcc, IssuedAsset(paymentAsset)) shouldBe paymentAssetAmount + } } } } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppBalanceCheckTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppBalanceCheckTest.scala index 5c7d70d5a75..98165fccaf2 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppBalanceCheckTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppBalanceCheckTest.scala @@ -12,10 +12,7 @@ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.diffs.ci.ciFee import com.wavesplatform.test.* import com.wavesplatform.test.DomainPresets.* -import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.utils.Signed -import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} +import com.wavesplatform.transaction.{GenesisTransaction, TxHelpers, TxVersion} class SyncDAppBalanceCheckTest extends PropSpec with WithDomain with TransactionGenBase { @@ -53,9 +50,9 @@ class SyncDAppBalanceCheckTest extends PropSpec with WithDomain with Transaction gTx1 = GenesisTransaction.create(invoker.toAddress, ENOUGH_AMT, ts).explicitGet() gTx2 = GenesisTransaction.create(dApp1.toAddress, 0.01.waves, ts).explicitGet() gTx3 = GenesisTransaction.create(dApp2.toAddress, ENOUGH_AMT, ts).explicitGet() - ssTx1 = SetScriptTransaction.selfSigned(1.toByte, dApp1, Some(dApp1Script(dApp2.toAddress)), 0.01.waves, ts).explicitGet() - ssTx2 = SetScriptTransaction.selfSigned(1.toByte, dApp2, Some(dApp2Script), 0.01.waves, ts).explicitGet() - invokeTx = () => Signed.invokeScript(TxVersion.V3, invoker, dApp1.toAddress, None, Nil, fee, Waves, ts) + ssTx1 = TxHelpers.setScript(dApp1, dApp1Script(dApp2.toAddress), 0.01.waves, 1.toByte) + ssTx2 = TxHelpers.setScript(dApp2, dApp2Script, 0.01.waves, 1.toByte) + invokeTx = () => TxHelpers.invoke(dApp1.toAddress, invoker = invoker, fee = fee, version = TxVersion.V3, timestamp = ts) } yield (Seq(gTx1, gTx2, gTx3, ssTx1, ssTx2), invokeTx) property("temporary negative balance of sync call produces error") { diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppListArgTypesTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppListArgTypesTest.scala index 6e9d66d6738..3b01d32544a 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppListArgTypesTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppListArgTypesTest.scala @@ -13,10 +13,8 @@ import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.diffs.ci.ciFee import com.wavesplatform.test.* -import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} -import com.wavesplatform.transaction.utils.Signed -import com.wavesplatform.transaction.{GenesisTransaction, Transaction, TxVersion} +import com.wavesplatform.transaction.smart.InvokeScriptTransaction +import com.wavesplatform.transaction.{GenesisTransaction, Transaction, TxHelpers, TxVersion} class SyncDAppListArgTypesTest extends PropSpec with WithDomain with TransactionGenBase { private val time = new TestTime @@ -47,9 +45,9 @@ class SyncDAppListArgTypesTest extends PropSpec with WithDomain with Transaction val dApp2 = accountGen.sample.get val fee = ciFee().sample.get val gTxs = Seq(invoker, dApp1, dApp2).map(acc => GenesisTransaction.create(acc.toAddress, ENOUGH_AMT, ts).explicitGet()) - val ssTx1 = SetScriptTransaction.selfSigned(1.toByte, dApp1, Some(dApp1Script(dApp2.toAddress, args)), fee, ts).explicitGet() - val ssTx2 = SetScriptTransaction.selfSigned(1.toByte, dApp2, Some(dApp2Script), fee, ts).explicitGet() - val invokeTx = () => Signed.invokeScript(TxVersion.V3, invoker, dApp1.toAddress, None, Nil, fee, Waves, ts) + val ssTx1 = TxHelpers.setScript(dApp1, dApp1Script(dApp2.toAddress, args), fee, 1.toByte) + val ssTx2 = TxHelpers.setScript(dApp2, dApp2Script, fee, 1.toByte) + val invokeTx = () => TxHelpers.invoke(dApp1.toAddress, invoker = invoker, fee = fee, version = TxVersion.V3, timestamp = ts) (gTxs ++ Seq(ssTx1, ssTx2), invokeTx) } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppMultiVersionTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppMultiVersionTest.scala index 1de179776d5..09eb4c46b39 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppMultiVersionTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/ci/sync/SyncDAppMultiVersionTest.scala @@ -9,10 +9,7 @@ import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.diffs.ci.ciFee import com.wavesplatform.test.* -import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} -import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.utils.Signed +import com.wavesplatform.transaction.{GenesisTransaction, TxHelpers, TxVersion} class SyncDAppMultiVersionTest extends PropSpec with WithDomain { import DomainPresets.* @@ -48,21 +45,20 @@ class SyncDAppMultiVersionTest extends PropSpec with WithDomain { gTx1 = GenesisTransaction.create(invoker.toAddress, ENOUGH_AMT, ts).explicitGet() gTx2 = GenesisTransaction.create(dApp1.toAddress, ENOUGH_AMT, ts).explicitGet() gTx3 = GenesisTransaction.create(dApp2.toAddress, ENOUGH_AMT, ts).explicitGet() - ssTx1 = SetScriptTransaction.selfSigned(1.toByte, dApp1, Some(dApp1Script(version1, dApp2.toAddress)), fee, ts).explicitGet() - ssTx2 = SetScriptTransaction.selfSigned(1.toByte, dApp2, Some(dApp2Script(version2)), fee, ts).explicitGet() - invokeTx = Signed.invokeScript(TxVersion.V3, invoker, dApp1.toAddress, None, Nil, fee, Waves, ts) + ssTx1 = TxHelpers.setScript(dApp1, dApp1Script(version1, dApp2.toAddress), fee, 1.toByte) + ssTx2 = TxHelpers.setScript(dApp2, dApp2Script(version2), fee, 1.toByte) + invokeTx = TxHelpers.invoke(dApp1.toAddress, invoker = invoker, fee = fee, version = TxVersion.V3, timestamp = ts) } yield (Seq(gTx1, gTx2, gTx3, ssTx1, ssTx2), invokeTx) property("sync call can be performed between V5 and V6 dApps") { Seq((V5, V6), (V6, V5)) - .foreach { - case (version1, version2) => - val (preparingTxs, invoke) = scenario(version1, version2).sample.get - withDomain(RideV6) { d => - d.appendBlock(preparingTxs*) - d.appendBlock(invoke) - d.blockchain.transactionSucceeded(invoke.txId) shouldBe true - } + .foreach { case (version1, version2) => + val (preparingTxs, invoke) = scenario(version1, version2).sample.get + withDomain(RideV6) { d => + d.appendBlock(preparingTxs*) + d.appendBlock(invoke) + d.blockchain.transactionSucceeded(invoke.txId) shouldBe true + } } } } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/freecall/InvokeExpressionTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/freecall/InvokeExpressionTest.scala index f074f49b9a2..3be1a3b8b0d 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/freecall/InvokeExpressionTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/freecall/InvokeExpressionTest.scala @@ -16,8 +16,7 @@ import com.wavesplatform.state.diffs.{ENOUGH_AMT, FeeValidation} import com.wavesplatform.state.{AssetInfo, AssetStaticInfo, AssetVolumeInfo, BinaryDataEntry, BooleanDataEntry} import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.assets.{IssueTransaction, SponsorFeeTransaction} -import com.wavesplatform.transaction.smart.{InvokeExpressionTransaction, SetScriptTransaction} +import com.wavesplatform.transaction.smart.InvokeExpressionTransaction import com.wavesplatform.transaction.{GenesisTransaction, Transaction, TxHelpers, TxVersion} import com.wavesplatform.utils.JsonMatchers import org.scalatest.{Assertion, EitherValues} @@ -107,9 +106,7 @@ class InvokeExpressionTest extends PropSpec with ScalaCheckPropertyChecks with W val freeCall = TestCompiler(V6).compileFreeCall(s"""strict test = invoke(Address(base58'${dAppAccount.toAddress}'), "test", [], []) |if (test == 123) then [] else throw("err")""".stripMargin) - val invoke = InvokeExpressionTransaction - .selfSigned(TxVersion.V1, TxHelpers.defaultSigner, freeCall, 1000000L, Waves, System.currentTimeMillis()) - .explicitGet() + val invoke = TxHelpers.invokeExpression(freeCall, TxHelpers.defaultSigner, 1000000L) withDomain(ContinuationTransaction) { d => d.helpers.creditWavesToDefaultSigner() d.helpers.creditWavesFromDefaultSigner(dAppAccount.toAddress) @@ -157,7 +154,12 @@ class InvokeExpressionTest extends PropSpec with ScalaCheckPropertyChecks with W d.blockchain.accountData(invoke.sender.toAddress, "check").get shouldBe BooleanDataEntry("check", true) d.blockchain.accountData(invoke.sender.toAddress, "transactionId").get shouldBe BinaryDataEntry("transactionId", invoke.txId) d.liquidSnapshot.assetStatics.size shouldBe 1 - checkAsset(invoke, d.liquidSnapshot.assetStatics.head._2._1, d.liquidSnapshot.assetNamesAndDescriptions.head._2, d.liquidSnapshot.assetVolumes.head._2) + checkAsset( + invoke, + d.liquidSnapshot.assetStatics.head._2._1, + d.liquidSnapshot.assetNamesAndDescriptions.head._2, + d.liquidSnapshot.assetVolumes.head._2 + ) } } @@ -378,8 +380,10 @@ private object InvokeExpressionTest { | [ | BooleanEntry("check", check), | BinaryEntry("transactionId", i.transactionId) - | ${if (issue) s""", Issue("$TestAssetName", "$TestAssetDesc", $TestAssetVolume, $TestAssetDecimals, $TestAssetReissuable, unit, 0) """ - else ""} + | ${ + if (issue) s""", Issue("$TestAssetName", "$TestAssetDesc", $TestAssetVolume, $TestAssetDecimals, $TestAssetReissuable, unit, 0) """ + else "" + } | ${if (transfersCount > 0) "," else ""} | ${(1 to transfersCount).map(_ => s"ScriptTransfer(Address(base58'$receiver'), 1, unit)").mkString(",")} | ] @@ -402,16 +406,15 @@ private object InvokeExpressionTest { val fee = ciFee(freeCall = enoughFee, nonNftIssue = if (issue) 1 else 0, sc = if (bigVerifier) 1 else 0).sample.get val genesis = GenesisTransaction.create(invoker.toAddress, ENOUGH_AMT, TxHelpers.timestamp).explicitGet() - val setVerifier = SetScriptTransaction.selfSigned(TxVersion.V2, invoker, verifier, fee, TxHelpers.timestamp).explicitGet() + val setVerifier = verifier.fold(TxHelpers.removeScript(invoker, fee, TxVersion.V2)) { s => TxHelpers.setScript(invoker, s, fee, TxVersion.V2) } - val sponsorIssueTx = - IssueTransaction.selfSigned(TxVersion.V2, invoker, "name", "", 1000, 1, true, None, 1.waves, TxHelpers.timestamp).explicitGet() - val sponsorAsset = IssuedAsset(sponsorIssueTx.id.value()) - val sponsorTx = SponsorFeeTransaction.selfSigned(TxVersion.V2, invoker, sponsorAsset, Some(1000L), fee, TxHelpers.timestamp).explicitGet() - val feeAsset = if (sponsor) sponsorAsset else Waves + val sponsorIssueTx = TxHelpers.issue(invoker, 1000, 1, "name", "", 1.waves, None, true, TxVersion.V2) + val sponsorAsset = IssuedAsset(sponsorIssueTx.id.value()) + val sponsorTx = TxHelpers.sponsor(sponsorAsset, Some(1000L), invoker, fee, TxVersion.V2) + val feeAsset = if (sponsor) sponsorAsset else Waves val call = makeExpression(invoker, fee, issue, transfersCount, receiver.toAddress, sigVerifyCount, raiseError) - val invoke = InvokeExpressionTransaction.selfSigned(version, invoker, call, fee, feeAsset, TxHelpers.timestamp).explicitGet() + val invoke = TxHelpers.invokeExpression(call, invoker, fee, feeAsset, version) (Seq(genesis, sponsorIssueTx, sponsorTx, setVerifier), invoke) } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/EstimationSwitchTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/EstimationSwitchTest.scala index d3363e8ffd8..eb8db2c2e34 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/EstimationSwitchTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/EstimationSwitchTest.scala @@ -11,11 +11,8 @@ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.diffs.ci.ciFee import com.wavesplatform.test.* import com.wavesplatform.test.DomainPresets.WavesSettingsOps -import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.TxHelpers.{defaultAddress, defaultSigner, setScript} -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.utils.Signed -import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} +import com.wavesplatform.transaction.TxHelpers.{defaultAddress, defaultSigner} +import com.wavesplatform.transaction.{GenesisTransaction, TxHelpers, TxVersion} class EstimationSwitchTest extends PropSpec with WithDomain with TransactionGenBase { private val time = new TestTime @@ -40,8 +37,8 @@ class EstimationSwitchTest extends PropSpec with WithDomain with TransactionGenB val fee = ciFee().sample.get val genesis1 = GenesisTransaction.create(invoker.toAddress, ENOUGH_AMT, ts).explicitGet() val genesis2 = GenesisTransaction.create(dApp.toAddress, ENOUGH_AMT, ts).explicitGet() - val setScript = () => SetScriptTransaction.selfSigned(1.toByte, dApp, Some(dAppScript), fee, ts).explicitGet() - val invoke = () => Signed.invokeScript(TxVersion.V3, invoker, dApp.toAddress, None, Nil, fee, Waves, ts) + val setScript = () => TxHelpers.setScript(dApp, dAppScript, fee, 1.toByte) + val invoke = () => TxHelpers.invoke(dApp.toAddress, invoker = invoker, fee = fee, version = TxVersion.V3, timestamp = ts) withDomain(domainSettingsWithFS(settings)) { d => d.appendBlock(genesis1, genesis2) @@ -80,11 +77,11 @@ class EstimationSwitchTest extends PropSpec with WithDomain with TransactionGenB """.stripMargin ) - d.appendBlock(setScript(defaultSigner, dApp)) + d.appendBlock(TxHelpers.setScript(defaultSigner, dApp)) d.blockchain.accountScript(defaultAddress).get.complexitiesByEstimator(3) shouldBe Map("overlapCase" -> 2701, "redundantOverheadCase" -> 181) - d.appendBlock(setScript(defaultSigner, dApp)) + d.appendBlock(TxHelpers.setScript(defaultSigner, dApp)) d.blockchain.accountScript(defaultAddress).get.complexitiesByEstimator(3) shouldBe Map("overlapCase" -> 1, "redundantOverheadCase" -> 180) } diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/MaxCallableComplexityTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/MaxCallableComplexityTest.scala index bb68010b1a9..ccfeb37be6b 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/MaxCallableComplexityTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/MaxCallableComplexityTest.scala @@ -12,8 +12,8 @@ import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.test.{NumericExt, PropSpec, TestTime} import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.{GenesisTransaction, Proofs, TxVersion, TransactionSignOps} -import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} +import com.wavesplatform.transaction.smart.InvokeScriptTransaction +import com.wavesplatform.transaction.{GenesisTransaction, Proofs, TxHelpers, TxVersion} class MaxCallableComplexityTest extends PropSpec with WithDomain with TransactionGenBase { @@ -24,7 +24,7 @@ class MaxCallableComplexityTest extends PropSpec with WithDomain with Transactio val dApp = accountGen.sample.get withDomain(DomainPresets.RideV5) { d => val genesis = GenesisTransaction.create(dApp.toAddress, ENOUGH_AMT, ts).explicitGet() - val setLargeScript = SetScriptTransaction.selfSigned(TxVersion.V2, dApp, Some(largeScript(V5, 50)), 0.01.waves, ts).explicitGet() + val setLargeScript = TxHelpers.setScript(dApp, largeScript(V5, 50), 0.01.waves, TxVersion.V2) d.appendBlock(genesis) intercept[Exception](d.appendBlock(setLargeScript)).getMessage should include("Contract function (test) is too complex: 10352 > 10000") @@ -37,8 +37,8 @@ class MaxCallableComplexityTest extends PropSpec with WithDomain with Transactio withDomain(DomainPresets.RideV6) { d => val genDApp = GenesisTransaction.create(dApp.toAddress, ENOUGH_AMT, ts).explicitGet() val genInvoker = GenesisTransaction.create(invoker.toAddress, ENOUGH_AMT, ts).explicitGet() - val setScript = SetScriptTransaction.selfSigned(TxVersion.V2, dApp, Some(largeScript(V6, 285)), 0.021.waves, ts).explicitGet() - val setLargeScript = SetScriptTransaction.selfSigned(TxVersion.V2, dApp, Some(largeScript(V6, 300)), 0.022.waves, ts).explicitGet() + val setScript = TxHelpers.setScript(dApp, largeScript(V6, 285), 0.021.waves, TxVersion.V2) + val setLargeScript = TxHelpers.setScript(dApp, largeScript(V6, 300), 0.022.waves, TxVersion.V2) d.appendBlock(genDApp, genInvoker, setScript) val invokeSnapshot = d.transactionDiffer(invokeScript(invoker, dApp.toAddress, "test")).resultE.explicitGet() @@ -57,8 +57,8 @@ class MaxCallableComplexityTest extends PropSpec with WithDomain with Transactio val genLargeDApp = GenesisTransaction.create(largeDApp.toAddress, ENOUGH_AMT, ts).explicitGet() val genInvokeDApp = GenesisTransaction.create(invokeDApp.toAddress, ENOUGH_AMT, ts).explicitGet() - val setLargeScript = SetScriptTransaction.selfSigned(TxVersion.V2, largeDApp, Some(largeScript(V6, 100)), 0.01.waves, ts).explicitGet() - val setInvokeScript = SetScriptTransaction.selfSigned(TxVersion.V2, invokeDApp, Some(invokeScript(V5, largeDApp.toAddress)), 0.01.waves, ts).explicitGet() + val setLargeScript = TxHelpers.setScript(largeDApp, largeScript(V6, 100), 0.01.waves, TxVersion.V2) + val setInvokeScript = TxHelpers.setScript(invokeDApp, invokeScript(V5, largeDApp.toAddress), 0.01.waves, TxVersion.V2) d.appendBlock(genInvoker, genLargeDApp, genInvokeDApp, setLargeScript, setInvokeScript) val invokeSnapshot = d.transactionDiffer(invokeScript(invoker, invokeDApp.toAddress, "invokeTest")).resultE.explicitGet() diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/eth/EthereumInvokeTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/eth/EthereumInvokeTest.scala index 6e9526cd07f..8db3fd85844 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/eth/EthereumInvokeTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/eth/EthereumInvokeTest.scala @@ -18,10 +18,7 @@ import com.wavesplatform.state.diffs.ci.ciFee import com.wavesplatform.state.diffs.smart.predef.{assertProvenPart, provenPart} import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.assets.{IssueTransaction, SetAssetScriptTransaction} -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{Asset, EthABIConverter, EthereumTransaction, GenesisTransaction} +import com.wavesplatform.transaction.{Asset, EthABIConverter, EthereumTransaction, GenesisTransaction, TxHelpers} import com.wavesplatform.utils.EthHelpers import org.scalatest.Inside @@ -119,20 +116,20 @@ class EthereumInvokeTest extends PropSpec with WithDomain with EthHelpers with I val emptyScript = Some(ExprScript(V4, Terms.TRUE).explicitGet()) val issues = (1 to paymentCount).map(_ => - IssueTransaction.selfSigned(2.toByte, dApp, "Asset", "", ENOUGH_AMT, 8, true, emptyScript, 1.waves, ts).explicitGet() + TxHelpers.issue(issuer = dApp, amount = ENOUGH_AMT, decimals = 8, name = "Asset", description = "", fee = 1.waves, script = emptyScript, reissuable = true, timestamp = ts, version = 2.toByte) ) val assets = issues.map(i => IssuedAsset(i.id())) val setAssetScripts = assets.map { asset => val resultScript = assetScript(dummyEthInvoke, dApp.toAddress, assets, asset, assetScriptVersion) - SetAssetScriptTransaction.selfSigned(1.toByte, dApp, asset, Some(resultScript), 1.waves, ts).explicitGet() + TxHelpers.setAssetScript(acc = dApp, asset = asset, script = resultScript, fee = 1.waves, timestamp = ts, version = 1.toByte) } val assetTransfers = - assets.map(a => TransferTransaction.selfSigned(2.toByte, dApp, invoker, a, ENOUGH_AMT, Waves, fee, ByteStr.empty, ts).explicitGet()) + assets.map(a => TxHelpers.transfer(from = dApp, to = invoker, amount = ENOUGH_AMT, asset = a, fee = fee, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts, version = 2.toByte)) val dAppScript = makeDAppScript(assets, dApp2.toAddress, dAppVersion, syncCall) val dAppScript2 = makeDAppScript2(if (dAppVersion >= V5) dAppVersion else V5, dApp2, dApp, invoker, invokerPk) - val setDApp = SetScriptTransaction.selfSigned(1.toByte, dApp, Some(dAppScript), fee, ts).explicitGet() - val setDApp2 = SetScriptTransaction.selfSigned(1.toByte, dApp2, Some(dAppScript2), fee, ts).explicitGet() + val setDApp = TxHelpers.setScript(acc = dApp, script = dAppScript, fee = fee, version = 1.toByte, timestamp = ts) + val setDApp2 = TxHelpers.setScript(acc = dApp2, script = dAppScript2, fee = fee, version = 1.toByte, timestamp = ts) val invoke = EthereumTransaction.Invocation(dApp.toAddress, hexData(dAppScript, assets)) val ethInvoke = dummyEthInvoke.copy(invoke) diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/eth/EthereumTransferSmartTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/eth/EthereumTransferSmartTest.scala index 6c4b19711e5..a6911fcd69f 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/eth/EthereumTransferSmartTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/eth/EthereumTransferSmartTest.scala @@ -3,7 +3,6 @@ package com.wavesplatform.state.diffs.smart.eth import com.wavesplatform.account.Address import com.wavesplatform.block.Block.ProtoBlockVersion import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.db.WithDomain import com.wavesplatform.db.WithState.AddrWithBalance import com.wavesplatform.lang.directives.DirectiveDictionary @@ -14,10 +13,7 @@ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.diffs.smart.predef.{assertProvenPart, provenPart} import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.assets.IssueTransaction -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{Asset, ERC20Address, EthTxGenerator, EthereumTransaction, TxHelpers} +import com.wavesplatform.transaction.{Asset, ERC20Address, EthTxGenerator, EthereumTransaction, TxHelpers, TxVersion} import com.wavesplatform.utils.EthHelpers import scala.math.Ordering.Implicits.infixOrderingOps @@ -73,7 +69,16 @@ class EthereumTransferSmartTest extends PropSpec with WithDomain with EthHelpers property("access to Ethereum transfer from RIDE script") { val recipient = RandomKeyPair() - val issue = IssueTransaction.selfSigned(2.toByte, recipient, "Asset", "", ENOUGH_AMT, 8, reissuable = true, None, 1.waves, ts).explicitGet() + val issue = TxHelpers.issue( + issuer = recipient, + amount = ENOUGH_AMT, + decimals = 8, + name = "Asset", + description = "", + script = None, + fee = 1.waves, + version = TxVersion.V2 + ) for { version <- DirectiveDictionary[StdLibVersion].all @@ -82,11 +87,21 @@ class EthereumTransferSmartTest extends PropSpec with WithDomain with EthHelpers val ethTransfer = EthTxGenerator.generateEthTransfer(TxHelpers.defaultEthSigner, recipient.toAddress, transferAmount, asset) val ethSender = ethTransfer.senderAddress() val transferIssuedAsset = - TransferTransaction.selfSigned(2.toByte, recipient, ethSender, asset, ENOUGH_AMT, Waves, 0.001.waves, ByteStr.empty, ts).explicitGet() + TxHelpers.transfer( + from = recipient, + to = ethSender, + amount = ENOUGH_AMT, + asset = asset, + fee = 0.001.waves, + feeAsset = Waves, + attachment = ByteStr.empty, + timestamp = ts, + version = 2.toByte + ) val function = if (version >= V3) "transferTransactionById" else "transactionById" val verifier = Some(accountScript(version, function, ethTransfer, asset, recipient.toAddress)) - val setVerifier = () => SetScriptTransaction.selfSigned(1.toByte, recipient, verifier, 0.01.waves, ts).explicitGet() + val setVerifier = () => TxHelpers.setScript(recipient, verifier.get, 0.01.waves, 1.toByte) withDomain(settingsForRide(version.max(V6)), Seq(AddrWithBalance(ethSender), AddrWithBalance(recipient.toAddress))) { d => if (asset != Waves) d.appendBlock(issue, transferIssuedAsset) @@ -131,11 +146,21 @@ class EthereumTransferSmartTest extends PropSpec with WithDomain with EthHelpers .foreach { version => val script = assetScript(version, dummyEthTransfer, recipient.toAddress) val issue = - IssueTransaction.selfSigned(2.toByte, recipient, "Asset", "", ENOUGH_AMT, 8, reissuable = true, Some(script), 1.waves, ts).explicitGet() + TxHelpers.issue(recipient, ENOUGH_AMT, 8, "Asset", "", fee = 1.waves, Some(script), true, ts, TxVersion.V2) val asset = IssuedAsset(issue.id()) val ethTransfer = dummyEthTransfer.copy(dummyTransfer.copy(Some(ERC20Address(asset.id.take(20))))) val preTransfer = - TransferTransaction.selfSigned(2.toByte, recipient, ethSender, asset, ENOUGH_AMT, Waves, 0.005.waves, ByteStr.empty, ts).explicitGet() + TxHelpers.transfer( + from = recipient, + to = ethSender, + amount = ENOUGH_AMT, + asset = asset, + fee = 0.005.waves, + feeAsset = Waves, + attachment = ByteStr.empty, + timestamp = ts, + version = 2.toByte + ) withDomain(settingsForRide(version.max(V6)), Seq(AddrWithBalance(ethSender), AddrWithBalance(recipient.toAddress))) { d => d.appendBlock(issue, preTransfer) diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ContextFunctionsTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ContextFunctionsTest.scala index 2b43b6ff11f..73356f8f3c4 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ContextFunctionsTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ContextFunctionsTest.scala @@ -28,7 +28,6 @@ import com.wavesplatform.state.diffs.smart.smartEnabledFS import com.wavesplatform.test.* import com.wavesplatform.transaction.TxHelpers.* import com.wavesplatform.transaction.serialization.impl.PBTransactionSerializer -import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.{TxHelpers, TxVersion} import com.wavesplatform.utils.* @@ -373,7 +372,7 @@ class ContextFunctionsTest extends PropSpec with WithDomain with EthHelpers { .explicitGet() ._1 - val setScriptTx = SetScriptTransaction.selfSigned(1.toByte, masterAcc, Some(script), 1000000L, transferTx.timestamp + 5).explicitGet() + val setScriptTx = setScript(acc = masterAcc, script = script, fee = 1000000L, timestamp = transferTx.timestamp + 5) append(Seq(setScriptTx)).explicitGet() append(Seq(transfer2)).explicitGet() @@ -865,9 +864,7 @@ class ContextFunctionsTest extends PropSpec with WithDomain with EthHelpers { .explicitGet() ._1 - val setScriptTx = SetScriptTransaction - .selfSigned(1.toByte, masterAcc, Some(script), 1000000L, transferTx.timestamp + 5) - .explicitGet() + val setScriptTx = setScript(acc = masterAcc, script = script, fee = 1000000L, timestamp = transferTx.timestamp + 5) append(Seq(setScriptTx)).explicitGet() append(Seq(transfer2)).explicitGet() @@ -949,9 +946,7 @@ class ContextFunctionsTest extends PropSpec with WithDomain with EthHelpers { """.stripMargin ) - val setScriptTx = SetScriptTransaction - .selfSigned(1.toByte, masterAcc, Some(script), 1000000L, transferTx.timestamp + 5) - .explicitGet() + val setScriptTx = setScript(acc = masterAcc, script = script, fee = 1000000L, timestamp = transferTx.timestamp + 5) append(Seq(setScriptTx)).explicitGet() append(Seq(transfer2)).explicitGet() diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/GenericRideActivationTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/GenericRideActivationTest.scala index e60b15ad69a..b57ab68f513 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/GenericRideActivationTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/GenericRideActivationTest.scala @@ -8,10 +8,7 @@ import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.diffs.ci.ciFee import com.wavesplatform.test.* -import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.GenesisTransaction -import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.transaction.utils.Signed +import com.wavesplatform.transaction.{GenesisTransaction, TxHelpers} import org.scalatest.EitherValues class GenericRideActivationTest extends PropSpec with WithDomain with EitherValues { @@ -37,9 +34,9 @@ class GenericRideActivationTest extends PropSpec with WithDomain with EitherValu fee <- ciFee(sc = 1) gTx1 = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet() gTx2 = GenesisTransaction.create(invoker.toAddress, ENOUGH_AMT, ts).explicitGet() - ssTx = SetScriptTransaction.selfSigned(1.toByte, master, Some(dApp(version)), 0.01.waves, ts).explicitGet() - ssTx2 = SetScriptTransaction.selfSigned(1.toByte, invoker, Some(verifier(version)), 0.01.waves, ts).explicitGet() - invoke = Signed.invokeScript(1.toByte, invoker, master.toAddress, None, Nil, fee, Waves, ts) + ssTx = TxHelpers.setScript(master, dApp(version), 0.01.waves, 1.toByte) + ssTx2 = TxHelpers.setScript(invoker, verifier(version), 0.01.waves, 1.toByte) + invoke = TxHelpers.invoke(master.toAddress, invoker = invoker, fee = fee, version = 1.toByte, timestamp = ts) } yield (Seq(gTx1, gTx2), Seq(ssTx, ssTx2), invoke) property("RIDE versions activation") { diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/MatcherBlockchainTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/MatcherBlockchainTest.scala index 73923518e50..ac2a83c3eec 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/MatcherBlockchainTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/MatcherBlockchainTest.scala @@ -4,7 +4,6 @@ import com.wavesplatform.account.{Address, Alias} import com.wavesplatform.block.Block.BlockId import com.wavesplatform.block.SignedBlockHeader import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.crypto.bls.BlsPublicKey import com.wavesplatform.db.WithDomain import com.wavesplatform.lang.ValidationError @@ -19,7 +18,7 @@ import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.script.ScriptRunner import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.transaction.{Asset, ERC20Address, Transaction} +import com.wavesplatform.transaction.{Asset, ERC20Address, Transaction, TxHelpers} class MatcherBlockchainTest extends PropSpec, WithDomain { property("ScriptRunner.applyGeneric() avoids Blockchain calls") { @@ -68,7 +67,17 @@ class MatcherBlockchainTest extends PropSpec, WithDomain { override def conflictGenerators(at: GenerationPeriod): ConflictGenerators = ??? } - val tx = TransferTransaction.selfSigned(1.toByte, accountGen.sample.get, accountGen.sample.get.toAddress, Waves, 1, Waves, 1, ByteStr.empty, 0) + val tx = TxHelpers.transfer( + from = accountGen.sample.get, + to = accountGen.sample.get.toAddress, + amount = 1, + asset = Waves, + fee = 1, + feeAsset = Waves, + attachment = ByteStr.empty, + timestamp = 0, + version = 1.toByte + ) val scripts = Seq( TestCompiler(V5).compileExpression("true"), @@ -92,7 +101,7 @@ class MatcherBlockchainTest extends PropSpec, WithDomain { scripts.foreach { script => ScriptRunner .applyGeneric( - tx.explicitGet(), + tx, blockchain, script, isAssetScript = false, diff --git a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/TransactionBindingsTest.scala b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/TransactionBindingsTest.scala index 081299da284..c95ad87a6f3 100644 --- a/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/TransactionBindingsTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/state/diffs/smart/predef/TransactionBindingsTest.scala @@ -452,8 +452,8 @@ class TransactionBindingsTest extends PropSpec, EitherValues, WithDomain { val fee = ciFee(freeCall = true).sample.get val account = accountGen.sample.get val asset = IssuedAsset(ByteStr.fromBytes(1, 2, 3)) - val tx1 = InvokeExpressionTransaction.selfSigned(TxVersion.V1, account, expression, fee, Waves, Random.nextLong()).explicitGet() - val tx2 = InvokeExpressionTransaction.selfSigned(TxVersion.V1, account, expression, fee, asset, Random.nextLong()).explicitGet() + val tx1 = TxHelpers.invokeExpression(expression, account, fee, Waves) + val tx2 = TxHelpers.invokeExpression(expression, account, fee, asset) runScriptWithCustomContext[CONST_BOOLEAN](script(tx1), tx1, V6) shouldBe evaluated(true) runScriptWithCustomContext[CONST_BOOLEAN](script(tx2), tx2, V6) shouldBe evaluated(true) diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/CreateAliasTransactionSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/CreateAliasTransactionSpecification.scala index a584ee29ea2..d1ac3c37f48 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/CreateAliasTransactionSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/CreateAliasTransactionSpecification.scala @@ -60,8 +60,8 @@ class CreateAliasTransactionSpecification extends PropSpec with WithDomain { property("The same aliases from different senders have the same id") { forAll(accountGen, accountGen, aliasGen, timestampGen) { case (a1: KeyPair, a2: KeyPair, a: Alias, t: Long) => - val tx1 = CreateAliasTransaction.selfSigned(1.toByte, a1, a.name, MinIssueFee, t).explicitGet() - val tx2 = CreateAliasTransaction.selfSigned(1.toByte, a2, a.name, MinIssueFee, t).explicitGet() + val tx1 = TxHelpers.createAlias(a.name, a1, MinIssueFee, timestamp = t) + val tx2 = TxHelpers.createAlias(a.name, a2, MinIssueFee, timestamp = t) tx1.id() shouldBe tx2.id() } } diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/DataTransactionSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/DataTransactionSpecification.scala index 0ae08468ecd..08b9369a382 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/DataTransactionSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/DataTransactionSpecification.scala @@ -2,7 +2,7 @@ package com.wavesplatform.transaction import com.google.common.primitives.Shorts import com.wavesplatform.account.PublicKey -import com.wavesplatform.api.http.requests.SignedDataRequest +import com.wavesplatform.api.http.requests.DataRequest import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, Base64} import com.wavesplatform.common.utils.EitherExt2.* @@ -107,7 +107,7 @@ class DataTransactionSpecification extends PropSpec { val json = tx.json() json.toString shouldEqual tx.toString - val req = json.as[SignedDataRequest] + val req = json.as[DataRequest] req.senderPublicKey shouldEqual Base58.encode(tx.sender.arr) req.fee shouldEqual tx.fee.value req.timestamp shouldEqual tx.timestamp diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/InvokeScriptTransactionSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/InvokeScriptTransactionSpecification.scala index 932ee54d8ff..ddbd6989a3c 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/InvokeScriptTransactionSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/InvokeScriptTransactionSpecification.scala @@ -2,7 +2,7 @@ package com.wavesplatform.transaction import com.google.protobuf.ByteString import com.wavesplatform.account.* -import com.wavesplatform.api.http.requests.{InvokeScriptRequest, SignedInvokeScriptRequest} +import com.wavesplatform.api.http.requests.InvokeScriptRequest import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.Base64 import com.wavesplatform.common.utils.EitherExt2.* @@ -21,7 +21,6 @@ import com.wavesplatform.transaction.TxHelpers.defaultAddress import com.wavesplatform.transaction.TxValidationError.NonPositiveAmount import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, Verifier} -import com.wavesplatform.transaction.utils.Signed import play.api.libs.json.{JsArray, JsObject, JsString, Json} class InvokeScriptTransactionSpecification extends PropSpec { @@ -146,9 +145,10 @@ class InvokeScriptTransactionSpecification extends PropSpec { } """) - val tx = Signed.invokeScript( + val sender = KeyPair("test3".getBytes("UTF-8")) + val tx = InvokeScriptTransaction( 1.toByte, - KeyPair("test3".getBytes("UTF-8")), + sender.publicKey, dApp, Some( Terms.FUNCTION_CALL( @@ -157,13 +157,15 @@ class InvokeScriptTransactionSpecification extends PropSpec { ) ), Seq(InvokeScriptTransaction.Payment(7, IssuedAsset(ByteStr.decodeBase58(publicKey).get))), - 100000, + TxPositiveAmount.unsafeFrom(100000), Waves, - 1526910778245L - ) + 1526910778245L, + Proofs.empty, + dApp.chainId + ).signWith(sender.privateKey) (tx.json() - "proofs") shouldEqual (js.asInstanceOf[JsObject] - "proofs") - TransactionFactory.fromSignedRequest(js) shouldBe Right(tx) + TransactionFactory.parseRequest(js.as[JsObject]) shouldBe Right(tx) } property("JSON format validation for InvokeScriptTransaction without FUNCTION_CALL") { @@ -184,28 +186,31 @@ class InvokeScriptTransactionSpecification extends PropSpec { "assetId" : "$publicKey" }] } - """) + """).as[JsObject] - val tx = Signed.invokeScript( + val sender2 = KeyPair("test3".getBytes("UTF-8")) + val tx = InvokeScriptTransaction( 1.toByte, - KeyPair("test3".getBytes("UTF-8")), + sender2.publicKey, dApp, None, Seq(InvokeScriptTransaction.Payment(7, IssuedAsset(ByteStr.decodeBase58(publicKey).get))), - 100000, + TxPositiveAmount.unsafeFrom(100000), Waves, - 1526910778245L - ) + 1526910778245L, + Proofs.empty, + dApp.chainId + ).signWith(sender2.privateKey) - (tx.json() - "proofs") shouldEqual (js.asInstanceOf[JsObject] - "proofs" + + (tx.json() - "proofs") shouldEqual (js - "proofs" + ("call" -> JsObject(Map("function" -> JsString("default"), "args" -> JsArray())))) - TransactionFactory.fromSignedRequest(js) shouldBe Right(tx) + TransactionFactory.parseRequest(js) shouldBe Right(tx) } property("Signed InvokeScriptTransactionRequest parser") { - val req = SignedInvokeScriptRequest( + val req = InvokeScriptRequest( None, - Some(1.toByte), + 1.toByte, senderPublicKey = publicKey, fee = 1, feeAssetId = None, @@ -314,9 +319,9 @@ class InvokeScriptTransactionSpecification extends PropSpec { } property("can't have zero amount") { - val req = SignedInvokeScriptRequest( + val req = InvokeScriptRequest( None, - Some(1.toByte), + 1.toByte, senderPublicKey = publicKey, fee = 1, feeAssetId = None, @@ -336,9 +341,9 @@ class InvokeScriptTransactionSpecification extends PropSpec { } property("can't have negative amount") { - val req = SignedInvokeScriptRequest( + val req = InvokeScriptRequest( None, - Some(1.toByte), + 1.toByte, senderPublicKey = publicKey, fee = 1, feeAssetId = None, diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/MassTransferTransactionSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/MassTransferTransactionSpecification.scala index 2111abed067..3043220f74b 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/MassTransferTransactionSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/MassTransferTransactionSpecification.scala @@ -11,7 +11,7 @@ import com.wavesplatform.transaction.TxValidationError.GenericError import com.wavesplatform.transaction.serialization.impl.{MassTransferTxSerializer, PBTransactionSerializer} import com.wavesplatform.transaction.transfer.* import com.wavesplatform.transaction.transfer.MassTransferTransaction.{MaxTransferCount, ParsedTransfer, Transfer} -import play.api.libs.json.Json +import play.api.libs.json.{JsObject, Json} import java.nio.charset.StandardCharsets import scala.util.{Random, Success} @@ -235,10 +235,10 @@ class MassTransferTransactionSpecification extends PropSpec { property("empty transfers validation") { val transaction = TransactionFactory - .fromSignedRequest( + .parseRequest( Json.parse( """{"senderPublicKey":"CkvZ3sY9o8zV1akquJk6Y5d9Ke4G68zGzfSTep1KZBhi","fee":51449505,"type":11,"transferCount":0,"version":1,"totalAmount":0,"attachment":"SQqypFfuVh4j4H6zaZaAXPT8fbuNQSo6cvv6jiQuYeFXDJjtjwvu7QE6bAzQJ7VSCpX8km6rTYbug7mi3i","sender":"3MrFBnLCGKibu1jrEcRiHqGBwYCeQgyUQHc","feeAssetId":null,"proofs":["uYVrE8fKzR2dcx1EXU2WLWPwgWfdgAizRuwDJd2eU19rgoSpPuUF9eQCQzmKxg1pA3Tcp31W9MnZiK3LEbQeBwe"],"assetId":"5TBkQTEnyN8qYvfnDMnVQss3DuRVLmXSnyFFLS5AnzvE","transfers":[],"id":"CwJMbjdXchdqupzCkoALGBzg5Zp72duzhGfURLR5iwK1","timestamp":215734165446088575}""" - ) + ).as[JsObject] ) .explicitGet() diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/ProtoVersionTransactionsSpec.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/ProtoVersionTransactionsSpec.scala index 28718901015..47a24d27078 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/ProtoVersionTransactionsSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/ProtoVersionTransactionsSpec.scala @@ -14,12 +14,12 @@ import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.assets.* import com.wavesplatform.transaction.assets.exchange.{ExchangeTransaction, Order} -import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} +import com.wavesplatform.transaction.lease.LeaseTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment -import com.wavesplatform.transaction.smart.SetScriptTransaction +import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} +import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTransfer import com.wavesplatform.transaction.transfer.{MassTransferTransaction, TransferTransaction} -import com.wavesplatform.transaction.utils.Signed import org.scalacheck.Gen class ProtoVersionTransactionsSpec extends FreeSpec { @@ -39,7 +39,7 @@ class ProtoVersionTransactionsSpec extends FreeSpec { "CreateAliasTransaction" in { val alias = aliasGen.sample.get - val aliasTx = CreateAliasTransaction.selfSigned(TxVersion.V3, Account, alias.name, MinFee, Now).explicitGet() + val aliasTx = TxHelpers.createAlias(name = alias.name, sender = Account, fee = MinFee, version = TxVersion.V3) val base64Tx = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(aliasTx))) decode(base64Tx) shouldBe aliasTx @@ -52,28 +52,13 @@ class ProtoVersionTransactionsSpec extends FreeSpec { val decimals = 2.toByte val reissuable = true - val issueTx = IssueTransaction - .selfSigned( - TxVersion.V3, - Account, - name, - description, - quantity, - decimals, - reissuable, - script = None, - MinIssueFee, - Now - ) - .explicitGet() + val issueTx = TxHelpers.issue(issuer = Account, amount = quantity, decimals = decimals, name = name, description = description, fee = MinIssueFee, script = None, reissuable = reissuable, version = TxVersion.V3) val base64IssueStr = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(issueTx))) - val reissueTx = ReissueTransaction - .selfSigned(TxVersion.V3, Account, issueTx.asset, quantity, reissuable, MinIssueFee, Now) - .explicitGet() + val reissueTx = TxHelpers.reissue(asset = issueTx.asset, sender = Account, amount = quantity, reissuable = reissuable, fee = MinIssueFee, version = TxVersion.V3) val base64reissueStr = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(reissueTx))) - val burnTx = BurnTransaction.selfSigned(TxVersion.V3, Account, issueTx.asset, quantity, MinIssueFee, Now).explicitGet() + val burnTx = TxHelpers.burn(asset = issueTx.asset, amount = quantity, sender = Account, fee = MinIssueFee, version = TxVersion.V3) val base64BurnStr = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(burnTx))) decode(base64IssueStr) shouldBe issueTx @@ -84,7 +69,7 @@ class ProtoVersionTransactionsSpec extends FreeSpec { "DataTransaction" in { val data = dataEntryGen(10).sample.get - val dataTx = DataTransaction.selfSigned(TxVersion.V2, Account, Seq(data), DataTxFee, Now).explicitGet() + val dataTx = TxHelpers.dataV2(account = Account, entries = Seq(data), fee = DataTxFee) val base64Str = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(dataTx))) decode(base64Str) shouldBe dataTx @@ -103,9 +88,7 @@ class ProtoVersionTransactionsSpec extends FreeSpec { .explicitGet() val exchangeTx = - ExchangeTransaction - .signed(TxVersion.V3, Account.privateKey, buyOrder, sellOrder, 100, 100, MinFee * 3, MinFee * 3, MinFee * 3, Now) - .explicitGet() + TxHelpers.exchange(buyOrder, sellOrder, Account, 100, 100, MinFee * 3, MinFee * 3, MinFee * 3, Now, TxVersion.V3) val base64Str = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(exchangeTx))) decode(base64Str) shouldBe exchangeTx @@ -115,16 +98,16 @@ class ProtoVersionTransactionsSpec extends FreeSpec { val dapp = accountOrAliasGen.sample.get val feeAssetId = bytes32gen.map(ByteStr(_)).sample.get - val invokeScriptTx = Signed.invokeScript( + val invokeScriptTx = InvokeScriptTransaction.create( TxVersion.V2, - Account, + Account.publicKey, dapp, Some(FUNCTION_CALL(User("hello"), List(CONST_LONG(42L)))), Seq(Payment(100, Asset.Waves)), InvokeScriptTxFee, IssuedAsset(feeAssetId), Now - ) + ).map(_.signWith(Account.privateKey)).explicitGet() val base64Str = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(invokeScriptTx))) decode(base64Str) shouldBe invokeScriptTx @@ -133,11 +116,9 @@ class ProtoVersionTransactionsSpec extends FreeSpec { "LeaseTransaction/LeaseCancelTransaction" in { val recipient = accountOrAliasGen.sample.get - val leaseTx = LeaseTransaction.selfSigned(TxVersion.V3, Account, recipient, 100, MinFee, Now).explicitGet() + val leaseTx = LeaseTransaction.create(TxVersion.V3, Account.publicKey, recipient, 100, MinFee, Now, Proofs.empty).map(_.signWith(Account.privateKey)).explicitGet() val leaseCancelTx = - LeaseCancelTransaction - .selfSigned(TxVersion.V3, Account, leaseTx.id(), MinFee, Now) - .explicitGet() + TxHelpers.leaseCancel(leaseId = leaseTx.id(), sender = Account, fee = MinFee, version = TxVersion.V3) val base64LeaseStr = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(leaseTx))) val base64CancelLeaseStr = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(leaseCancelTx))) @@ -152,7 +133,8 @@ class ProtoVersionTransactionsSpec extends FreeSpec { val transferTx = TransferTransaction - .selfSigned(TxVersion.V3, Account, recipient, asset, 100, Asset.Waves, MinFee, ByteStr(attachment), Now) + .create(TxVersion.V3, Account.publicKey, recipient, asset, 100, Asset.Waves, MinFee, ByteStr(attachment), Now, Proofs.empty) + .map(_.signWith(Account.privateKey)) .explicitGet() val base64Str = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(transferTx))) @@ -167,7 +149,8 @@ class ProtoVersionTransactionsSpec extends FreeSpec { val massTransferTx = MassTransferTransaction - .selfSigned(TxVersion.V2, Account, Asset.Waves, transfers, MassTransferTxFee, Now, ByteStr(attachment)) + .create(TxVersion.V2, Account.publicKey, Asset.Waves, transfers, MassTransferTxFee, Now, ByteStr(attachment), Proofs.empty) + .map(_.signWith(Account.privateKey)) .explicitGet() val base64Str = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(massTransferTx))) @@ -177,7 +160,7 @@ class ProtoVersionTransactionsSpec extends FreeSpec { "SetScriptTransaction" in { val script = scriptGen.sample.get - val setScriptTx = SetScriptTransaction.selfSigned(TxVersion.V2, Account, Some(script), SetScriptFee, Now).explicitGet() + val setScriptTx = SetScriptTransaction.create(TxVersion.V2, Account.publicKey, Some(script), SetScriptFee, Now, Proofs.empty).map(_.signWith(Account.privateKey)).explicitGet() val base64Str = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(setScriptTx))) decode(base64Str) shouldBe setScriptTx @@ -187,7 +170,7 @@ class ProtoVersionTransactionsSpec extends FreeSpec { val asset = IssuedAsset(bytes32gen.map(ByteStr(_)).sample.get) val script = scriptGen.sample.get - val setAssetScriptTx = SetAssetScriptTransaction.selfSigned(TxVersion.V2, Account, asset, Some(script), SetAssetScriptFee, Now).explicitGet() + val setAssetScriptTx = SetAssetScriptTransaction.create(TxVersion.V2, Account.publicKey, asset, Some(script), SetAssetScriptFee, Now, Proofs.empty).map(_.signWith(Account.privateKey)).explicitGet() val base64Str = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(setAssetScriptTx))) decode(base64Str) shouldBe setAssetScriptTx @@ -196,7 +179,7 @@ class ProtoVersionTransactionsSpec extends FreeSpec { "SponsorshipTransaction" in { val asset = IssuedAsset(bytes32gen.map(ByteStr(_)).sample.get) - val sponsorshipTx = SponsorFeeTransaction.selfSigned(TxVersion.V2, Account, asset, Some(100), MinFee, Now).explicitGet() + val sponsorshipTx = SponsorFeeTransaction.create(TxVersion.V2, Account.publicKey, asset, Some(100), MinFee, Now, Proofs.empty).map(_.signWith(Account.privateKey)).explicitGet() val base64Str = Base64.encode(PBUtils.encodeDeterministic(PBTransactions.protobuf(sponsorshipTx))) decode(base64Str) shouldBe sponsorshipTx diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV2Specification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV2Specification.scala index 78643e222fa..734359db111 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV2Specification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV2Specification.scala @@ -35,9 +35,9 @@ class ReissueTransactionV2Specification extends GenericTransactionSpecification[ reissuable <- Gen.oneOf(true, false) } yield { val issue = IssueTransaction - .selfSigned( + .create( TxVersion.V1, - sender, + sender.publicKey, new String(assetName), new String(description), quantity, @@ -47,9 +47,11 @@ class ReissueTransactionV2Specification extends GenericTransactionSpecification[ iFee, timestamp ) + .map(_.signWith(sender.privateKey)) .explicitGet() val reissue1 = ReissueTransaction - .selfSigned(2.toByte, sender, issue.asset, quantity, reissuable = reissuable, fee, timestamp) + .create(2.toByte, sender.publicKey, issue.asset, quantity, reissuable = reissuable, fee, timestamp, Proofs.empty) + .map(_.signWith(sender.privateKey)) .explicitGet() (Seq(issue), reissue1) } diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/SetAssetScriptTransactionSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/SetAssetScriptTransactionSpecification.scala index ebbe6a8c7e3..ad725b1c444 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/SetAssetScriptTransactionSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/SetAssetScriptTransactionSpecification.scala @@ -9,6 +9,7 @@ import com.wavesplatform.lang.directives.values.* import com.wavesplatform.lang.script.{ContractScript, Script} import com.wavesplatform.protobuf.dapp.DAppMeta import com.wavesplatform.transaction.Asset.IssuedAsset +import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.assets.SetAssetScriptTransaction import org.scalacheck.Gen import play.api.libs.json.* @@ -36,7 +37,7 @@ class SetAssetScriptTransactionSpecification extends GenericTransactionSpecifica asset <- bytes32gen fee <- smallFeeGen ts <- timestampGen - txEi = SetAssetScriptTransaction.selfSigned(TxVersion.V2, acc, IssuedAsset(ByteStr(asset)), None, fee, ts) + txEi = SetAssetScriptTransaction.create(TxVersion.V2, acc.publicKey, IssuedAsset(ByteStr(asset)), None, fee, ts, Proofs.empty) } yield txEi forAll(gen)(_ should produce("Cannot set empty script")) diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/SponsorFeeTransactionSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/SponsorFeeTransactionSpecification.scala index 8e7a5507411..64cc88e4e93 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/SponsorFeeTransactionSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/SponsorFeeTransactionSpecification.scala @@ -14,7 +14,8 @@ import com.wavesplatform.settings.{Constants, FunctionalitySettings, TestFunctio import com.wavesplatform.state.diffs.* import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.assets.{IssueTransaction, SponsorFeeTransaction} +import com.wavesplatform.transaction.assets.SponsorFeeTransaction +import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.serialization.impl.SponsorFeeTxSerializer import com.wavesplatform.transaction.transfer.TransferTransaction import org.scalacheck.Gen @@ -151,23 +152,10 @@ class SponsorFeeTransactionSpecification extends PropSpec with WithState { for { sender <- accountGen (_, assetName, description, quantity, decimals, reissuable, iFee, timestamp) <- issueParamGen - issue = IssueTransaction - .selfSigned( - TxVersion.V1, - sender, - new String(assetName), - new String(description), - quantity, - decimals, - reissuable = reissuable, - script = None, - iFee, - timestamp - ) - .explicitGet() + issue = TxHelpers.issue(issuer = sender, amount = quantity, decimals = decimals, name = new String(assetName), description = new String(description), fee = iFee, script = None, reissuable = reissuable, timestamp = timestamp, version = TxVersion.V1) minFee <- smallFeeGen assetId = issue.assetId - } yield SponsorFeeTransaction.selfSigned(1.toByte, sender, IssuedAsset(assetId), Some(minFee), fee, timestamp) should produce( + } yield SponsorFeeTransaction.create(1.toByte, sender.publicKey, IssuedAsset(assetId), Some(minFee), fee, timestamp, Proofs.empty).map(_.signWith(sender.privateKey)) should produce( "insufficient fee" ) } @@ -178,23 +166,10 @@ class SponsorFeeTransactionSpecification extends PropSpec with WithState { for { sender <- accountGen (_, assetName, description, quantity, decimals, reissuable, iFee, timestamp) <- issueParamGen - issue = IssueTransaction - .selfSigned( - TxVersion.V1, - sender, - new String(assetName), - new String(description), - quantity, - decimals, - reissuable = reissuable, - script = None, - iFee, - timestamp - ) - .explicitGet() + issue = TxHelpers.issue(issuer = sender, amount = quantity, decimals = decimals, name = new String(assetName), description = new String(description), fee = iFee, script = None, reissuable = reissuable, timestamp = timestamp, version = TxVersion.V1) minFee = None assetId = issue.assetId - } yield SponsorFeeTransaction.selfSigned(1.toByte, sender, IssuedAsset(assetId), minFee, fee, timestamp) should produce("insufficient fee") + } yield SponsorFeeTransaction.create(1.toByte, sender.publicKey, IssuedAsset(assetId), minFee, fee, timestamp, Proofs.empty).map(_.signWith(sender.privateKey)) should produce("insufficient fee") } } @@ -202,13 +177,12 @@ class SponsorFeeTransactionSpecification extends PropSpec with WithState { val setup = for { (acc, name, desc, quantity, decimals, reissuable, fee, ts) <- issueParamGen genesis = GenesisTransaction.create(acc.toAddress, ENOUGH_AMT, ts).explicitGet() - issue = IssueTransaction - .selfSigned(TxVersion.V1, acc, new String(name), new String(desc), quantity, decimals, reissuable, script = None, fee, ts) - .explicitGet() + issue = TxHelpers.issue(issuer = acc, amount = quantity, decimals = decimals, name = new String(name), description = new String(desc), fee = fee, script = None, reissuable = reissuable, timestamp = ts, version = TxVersion.V1) minFee <- Gen.choose(1L, issue.quantity.value) - sponsor = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee), One, ts).explicitGet() + sponsor = SponsorFeeTransaction.create(1.toByte, acc.publicKey, IssuedAsset(issue.id()), Some(minFee), One, ts, Proofs.empty).map(_.signWith(acc.privateKey)).explicitGet() transfer = TransferTransaction - .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee, ByteStr.empty, ts) + .create(1.toByte, acc.publicKey, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee, ByteStr.empty, ts, Proofs.empty) + .map(_.signWith(acc.privateKey)) .explicitGet() } yield (acc, genesis, issue, sponsor, transfer) @@ -229,16 +203,16 @@ class SponsorFeeTransactionSpecification extends PropSpec with WithState { val setup = for { (acc, name, desc, quantity, decimals, reissuable, fee, ts) <- issueParamGen genesis = GenesisTransaction.create(acc.toAddress, ENOUGH_AMT, ts).explicitGet() - issue = IssueTransaction - .selfSigned(TxVersion.V1, acc, new String(name), new String(desc), quantity, decimals, reissuable, script = None, fee, ts) - .explicitGet() + issue = TxHelpers.issue(issuer = acc, amount = quantity, decimals = decimals, name = new String(name), description = new String(desc), fee = fee, script = None, reissuable = reissuable, timestamp = ts, version = TxVersion.V1) minFee <- Gen.choose(1000000L, issue.quantity.value) - sponsor = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee), One, ts).explicitGet() + sponsor = SponsorFeeTransaction.create(1.toByte, acc.publicKey, IssuedAsset(issue.id()), Some(minFee), One, ts, Proofs.empty).map(_.signWith(acc.privateKey)).explicitGet() transfer1 = TransferTransaction - .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee + 7, ByteStr.empty, ts) + .create(1.toByte, acc.publicKey, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee + 7, ByteStr.empty, ts, Proofs.empty) + .map(_.signWith(acc.privateKey)) .explicitGet() transfer2 = TransferTransaction - .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee + 9, ByteStr.empty, ts) + .create(1.toByte, acc.publicKey, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee + 9, ByteStr.empty, ts, Proofs.empty) + .map(_.signWith(acc.privateKey)) .explicitGet() } yield (acc, genesis, issue, sponsor, transfer1, transfer2) @@ -259,18 +233,18 @@ class SponsorFeeTransactionSpecification extends PropSpec with WithState { val setup = for { (acc, name, desc, quantity, decimals, reissuable, fee, ts) <- issueParamGen genesis = GenesisTransaction.create(acc.toAddress, ENOUGH_AMT, ts).explicitGet() - issue = IssueTransaction - .selfSigned(TxVersion.V1, acc, new String(name), new String(desc), quantity, decimals, reissuable, script = None, fee, ts) - .explicitGet() + issue = TxHelpers.issue(issuer = acc, amount = quantity, decimals = decimals, name = new String(name), description = new String(desc), fee = fee, script = None, reissuable = reissuable, timestamp = ts, version = TxVersion.V1) minFee <- Gen.choose(1L, issue.quantity.value / 11) - sponsor1 = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee), One, ts).explicitGet() + sponsor1 = SponsorFeeTransaction.create(1.toByte, acc.publicKey, IssuedAsset(issue.id()), Some(minFee), One, ts, Proofs.empty).map(_.signWith(acc.privateKey)).explicitGet() transfer1 = TransferTransaction - .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, IssuedAsset(issue.id()), fee = minFee, ByteStr.empty, ts) + .create(1.toByte, acc.publicKey, acc.toAddress, Waves, 1L, IssuedAsset(issue.id()), fee = minFee, ByteStr.empty, ts, Proofs.empty) + .map(_.signWith(acc.privateKey)) .explicitGet() - sponsor2 = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee * 10), One, ts).explicitGet() + sponsor2 = SponsorFeeTransaction.create(1.toByte, acc.publicKey, IssuedAsset(issue.id()), Some(minFee * 10), One, ts, Proofs.empty).map(_.signWith(acc.privateKey)).explicitGet() transfer2 = TransferTransaction - .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, IssuedAsset(issue.id()), fee = minFee * 10, ByteStr.empty, ts) + .create(1.toByte, acc.publicKey, acc.toAddress, Waves, 1L, IssuedAsset(issue.id()), fee = minFee * 10, ByteStr.empty, ts, Proofs.empty) + .map(_.signWith(acc.privateKey)) .explicitGet() } yield (acc, genesis, issue, sponsor1, transfer1, sponsor2, transfer2) @@ -291,12 +265,10 @@ class SponsorFeeTransactionSpecification extends PropSpec with WithState { val setup = for { (acc, name, desc, quantity, decimals, reissuable, fee, ts) <- issueParamGen genesis = GenesisTransaction.create(acc.toAddress, ENOUGH_AMT, ts).explicitGet() - issue = IssueTransaction - .selfSigned(TxVersion.V1, acc, new String(name), new String(desc), quantity, decimals, reissuable, script = None, fee, ts) - .explicitGet() + issue = TxHelpers.issue(issuer = acc, amount = quantity, decimals = decimals, name = new String(name), description = new String(desc), fee = fee, script = None, reissuable = reissuable, timestamp = ts, version = TxVersion.V1) minSponsoredAssetFee <- Gen.choose(1L, issue.quantity.value / 11) minFee <- Gen.choose(One / 1000, One - 1) - sponsor = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minSponsoredAssetFee), minFee, ts).explicitGet() + sponsor = TxHelpers.sponsor(asset = IssuedAsset(issue.id()), minSponsoredAssetFee = Some(minSponsoredAssetFee), sender = acc, fee = minFee, version = 1.toByte) } yield (genesis, issue, sponsor, minFee) forAll(setup) { diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/TransactionFeeSpec.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/TransactionFeeSpec.scala index da2329ccea3..a38691d174c 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/TransactionFeeSpec.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/TransactionFeeSpec.scala @@ -1,6 +1,5 @@ package com.wavesplatform.transaction -import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.db.WithDomain import com.wavesplatform.db.WithState.AddrWithBalance @@ -11,9 +10,7 @@ import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.test.DomainPresets.* import com.wavesplatform.test.{FreeSpec, NumericExt} import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.assets.SponsorFeeTransaction import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} -import com.wavesplatform.transaction.transfer.TransferTransaction class TransactionFeeSpec extends FreeSpec with WithDomain { "invoke script" - { @@ -43,7 +40,7 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { } "with issued assets" in { - val dAppSigner = TxHelpers.defaultSigner + val dAppSigner = TxHelpers.defaultSigner val dAppAddress = dAppSigner.toAddress val balances = Seq(AddrWithBalance(dAppAddress, 10.waves)) @@ -51,25 +48,26 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { withDomain(settingsWithFeatures(BF.BlockV5, BF.Ride4DApps, BF.SynchronousCalls), balances) { d => d.appendBlock( SetScriptTransaction - .selfSigned( + .create( 2.toByte, - dAppSigner, - Some(TestCompiler(V5).compileContract( - """{-# STDLIB_VERSION 5 #-} - |{-# SCRIPT_TYPE ACCOUNT #-} - |{-# CONTENT_TYPE DAPP #-} - | - |@Callable(i) - |func default() = { - | [ - | Issue("name", "description", 1000, 4, true, unit, 0), - | Issue("name", "description", 1000, 4, true, unit, 1) - | ] - |} - |""".stripMargin)), + dAppSigner.publicKey, + Some(TestCompiler(V5).compileContract("""{-# STDLIB_VERSION 5 #-} + |{-# SCRIPT_TYPE ACCOUNT #-} + |{-# CONTENT_TYPE DAPP #-} + | + |@Callable(i) + |func default() = { + | [ + | Issue("name", "description", 1000, 4, true, unit, 0), + | Issue("name", "description", 1000, 4, true, unit, 1) + | ] + |} + |""".stripMargin)), 0.01.waves, - ntpTime.getTimestamp() + ntpTime.getTimestamp(), + Proofs.empty ) + .map(_.signWith(dAppSigner.privateKey)) .explicitGet() ) @@ -90,9 +88,9 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { withDomain(settingsWithFeatures(BF.BlockV5, BF.Ride4DApps, BF.SynchronousCalls), balances) { d => d.appendBlock( SetScriptTransaction - .selfSigned( + .create( 2.toByte, - sender, + sender.publicKey, Some(TestCompiler(V5).compileContract("""{-# STDLIB_VERSION 5 #-} |{-# SCRIPT_TYPE ACCOUNT #-} |{-# CONTENT_TYPE DAPP #-} @@ -103,13 +101,15 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { |} |""".stripMargin)), 0.01.waves, - ntpTime.getTimestamp() + ntpTime.getTimestamp(), + Proofs.empty ) + .map(_.signWith(sender.privateKey)) .explicitGet(), SetScriptTransaction - .selfSigned( + .create( 2.toByte, - dappAccount, + dappAccount.publicKey, Some(TestCompiler(V5).compileContract(s"""{-# STDLIB_VERSION 5 #-} |{-# CONTENT_TYPE DAPP #-} |{-# SCRIPT_TYPE ACCOUNT #-} @@ -117,8 +117,8 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { |@Callable(i) |func default() = { | strict test = ${(1 to 10) - .map(_ => "sigVerify(base58'', base58'', base58'')") - .mkString(" || ")} + .map(_ => "sigVerify(base58'', base58'', base58'')") + .mkString(" || ")} | ( | [ | ScriptTransfer(i.caller, 100, unit)], @@ -129,13 +129,15 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { |@Callable(i) |func test() = { | strict test = ${(1 to 10) - .map(_ => "sigVerify(base58'', base58'', base58'')") - .mkString(" || ")} + .map(_ => "sigVerify(base58'', base58'', base58'')") + .mkString(" || ")} | [ScriptTransfer(i.caller, 100, unit)] |}""".stripMargin)), 0.01.waves, - ntpTime.getTimestamp() + ntpTime.getTimestamp(), + Proofs.empty ) + .map(_.signWith(dappAccount.privateKey)) .explicitGet() ) @@ -167,9 +169,9 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { withDomain(settingsWithFeatures(BF.BlockV5, BF.Ride4DApps, BF.SynchronousCalls), balances) { d => d.appendBlock( SetScriptTransaction - .selfSigned( + .create( 2.toByte, - sender, + sender.publicKey, Some(TestCompiler(V5).compileContract("""{-# STDLIB_VERSION 5 #-} |{-# SCRIPT_TYPE ACCOUNT #-} |{-# CONTENT_TYPE DAPP #-} @@ -184,13 +186,15 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { |} |""".stripMargin)), 0.01.waves, - ntpTime.getTimestamp() + ntpTime.getTimestamp(), + Proofs.empty ) + .map(_.signWith(sender.privateKey)) .explicitGet(), SetScriptTransaction - .selfSigned( + .create( 2.toByte, - dappAccount, + dappAccount.publicKey, Some(TestCompiler(V5).compileContract(s"""{-# STDLIB_VERSION 5 #-} |{-# CONTENT_TYPE DAPP #-} |{-# SCRIPT_TYPE ACCOUNT #-} @@ -198,8 +202,8 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { |@Callable(i) |func default() = { | strict test = ${(1 to 10) - .map(_ => "sigVerify(base58'', base58'', base58'')") - .mkString(" || ")} + .map(_ => "sigVerify(base58'', base58'', base58'')") + .mkString(" || ")} | ( | [ | ScriptTransfer(i.caller, 100, unit)], @@ -208,8 +212,10 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { |} |""".stripMargin)), 0.01.waves, - ntpTime.getTimestamp() + ntpTime.getTimestamp(), + Proofs.empty ) + .map(_.signWith(dappAccount.privateKey)) .explicitGet() ) @@ -231,25 +237,20 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { val issue = TxHelpers.issue() d.appendBlock(issue) d.appendBlock( - SponsorFeeTransaction - .selfSigned(TxVersion.V1, TxHelpers.defaultSigner, issue.asset, Some(1L), 1.waves, ntpTime.getTimestamp()) - .explicitGet() + TxHelpers.sponsor(issue.asset, Some(1L), TxHelpers.defaultSigner, 1.waves) ) - val transfer = TransferTransaction - .selfSigned( - TxVersion.V2, - TxHelpers.defaultSigner, - TxHelpers.secondAddress, - Waves, - 1, - issue.asset, - 1L, - ByteStr.empty, - ntpTime.getTimestamp() - ) - .explicitGet() - d.commonApi.calculateFee(transfer) shouldBe ((issue.asset, 1L, 0.001.waves)) + val transfer = TxHelpers.transfer( + TxHelpers.defaultSigner, + TxHelpers.secondAddress, + 1, + Waves, + 1L, + issue.asset, + version = TxVersion.V2, + timestamp = ntpTime.getTimestamp() + ) + d.commonApi.calculateFee(transfer) shouldBe (issue.asset, 1L, 0.001.waves) } } @@ -291,41 +292,38 @@ class TransactionFeeSpec extends FreeSpec with WithDomain { withDomain(DomainPresets.RideV5, balances) { d => d.appendBlock( - SetScriptTransaction - .selfSigned( - 2.toByte, + TxHelpers + .setScript( defaultSigner, - Some(TestCompiler(V5).compileExpression("""{-# STDLIB_VERSION 5 #-} - |{-# CONTENT_TYPE EXPRESSION #-} - |{-# SCRIPT_TYPE ACCOUNT #-} - | - |sigVerify_16Kb(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey) - |""".stripMargin)), + TestCompiler(V5).compileExpression("""{-# STDLIB_VERSION 5 #-} + |{-# CONTENT_TYPE EXPRESSION #-} + |{-# SCRIPT_TYPE ACCOUNT #-} + | + |sigVerify_16Kb(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey) + |""".stripMargin), 0.01.waves, - ntpTime.getTimestamp() - ) - .explicitGet(), - SetScriptTransaction - .selfSigned( 2.toByte, - secondSigner, - Some(TestCompiler(V5).compileExpression("""{-# STDLIB_VERSION 5 #-} - |{-# CONTENT_TYPE EXPRESSION #-} - |{-# SCRIPT_TYPE ACCOUNT #-} - | - |match tx { - | case t: Order | SetScriptTransaction => false - | case _ => - | let s0 = if (sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey)) then 1 else 0 - | let s1 = if (sigVerify(tx.bodyBytes, tx.proofs[1], tx.senderPublicKey)) then 1 else 0 - | let s2 = if (sigVerify(tx.bodyBytes, tx.proofs[2], tx.senderPublicKey)) then 1 else 0 - | s0 + s1 + s2 > 1 - |} - |""".stripMargin)), - 0.01.waves, - ntpTime.getTimestamp() - ) - .explicitGet() + timestamp = ntpTime.getTimestamp() + ), + TxHelpers.setScript( + secondSigner, + TestCompiler(V5).compileExpression("""{-# STDLIB_VERSION 5 #-} + |{-# CONTENT_TYPE EXPRESSION #-} + |{-# SCRIPT_TYPE ACCOUNT #-} + | + |match tx { + | case t: Order | SetScriptTransaction => false + | case _ => + | let s0 = if (sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey)) then 1 else 0 + | let s1 = if (sigVerify(tx.bodyBytes, tx.proofs[1], tx.senderPublicKey)) then 1 else 0 + | let s2 = if (sigVerify(tx.bodyBytes, tx.proofs[2], tx.senderPublicKey)) then 1 else 0 + | s0 + s1 + s2 > 1 + |} + |""".stripMargin), + 0.01.waves, + 2.toByte, + timestamp = ntpTime.getTimestamp() + ) ) d.commonApi.calculateWavesFee(TxHelpers.transfer(defaultSigner, defaultRecipient.toAddress)) shouldBe 0.001.waves diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/TransferTransactionV1Specification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/TransferTransactionV1Specification.scala index 856b8fbf286..233bbf221e0 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/TransferTransactionV1Specification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/TransferTransactionV1Specification.scala @@ -6,6 +6,7 @@ import com.wavesplatform.common.utils.Base58 import com.wavesplatform.common.utils.EitherExt2.* import com.wavesplatform.test.* import com.wavesplatform.transaction.Asset.Waves +import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.serialization.impl.TransferTxSerializer import com.wavesplatform.transaction.transfer.* import play.api.libs.json.Json @@ -105,7 +106,7 @@ class TransferTransactionV1Specification extends PropSpec { property("negative") { for { (_, sender, recipient, amount, timestamp, _, feeAmount, attachment) <- transferParamGen - } yield TransferTransaction.selfSigned(1.toByte, sender, recipient, Waves, amount, Waves, feeAmount, attachment, timestamp) should produce( + } yield TransferTransaction.create(1.toByte, sender.publicKey, recipient, Waves, amount, Waves, feeAmount, attachment, timestamp, Proofs.empty).map(_.signWith(sender.privateKey)) should produce( "insufficient fee" ) } diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/UpdateAssetInfoTransactionSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/UpdateAssetInfoTransactionSpecification.scala index 37f4a1a9551..682e19c8258 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/UpdateAssetInfoTransactionSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/UpdateAssetInfoTransactionSpecification.scala @@ -6,7 +6,7 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto.DigestLength import com.wavesplatform.lang.ValidationError import com.wavesplatform.test.PropSpec -import com.wavesplatform.transaction.Asset.Waves +import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError.{InvalidName, TooBigArray} import com.wavesplatform.transaction.assets.IssueTransaction.{MaxAssetDescriptionLength, MaxAssetNameLength, MinAssetNameLength} import com.wavesplatform.transaction.assets.UpdateAssetInfoTransaction @@ -49,7 +49,7 @@ class UpdateAssetInfoTransactionSpecification extends PropSpec { UpdateAssetInfoTransaction.create( version = TxVersion.V1, sender = TxHelpers.signer(1).publicKey, - assetId = ByteStr.fill(DigestLength)(1), + assetId = IssuedAsset(ByteStr.fill(DigestLength)(1)), name = name, description = description, timestamp = System.currentTimeMillis(), diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/api/http/assets/SignedRequestsTest.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/api/http/assets/SignedRequestsTest.scala index dc2ef648569..96d0647b142 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/api/http/assets/SignedRequestsTest.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/api/http/assets/SignedRequestsTest.scala @@ -164,8 +164,6 @@ class SignedRequestsTest extends FunSuite { } test("SponsorFeeRequest json parsing works") { - import com.wavesplatform.api.http.requests.SponsorFeeRequest.* - val One = 100000000L val js1 = s"""{ "type": 14, @@ -223,7 +221,7 @@ class SignedRequestsTest extends FunSuite { "minSponsoredAssetFee": null }""" - val req = Json.parse(js1).validate[SignedSponsorFeeRequest].get.toTx.explicitGet() + val req = Json.parse(js1).validate[SponsorFeeRequest].get.toTx.explicitGet() req.proofs shouldBe Proofs( Seq(ByteStr.decodeBase58("3QrF81WkwGhbNvKcwpAVyBPL1MLuAG5qmR6fmtK9PTYQoFKGsFg1Rtd2kbMBuX2ZfiFX58nR1XwC19LUXZUmkXE7").get) ) @@ -231,7 +229,7 @@ class SignedRequestsTest extends FunSuite { req.minSponsoredAssetFee.map(_.value) shouldBe Some(100000) for (js <- Seq(js2, js3, js4)) { - val req = Json.parse(js).validate[SignedSponsorFeeRequest].get.toTx.explicitGet() + val req = Json.parse(js).validate[SponsorFeeRequest].get.toTx.explicitGet() Proofs(Seq(ByteStr.decodeBase58("3QrF81WkwGhbNvKcwpAVyBPL1MLuAG5qmR6fmtK9PTYQoFKGsFg1Rtd2kbMBuX2ZfiFX58nR1XwC19LUXZUmkXE7").get)) req.fee.value shouldBe 100000000L req.minSponsoredAssetFee.map(_.value) shouldBe None @@ -253,7 +251,7 @@ class SignedRequestsTest extends FunSuite { |] |} """.stripMargin - val req = Json.parse(json).validate[SignedSetAssetScriptRequest].get + val req = Json.parse(json).validate[SetAssetScriptRequest].get req.assetId.id.toString shouldBe "Ha35nwsnmYxHRF8UmKG3S523BycBLZFU4FZnjXryKd4L" req.proofs shouldBe Proofs( Seq(ByteStr.decodeBase58("3QrF81WkwGhbNvKcwpAVyBPL1MLuAG5qmR6fmtK9PTYQoFKGsFg1Rtd2kbMBuX2ZfiFX58nR1XwC19LUXZUmkXE7").get) diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/assets/exchange/ExchangeTransactionSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/assets/exchange/ExchangeTransactionSpecification.scala index 9412ee2e21b..920f0700ae1 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/assets/exchange/ExchangeTransactionSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/assets/exchange/ExchangeTransactionSpecification.scala @@ -235,7 +235,6 @@ class ExchangeTransactionSpecification extends PropSpec with NTPTime with JsonMa .explicitGet() def create( - matcher: KeyPair = sender1, buyOrder: Order = buy, sellOrder: Order = sell, amount: Long = buyAmount, @@ -246,10 +245,8 @@ class ExchangeTransactionSpecification extends PropSpec with NTPTime with JsonMa timestamp: Long = expirationTimestamp - Order.MaxLiveTime, version: Byte = exchangeV ): Either[ValidationError, ExchangeTransaction] = { - if (version == 1) { - ExchangeTransaction.signed( - 1.toByte, - matcher = matcher.privateKey, + ExchangeTransaction + .create( order1 = buyOrder, order2 = sellOrder, amount = amount, @@ -257,22 +254,9 @@ class ExchangeTransactionSpecification extends PropSpec with NTPTime with JsonMa buyMatcherFee = buyMatcherFee, sellMatcherFee = sellMatcherFee, fee = fee, - timestamp = timestamp + timestamp = timestamp, + version = version ) - } else { - ExchangeTransaction.signed( - version, - matcher = matcher.privateKey, - order1 = buyOrder, - order2 = sellOrder, - amount = amount, - price = price, - buyMatcherFee = buyMatcherFee, - sellMatcherFee = sellMatcherFee, - fee = fee, - timestamp = timestamp - ) - } } buy.version shouldBe buyV @@ -314,37 +298,21 @@ class ExchangeTransactionSpecification extends PropSpec with NTPTime with JsonMa } } - def createExTx(buy: Order, sell: Order, price: Long, matcher: KeyPair, version: TxVersion): Either[ValidationError, ExchangeTransaction] = { + def createExTx(buy: Order, sell: Order, price: Long, version: TxVersion): Either[ValidationError, ExchangeTransaction] = { val matcherFee = 300000L val amount = math.min(buy.amount.value, sell.amount.value) - if (version == 1) { - ExchangeTransaction.signed( - 1.toByte, - matcher = matcher.privateKey, - order1 = buy, - order2 = sell, - amount = amount, - price = price, - buyMatcherFee = (BigInt(matcherFee) * amount / buy.amount.value).toLong, - sellMatcherFee = (BigInt(matcherFee) * amount / sell.amount.value).toLong, - fee = matcherFee, - timestamp = ntpTime.correctedTime() - ) - } else { - ExchangeTransaction.signed( - 2.toByte, - matcher = matcher.privateKey, - order1 = buy, - order2 = sell, - amount = amount, - price = price, - buyMatcherFee = (BigInt(matcherFee) * amount / buy.amount.value).toLong, - sellMatcherFee = (BigInt(matcherFee) * amount / sell.amount.value).toLong, - fee = matcherFee, - timestamp = ntpTime.correctedTime() - ) - } + ExchangeTransaction.create( + order1 = buy, + order2 = sell, + amount = amount, + price = price, + buyMatcherFee = (BigInt(matcherFee) * amount / buy.amount.value).toLong, + sellMatcherFee = (BigInt(matcherFee) * amount / sell.amount.value).toLong, + fee = matcherFee, + timestamp = ntpTime.correctedTime(), + version = version + ) } property("Test transaction with small amount and expired order") { @@ -388,14 +356,14 @@ class ExchangeTransactionSpecification extends PropSpec with NTPTime with JsonMa ) .explicitGet() - createExTx(buy, sell, sellPrice, matcher, exchangeV) shouldBe an[Right[?, ?]] + createExTx(buy, sell, sellPrice, exchangeV) shouldBe an[Right[?, ?]] val sell1 = if (sellV == 3) { Order.sell(sellV, sender2, matcher.publicKey, pair, 1, buyPrice, time, time - 1, matcherFee, sellerMatcherFeeAssetId).explicitGet() } else Order.sell(sellV, sender2, matcher.publicKey, pair, 1, buyPrice, time, time - 1, matcherFee).explicitGet() - createExTx(buy, sell1, buyPrice, matcher, exchangeV) shouldBe Left(OrderValidationError(sell1, "expiration should be > currentTime")) + createExTx(buy, sell1, buyPrice, exchangeV) shouldBe Left(OrderValidationError(sell1, "expiration should be > currentTime")) } } diff --git a/node/tests/src/test/scala/com/wavesplatform/transaction/smart/VerifierSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/transaction/smart/VerifierSpecification.scala index a0a811e934b..a777bb97150 100644 --- a/node/tests/src/test/scala/com/wavesplatform/transaction/smart/VerifierSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/transaction/smart/VerifierSpecification.scala @@ -13,28 +13,25 @@ import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.test.* import com.wavesplatform.test.DomainPresets.* -import com.wavesplatform.transaction.Asset import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} +import com.wavesplatform.transaction.assets.SetAssetScriptTransaction import com.wavesplatform.transaction.assets.exchange.* -import com.wavesplatform.transaction.assets.{IssueTransaction, SetAssetScriptTransaction} import com.wavesplatform.transaction.smart.script.ScriptCompiler +import com.wavesplatform.transaction.{Asset, TxHelpers} class VerifierSpecification extends PropSpec with NTPTime with WithDomain { private def mkIssue(issuer: KeyPair, name: String, script: Option[Script] = None) = - IssueTransaction - .selfSigned( - 2.toByte, - issuer, - name, - "", - 100000_00, - 2, - reissuable = false, - script, - 1.waves, - ntpTime.getTimestamp() - ) - .explicitGet() + TxHelpers.issue( + issuer, + 100000_00, + 2, + name, + "", + 1.waves, + script, + reissuable = false, + ntpTime.getTimestamp() + ) private def mkOrder( sender: KeyPair, @@ -85,43 +82,35 @@ class VerifierSpecification extends PropSpec with NTPTime with WithDomain { ) { d => d.appendBlock(genesisTxs*) d.appendBlock( - SetScriptTransaction - .selfSigned( - 1.toByte, - sender, - Some( - ScriptCompiler - .compile( - """match tx { - | case _: Order => height >= 0 - | case _ => true - |}""".stripMargin, - ScriptEstimatorV2 - ) - .explicitGet() - ._1 - ), - 0.001.waves, - ntpTime.getTimestamp() - ) - .explicitGet() + TxHelpers.setScript( + sender, + ScriptCompiler + .compile( + """match tx { + | case _: Order => height >= 0 + | case _ => true + |}""".stripMargin, + ScriptEstimatorV2 + ) + .explicitGet() + ._1, + 0.001.waves, + timestamp = ntpTime.getTimestamp() + ) ) d.appendBlock( - ExchangeTransaction - .signed( - 2.toByte, - matcher.privateKey, - mkOrder(sender, OrderType.BUY, matcher.publicKey, assetPair), - mkOrder(sender, OrderType.SELL, matcher.publicKey, assetPair), - 100, - 5.waves, - 0.003.waves, - 0.003.waves, - 0.003.waves, - ntpTime.getTimestamp() - ) - .explicitGet() + TxHelpers.exchange( + mkOrder(sender, OrderType.BUY, matcher.publicKey, assetPair), + mkOrder(sender, OrderType.SELL, matcher.publicKey, assetPair), + matcher, + 100, + 5.waves, + 0.003.waves, + 0.003.waves, + 0.003.waves, + ntpTime.getTimestamp() + ) ) } } @@ -136,28 +125,25 @@ class VerifierSpecification extends PropSpec with NTPTime with WithDomain { } yield ( sender, genesisTxs ++ Seq(buyFeeAssetTx, sellFeeAssetTx), - ExchangeTransaction - .signed( - 2.toByte, - matcher.privateKey, - mkOrder(sender, OrderType.BUY, matcher.publicKey, assetPair, 100, buyFeeAssetId), - mkOrder(sender, OrderType.SELL, matcher.publicKey, assetPair, 100, sellFeeAssetId), - 100, - 5.waves, - 100, - 100, - 0.003.waves, - ntpTime.getTimestamp() - ) - .explicitGet(), + TxHelpers.exchange( + mkOrder(sender, OrderType.BUY, matcher.publicKey, assetPair, 100, buyFeeAssetId), + mkOrder(sender, OrderType.SELL, matcher.publicKey, assetPair, 100, sellFeeAssetId), + matcher, + 100, + 5.waves, + 100, + 100, + 0.003.waves, + timestamp = ntpTime.getTimestamp() + ), buyFeeAssetId, sellFeeAssetId ) property("matcher fee asset script is executed during exchange transaction validation") { forAll(sharedParamGen2) { case (sender, genesisTxs, exchangeTx, buyFeeAsset, sellFeeAsset) => - def setAssetScript(assetId: IssuedAsset, script: Option[Script]): SetAssetScriptTransaction = - SetAssetScriptTransaction.selfSigned(1.toByte, sender, assetId, script, 0.001.waves, ntpTime.getTimestamp()).explicitGet() + def setAssetScript(assetId: IssuedAsset, script: Script): SetAssetScriptTransaction = + TxHelpers.setAssetScript(sender, assetId, script, 0.001.waves, ntpTime.getTimestamp()) withDomain( domainSettingsWithPreactivatedFeatures( @@ -170,13 +156,13 @@ class VerifierSpecification extends PropSpec with NTPTime with WithDomain { d.appendBlock(genesisTxs*) d.blockchainUpdater.processBlock( - d.createBlock(Seq(setAssetScript(buyFeeAsset, Some(ExprScript(Terms.FALSE).explicitGet())), exchangeTx), version = Block.PlainBlockVersion) + d.createBlock(Seq(setAssetScript(buyFeeAsset, ExprScript(Terms.FALSE).explicitGet()), exchangeTx), version = Block.PlainBlockVersion) ) should produce("TransactionNotAllowedByScript") d.blockchainUpdater.processBlock( d.createBlock( Seq( - setAssetScript(sellFeeAsset, Some(ScriptCompiler.compile("(5 / 0) == 2", ScriptEstimatorV2).explicitGet()._1)), + setAssetScript(sellFeeAsset, ScriptCompiler.compile("(5 / 0) == 2", ScriptEstimatorV2).explicitGet()._1), exchangeTx ), version = Block.PlainBlockVersion diff --git a/node/tests/src/test/scala/com/wavesplatform/utx/UtxPoolSpecification.scala b/node/tests/src/test/scala/com/wavesplatform/utx/UtxPoolSpecification.scala index 63687cb74fb..8380f75fe93 100644 --- a/node/tests/src/test/scala/com/wavesplatform/utx/UtxPoolSpecification.scala +++ b/node/tests/src/test/scala/com/wavesplatform/utx/UtxPoolSpecification.scala @@ -35,7 +35,6 @@ import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.* import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTransfer -import com.wavesplatform.transaction.utils.Signed import com.wavesplatform.transaction.{Transaction, *} import com.wavesplatform.utils.{EmptyBlockchain, Time} import com.wavesplatform.utx.UtxPool.PackStrategy @@ -112,14 +111,12 @@ class UtxPoolSpecification extends FreeSpec, BlocksTransactionsHelpers, WithDoma amount <- chooseNum(1L, (maxAmount * 0.9).toLong) recipient <- accountGen fee <- chooseNum(extraFee, (maxAmount * 0.1).toLong) - } yield TransferTransaction - .selfSigned(1.toByte, sender, recipient.toAddress, Waves, amount, Waves, fee, ByteStr.empty, time.getTimestamp()) - .explicitGet()) + } yield TxHelpers.transfer(from = sender, to = recipient.toAddress, amount = amount, asset = Waves, fee = fee, feeAsset = Waves, attachment = ByteStr.empty, timestamp = time.getTimestamp(), version = 1.toByte)) .label("transferTransaction") private def invokeScript(sender: KeyPair, dApp: Address, time: Time) = Gen.choose(500000L, 600000L).map { fee => - Signed.invokeScript(TxVersion.V1, sender, dApp, None, Seq.empty, fee, Waves, time.getTimestamp()) + TxHelpers.invoke(dApp, None, Seq.empty, Seq.empty, sender, fee, Waves, TxVersion.V1, time.getTimestamp()) } private def dAppSetScript(sender: KeyPair, time: Time) = { @@ -132,7 +129,7 @@ class UtxPoolSpecification extends FreeSpec, BlocksTransactionsHelpers, WithDoma |func default() = { WriteSet([DataEntry("0", true)]) } |""".stripMargin val script = ScriptCompiler.compile(scriptText, ScriptEstimatorV1).explicitGet()._1 - SetScriptTransaction.selfSigned(TxVersion.V1, sender, Some(script), extraFee, time.getTimestamp()).explicitGet() + TxHelpers.setScript(acc = sender, script = script, fee = extraFee, version = TxVersion.V1, timestamp = time.getTimestamp()) } private def withState[A](test: (KeyPair, Long, BlockchainUpdaterImpl) => A): A = { @@ -341,29 +338,23 @@ class UtxPoolSpecification extends FreeSpec, BlocksTransactionsHelpers, WithDoma } private def transfer(sender: KeyPair, time: Time) = - TransferTransaction - .selfSigned(1.toByte, sender, TxHelpers.address(2), Waves, 1, Waves, extraFee, ByteStr.empty, time.getTimestamp()) - .explicitGet() + TxHelpers.transfer(from = sender, to = TxHelpers.address(2), amount = 1, asset = Waves, fee = extraFee, feeAsset = Waves, attachment = ByteStr.empty, timestamp = time.getTimestamp(), version = 1.toByte) private def transferWithRecipient(sender: KeyPair, recipient: PublicKey, time: Time) = - TransferTransaction - .selfSigned(1.toByte, sender, recipient.toAddress, Waves, 1, Waves, extraFee, ByteStr.empty, time.getTimestamp()) - .explicitGet() + TxHelpers.transfer(from = sender, to = recipient.toAddress, amount = 1, asset = Waves, fee = extraFee, feeAsset = Waves, attachment = ByteStr.empty, timestamp = time.getTimestamp(), version = 1.toByte) private def massTransferWithRecipients(sender: KeyPair, recipients: Seq[PublicKey], maxAmount: Long, time: Time) = { val amount = maxAmount / (recipients.size + 1) val transfers = recipients.map(r => ParsedTransfer(r.toAddress, TxNonNegativeAmount.unsafeFrom(amount))) val minFee = FeeValidation.FeeConstants(TransactionType.Transfer) + FeeValidation.FeeConstants(TransactionType.MassTransfer) * transfers.size - MassTransferTransaction - .selfSigned(1.toByte, sender, Waves, transfers, minFee, time.getTimestamp(), ByteStr.empty) - .explicitGet() + TxHelpers.massTransfer(sender, transfers.map(t => (t.address, t.amount.value)), Waves, minFee, time.getTimestamp(), 1.toByte) } private def transactionV1(sender: KeyPair, ts: Long, feeAmount: Long): TransferTransaction = - TransferTransaction.selfSigned(1.toByte, sender, TxHelpers.address(2), Waves, waves(1), Waves, feeAmount, ByteStr.empty, ts).explicitGet() + TxHelpers.transfer(from = sender, to = TxHelpers.address(2), amount = waves(1), asset = Waves, fee = feeAmount, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts, version = 1.toByte) private def transactionV2(sender: KeyPair, ts: Long, feeAmount: Long): TransferTransaction = - TransferTransaction.selfSigned(2.toByte, sender, TxHelpers.address(2), Waves, waves(1), Waves, feeAmount, ByteStr.empty, ts).explicitGet() + TxHelpers.transfer(from = sender, to = TxHelpers.address(2), amount = waves(1), asset = Waves, fee = feeAmount, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts, version = 2.toByte) private def utxTest(utxSettings: UtxSettings, txCount: Int = 10)(f: (Seq[TransferTransaction], UtxPool, TestTime) => Unit): Unit = { withState { case (sender, _, bcu) => @@ -384,7 +375,7 @@ class UtxPoolSpecification extends FreeSpec, BlocksTransactionsHelpers, WithDoma |true """.stripMargin ) - val setScript = SetScriptTransaction.selfSigned(1.toByte, master, Some(script), 100000L, ts + 1).explicitGet() + val setScript = TxHelpers.setScript(acc = master, script = script, fee = 100000L, version = 1.toByte, timestamp = ts + 1) Seq(TestBlock.create(ts + 1, lastBlockId, Seq(setScript)).block) } @@ -617,16 +608,11 @@ class UtxPoolSpecification extends FreeSpec, BlocksTransactionsHelpers, WithDoma txs = Seq( GenesisTransaction.create(richAccount.toAddress, ENOUGH_AMT, ntpNow).explicitGet(), GenesisTransaction.create(randomAccount.toAddress, ENOUGH_AMT, ntpNow).explicitGet(), - SetScriptTransaction - .signed( - 1.toByte, - richAccount.publicKey, - Some(Script.fromBase64String("AQkAAGcAAAACAHho/EXujJiPAJUhuPXZYac+rt2jYg==").explicitGet()), + TxHelpers.setScript( + richAccount, + Script.fromBase64String("AQkAAGcAAAACAHho/EXujJiPAJUhuPXZYac+rt2jYg==").explicitGet(), QuickTX.FeeAmount * 4, - ntpNow, - richAccount.privateKey ) - .explicitGet() ), signer = TestBlock.defaultSigner, version = 3, @@ -1099,12 +1085,8 @@ class UtxPoolSpecification extends FreeSpec, BlocksTransactionsHelpers, WithDoma ts = System.currentTimeMillis() fee <- smallFeeGen genesis = GenesisTransaction.create(richAcc.toAddress, ENOUGH_AMT, ts).explicitGet() - validTransfer = TransferTransaction - .selfSigned(TxVersion.V1, richAcc, secondAcc.toAddress, Waves, 1L, Waves, fee, ByteStr.empty, ts) - .explicitGet() - invalidTransfer = TransferTransaction - .selfSigned(TxVersion.V1, secondAcc, richAcc.toAddress, Waves, 2L, Waves, fee, ByteStr.empty, ts) - .explicitGet() + validTransfer = TxHelpers.transfer(from = richAcc, to = secondAcc.toAddress, amount = 1L, asset = Waves, fee = fee, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts, version = TxVersion.V1) + invalidTransfer = TxHelpers.transfer(from = secondAcc, to = richAcc.toAddress, amount = 2L, asset = Waves, fee = fee, feeAsset = Waves, attachment = ByteStr.empty, timestamp = ts, version = TxVersion.V1) } yield (genesis, validTransfer, invalidTransfer) forAll(preconditions) { case (genesis, validTransfer, invalidTransfer) => diff --git a/project/Dependencies.scala b/project/Dependencies.scala index 491a5da2936..ab25a695de2 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -155,7 +155,7 @@ object Dependencies { "com.esaulpaugh" % "headlong" % "13.3.1", "com.github.jbellis" % "jamm" % "0.4.0", // Weighing caches web3jModule("abi").excludeAll(ExclusionRule("org.bouncycastle", "bcprov-jdk15on")), - "com.wavesplatform" % "blst-java" % "0.3.15", + "com.wavesplatform" % "blst-java" % "0.3.16-SNAPSHOT", amazonCorretto("linux-x86_64") % Optional, amazonCorretto("linux-aarch_64") % Optional ) ++ console ++ logDeps ++ protobuf.value