diff --git a/.github/workflows/check-pr.yaml b/.github/workflows/check-pr.yaml new file mode 100644 index 00000000000..836261f3c20 --- /dev/null +++ b/.github/workflows/check-pr.yaml @@ -0,0 +1,21 @@ +name: Check PR +on: [push] +jobs: + check-pr: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Cache SBT + uses: actions/cache@v1 + with: + path: ~/.sbt + key: sbt-cache-${{ hashFiles('project/build.properties') }} + - name: Cache Coursier + uses: actions/cache@v1 + with: + path: ~/.cache/coursier + key: coursier-cache + - name: Check PR + run: | + sbt --mem 6144 --batch checkPR + find ~/.cache/coursier -type d -name '*SNAPSHOT' | xargs rm -vrf {} \; diff --git a/.gitignore b/.gitignore index ed80b92a736..2637a704c84 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .idea .ensime .ensime_cache/ +.bsp # scala build folders and files target diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index d392a10ea47..00000000000 --- a/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: scala -# Use container-based infrastructure -sudo: false -jdk: - - openjdk8 -scala: - - 2.13.3 -env: - global: - - secure: NYdeuFBQVVjN5gon2KQEDfNfyp9Bk6AZJ7V1tfLJW54y5Dd/4PHdWGWeOyhCMIqwX3UaUmWExY1KcKXpbDMLwTmahNLjiDc3e3rCqxghL5cDgqs6OHcwNGw+CwNiw3tufo5PZ9mhK/ZJh0qgOHWyETs/ifq4VyacvgYH9IZzK4YdKYdwf+T9c3Q7VO3KmzOXiHkvPvLfkc8I8cSZlT1kJFCGawRdE/0nygPd8HYfCxiEFuXOKpRz0hlm8njjZdlZpMcou8TLeH5fFSvHtELIHFvSTEj/QilSTmCXgFRVUd8sd53n3uTouwtVbdCHsXNm4Nphf0lUJnN7fTzbD2xpOZN9zS+SO/YTkIxZpSgQLwsJsWzIHI+6IOlcjeNwZHbYBfsAdv1c4GMkgFfxsWWtb4r7+ooXDTbyy1qeZgVU4caGBMwoNE+l0Y60JdGYT4hrTfJ5c+GpcPzIV3CYVOUkHmoCYXRCtxnfDFXCR0mDVfYAA14osLi3v+EKdTxHDfqP6fICIW9y7oZd//38iEQrDy+k9iCyNmvOsqvDxXZithmSP0WzeGCXQDI+s3FxB5ywt8yDvzFbF5JYY74o1tnNFG7TlSF5v8EHSHxzXBeBtnE9V1g2wxYnvW2HYk5kW6WZJgYE9LCc6ubpQ2W387PRfCJjoLNjHqNlNGkEYlkPuaw= - - secure: rvBDWIiECsp1rI5wUjtw0098Gb2qE4r1uj33w+OtEnszftoZ+XgvvyyyfeykkcAAWob56pOFLox6CO1t/t3YyIyi8sXCPrf1eLBaFt4p6K5czNkWyWY6rlgd/cEXrJeE63UZhx9trN+jiZVjZ7oPpVNSNVAqXhf7dCHWOsKKu7i2gclzGYG1JeBL4eES/WJNVlgcsOdXbWG/udz9A/3+26afgN8Y5N/UMc0PJEmWUKcX7xWfLIcg4UIIvyPp5P55CT698N1jz57GHESDyYrMxMpZOO+0Q26Rjm+7A0U2+mm9XFE7cXT1JNFrJbUs/mvOpjTe0pScT34hRpH1pJcU3vppG/ffJ3IXB9/L2UfWcSemx4pNpdHuvt8Q2otdIlHxZrZpvHAOi6m/HkNBQlNYdRu9hjMVEmJUxiPtLl7npeMfbranEZ+gUtZoFV64aNBV6SUAmsi2supmj9xKmt3R0XOoMCR5zRglm/2EQY2fGhhp+OPrIWgSbGSTXXcUc5hEVM7sdTHo3taIbZsWya6NfjVJ/cxpBjc9hGpuSITU+r0WfSgTLqvEI3cgXQki/ggqVnDM80ft32KIUKIUaoaZSI7r5REps4A1F7HAP9+6VEJRk1p70Ls2IonzDifLij2LQDds1q8LbA9qOQtdj9beAGPvgKPJnBbH4rjNG5k+Iyw= -script: - - unset _JAVA_OPTIONS - - unset SBT_OPTS - - travis_wait 30 sbt -Dsbt.supershell=false -Dquill.macro.log=false -J-Xms3G -J-Xmx3G -J-XX:+UseConcMarkSweepGC -J-XX:+CMSClassUnloadingEnabled "checkPR" -# These directories are cached to S3 at the end of the build -cache: - directories: - - $HOME/.cache/coursier/v1 - - $HOME/.sbt -before_cache: - # Cleanup the cached directories to avoid unnecessary cache updates - - find $HOME/.cache/coursier/v1 -type d -name "*SNAPSHOT" | xargs rm -rf {} \; - - find $HOME/.sbt -name "*.lock" -print -delete diff --git a/benchmark/build.sbt b/benchmark/build.sbt index 36bdf1370a8..821b3f4f8da 100644 --- a/benchmark/build.sbt +++ b/benchmark/build.sbt @@ -1,7 +1,9 @@ enablePlugins(JmhPlugin) +Jmh / version := "1.32" + libraryDependencies ++= Seq( - "org.scodec" %% "scodec-core" % "1.11.7" + "org.scodec" %% "scodec-core" % "1.11.8" ) ++ Dependencies.logDeps // https://github.com/ktoso/sbt-jmh#adding-to-your-project diff --git a/benchmark/src/test/scala/com/wavesplatform/common/AddressBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/common/AddressBenchmark.scala index 11b53107f62..57c02bedce0 100644 --- a/benchmark/src/test/scala/com/wavesplatform/common/AddressBenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/common/AddressBenchmark.scala @@ -4,6 +4,7 @@ import java.util.concurrent.TimeUnit import com.wavesplatform.account.{Address, PublicKey} import com.wavesplatform.common.AddressBenchmark.{CachedAddress, PublicKeySt, UncachedAddress} +import com.wavesplatform.crypto.Curve25519 import org.openjdk.jmh.annotations._ import org.openjdk.jmh.infra.Blackhole @@ -37,7 +38,7 @@ class AddressBenchmark { object AddressBenchmark { @State(Scope.Benchmark) class PublicKeySt { - val publicKey = new Array[Byte](scorex.crypto.signatures.Curve25519.KeyLength25519) + val publicKey = new Array[Byte](Curve25519.KeyLength) Random.nextBytes(publicKey) } diff --git a/benchmark/src/test/scala/com/wavesplatform/common/EcrecoverBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/common/EcrecoverBenchmark.scala index 2da3ec07154..ddfef5ab783 100644 --- a/benchmark/src/test/scala/com/wavesplatform/common/EcrecoverBenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/common/EcrecoverBenchmark.scala @@ -2,12 +2,12 @@ package com.wavesplatform.common import java.util.concurrent.TimeUnit +import com.google.common.io.BaseEncoding import com.wavesplatform.common.EcrecoverBenchmark.{EcrecoverSt1, EcrecoverSt2} +import com.wavesplatform.crypto.Keccak256 import com.wavesplatform.lang.Global import org.openjdk.jmh.annotations._ import org.openjdk.jmh.infra.Blackhole -import scorex.crypto.hash.Keccak256 -import scorex.util.encode.Base16 @OutputTimeUnit(TimeUnit.MICROSECONDS) @BenchmarkMode(Array(Mode.AverageTime)) @@ -29,9 +29,11 @@ class EcrecoverBenchmark { object EcrecoverBenchmark { @State(Scope.Benchmark) class EcrecoverSt1 { - val signature = Base16.decode( - "848ffb6a07e7ce335a2bfe373f1c17573eac320f658ea8cf07426544f2203e9d52dbba4584b0b6c0ed5333d84074002878082aa938fdf68c43367946b2f615d01b" - ).get + val signature = BaseEncoding + .base16() + .decode( + "848ffb6a07e7ce335a2bfe373f1c17573eac320f658ea8cf07426544f2203e9d52dbba4584b0b6c0ed5333d84074002878082aa938fdf68c43367946b2f615d01b" + ) val message = "i am the owner" val prefix = "\u0019Ethereum Signed Message:\n" + message.length val messageHash = Keccak256.hash((prefix + message).getBytes) @@ -39,9 +41,11 @@ object EcrecoverBenchmark { @State(Scope.Benchmark) class EcrecoverSt2 { - val signature = Base16.decode( - "3b163bbd90556272b57c35d1185b46824f8e16ca229bdb36f8dfd5eaaee9420723ef7bc3a6c0236568217aa990617cf292b1bef1e7d1d936fb2faef3d846c5751b" - ).get + val signature = BaseEncoding + .base16() + .decode( + "3b163bbd90556272b57c35d1185b46824f8e16ca229bdb36f8dfd5eaaee9420723ef7bc3a6c0236568217aa990617cf292b1bef1e7d1d936fb2faef3d846c5751b" + ) val message = "what's up jim" val prefix = "\u0019Ethereum Signed Message:\n" + message.length val messageHash = Keccak256.hash((prefix + message).getBytes) diff --git a/benchmark/src/test/scala/com/wavesplatform/common/MerkleBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/common/MerkleBenchmark.scala index 188e1caf54a..7429f57352b 100644 --- a/benchmark/src/test/scala/com/wavesplatform/common/MerkleBenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/common/MerkleBenchmark.scala @@ -3,12 +3,10 @@ package com.wavesplatform.common import java.util.concurrent.TimeUnit import com.google.common.primitives.Ints +import com.wavesplatform.common.merkle._ import com.wavesplatform.common.merkle.Merkle._ -import org.openjdk.jmh.annotations._ +import org.openjdk.jmh.annotations.{Level => _, _} import org.openjdk.jmh.infra.Blackhole -import scorex.crypto.authds.LeafData -import scorex.crypto.authds.merkle.MerkleTree -import scorex.crypto.hash.{Blake2b256, CryptographicHash32, Digest32} import scala.util.Random @@ -50,22 +48,16 @@ class MerkleBenchmark { } object MerkleBenchmark { - implicit val fastHash = new CryptographicHash32 { - override def hash(input: Message): Digest32 = Blake2b256.hash(input) - } - def testData(deep: Int): (MerkleTree[Digest32], List[LeafData]) = { + def testData(deep: Int): (Seq[Level], List[LeafData]) = { val n = BigInt(2).pow(deep - 1).toInt val size = n + 1 + Random.nextInt(n) val data: List[LeafData] = List .fill(size)(Random.nextInt(10000)) .map(Ints.toByteArray) - .map(LeafData @@ _) - - val tree = MerkleTree[Digest32](data)(fastHash) - (tree, data) + (mkLevels(data), data) } class MerkleDeep(size: Int) { diff --git a/benchmark/src/test/scala/com/wavesplatform/common/SigVerifyBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/common/SigVerifyBenchmark.scala index 582e6a3f7ac..e1e1f999bdc 100644 --- a/benchmark/src/test/scala/com/wavesplatform/common/SigVerifyBenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/common/SigVerifyBenchmark.scala @@ -3,10 +3,10 @@ package com.wavesplatform.common import java.util.concurrent.TimeUnit import com.wavesplatform.common.SigVerifyBenchmark._ +import com.wavesplatform.crypto.Curve25519 import com.wavesplatform.lang.v1.EnvironmentFunctionsBenchmark.{curve25519, randomBytes} import org.openjdk.jmh.annotations._ import org.openjdk.jmh.infra.Blackhole -import scorex.crypto.signatures.{Curve25519, Signature} @OutputTimeUnit(TimeUnit.MICROSECONDS) @BenchmarkMode(Array(Mode.AverageTime)) @@ -17,52 +17,52 @@ import scorex.crypto.signatures.{Curve25519, Signature} class SigVerifyBenchmark { @Benchmark def sigVerify_128b(st: CurveSt128b, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_1Kb(st: CurveSt1Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_5Kb(st: CurveSt5Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_6Kb(st: CurveSt6Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_7Kb(st: CurveSt7Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_8Kb(st: CurveSt8Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_16Kb(st: CurveSt16Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_32Kb(st: CurveSt32Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_64Kb(st: CurveSt64Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_128Kb(st: CurveSt128Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) @Benchmark def sigVerify_150Kb(st: CurveSt150Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) // For DataTransaction.MaxProtoBytes @Benchmark def sigVerify_162Kb(st: CurveSt162Kb, bh: Blackhole): Unit = - bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey)) + bh.consume(Curve25519.verify(st.signature, st.message, st.publicKey)) } @@ -105,7 +105,7 @@ object SigVerifyBenchmark { class CurveSt(size: Int) { val (privateKey, publicKey) = curve25519.generateKeypair - val message = randomBytes(size) - val signature = curve25519.sign(privateKey, message) + val message = randomBytes(size) + val signature = curve25519.sign(privateKey, message) } } diff --git a/benchmark/src/test/scala/com/wavesplatform/lang/v1/CalculateAssetIdBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/lang/v1/CalculateAssetIdBenchmark.scala index b7b5471eaca..7a4fedc738a 100644 --- a/benchmark/src/test/scala/com/wavesplatform/lang/v1/CalculateAssetIdBenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/lang/v1/CalculateAssetIdBenchmark.scala @@ -9,7 +9,7 @@ import com.wavesplatform.lang.v1.traits.domain.Recipient.{Address, Alias} import com.wavesplatform.lang.v1.traits.domain.{Issue, Lease} import org.openjdk.jmh.annotations._ import org.openjdk.jmh.infra.Blackhole -import scorex.crypto.hash.{Blake2b256, Keccak256, Sha256} +import com.wavesplatform.crypto.{Blake2b256, Keccak256, Sha256} @OutputTimeUnit(TimeUnit.MICROSECONDS) @BenchmarkMode(Array(Mode.AverageTime)) diff --git a/benchmark/src/test/scala/com/wavesplatform/lang/v1/EnvironmentFunctionsBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/lang/v1/EnvironmentFunctionsBenchmark.scala index a9661eec0fa..14545236229 100644 --- a/benchmark/src/test/scala/com/wavesplatform/lang/v1/EnvironmentFunctionsBenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/lang/v1/EnvironmentFunctionsBenchmark.scala @@ -2,11 +2,13 @@ package com.wavesplatform.lang.v1 import java.nio.charset.StandardCharsets import java.util.concurrent.{ThreadLocalRandom, TimeUnit} + import cats.Id -import cats.implicits._ +import cats.syntax.bifunctor._ import com.wavesplatform.account import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 +import com.wavesplatform.crypto.Curve25519 import com.wavesplatform.lang.directives.DirectiveSet import com.wavesplatform.lang.directives.values.{Account, DApp, V4} import com.wavesplatform.lang.script.Script @@ -19,13 +21,11 @@ import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.{Functions, WavesConte import com.wavesplatform.lang.v1.traits._ import com.wavesplatform.lang.v1.traits.domain.Recipient.Address import com.wavesplatform.lang.v1.traits.domain.{BlockInfo, Recipient, ScriptAssetInfo, Tx} -import com.wavesplatform.lang.{Common, Global} -import com.wavesplatform.lang.ValidationError +import com.wavesplatform.lang.{Common, Global, ValidationError} import com.wavesplatform.wallet.Wallet import monix.eval.Coeval import org.openjdk.jmh.annotations._ import org.openjdk.jmh.infra.Blackhole -import scorex.crypto.signatures.{Curve25519, PrivateKey, PublicKey, Signature} import scala.util.Random @@ -69,7 +69,7 @@ class EnvironmentFunctionsBenchmark { def secureHash_test(): Array[Byte] = hashTest(Global.secureHash) @Benchmark - def curve25519_generateKeypair_test(): (PrivateKey, PublicKey) = curve25519.generateKeypair + def curve25519_generateKeypair_test(): (Array[Byte], Array[Byte]) = curve25519.generateKeypair @Benchmark def curve25519_sign_full_test(): Array[Byte] = { @@ -82,7 +82,7 @@ class EnvironmentFunctionsBenchmark { val (privateKey, publicKey) = curve25519.generateKeypair val message = randomBytes(DataBytesLength) val signature = curve25519.sign(privateKey, message) - Curve25519.verify(Signature @@ signature, message, publicKey) + Curve25519.verify(signature, message, publicKey) } @Benchmark @@ -128,8 +128,15 @@ object EnvironmentFunctionsBenchmark { _.toString, address => Address(ByteStr(address.bytes)) ) - override def accountScript(addressOrAlias: Recipient): Option[Script] = ??? - override def callScript(dApp: Address, func: String, args: List[EVALUATED], payments: Seq[(Option[Array[Byte]], Long)], availableComplexity: Int, reentrant: Boolean): Coeval[(Either[ValidationError, EVALUATED], Int)] = ??? + override def accountScript(addressOrAlias: Recipient): Option[Script] = ??? + override def callScript( + dApp: Address, + func: String, + args: List[EVALUATED], + payments: Seq[(Option[Array[Byte]], Long)], + availableComplexity: Int, + reentrant: Boolean + ): Coeval[(Either[ValidationError, EVALUATED], Int)] = ??? } val environmentFunctions = new EnvironmentFunctions(defaultEnvironment) @@ -150,21 +157,23 @@ object EnvironmentFunctionsBenchmark { def hashTest[T](len: Int, f: Array[Byte] => T): T = f(randomBytes(len)) object curve25519 { - def generateKeypair: (PrivateKey, PublicKey) = Curve25519.createKeyPair(randomBytes(SeedBytesLength)) - def sign(privateKey: PrivateKey, message: Array[Byte]): Array[Byte] = Curve25519.sign(privateKey, message) + def generateKeypair = Curve25519.createKeyPair(randomBytes(SeedBytesLength)) + def sign(privateKey: Array[Byte], message: Array[Byte]): Array[Byte] = Curve25519.sign(privateKey, message) } } @State(Scope.Benchmark) class AddressFromString { val ctx: EvaluationContext[Environment, Id] = - WavesContext.build(Global, DirectiveSet(V4, Account, DApp).explicitGet()) + WavesContext + .build(Global, DirectiveSet(V4, Account, DApp).explicitGet()) .evaluationContext(defaultEnvironment) val expr: Array[EXPR] = (1 to 100).map { _ => val address = - Wallet.generateNewAccount(Random.nextBytes(8), 1) + Wallet + .generateNewAccount(Random.nextBytes(8), 1) .publicKey .toAddress(ChainId) .toString diff --git a/benchmark/src/test/scala/com/wavesplatform/lang/v1/EvaluatorV2Benchmark.scala b/benchmark/src/test/scala/com/wavesplatform/lang/v1/EvaluatorV2Benchmark.scala index fb66679f84a..8f2bb093717 100644 --- a/benchmark/src/test/scala/com/wavesplatform/lang/v1/EvaluatorV2Benchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/lang/v1/EvaluatorV2Benchmark.scala @@ -57,7 +57,7 @@ class Funcs { """.stripMargin val parsed = Parser.parseExpr(script).get.value - val expr = ExpressionCompiler(pureContext.compilerContext, parsed).explicitGet()._1 + val expr = ExpressionCompiler(pureContext.compilerContext, parsed).explicitGet()._1 } @State(Scope.Benchmark) diff --git a/benchmark/src/test/scala/com/wavesplatform/lang/v1/PureFunctionsRebenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/lang/v1/PureFunctionsRebenchmark.scala index 0d22479b4c8..c72393c24bc 100644 --- a/benchmark/src/test/scala/com/wavesplatform/lang/v1/PureFunctionsRebenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/lang/v1/PureFunctionsRebenchmark.scala @@ -233,10 +233,12 @@ class PureFunctionsRebenchmark { object PureFunctionsRebenchmark { val context: EvaluationContext[Environment, Id] = - Monoid.combine( - PureContext.build(V4, fixUnicodeFunctions = true).evaluationContext, - CryptoContext.build(Global, V4).evaluationContext - ).asInstanceOf[EvaluationContext[Environment, Id]] + Monoid + .combine( + PureContext.build(V4, fixUnicodeFunctions = true).evaluationContext, + CryptoContext.build(Global, V4).evaluationContext + ) + .asInstanceOf[EvaluationContext[Environment, Id]] val eval: EXPR => (Log[Id], Int, Either[ExecutionError, EVALUATED]) = EvaluatorV2.applyCompleted(context, _, V4) @@ -252,7 +254,7 @@ object PureFunctionsRebenchmark { @State(Scope.Benchmark) class SplitString { - val separator = "," + val separator = "," val separatedString = List.fill(1000)(Random.nextPrintableChar().toString * 31).mkString(separator) val expr: EXPR = FUNCTION_CALL( diff --git a/benchmark/src/test/scala/com/wavesplatform/lang/v1/ScriptEvaluatorBenchmark.scala b/benchmark/src/test/scala/com/wavesplatform/lang/v1/ScriptEvaluatorBenchmark.scala index e4d86d04da4..64508e5ddea 100644 --- a/benchmark/src/test/scala/com/wavesplatform/lang/v1/ScriptEvaluatorBenchmark.scala +++ b/benchmark/src/test/scala/com/wavesplatform/lang/v1/ScriptEvaluatorBenchmark.scala @@ -20,7 +20,7 @@ import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, PureContext} import com.wavesplatform.lang.v1.evaluator.{EvaluatorV1, FunctionIds} import org.openjdk.jmh.annotations._ import org.openjdk.jmh.infra.Blackhole -import scorex.crypto.signatures.Curve25519 +import com.wavesplatform.crypto.Curve25519 import scala.util.Random diff --git a/build.sbt b/build.sbt index 9177d6d631b..6d9460fa633 100644 --- a/build.sbt +++ b/build.sbt @@ -7,43 +7,28 @@ */ import sbt.Keys._ -import sbt.{File, IO, Project, _} +import sbt.{**, Compile, CrossVersion, File, IO, Project, compilerPlugin, inConfig, _} import sbtcrossproject.CrossPlugin.autoImport.{CrossType, crossProject} -val langPublishSettings = Seq( - coverageExcludedPackages := "", - publishMavenStyle := true, - publishTo := Some("Sonatype Nexus" at "https://oss.sonatype.org/service/local/staging/deploy/maven2"), - homepage := Some(url("https://docs.wavesplatform.com/en/technical-details/waves-contracts-language-description/maven-compiler-package.html")), - developers := List( - Developer("petermz", "Peter Zhelezniakov", "peterz@rambler.ru", url("https://wavesplatform.com")) - ) -) - lazy val lang = crossProject(JSPlatform, JVMPlatform) .withoutSuffixFor(JVMPlatform) .crossType(CrossType.Full) .settings( - coverageExcludedPackages := ".*", - test in assembly := {}, + assembly / test := {}, libraryDependencies ++= Dependencies.lang.value ++ Dependencies.test, inConfig(Compile)( Seq( - sourceGenerators += Tasks.docSource, - PB.targets += scalapb.gen(flatPackage = true) -> sourceManaged.value, - PB.protoSources := Seq(PB.externalIncludePath.value, baseDirectory.value.getParentFile / "shared" / "src" / "main" / "protobuf"), - includeFilter in PB.generate := { (f: File) => - (** / "DAppMeta.proto").matches(f.toPath) || - (** / "waves" / "*.proto").matches(f.toPath) - }, + PB.protoSources := Seq(baseDirectory.value.getParentFile / "shared" / "src" / "main" / "protobuf"), + PB.targets := Seq( + scalapb.gen(flatPackage = true) -> sourceManaged.value + ), PB.deleteTargetDirectory := false ) ) ) lazy val `lang-jvm` = lang.jvm - .settings(langPublishSettings) .settings( name := "RIDE Compiler", normalizedName := "lang", @@ -54,33 +39,65 @@ lazy val `lang-jvm` = lang.jvm lazy val `lang-js` = lang.js .enablePlugins(VersionObject) .settings( - libraryDependencies += Dependencies.circeJsInterop.value + Compile / sourceGenerators += Tasks.docSource ) lazy val `lang-testkit` = project .dependsOn(`lang-jvm`) .in(file("lang/testkit")) - .settings(langPublishSettings) .settings( libraryDependencies ++= Dependencies.test.map(_.withConfigurations(Some("compile"))) ) -lazy val `lang-tests` = project.in(file("lang/tests")).dependsOn(`lang-testkit`) +lazy val `lang-tests` = project + .in(file("lang/tests")) + .dependsOn(`lang-testkit`) + .settings( + Compile / sourceGenerators += Tasks.docSource + ) lazy val `lang-doc` = project .in(file("lang/doc")) .dependsOn(`lang-jvm`) .settings( + Compile / sourceGenerators += Tasks.docSource, libraryDependencies ++= Seq("com.github.spullara.mustache.java" % "compiler" % "0.9.5") ++ Dependencies.test ) lazy val node = project.dependsOn(`lang-jvm`, `lang-testkit` % "test") lazy val `grpc-server` = project.dependsOn(node % "compile;test->test;runtime->provided") -lazy val `node-it` = project.dependsOn(node, `grpc-server`) -lazy val `node-generator` = project.dependsOn(node, `node` % "compile") +lazy val `node-it` = project.dependsOn(node, `lang-testkit`, `repl-jvm`, `grpc-server`) +lazy val `node-generator` = project.dependsOn(node) lazy val benchmark = project.dependsOn(node % "compile;test->test") +lazy val repl = crossProject(JSPlatform, JVMPlatform) + .withoutSuffixFor(JVMPlatform) + .crossType(CrossType.Full) + .settings( + libraryDependencies ++= Dependencies.protobuf.value ++ Dependencies.langCompilerPlugins.value, + inConfig(Compile)( + Seq( + PB.targets += scalapb.gen(flatPackage = true) -> sourceManaged.value, + PB.protoSources += PB.externalIncludePath.value, + PB.generate / includeFilter := { (f: File) => + (** / "waves" / "*.proto").matches(f.toPath) + } + ) + ) + ) + +lazy val `repl-jvm` = repl.jvm + .dependsOn(`lang-jvm`) + .settings( + libraryDependencies ++= Dependencies.circe.value ++ Seq( + "org.scala-js" %% "scalajs-stubs" % "1.0.0" % Provided, + Dependencies.sttp3 + ) + ) + +lazy val `repl-js` = repl.js.dependsOn(`lang-js`) + lazy val `curve25519-test` = project.dependsOn(node) lazy val root = (project in file(".")) @@ -97,12 +114,11 @@ lazy val root = (project in file(".")) inScope(Global)( Seq( - scalaVersion := "2.13.3", + scalaVersion := "2.13.6", organization := "com.wavesplatform", organizationName := "Waves Platform", V.fallback := (1, 3, 5), organizationHomepage := Some(url("https://wavesplatform.com")), - scmInfo := Some(ScmInfo(url("https://github.com/wavesplatform/Waves"), "git@github.com:wavesplatform/Waves.git", None)), licenses := Seq(("MIT", url("https://github.com/wavesplatform/Waves/blob/master/LICENSE"))), scalacOptions ++= Seq( "-feature", @@ -121,8 +137,6 @@ inScope(Global)( scalafmtOnCompile := false, dependencyOverrides ++= Dependencies.enforcedVersions.value, cancelable := true, - logBuffered := false, - coverageExcludedPackages := ".*", parallelExecution := false, testListeners := Seq.empty, // Fix for doubled test reports /* http://www.scalatest.org/user_guide/using_the_runner @@ -137,8 +151,8 @@ inScope(Global)( testOptions += Tests.Setup(_ => sys.props("sbt-testing") = "true"), network := Network(sys.props.get("network")), resolvers += Resolver.sonatypeRepo("snapshots"), - sources in (Compile, doc) := Seq.empty, - publishArtifact in (Compile, packageDoc) := false + Compile / doc / sources := Seq.empty, + Compile / packageDoc / publishArtifact := false ) ) @@ -165,6 +179,7 @@ checkPRRaw := Def (`lang-js` / Compile / fastOptJS).value (`grpc-server` / Test / test).value (node / Test / test).value + (`repl-js` / Compile / fastOptJS).value } ) .value diff --git a/grpc-server/build.sbt b/grpc-server/build.sbt index 479f87b3dc3..ac2780adbf0 100644 --- a/grpc-server/build.sbt +++ b/grpc-server/build.sbt @@ -11,8 +11,8 @@ extensionClasses ++= Seq( inConfig(Compile)( Seq( - PB.protoSources in Compile := Seq(PB.externalIncludePath.value), - includeFilter in PB.generate := new SimpleFileFilter( + Compile / PB.protoSources := Seq(PB.externalIncludePath.value), + PB.generate / includeFilter := new SimpleFileFilter( (f: File) => ((** / "waves" / "node" / "grpc" / ** / "*.proto") || (** / "waves" / "events" / ** / "*.proto")) .accept(f.toPath, FileAttributes(f.toPath).getOrElse(FileAttributes.NonExistent)) diff --git a/grpc-server/src/main/scala/com/wavesplatform/api/grpc/AccountsApiGrpcImpl.scala b/grpc-server/src/main/scala/com/wavesplatform/api/grpc/AccountsApiGrpcImpl.scala index 1603bb0fa96..e6071a4e90d 100644 --- a/grpc-server/src/main/scala/com/wavesplatform/api/grpc/AccountsApiGrpcImpl.scala +++ b/grpc-server/src/main/scala/com/wavesplatform/api/grpc/AccountsApiGrpcImpl.scala @@ -1,9 +1,6 @@ package com.wavesplatform.api.grpc -import scala.concurrent.Future - import com.google.protobuf.ByteString -import com.google.protobuf.wrappers.{BytesValue, StringValue} import com.wavesplatform.account.{Address, Alias} import com.wavesplatform.api.common.{CommonAccountsApi, LeaseInfo} import com.wavesplatform.protobuf._ @@ -14,6 +11,8 @@ import io.grpc.stub.StreamObserver import monix.execution.Scheduler import monix.reactive.Observable +import scala.concurrent.Future + class AccountsApiGrpcImpl(commonApi: CommonAccountsApi)(implicit sc: Scheduler) extends AccountsApiGrpc.AccountsApi { private def loadWavesBalance(address: Address): BalanceResponse = { @@ -94,12 +93,12 @@ class AccountsApiGrpcImpl(commonApi: CommonAccountsApi)(implicit sc: Scheduler) responseObserver.completeWith(stream.map(de => DataEntryResponse(request.address, Some(PBTransactions.toPBDataEntry(de))))) } - override def resolveAlias(request: StringValue): Future[BytesValue] = + override def resolveAlias(request: String): Future[ByteString] = Future { val result = for { - alias <- Alias.create(request.value) + alias <- Alias.create(request) address <- commonApi.resolveAlias(alias) - } yield BytesValue(ByteString.copyFrom(address.bytes)) + } yield ByteString.copyFrom(address.bytes) result.explicitGetErr() } diff --git a/grpc-server/src/main/scala/com/wavesplatform/api/grpc/BlocksApiGrpcImpl.scala b/grpc-server/src/main/scala/com/wavesplatform/api/grpc/BlocksApiGrpcImpl.scala index 7148777b826..e530a8d7a54 100644 --- a/grpc-server/src/main/scala/com/wavesplatform/api/grpc/BlocksApiGrpcImpl.scala +++ b/grpc-server/src/main/scala/com/wavesplatform/api/grpc/BlocksApiGrpcImpl.scala @@ -1,7 +1,6 @@ package com.wavesplatform.api.grpc import com.google.protobuf.empty.Empty -import com.google.protobuf.wrappers.UInt32Value import com.wavesplatform.api.BlockMeta import com.wavesplatform.api.common.CommonBlocksApi import com.wavesplatform.api.grpc.BlockRangeRequest.Filter @@ -18,8 +17,8 @@ import scala.concurrent.Future class BlocksApiGrpcImpl(commonApi: CommonBlocksApi)(implicit sc: Scheduler) extends BlocksApiGrpc.BlocksApi { import BlocksApiGrpcImpl._ - override def getCurrentHeight(request: Empty): Future[UInt32Value] = { - Future.successful(UInt32Value(commonApi.currentHeight)) + override def getCurrentHeight(request: Empty): Future[Int] = { + Future.successful(commonApi.currentHeight) } override def getBlockRange(request: BlockRangeRequest, responseObserver: StreamObserver[BlockWithHeight]): Unit = responseObserver.interceptErrors { diff --git a/grpc-server/src/main/scala/com/wavesplatform/api/grpc/TransactionsApiGrpcImpl.scala b/grpc-server/src/main/scala/com/wavesplatform/api/grpc/TransactionsApiGrpcImpl.scala index ad7780b77e2..f40ad901f5a 100644 --- a/grpc-server/src/main/scala/com/wavesplatform/api/grpc/TransactionsApiGrpcImpl.scala +++ b/grpc-server/src/main/scala/com/wavesplatform/api/grpc/TransactionsApiGrpcImpl.scala @@ -55,8 +55,10 @@ class TransactionsApiGrpcImpl(commonApi: CommonTransactionsApi)(implicit sc: Sch val transactionIdSet = transactionIds.toSet responseObserver.completeWith( stream - .filter { case TransactionMeta(_, tx, _) => transactionIdSet.isEmpty || transactionIdSet(tx.id()) } - .map(TransactionsApiGrpcImpl.toTransactionResponse) + .collect { + case m if transactionIdSet.isEmpty || transactionIdSet(m.transaction.id()) => + TransactionsApiGrpcImpl.toTransactionResponse(m) + } ) } @@ -120,14 +122,13 @@ class TransactionsApiGrpcImpl(commonApi: CommonTransactionsApi)(implicit sc: Sch private object TransactionsApiGrpcImpl { def toTransactionResponse(meta: TransactionMeta): TransactionResponse = { - val TransactionMeta(height, tx, succeeded) = meta - val transactionId = tx.id().toByteString - val status = if (succeeded) ApplicationStatus.SUCCEEDED else ApplicationStatus.SCRIPT_EXECUTION_FAILED + val transactionId = meta.transaction.id().toByteString + val status = if (meta.succeeded) ApplicationStatus.SUCCEEDED else ApplicationStatus.SCRIPT_EXECUTION_FAILED val invokeScriptResult = meta match { case TransactionMeta.Invoke(_, _, _, r) => r.map(VISR.toPB) case _ => None } - TransactionResponse(transactionId, height, Some(tx.toPB), status, invokeScriptResult) + TransactionResponse(transactionId, meta.height, Some(meta.transaction.toPB), status, invokeScriptResult) } } diff --git a/grpc-server/src/main/scala/com/wavesplatform/events/repo/UpdatesRepoImpl.scala b/grpc-server/src/main/scala/com/wavesplatform/events/repo/UpdatesRepoImpl.scala index b3e8dc35a65..48a5b2868a3 100644 --- a/grpc-server/src/main/scala/com/wavesplatform/events/repo/UpdatesRepoImpl.scala +++ b/grpc-server/src/main/scala/com/wavesplatform/events/repo/UpdatesRepoImpl.scala @@ -2,10 +2,6 @@ package com.wavesplatform.events.repo import java.nio.{ByteBuffer, ByteOrder} -import scala.annotation.tailrec -import scala.jdk.CollectionConverters._ -import scala.util.{Failure, Success, Try} - import cats.kernel.Monoid import com.wavesplatform.Shutdownable import com.wavesplatform.api.common.CommonBlocksApi @@ -13,8 +9,8 @@ import com.wavesplatform.block.Block import com.wavesplatform.common.state.ByteStr import com.wavesplatform.database.openDB import com.wavesplatform.events._ -import com.wavesplatform.events.protobuf.{BlockchainUpdated => PBBlockchainUpdated} import com.wavesplatform.events.protobuf.serde._ +import com.wavesplatform.events.protobuf.{BlockchainUpdated => PBBlockchainUpdated} import com.wavesplatform.state.Blockchain import com.wavesplatform.utils.{OptimisticLockable, ScorexLogging} import monix.eval.Task @@ -22,6 +18,10 @@ import monix.execution.{Ack, Scheduler} import monix.reactive.Observable import monix.reactive.subjects.ConcurrentSubject +import scala.annotation.tailrec +import scala.jdk.CollectionConverters._ +import scala.util.{Failure, Success, Try} + class UpdatesRepoImpl(directory: String, blocks: CommonBlocksApi)(implicit val scheduler: Scheduler) extends UpdatesRepo.Read with UpdatesRepo.Write @@ -214,10 +214,10 @@ class UpdatesRepoImpl(directory: String, blocks: CommonBlocksApi)(implicit val s microBlocks: Seq[MicroBlockAppended], id: ByteStr, dropped: Seq[MicroBlockAppended] = Nil - ): (Seq[MicroBlockAppended], Seq[MicroBlockAppended]) = microBlocks match { - case Nil => (Nil, dropped) - case rest @ (_ :+ block) if block.id == id => (rest, dropped) - case rest :+ block => dropUntilId(rest, id, block +: dropped) + ): (Seq[MicroBlockAppended], Seq[MicroBlockAppended]) = (microBlocks: @unchecked) match { + case Nil => (Nil, dropped) + case rest @ _ :+ block if block.id == id => (rest, dropped) + case rest :+ block => dropUntilId(rest, id, block +: dropped) } val (keep, drop) = dropUntilId(ls.microBlocks, toId) if (keep.isEmpty) { diff --git a/grpc-server/src/main/scala/com/wavesplatform/events/settings/BlockchainUpdatesSettings.scala b/grpc-server/src/main/scala/com/wavesplatform/events/settings/BlockchainUpdatesSettings.scala index 6745ab8ffda..0aa02475422 100644 --- a/grpc-server/src/main/scala/com/wavesplatform/events/settings/BlockchainUpdatesSettings.scala +++ b/grpc-server/src/main/scala/com/wavesplatform/events/settings/BlockchainUpdatesSettings.scala @@ -1,14 +1,13 @@ package com.wavesplatform.events.settings import scala.concurrent.duration.FiniteDuration - import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader.arbitraryTypeValueReader -import net.ceedubs.ficus.readers.ValueReader +import net.ceedubs.ficus.readers.{Generated, ValueReader} import net.ceedubs.ficus.readers.namemappers.implicits.hyphenCase case class BlockchainUpdatesSettings(grpcPort: Int, minKeepAlive: FiniteDuration) object BlockchainUpdatesSettings { - implicit val valueReader: ValueReader[BlockchainUpdatesSettings] = arbitraryTypeValueReader + implicit val valueReader: Generated[ValueReader[BlockchainUpdatesSettings]] = arbitraryTypeValueReader } 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 8b422d3101f..dad3292b7f3 100644 --- a/grpc-server/src/test/scala/com/wavesplatform/events/BlockchainUpdatesSpec.scala +++ b/grpc-server/src/test/scala/com/wavesplatform/events/BlockchainUpdatesSpec.scala @@ -17,13 +17,13 @@ import com.wavesplatform.events.protobuf.serde._ import com.wavesplatform.events.repo.UpdatesRepoImpl import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms.FUNCTION_CALL import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.settings.{Constants, FunctionalitySettings, TestFunctionalitySettings, WavesSettings} import com.wavesplatform.state.diffs.BlockDiffer import com.wavesplatform.state.{AssetDescription, Blockchain, EmptyDataEntry, Height, LeaseBalance, StringDataEntry} +import com.wavesplatform.test.{FreeSpec, _} import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} @@ -35,14 +35,13 @@ import monix.execution.Scheduler.Implicits.global import org.scalactic.source.Position import org.scalamock.scalatest.PathMockFactory import org.scalatest.concurrent.ScalaFutures -import org.scalatest.{FreeSpec, Matchers} import scala.concurrent.duration._ import scala.concurrent.{Await, Promise} import scala.reflect.ClassTag import scala.util.Random -class BlockchainUpdatesSpec extends FreeSpec with Matchers with WithDomain with ScalaFutures with PathMockFactory { +class BlockchainUpdatesSpec extends FreeSpec with WithDomain with ScalaFutures with PathMockFactory { var currentSettings: WavesSettings = domainSettingsWithFS( TestFunctionalitySettings.withFeatures( BlockchainFeatures.BlockReward, diff --git a/lang/js/build.sbt b/lang/js/build.sbt index 278ec81cb82..adc4239a648 100644 --- a/lang/js/build.sbt +++ b/lang/js/build.sbt @@ -1,3 +1,5 @@ scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.CommonJSModule) } + +libraryDependencies ++= Dependencies.circe.value diff --git a/lang/js/src/main/scala/JsAPI.scala b/lang/js/src/main/scala/JsAPI.scala index f1a0758969e..244072365df 100644 --- a/lang/js/src/main/scala/JsAPI.scala +++ b/lang/js/src/main/scala/JsAPI.scala @@ -10,19 +10,15 @@ import com.wavesplatform.lang.v1.BaseGlobal.DAppInfo import com.wavesplatform.lang.v1.estimator.ScriptEstimator import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.WavesContext import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, PureContext} -import com.wavesplatform.lang.v1.repl.Repl -import com.wavesplatform.lang.v1.repl.node.http.NodeConnectionSettings import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.{CTX, ContractLimits} import com.wavesplatform.lang.{Global, Version} -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future import scala.scalajs.js import scala.scalajs.js.Dynamic.{literal => jObj} import scala.scalajs.js.JSConverters._ import scala.scalajs.js.annotation.JSExportTopLevel -import scala.scalajs.js.{Any, Dictionary, Promise, UndefOr} +import scala.scalajs.js.{Any, Dictionary} object JsAPI { @@ -165,7 +161,7 @@ object JsAPI { case (bytes, complexity, exprScript, compErrorList) => js.Dynamic.literal( "result" -> Global.toBuffer(bytes), - "complexity" -> complexity, + "complexity" -> complexity.toDouble, "exprAst" -> expressionScriptToJs(exprScript), "errorList" -> compErrorList.map(compilationErrToJs).toJSArray ) @@ -179,7 +175,7 @@ object JsAPI { js.Dynamic.literal( "result" -> Global.toBuffer(bytes), "ast" -> toJs(ast), - "complexity" -> complexity + "complexity" -> complexity.toDouble ) } case DAppType => @@ -189,8 +185,8 @@ object JsAPI { case (bytes, complexityWithMap, exprDApp, compErrorList) => js.Dynamic.literal( "result" -> Global.toBuffer(bytes), - "complexity" -> complexityWithMap._1, - "complexityByFunc" -> complexityWithMap._2.view.mapValues(c => c: Any).toMap.toJSDictionary, + "complexity" -> complexityWithMap._1.toDouble, + "complexityByFunc" -> complexityWithMap._2.view.mapValues(_.toDouble).toMap.toJSDictionary, "dAppAst" -> dAppToJs(exprDApp), "errorList" -> compErrorList.map(compilationErrToJs).toJSArray ) @@ -242,7 +238,7 @@ object JsAPI { val resultFields: Seq[(String, Any)] = Seq( "result" -> Global.toBuffer(bytes), "ast" -> toJs(expr), - "complexity" -> complexity + "complexity" -> complexity.toDouble ) val errorFieldOpt: Seq[(String, Any)] = Global @@ -262,7 +258,7 @@ object JsAPI { js.Dynamic.literal( "result" -> Global.toBuffer(bytes), "ast" -> toJs(expr), - "complexity" -> complexity + "complexity" -> complexity.toDouble ) } case DAppType => @@ -283,11 +279,11 @@ object JsAPI { val resultFields: Seq[(String, Any)] = Seq( "result" -> Global.toBuffer(bytes), "ast" -> toJs(dApp), - "complexity" -> maxComplexity, - "verifierComplexity" -> verifierComplexity, - "callableComplexities" -> callableComplexities.view.mapValues(c => c: Any).toMap.toJSDictionary, - "userFunctionComplexities" -> userFunctionComplexities.view.mapValues(c => c: Any).toMap.toJSDictionary, - "globalVariableComplexities" -> globalVariableComplexities.view.mapValues(c => c: Any).toMap.toJSDictionary + "complexity" -> maxComplexity.toDouble, + "verifierComplexity" -> verifierComplexity.toDouble, + "callableComplexities" -> callableComplexities.view.mapValues(_.toDouble).toMap.toJSDictionary, + "userFunctionComplexities" -> userFunctionComplexities.view.mapValues(_.toDouble).toMap.toJSDictionary, + "globalVariableComplexities" -> globalVariableComplexities.view.mapValues(_.toDouble).toMap.toJSDictionary ) val errorFieldOpt: Seq[(String, Any)] = { Global @@ -313,30 +309,4 @@ object JsAPI { @JSExportTopLevel("nodeVersion") def nodeVersion(): js.Dynamic = js.Dynamic.literal("version" -> Version.VersionString) - - @JSExportTopLevel("repl") - def repl( - settings: UndefOr[NodeConnectionSettings], - libraries: js.Array[String] = js.Array() - ): js.Dynamic = asJs(Repl(settings.toOption, libraries.toList)) - - private def asJs(repl: Repl): js.Dynamic = - jObj( - "evaluate" -> (repl.execute _ andThen mapResult), - "info" -> repl.info _, - "totalInfo" -> (() => repl.totalInfo), - "clear" -> repl.clear _, - "reconfigure" -> (repl.reconfigure _ andThen asJs) - ) - - private def mapResult(eval: Future[Either[String, String]]): Promise[js.Object with js.Dynamic] = - eval - .map( - _.fold( - e => jObj("error" -> e), - r => jObj("result" -> r) - ) - ) - .toJSPromise - } diff --git a/lang/js/src/main/scala/JsApiUtils.scala b/lang/js/src/main/scala/JsApiUtils.scala index 49ab57296f1..639ddfd7fa2 100644 --- a/lang/js/src/main/scala/JsApiUtils.scala +++ b/lang/js/src/main/scala/JsApiUtils.scala @@ -266,7 +266,7 @@ package object JsApiUtils { def toJs(ast: EXPR): js.Object = { def r(expr: EXPR): js.Object = { expr match { - case CONST_LONG(t) => jObj.applyDynamic("apply")("type" -> "LONG", "value" -> t) + case CONST_LONG(t) => jObj.applyDynamic("apply")("type" -> "LONG", "value" -> t.toDouble) case GETTER(ref, field) => jObj.applyDynamic("apply")("type" -> "GETTER", "ref" -> r(ref), "field" -> field) case CONST_BYTESTR(bs) => jObj.applyDynamic("apply")("type" -> "BYTESTR", "value" -> bs.arr.toJSArray) case CONST_STRING(s) => jObj.applyDynamic("apply")("type" -> "STRING", "value" -> s) diff --git a/lang/js/src/main/scala/com/wavesplatform/lang/Global.scala b/lang/js/src/main/scala/com/wavesplatform/lang/Global.scala index 311df3ea02b..0554ce7541e 100644 --- a/lang/js/src/main/scala/com/wavesplatform/lang/Global.scala +++ b/lang/js/src/main/scala/com/wavesplatform/lang/Global.scala @@ -1,16 +1,13 @@ package com.wavesplatform.lang -import cats.implicits._ +import java.math.{BigInteger, BigDecimal => BD} + +import cats.syntax.either._ import com.wavesplatform.lang.v1.BaseGlobal import com.wavesplatform.lang.v1.evaluator.ctx.impl.Rounding import com.wavesplatform.lang.v1.evaluator.ctx.impl.crypto.RSA.DigestAlgorithm -import com.wavesplatform.lang.v1.repl.node.http.response.model.NodeResponse -import java.math.{BigInteger, BigDecimal => BD} import scala.collection.mutable -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future -import scala.scalajs.js import scala.scalajs.js.JSConverters._ import scala.scalajs.js.typedarray.{ArrayBuffer, Int8Array} import scala.util.Try @@ -146,12 +143,6 @@ object Global extends BaseGlobal { ) } - override def requestNode(url: String): Future[NodeResponse] = - impl.Global - .httpGet(js.Dynamic.literal(url = url)) - .toFuture - .map(r => NodeResponse(r.status.asInstanceOf[Int], r.body.asInstanceOf[String])) - override def groth16Verify(verifyingKey: Array[Byte], proof: Array[Byte], inputs: Array[Byte]): Boolean = ??? diff --git a/lang/jvm/build.sbt b/lang/jvm/build.sbt deleted file mode 100644 index b065668534d..00000000000 --- a/lang/jvm/build.sbt +++ /dev/null @@ -1,13 +0,0 @@ -coverageExcludedPackages := "" -publishMavenStyle := true -publishTo := Some("Sonatype Nexus" at "https://oss.sonatype.org/service/local/staging/deploy/maven2") -name := "RIDE Compiler" -normalizedName := "lang" -description := "The RIDE smart contract language compiler" -homepage := Some(url("https://docs.wavesplatform.com/en/technical-details/waves-contracts-language-description/maven-compiler-package.html")) -developers := List(Developer("petermz", "Peter Zhelezniakov", "peterz@rambler.ru", url("https://wavesplatform.com"))) -libraryDependencies ++= - Seq( - "org.scala-js" %% "scalajs-stubs" % "1.0.0" % Provided, - "com.github.spullara.mustache.java" % "compiler" % "0.9.5" - ) diff --git a/lang/jvm/src/main/scala/com/wavesplatform/crypto/BCDigest.scala b/lang/jvm/src/main/scala/com/wavesplatform/crypto/BCDigest.scala new file mode 100644 index 00000000000..7c0e51cb80d --- /dev/null +++ b/lang/jvm/src/main/scala/com/wavesplatform/crypto/BCDigest.scala @@ -0,0 +1,17 @@ +package com.wavesplatform.crypto + +import org.bouncycastle.crypto.Digest + +private[crypto] abstract class BCDigest(initial: () => Digest, digestSize: Int) { + protected val digest: ThreadLocal[Digest] = new ThreadLocal[Digest] { + override def initialValue(): Digest = initial() + } + + def hash(message: Array[Byte]): Array[Byte] = { + val d = digest.get() + d.update(message, 0, message.length) + val result = new Array[Byte](digestSize) + d.doFinal(result, 0) + result + } +} diff --git a/lang/jvm/src/main/scala/com/wavesplatform/crypto/Blake2b256.scala b/lang/jvm/src/main/scala/com/wavesplatform/crypto/Blake2b256.scala new file mode 100644 index 00000000000..beaca42c9ab --- /dev/null +++ b/lang/jvm/src/main/scala/com/wavesplatform/crypto/Blake2b256.scala @@ -0,0 +1,5 @@ +package com.wavesplatform.crypto + +import org.bouncycastle.crypto.digests.Blake2bDigest + +object Blake2b256 extends BCDigest(() => new Blake2bDigest(256), 32) diff --git a/lang/jvm/src/main/scala/com/wavesplatform/crypto/Curve25519.scala b/lang/jvm/src/main/scala/com/wavesplatform/crypto/Curve25519.scala new file mode 100644 index 00000000000..3e19e95287c --- /dev/null +++ b/lang/jvm/src/main/scala/com/wavesplatform/crypto/Curve25519.scala @@ -0,0 +1,33 @@ +package com.wavesplatform.crypto + +import java.lang.reflect.Constructor + +import org.whispersystems.curve25519.OpportunisticCurve25519Provider + +object Curve25519 { + private lazy val provider: OpportunisticCurve25519Provider = { + val constructor = classOf[OpportunisticCurve25519Provider].getDeclaredConstructors.head + .asInstanceOf[Constructor[OpportunisticCurve25519Provider]] + constructor.setAccessible(true) + constructor.newInstance() + } + + val KeyLength: Int = 32 + + val SignatureLength: Int = 64 + + def privateKeyFromSeed(seed: Array[Byte]): Array[Byte] = provider.generatePrivateKey(Sha256.hash(seed)) + def publicKeyFromPrivateKey(privateKey: Array[Byte]): Array[Byte] = provider.generatePublicKey(privateKey) + + def createKeyPair(seed: Array[Byte]): (Array[Byte], Array[Byte]) = { + val sk = privateKeyFromSeed(seed) + val pk = publicKeyFromPrivateKey(sk) + (sk, pk) + } + + def sign(privateKey: Array[Byte], message: Array[Byte]): Array[Byte] = + provider.calculateSignature(provider.getRandom(SignatureLength), privateKey, message) + + def verify(signature: Array[Byte], message: Array[Byte], publicKey: Array[Byte]): Boolean = provider.verifySignature(publicKey, message, signature) + +} diff --git a/lang/jvm/src/main/scala/com/wavesplatform/crypto/Keccak256.scala b/lang/jvm/src/main/scala/com/wavesplatform/crypto/Keccak256.scala new file mode 100644 index 00000000000..44b3b705141 --- /dev/null +++ b/lang/jvm/src/main/scala/com/wavesplatform/crypto/Keccak256.scala @@ -0,0 +1,5 @@ +package com.wavesplatform.crypto + +import org.bouncycastle.crypto.digests.KeccakDigest + +object Keccak256 extends BCDigest(() => new KeccakDigest(256), 32) diff --git a/lang/jvm/src/main/scala/com/wavesplatform/crypto/Sha256.scala b/lang/jvm/src/main/scala/com/wavesplatform/crypto/Sha256.scala new file mode 100644 index 00000000000..e8232913b8d --- /dev/null +++ b/lang/jvm/src/main/scala/com/wavesplatform/crypto/Sha256.scala @@ -0,0 +1,15 @@ +package com.wavesplatform.crypto + +import java.security.MessageDigest + +object Sha256 { + private[this] val digest = new ThreadLocal[MessageDigest]() { + override def initialValue(): MessageDigest = MessageDigest.getInstance("SHA-256") + } + + def hash(message: Array[Byte]): Array[Byte] = { + val result = digest.get().digest(message) + digest.get().reset() + result + } +} diff --git a/lang/jvm/src/main/scala/com/wavesplatform/lang/Global.scala b/lang/jvm/src/main/scala/com/wavesplatform/lang/Global.scala index ca79f4410d3..baf3c1a8e8b 100644 --- a/lang/jvm/src/main/scala/com/wavesplatform/lang/Global.scala +++ b/lang/jvm/src/main/scala/com/wavesplatform/lang/Global.scala @@ -2,26 +2,23 @@ package com.wavesplatform.lang import java.math.{MathContext, BigDecimal => BD} import java.security.spec.InvalidKeySpecException -import cats.implicits._ +import cats.syntax.either._ import ch.obermuhlner.math.big.BigDecimalMath import com.google.common.base.Utf8 import com.google.common.io.BaseEncoding +import com.wavesplatform.common.merkle.Merkle import com.wavesplatform.common.utils.{Base58, Base64} +import com.wavesplatform.crypto.{Blake2b256, Curve25519, Keccak256, Sha256} import com.wavesplatform.lang.v1.BaseGlobal import com.wavesplatform.lang.v1.evaluator.ctx.impl.Rounding import com.wavesplatform.lang.v1.evaluator.ctx.impl.crypto.RSA import com.wavesplatform.lang.v1.evaluator.ctx.impl.crypto.RSA.DigestAlgorithm -import com.wavesplatform.lang.v1.repl.node.http.response.model.NodeResponse -import com.wavesplatform.utils.Merkle import com.wavesplatform.zwaves.bls12.{Groth16 => Bls12Groth16} import com.wavesplatform.zwaves.bn256.{Groth16 => Bn256Groth16} import org.web3j.crypto.Sign import org.web3j.crypto.Sign.SignatureData -import scorex.crypto.hash.{Blake2b256, Keccak256, Sha256} -import scorex.crypto.signatures.{Curve25519, PublicKey, Signature} import scala.annotation.tailrec -import scala.concurrent.Future import scala.util.Try object Global extends BaseGlobal { @@ -63,11 +60,11 @@ object Global extends BaseGlobal { if (th.getCause == null) th else findThrowableCause(th.getCause) - def curve25519verify(message: Array[Byte], sig: Array[Byte], pub: Array[Byte]): Boolean = Curve25519.verify(Signature(sig), message, PublicKey(pub)) + def curve25519verify(message: Array[Byte], sig: Array[Byte], pub: Array[Byte]): Boolean = + Curve25519.verify(sig, message, pub) override def rsaVerify(alg: DigestAlgorithm, message: Array[Byte], sig: Array[Byte], pub: Array[Byte]): Either[String, Boolean] = - Try(RSA.verify(alg, message, sig, pub)) - .toEither + Try(RSA.verify(alg, message, sig, pub)).toEither .leftMap { case err: InvalidKeySpecException => s"Invalid key base58'${Base58.encode(pub)}': ${findThrowableCause(err).getMessage}" case err => findThrowableCause(err).getMessage @@ -117,10 +114,6 @@ object Global extends BaseGlobal { BigInt(res.setScale(rp.toInt, round.mode).unscaledValue) } - private val client = new SttpClient() - override def requestNode(url: String): Future[NodeResponse] = - client.requestNode(url) - override def groth16Verify(verifyingKey: Array[Byte], proof: Array[Byte], inputs: Array[Byte]): Boolean = Bls12Groth16.verify(verifyingKey, proof, inputs) @@ -131,9 +124,9 @@ object Global extends BaseGlobal { // https://github.com/web3j/web3j/blob/master/crypto/src/test/java/org/web3j/crypto/ECRecoverTest.java#L43 val signatureData = { val vTemp = signature(64) - val v = if (vTemp < 27) (vTemp + 27).toByte else vTemp - val r = signature.slice(0, 32) - val s = signature.slice(32, 64) + val v = if (vTemp < 27) (vTemp + 27).toByte else vTemp + val r = signature.slice(0, 32) + val s = signature.slice(32, 64) new SignatureData(v, r, s) } val pk = Sign.signedMessageHashToKey(messageHash, signatureData) diff --git a/lang/jvm/src/main/scala/com/wavesplatform/lang/SttpClient.scala b/lang/jvm/src/main/scala/com/wavesplatform/lang/SttpClient.scala deleted file mode 100644 index 4adba74521a..00000000000 --- a/lang/jvm/src/main/scala/com/wavesplatform/lang/SttpClient.scala +++ /dev/null @@ -1,34 +0,0 @@ -package com.wavesplatform.lang - -import com.softwaremill.sttp.{HttpURLConnectionBackend, MonadError, Request, Response, SttpBackend, sttp, _} -import com.wavesplatform.lang.v1.repl.node.http.response.model.NodeResponse - -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.{ExecutionContext, Future} - -class SttpClient { - private implicit val sttpBackend: SttpBackend[Future, Nothing] = new SttpBackend[Future, Nothing] { - val internal = HttpURLConnectionBackend() - - override def send[T](request: Request[T, Nothing]): Future[Response[T]] = - Future(internal.send(request))(ExecutionContext.global) - - override def close(): Unit = - internal.close() - - override def responseMonad: MonadError[Future] = ??? - } - - private val schemaRegex = "^\\w+://.+".r - - def requestNode(url: String): Future[NodeResponse] = { - val urlPrefix = - if (schemaRegex.findFirstMatchIn(url).nonEmpty) "" - else "http://" - - sttp.get(uri"${urlPrefix + url}") - .header("user-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36") - .send() - .map(r => NodeResponse(r.code, r.body.fold(identity, identity))) - } -} diff --git a/lang/shared/src/main/scala/com/wavesplatform/common/merkle/Merkle.scala b/lang/shared/src/main/scala/com/wavesplatform/common/merkle/Merkle.scala index 195a33e2459..c278c68ba1e 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/common/merkle/Merkle.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/common/merkle/Merkle.scala @@ -1,21 +1,15 @@ package com.wavesplatform.common.merkle -import com.wavesplatform.lang.Global - import scala.annotation.tailrec object Merkle { - private type Message = Array[Byte] - private type Digest = Array[Byte] - private type Level = Seq[Digest] - private val empty: Digest = hash(Array[Byte](0)) private val emptyLevels: Seq[Level] = Seq(Seq(empty)) @inline private def isLeft(i: Int): Boolean = i % 2 == 0 /** Hash function */ - def hash(input: Message): Digest = Global.blake2b256(input) + def hash(input: Message): Digest = com.wavesplatform.lang.Global.blake2b256(input) /** Makes levels of merkle tree (from top to bottom) */ def mkLevels(data: Seq[Message]): Seq[Level] = { @@ -25,7 +19,7 @@ object Merkle { def loop(prevLevel: Seq[Digest], acc: Seq[Level]): Seq[Level] = { val level = prevLevel .grouped(2) - .map { + .collect { case Seq(l, r) => hash(l ++ r) case Seq(l) => hash(l ++ empty) } @@ -60,7 +54,7 @@ object Merkle { case ((left, idx), right) if isLeft(idx) => (hash(left ++ right), idx / 2) case ((right, idx), left) => (hash(left ++ right), idx / 2) } - if(rest != 0) { + if (rest != 0) { throw new Exception(s"Index $index out of range allowed by proof list length ${proofs.length}") } calculated @@ -76,4 +70,13 @@ object Merkle { def verify(digest: Digest, index: Int, proofs: Seq[Digest], root: Digest): Boolean = { (1 << proofs.length) > index && index >= 0 && (createRoot(digest, index, proofs) sameElements root) } + + def verify(rootBytes: Array[Byte], proofBytes: Array[Byte], valueBytes: Array[Byte]): Boolean = { + (for { + rootDigest <- parseRoot(rootBytes) + merkleProof <- ScryptoMerkleProof.parse(proofBytes, valueBytes) + } yield merkleProof.valid(rootDigest)).getOrElse(false) + } + + def parseRoot(bytes: Array[Byte]): Option[Digest] = if (bytes.length == 32) Some(bytes) else None } diff --git a/lang/shared/src/main/scala/com/wavesplatform/common/merkle/ScryptoMerkleProof.scala b/lang/shared/src/main/scala/com/wavesplatform/common/merkle/ScryptoMerkleProof.scala new file mode 100644 index 00000000000..a117813e3c2 --- /dev/null +++ b/lang/shared/src/main/scala/com/wavesplatform/common/merkle/ScryptoMerkleProof.scala @@ -0,0 +1,65 @@ +package com.wavesplatform.common.merkle + +import com.wavesplatform.common.merkle.ScryptoMerkleProof._ + +import scala.util.Try + +case class ScryptoMerkleProof(leafData: LeafData, levels: Seq[(Digest, Byte)]) { + def valid(expectedRootHash: Digest): Boolean = { + val leafHash = Merkle.hash(LeafPrefix +: leafData) + + levels + .foldLeft(leafHash) { + case (prevHash, (hash, side)) => + if (side == ScryptoMerkleProof.LeftSide) { + Merkle.hash(InternalNodePrefix +: (prevHash ++ hash)) + } else { + Merkle.hash(InternalNodePrefix +: (hash ++ prevHash)) + } + } + .sameElements(expectedRootHash) + } +} + +object ScryptoMerkleProof { + val LeftSide: Byte = 0.toByte + val RightSide: Byte = 1.toByte + + val LeafPrefix: Byte = 0: Byte + val InternalNodePrefix: Byte = 1: Byte + + def parse(proofBytes: Array[Byte], valueHash: Array[Byte]): Option[ScryptoMerkleProof] = + parseMerkleProofLevels(proofBytes).map { data => + ScryptoMerkleProof(valueHash, data) + }.toOption + + private def parseMerkleProofLevels(arr: Array[Byte]): Either[String, List[(Digest, Byte)]] = { + def parseHashAndSide(arr: Array[Byte]): Either[String, (Byte, Digest, Array[Byte])] = { + val side = + if (arr(0) == ScryptoMerkleProof.LeftSide) ScryptoMerkleProof.LeftSide + else ScryptoMerkleProof.RightSide + val hashLen = arr(1).toInt + lazy val hash = arr.slice(2, 2 + hashLen) + + Either + .cond( + hashLen >= 0, + (side, hash, arr.drop(2 + hashLen)), + s"Invalid proof hash length: $hashLen" + ) + } + + def parseLevels(arr: Array[Byte], acc: List[(Digest, Byte)]): Either[String, List[(Digest, Byte)]] = { + if (arr.nonEmpty) { + parseHashAndSide(arr) + .flatMap { + case (side, hash, rest) => + parseLevels(rest, (hash, side) :: acc) + } + } else Right(acc.reverse) + } + + Try(parseLevels(arr, Nil)) + .getOrElse(Left("Can't parse proof bytes")) + } +} diff --git a/lang/shared/src/main/scala/com/wavesplatform/common/merkle/package.scala b/lang/shared/src/main/scala/com/wavesplatform/common/merkle/package.scala new file mode 100644 index 00000000000..d82565ba77c --- /dev/null +++ b/lang/shared/src/main/scala/com/wavesplatform/common/merkle/package.scala @@ -0,0 +1,8 @@ +package com.wavesplatform.common + +package object merkle { + type LeafData = Array[Byte] + type Message = Array[Byte] + type Digest = Array[Byte] + type Level = Seq[Digest] +} diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/contract/ContractSerDe.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/contract/ContractSerDe.scala index 4153d24c33f..d24ed0a5619 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/contract/ContractSerDe.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/contract/ContractSerDe.scala @@ -4,7 +4,11 @@ import java.io.ByteArrayOutputStream import java.nio.ByteBuffer import java.nio.charset.StandardCharsets -import cats.implicits._ +import cats.syntax.either._ +import cats.syntax.traverse._ +import cats.instances.either._ +import cats.syntax.option._ +import cats.instances.list._ import com.wavesplatform.lang.contract.DApp._ import com.wavesplatform.lang.utils.Serialize._ import com.wavesplatform.lang.v1.Serde.desAux @@ -118,7 +122,7 @@ object ContractSerDe { val len = bb.getInt if (len <= (bb.limit() - bb.position()) && len >= 0) { (1 to len).toList - .traverse[Either[String, ?], A](_ => df(bb)) + .traverse[Either[String, *], A](_ => df(bb)) } else { Left(s"At position ${bb.position()} array of arguments too big.") } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/DataMetaMapper.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/DataMetaMapper.scala index 2b93eceeb9d..604fbd51525 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/DataMetaMapper.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/DataMetaMapper.scala @@ -1,6 +1,7 @@ package com.wavesplatform.lang.contract.meta -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.google.protobuf.ByteString import com.wavesplatform.lang.v1.compiler.Types.FINAL import com.wavesplatform.protobuf.dapp.DAppMeta @@ -35,7 +36,7 @@ class DataMetaMapper(mapper: TypeBitMapper, version: MetaVersion) { meta.funcs.toList.traverse(protoToFunc) private def protoToFunc(funcs: CallableFuncSignature): Either[String, List[FINAL]] = - funcs.types.toByteArray.toList + funcs.types.toByteArray().toList .traverse(b => mapper.fromIndex(b.toInt)) } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/MetaMapper.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/MetaMapper.scala index 122fbc05db6..20edd127c4f 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/MetaMapper.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/MetaMapper.scala @@ -1,7 +1,7 @@ package com.wavesplatform.lang.contract.meta -import cats.implicits._ import cats.data.OptionT +import cats.instances.either._ import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.v1.compiler.Types.FINAL import com.wavesplatform.protobuf.dapp.DAppMeta diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/TypeBitMapper.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/TypeBitMapper.scala index 729b15599dc..a5e2f2fbf84 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/TypeBitMapper.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/contract/meta/TypeBitMapper.scala @@ -1,6 +1,9 @@ package com.wavesplatform.lang.contract.meta -import cats.implicits._ +import cats.syntax.either._ +import cats.syntax.traverse._ +import cats.instances.list._ +import cats.instances.either._ import com.wavesplatform.lang.v1.compiler.Types.{FINAL, LIST, UNION} import scala.util.Try @@ -17,12 +20,11 @@ case class SingleTypeMapper(types: Seq[FINAL]) extends TypeBitMapper { override def toIndex(t: FINAL): Either[String, Int] = types.indexOf(t) match { case -1 => Left(s"Unexpected callable func arg type: $t") - case i => Right(1 << i) + case i => Right(1 << i) } override def fromIndex(i: Int): Either[String, FINAL] = - Try(types(i)) - .toEither + Try(types(i)).toEither .leftMap(_ => s"Unexpected callable type absence for index=$i") override def length: Int = @@ -44,17 +46,16 @@ case class UnionTypeMapper(bitMapper: TypeBitMapper) extends TypeBitMapper { Left(s"Unexpected negative index=$i") else if (i == 0) constructType(types) + else if (i % 2 == 1) + bitMapper.fromIndex(offset).flatMap(t => fromIndexRec(i >> 1, offset + 1, t :: types)) else - if (i % 2 == 1) - bitMapper.fromIndex(offset).flatMap(t => fromIndexRec(i >> 1, offset + 1, t :: types)) - else - fromIndexRec(i >> 1, offset + 1, types) + fromIndexRec(i >> 1, offset + 1, types) private def constructType(foundTypes: List[FINAL]): Either[String, FINAL] = foundTypes match { - case List(single) => Right(single) - case l@List(_, _*) => Right(UNION.create(l)) case Nil => Left("Unexpected callable func arg type absence") + case single :: Nil => Right(single) + case l => Right(UNION.create(l)) } override def length: Int = @@ -76,4 +77,4 @@ case class ListTypeMapper(bitMapper: TypeBitMapper) extends TypeBitMapper { override def length: Int = bitMapper.length + 1 -} \ No newline at end of file +} diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/directives/DirectiveParser.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/directives/DirectiveParser.scala index 7b182de5091..8f5bfff79b9 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/directives/DirectiveParser.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/directives/DirectiveParser.scala @@ -1,10 +1,10 @@ package com.wavesplatform.lang.directives +import cats.syntax.either._ import com.wavesplatform.lang.ExecutionError -import fastparse._ -import fastparse.Parsed.{Failure, Success} import fastparse.MultiLineWhitespace._ -import cats.implicits._ +import fastparse.Parsed.{Failure, Success} +import fastparse._ object DirectiveParser { @@ -16,19 +16,21 @@ object DirectiveParser { private def directiveKeyP[_: P]: P[String] = P(CharIn("a-zA-Z0-9_")) - .repX(1).! + .repX(1) + .! - private def directiveValueP[_:P]: P[String] = + private def directiveValueP[_: P]: P[String] = P(CharIn("a-zA-Z0-9/\\., ")) - .repX(1).! + .repX(1) + .! - private def parser[_:P]: P[Either[ExecutionError, Directive]] = + private def parser[_: P]: P[Either[ExecutionError, Directive]] = P(space ~ start ~ directiveKeyP ~ directiveValueP ~ end ~ space) .map { case (parsedKey, parsedValue) => { val valueRaw = parsedValue.replace(" ", "") for { - key <- DirectiveKey.textMap.get(parsedKey).toRight(s"Illegal directive key $parsedKey") + key <- DirectiveKey.textMap.get(parsedKey).toRight(s"Illegal directive key $parsedKey") value <- key match { case k: PredefinedDirectiveKey => k.valueDic.textMap.get(valueRaw).toRight(s"Illegal directive value $valueRaw for key $parsedKey") case k: ArbitraryDirectiveKey => Right(k.valueMapper(valueRaw)) @@ -38,7 +40,8 @@ object DirectiveParser { } def apply(input: String): Either[ExecutionError, List[Directive]] = - input.split("\n") + input + .split("\n") .filter(_.matches(s"\\s*\\$start.*$end\\s*")) .map(parse(_, parser(_))) .foldLeft(Map[DirectiveKey, Directive]().asRight[ExecutionError]) { diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/package.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/package.scala index ce2e1f6cfb8..247bab26749 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/package.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/package.scala @@ -8,5 +8,5 @@ package object lang { type ExecutionLog = String type EvalF[F[_], A] = Eval[F[A]] - type TrampolinedExecResult[F[_], T] = EitherT[EvalF[F, ?], ExecutionError, T] + type TrampolinedExecResult[F[_], T] = EitherT[EvalF[F, *], ExecutionError, T] } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/script/ContractScript.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/script/ContractScript.scala index 115497f4ab9..5cce610912d 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/script/ContractScript.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/script/ContractScript.scala @@ -1,6 +1,12 @@ package com.wavesplatform.lang.script -import cats.implicits._ +import cats.instances.either._ +import cats.instances.list._ +import cats.instances.option._ +import cats.syntax.either._ +import cats.syntax.flatMap._ +import cats.syntax.foldable._ +import cats.syntax.traverse._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.contract.DApp.VerifierFunction diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/script/Script.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/script/Script.scala index 17527c940c6..156ccb10c77 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/script/Script.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/script/Script.scala @@ -53,7 +53,7 @@ object Script { case _ => DAppType } val ctx = getDecompilerContext(s.stdLibVersion, cType) - val (scriptText, directives) = s match { + val (scriptText, directives) = (s: @unchecked) match { case e: ExprScript => (Decompiler(e.expr, ctx), List(s.stdLibVersion, Expression)) case ContractScriptImpl(_, contract) => (Decompiler(contract, ctx), List(s.stdLibVersion, Account, DAppType)) } @@ -70,7 +70,7 @@ object Script { estimator: ScriptEstimator, useContractVerifierLimit: Boolean ): Either[String, ComplexityInfo] = - script match { + (script: @unchecked) match { case script: ExprScript => ExprScript .estimate(script.expr, script.stdLibVersion, estimator, useContractVerifierLimit) diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/script/ScriptPreprocessor.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/script/ScriptPreprocessor.scala index 13d8026863e..880c78b0f62 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/script/ScriptPreprocessor.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/script/ScriptPreprocessor.scala @@ -1,16 +1,22 @@ package com.wavesplatform.lang.script import cats.data.NonEmptyChain +import cats.instances.either._ +import cats.instances.list._ +import cats.instances.map._ import cats.kernel.CommutativeSemigroup -import cats.implicits._ -import com.wavesplatform.lang.directives.{Directive, DirectiveKey, DirectiveParser} +import cats.syntax.foldable._ +import cats.syntax.option._ +import cats.syntax.traverse._ +import cats.syntax.unorderedTraverse._ import com.wavesplatform.lang.directives.values.{Imports, Library} +import com.wavesplatform.lang.directives.{Directive, DirectiveKey, DirectiveParser} object ScriptPreprocessor { def apply( - scriptText: String, - libraries: Map[String, String], - imports: Imports + scriptText: String, + libraries: Map[String, String], + imports: Imports ): Either[String, String] = for { matchedLibraries <- resolveLibraries(libraries, imports) @@ -18,8 +24,8 @@ object ScriptPreprocessor { } yield gatherScriptText(scriptText, matchedLibraries) private def resolveLibraries( - libraries: Map[String, String], - imports: Imports + libraries: Map[String, String], + imports: Imports ): Either[String, Map[String, String]] = { implicit val cs: CommutativeSemigroup[NonEmptyChain[String]] = _ ++ _ imports.fileNames @@ -31,7 +37,7 @@ object ScriptPreprocessor { } private def checkLibrariesDirectives( - matchedLibraries: Map[String, String] + matchedLibraries: Map[String, String] ): Either[String, List[Unit]] = matchedLibraries .map { case (name, src) => checkLibraryDirectives(name, src) } @@ -39,8 +45,8 @@ object ScriptPreprocessor { .sequence private def checkLibraryDirectives( - libraryName: String, - librarySrc: String + libraryName: String, + librarySrc: String ): Either[String, Unit] = for { directives <- DirectiveParser(librarySrc) @@ -48,7 +54,7 @@ object ScriptPreprocessor { _ <- Either.cond(ds.contentType == Library, (), s"CONTENT_TYPE of `$libraryName` is not LIBRARY") } yield () - private val importRegex = s"\\${DirectiveParser.start}\\s*${DirectiveKey.IMPORT.text}.*${DirectiveParser.end}" + private val importRegex = s"\\${DirectiveParser.start}\\s*${DirectiveKey.IMPORT.text}.*${DirectiveParser.end}" private val directiveRegex = s"\\${DirectiveParser.start}.*${DirectiveParser.end}" private def gatherScriptText(src: String, libraries: Map[String, String]) = { diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/script/v1/ExprScript.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/script/v1/ExprScript.scala index 4d8a7d2da7c..8705825ba3c 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/script/v1/ExprScript.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/script/v1/ExprScript.scala @@ -1,6 +1,8 @@ package com.wavesplatform.lang.script.v1 -import cats.implicits._ +import cats.instances.either._ +import cats.syntax.either._ +import cats.syntax.flatMap._ import com.google.common.annotations.VisibleForTesting import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.directives.values._ diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/BaseGlobal.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/BaseGlobal.scala index 525f5a3d25c..128567ac94a 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/BaseGlobal.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/BaseGlobal.scala @@ -1,6 +1,6 @@ package com.wavesplatform.lang.v1 -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.lang.ValidationError.ScriptParseError import com.wavesplatform.lang.contract.meta.{FunctionSignatures, MetaMapper, ParsedMeta} import com.wavesplatform.lang.contract.{ContractSerDe, DApp} @@ -20,10 +20,8 @@ import com.wavesplatform.lang.v1.evaluator.ctx.impl.Rounding import com.wavesplatform.lang.v1.evaluator.ctx.impl.crypto.RSA.DigestAlgorithm import com.wavesplatform.lang.v1.parser.Expressions import com.wavesplatform.lang.v1.parser.Expressions.Pos.AnyPos -import com.wavesplatform.lang.v1.repl.node.http.response.model.NodeResponse import scala.annotation.tailrec -import scala.concurrent.Future import scala.util.Random /** @@ -257,8 +255,6 @@ trait BaseGlobal { def powBigInt(b: BigInt, bp: Long, e: BigInt, ep: Long, rp: Long, round: Rounding): Either[String, BigInt] def logBigInt(b: BigInt, bp: Long, e: BigInt, ep: Long, rp: Long, round: Rounding): Either[String, BigInt] - def requestNode(url: String): Future[NodeResponse] - def groth16Verify(verifyingKey: Array[Byte], proof: Array[Byte], inputs: Array[Byte]): Boolean def bn256Groth16Verify(verifyingKey: Array[Byte], proof: Array[Byte], inputs: Array[Byte]): Boolean @@ -270,11 +266,11 @@ trait BaseGlobal { @tailrec def findKMedianInPlace(arr: ArrayView[T], k: Int)(implicit choosePivot: ArrayView[T] => T): T = { val a = choosePivot(arr) - val (s, b) = arr partitionInPlace (a >) + val (s, b) = arr partitionInPlace (a > _) if (s.size == k) a // The following test is used to avoid infinite repetition else if (s.isEmpty) { - val (s, b) = arr partitionInPlace (a ==) + val (s, b) = arr partitionInPlace (a == _) if (s.size > k) a else findKMedianInPlace(b, k - s.size) } else if (s.size < k) findKMedianInPlace(b, k - s.size) diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/Serde.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/Serde.scala index 5b295696c66..149f2f0d547 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/Serde.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/Serde.scala @@ -3,7 +3,10 @@ package com.wavesplatform.lang.v1 import java.io.ByteArrayOutputStream import java.nio.ByteBuffer -import cats.implicits._ +import cats.instances.lazyList._ +import cats.instances.list._ +import cats.syntax.apply._ +import cats.syntax.traverse._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.lang.utils.Serialize._ @@ -55,7 +58,7 @@ object Serde { } def deserializeDeclaration(bb: ByteBuffer, aux: => Coeval[EXPR], decType: Byte): Coeval[DECLARATION] = { - decType match { + (decType: @unchecked) match { case DEC_LET => for { name <- Coeval.now(bb.getString) @@ -81,7 +84,7 @@ object Serde { desAuxR(bb, allowObjects, acc) private def desAuxR(bb: ByteBuffer, allowObjects: Boolean, acc: Coeval[Unit]): Coeval[EXPR] = acc.flatMap { _ => - bb.get() match { + (bb.get(): @unchecked) match { case E_LONG => Coeval.now(CONST_LONG(bb.getLong)) case E_BYTES => Coeval.now(CONST_BYTESTR(ByteStr(bb.getBytes)).explicitGet()) case E_STRING => Coeval.now(CONST_STRING(bb.getString).explicitGet()) @@ -123,7 +126,8 @@ object Serde { .flatMap( argsCount => if (argsCount <= (bb.limit() - bb.position()) && argsCount >= 0) - (1 to argsCount).to(LazyList) + (1 to argsCount) + .to(LazyList) .traverse(_ => evaluatedOnly(desAuxR(bb, allowObjects, acc))) .map(elements => ARR(elements.toIndexedSeq, limited = false).explicitGet()) else @@ -132,7 +136,8 @@ object Serde { case E_CASE_OBJ if allowObjects => for { (typeName, fieldsNumber) <- Coeval((bb.getString, bb.getInt)) - fields <- (1 to fieldsNumber).to(LazyList) + fields <- (1 to fieldsNumber) + .to(LazyList) .traverse( _ => for { diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/ContractCompiler.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/ContractCompiler.scala index 25345e2ff37..b4073d9a33d 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/ContractCompiler.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/ContractCompiler.scala @@ -1,6 +1,11 @@ package com.wavesplatform.lang.v1.compiler -import cats.implicits._ +import cats.instances.list._ +import cats.instances.option._ +import cats.instances.vector._ +import cats.syntax.applicative._ +import cats.syntax.either._ +import cats.syntax.traverse._ import cats.{Id, Show} import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.contract.DApp._ @@ -95,7 +100,11 @@ object ContractCompiler { } yield (resultAnnFunc, typedParams, parseNodeExpr, errorList) } - private def compileDeclaration(dec: Expressions.Declaration, saveExprContext: Boolean, allowIllFormedStrings: Boolean): CompileM[CompilationStepResultDec] = { + private def compileDeclaration( + dec: Expressions.Declaration, + saveExprContext: Boolean, + allowIllFormedStrings: Boolean + ): CompileM[CompilationStepResultDec] = { dec match { case l: Expressions.LET => for { @@ -122,7 +131,9 @@ object ContractCompiler { allowIllFormedStrings: Boolean = false ): CompileM[(Option[DApp], Expressions.DAPP, Iterable[CompilationError])] = { for { - decsCompileResult <- parsedDapp.decs.traverse[CompileM, CompilationStepResultDec](dec => compileDeclaration(dec, saveExprContext, allowIllFormedStrings)) + decsCompileResult <- parsedDapp.decs.traverse[CompileM, CompilationStepResultDec]( + dec => compileDeclaration(dec, saveExprContext, allowIllFormedStrings) + ) decs = decsCompileResult.map(_.dec) parsedNodeDecs = decsCompileResult.map(_.parseNodeExpr) duplicateVarsErr <- validateDuplicateVarsInContract(parsedDapp).handleError() @@ -353,7 +364,7 @@ object ContractCompiler { case Left(err) => Left(err) case Right(c) => Right(c) } - case f @ fastparse.Parsed.Failure(_, _, _) => Left(f.toString) + case f: fastparse.Parsed.Failure => Left(f.toString) } } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Decompiler.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Decompiler.scala index 12aae1850d6..c82bfad7027 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Decompiler.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Decompiler.scala @@ -1,13 +1,14 @@ package com.wavesplatform.lang.v1.compiler -import cats.implicits._ +import cats.instances.vector._ +import cats.syntax.traverse._ import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.contract.DApp.{CallableFunction, VerifierFunction} import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.FunctionHeader.{Native, User} import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.lang.v1.evaluator.FunctionIds -import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.{ExtractedFuncPrefix, ExtractedFuncPostfix} +import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.{ExtractedFuncPostfix, ExtractedFuncPrefix} import monix.eval.Coeval import scala.util.Try @@ -123,7 +124,7 @@ object Decompiler { val i = if (firstLinePolicy == DontIndentFirstLine) 0 else ctx.ident - e flatMap { + e.flatMap(v => (v: @unchecked) match { case Terms.BLOCK(Terms.LET(MatchRef(name), e), body) => matchBlock(name, pure(body), ctx.incrementIdent()) flatMap { b => expr(pure(e), ctx.incrementIdent(), NoBraces, DontIndentFirstLine) map { ex => out("match " ++ ex ++ " {" ++ NEWLINE, ctx.ident) ++ @@ -203,7 +204,7 @@ object Decompiler { } case _: Terms.ARR => ??? // never happens case obj: Terms.CaseObj => pureOut(obj.toString, i) // never happens - } + }) } private val extractedFuncR = s"$ExtractedFuncPrefix(\\w+)\\((.+)\\)".r diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/ExpressionCompiler.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/ExpressionCompiler.scala index 54df6bb7935..ad73428374c 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/ExpressionCompiler.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/ExpressionCompiler.scala @@ -1,7 +1,12 @@ package com.wavesplatform.lang.v1.compiler -import cats.implicits._ import cats.{Id, Show} +import cats.syntax.either._ +import cats.syntax.applicative._ +import cats.instances.list._ +import cats.syntax.traverse._ +import cats.instances.option._ +import cats.syntax.monadError._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.v1.compiler.CompilationError._ import com.wavesplatform.lang.v1.compiler.CompilerContext._ @@ -40,15 +45,15 @@ object ExpressionCompiler { def compile(input: String, ctx: CompilerContext, allowIllFormedStrings: Boolean = false): Either[String, (EXPR, FINAL)] = { Parser.parseExpr(input) match { - case fastparse.Parsed.Success(xs, _) => ExpressionCompiler(ctx, xs, allowIllFormedStrings) - case f @ fastparse.Parsed.Failure(_, _, _) => Left(f.toString) + case fastparse.Parsed.Success(xs, _) => ExpressionCompiler(ctx, xs, allowIllFormedStrings) + case f: fastparse.Parsed.Failure => Left(f.toString) } } def compileBoolean(input: String, ctx: CompilerContext): Either[String, EXPR] = { compile(input, ctx).flatMap { case (expr, BOOLEAN) => Right(expr) - case (_, _) => Left("Script should return boolean") + case _ => Left("Script should return boolean") } } @@ -238,7 +243,7 @@ object ExpressionCompiler { _ <- { val defaultCasesCount = cases.count { case MATCH_CASE(_, TypedVar(_, t), _, _, _) => t.isEmpty - case _ => false + case _ => false } Either .cond( @@ -258,14 +263,14 @@ object ExpressionCompiler { case _ => None } matchTypes <- cases.traverse { - case MATCH_CASE(_, TypedVar(_, t), _, _, _) => handleCompositeType(p, t, Some(exprTypes), allowShadowVarName) + case MATCH_CASE(_, TypedVar(_, t), _, _, _) => handleCompositeType(p, t, Some(exprTypes), allowShadowVarName) case MATCH_CASE(_, ObjPat(_, t, _), _, _, _) => handleCompositeType(p, t, Some(exprTypes), allowShadowVarName) - case _ => (NOTHING: FINAL).pure[CompileM] + case _ => (NOTHING: FINAL).pure[CompileM] } defaultType = exprTypes match { - case ANY => ANY + case ANY => ANY case UNION(tl, _) => UNION(tl.filter(t => !matchTypes.contains(t)), None) - case _ => NOTHING + case _ => NOTHING } ifCasesWithErr <- inspectFlat[Id, CompilerContext, CompilationError, Expressions.EXPR]( updatedCtx => { @@ -279,20 +284,20 @@ object ExpressionCompiler { ifCasesWithErr._1.getOrElse( Expressions.INVALID( p, - ifCasesWithErr._2.map(e => Show[CompilationError].show(e)).mkString_("\n"), + ifCasesWithErr._2.map(e => Show[CompilationError].show(e)).mkString("\n"), ctxOpt = saveExprContext.toOption(ctx.getSimpleContext()) ) ), saveExprContext, allowIllFormedStrings ) - checktypes = if(matchTypes.contains(LIST(ANY))) { + checktypes = if (matchTypes.contains(LIST(ANY))) { (matchTypes.filter(_ != LIST(ANY)), UNION.create((exprTypes match { case ANY => List(ANY) - case t => t.typeList + case t => t.typeList }).filter { case LIST(_) => false - case _ => true + case _ => true })) } else { (matchTypes, exprTypes) @@ -613,7 +618,8 @@ object ExpressionCompiler { for { keyWithErr <- handlePart(keyPart).handleError() ctx <- get[Id, CompilerContext, CompilationError] - typeWithErr = ctx.resolveVar(keyWithErr._1.getOrElse("")) + typeWithErr = ctx + .resolveVar(keyWithErr._1.getOrElse("")) .fold[(Option[FINAL], Iterable[CompilationError])]((None, List(DefNotFound(p.start, p.end, keyWithErr._1.getOrElse("")))))( info => (Some(info.vType), List.empty) ) @@ -709,8 +715,8 @@ object ExpressionCompiler { ): Either[CompilationError, Expressions.EXPR] = { def mkGet(path: Seq[PART[String]], ref: Expressions.EXPR, pos: Pos): Expressions.EXPR = { - path.foldRight(ref) { - (field, exp) => Expressions.GETTER(pos, exp, field) + path.foldRight(ref) { (field, exp) => + Expressions.GETTER(pos, exp, field) } } @@ -723,10 +729,11 @@ object ExpressionCompiler { case _ => false } val t = caseType match { - case UNION(Seq(),_) => defaultType match { - case UNION(Seq(t), _) => t - case _ => defaultType - } + case UNION(Seq(), _) => + defaultType match { + case UNION(Seq(t), _) => t + case _ => defaultType + } case _ => caseType } Expressions.BLOCK(mc.position, Expressions.LET(mc.position, nv, refTmp, Some(t), allowShadowing), mc.expr) @@ -756,9 +763,9 @@ object ExpressionCompiler { ) (mc.pattern, caseType.unfold) match { - case (_:TypedVar, ANY) => Right(blockWithNewVar) - case (_:TypedVar, UNION(Nil, _)) => Right(blockWithNewVar) - case (x:TypedVar, UNION(types, _)) => + case (_: TypedVar, ANY) => Right(blockWithNewVar) + case (_: TypedVar, UNION(Nil, _)) => Right(blockWithNewVar) + case (x: TypedVar, UNION(types, _)) => for { cases <- types.map(_.name) match { case hType :: tTypes => @@ -768,57 +775,76 @@ object ExpressionCompiler { case Nil => ??? } } yield cases - case (_:TypedVar, t) => + case (_: TypedVar, t) => Right(Expressions.IF(mc.position, isInst(t.name), blockWithNewVar, further)) case (ConstsPat(consts, _), _) => - val cond = consts.map(c => BINARY_OP(mc.position, c, BinaryOperation.EQ_OP, refTmp)).reduceRight((c, r) => BINARY_OP(mc.position, c, BinaryOperation.OR_OP, r)) + val cond = consts + .map(c => BINARY_OP(mc.position, c, BinaryOperation.EQ_OP, refTmp)) + .reduceRight((c, r) => BINARY_OP(mc.position, c, BinaryOperation.OR_OP, r)) Right(Expressions.IF(mc.position, cond, blockWithNewVar, further)) - case (p:CompositePattern, _) => - val pos = p.position + case (p: CompositePattern, _) => + val pos = p.position val newRef = p.caseType.fold(refTmp)(t => refTmp.copy(resultType = Some(caseType))) val conds = p.subpatterns collect { case (pat @ TypedVar(_, Expressions.Union(types)), path) if types.nonEmpty => val pos = pat.position - val v = mkGet(path, newRef, pos) + val v = mkGet(path, newRef, pos) types map { case Expressions.Single(t, None) => - Expressions.FUNCTION_CALL(pos, PART.VALID(pos, "_isInstanceOf"), List(v, Expressions.CONST_STRING(pos, t))): Expressions.EXPR + Expressions.FUNCTION_CALL(pos, PART.VALID(pos, "_isInstanceOf"), List(v, Expressions.CONST_STRING(pos, t))): Expressions.EXPR case Expressions.Single(PART.VALID(pos, "List"), Some(PART.VALID(_, Expressions.AnyType(_)))) => - Expressions.FUNCTION_CALL(pos, PART.VALID(pos, "_isInstanceOf"), List(v, Expressions.CONST_STRING(pos, PART.VALID(pos, "List[Any]")))): Expressions.EXPR + Expressions.FUNCTION_CALL( + pos, + PART.VALID(pos, "_isInstanceOf"), + List(v, Expressions.CONST_STRING(pos, PART.VALID(pos, "List[Any]"))) + ): Expressions.EXPR case _ => ??? - } reduceRight { (c,r) => + } reduceRight { (c, r) => BINARY_OP(pos, c, BinaryOperation.OR_OP, r): Expressions.EXPR } case (pat @ TypedVar(_, Expressions.Single(PART.VALID(pos, "List"), Some(PART.VALID(_, Expressions.AnyType(_))))), path) => val pos = pat.position - val v = mkGet(path, newRef, pos) + val v = mkGet(path, newRef, pos) Expressions.FUNCTION_CALL(pos, PART.VALID(pos, "_isInstanceOf"), List(v, Expressions.CONST_STRING(pos, PART.VALID(pos, "List[Any]")))): Expressions.EXPR case (pat @ TypedVar(_, Expressions.Single(t, None)), path) => val pos = pat.position - val v = mkGet(path, newRef, pos) + val v = mkGet(path, newRef, pos) Expressions.FUNCTION_CALL(pos, PART.VALID(pos, "_isInstanceOf"), List(v, Expressions.CONST_STRING(pos, t))): Expressions.EXPR case (pat @ TypedVar(_, Expressions.Single(_, _)), _) => ??? case (pat @ ConstsPat(consts, pos), path) => val pos = pat.position - val v = mkGet(path, newRef, pos) + val v = mkGet(path, newRef, pos) consts map { c => BINARY_OP(pos, c, BinaryOperation.EQ_OP, v) - } reduceRight { (c,r) => + } reduceRight { (c, r) => BINARY_OP(pos, c, BinaryOperation.OR_OP, r) } } - val cond = if(conds.isEmpty) { - Expressions.TRUE(pos): Expressions.EXPR - } else { - conds.reduceRight { (c, r) => BINARY_OP(pos, c, BinaryOperation.AND_OP, r): Expressions.EXPR } + val cond = if (conds.isEmpty) { + Expressions.TRUE(pos): Expressions.EXPR + } else { + conds.reduceRight { (c, r) => + BINARY_OP(pos, c, BinaryOperation.AND_OP, r): Expressions.EXPR } - Right(Expressions.IF(mc.position, p.caseType.fold(cond)(t => - BINARY_OP(pos, - Expressions.FUNCTION_CALL(pos, PART.VALID(pos, "_isInstanceOf"), List(refTmp, Expressions.CONST_STRING(pos, t.name))), - BinaryOperation.AND_OP, - Expressions.BLOCK(pos, Expressions.LET(pos, newRef.key, newRef, Some(caseType), true), cond))), blockWithNewVar, further)) + } + Right( + Expressions.IF( + mc.position, + p.caseType.fold(cond)( + t => + BINARY_OP( + pos, + Expressions.FUNCTION_CALL(pos, PART.VALID(pos, "_isInstanceOf"), List(refTmp, Expressions.CONST_STRING(pos, t.name))), + BinaryOperation.AND_OP, + Expressions.BLOCK(pos, Expressions.LET(pos, newRef.key, newRef, Some(caseType), true), cond) + ) + ), + blockWithNewVar, + further + ) + ) } } @@ -897,7 +923,7 @@ object ExpressionCompiler { types.toList .traverse(handleCompositeType(pos, _, expectedType, varName)) .map(types => TUPLE(types)) - case Expressions.AnyType(pos) => (ANY:FINAL).pure[CompileM] + case Expressions.AnyType(pos) => (ANY: FINAL).pure[CompileM] } def handlePart[T](part: PART[T]): CompileM[T] = part match { diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Terms.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Terms.scala index f6edb593462..c8aed6b8749 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Terms.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Terms.scala @@ -3,7 +3,8 @@ package com.wavesplatform.lang.v1.compiler import java.nio.charset.StandardCharsets import cats.Eval -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils._ import com.wavesplatform.lang.ExecutionError diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/TypeInferrer.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/TypeInferrer.scala index 1769396610b..5b40fad9d09 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/TypeInferrer.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/TypeInferrer.scala @@ -1,6 +1,8 @@ package com.wavesplatform.lang.v1.compiler -import cats.implicits._ +import cats.instances.either._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.lang.v1.compiler.Types._ @@ -15,32 +17,32 @@ object TypeInferrer { val matchResults: Map[TYPEPARAM, Seq[MatchResult]] = matching.flatMap(_.explicitGet()).groupBy(_.name) val resolved = matchResults.view.mapValues { case h :: Nil => Right(h.tpe) - case matchResults @ (h :: t) => - val commonType = t.map(_.tpe).toVector.foldLeft(h.tpe)(findCommonType(_, _)) + case matchResults => + val commonType = matchResults.map(_.tpe).toVector.reduce(findCommonType(_, _)) commonType match { case NOTHING => Right(NOTHING) case commonTuple: TUPLE => val matchingTuples = matchResults.collect { case MatchResult(t: TUPLE, _) => t }.toList val commonTypeExists = checkTuplesCommonType(matchingTuples, commonTuple) - typeMatchResult(matchResults, h.name, commonTuple, commonTypeExists) + typeMatchResult(matchResults, matchResults.head.name, commonTuple, commonTypeExists) case p: SINGLE => Right(p) - case ANY => Right(ANY) + case ANY => Right(ANY) case u @ UNION(plainTypes, _) => val commonTypeExists = plainTypes.exists { p => matchResults.map(_.tpe).forall(e => e >= p) } - typeMatchResult(matchResults, h.name, u, commonTypeExists) + typeMatchResult(matchResults, matchResults.head.name, u, commonTypeExists) } } resolved.find(_._2.isLeft) match { case Some((_, left)) => left.asInstanceOf[Left[String, Nothing]] case None => - Right((resolved.mapValues { t => + Right(resolved.mapValues { t => t.explicitGet() match { case UNION(x :: Nil, _) => x case x => x } - }).toMap) + }.toMap) } } } @@ -77,24 +79,26 @@ object TypeInferrer { lazy val err = s"Non-matching types: expected: $matchingTypeStr, actual: $argTypeStr" (placeholder, argType) match { - case (tp @ TYPEPARAM(char), _) => Right(Some(MatchResult(argType, tp))) - case (tp @ PARAMETERIZEDLIST(innerTypeParam), LIST(t)) => matchTypes(t, innerTypeParam, knownTypes, argTypeStr, matchingTypeStr) - case (tp @ PARAMETERIZEDLIST(innerTypeParam), UNION(l, _)) => l.foldLeft(Right(UNION(List(), None)):Either[String, FINAL]) { - (u, tl) => u match { - case Left(e) => Left(e) - case Right(UNION(l, _)) => tl match { - case LIST(t: REAL) => Right(UNION(t::l, None)) - case _ => Left(err) + case (tp @ TYPEPARAM(_), _) => Right(Some(MatchResult(argType, tp))) + case (PARAMETERIZEDLIST(innerTypeParam), LIST(t)) => matchTypes(t, innerTypeParam, knownTypes, argTypeStr, matchingTypeStr) + case (PARAMETERIZEDLIST(innerTypeParam), UNION(l, _)) => + l.foldLeft(Right(UNION(List(), None)): Either[String, FINAL]) { (u, tl) => + u match { + case Left(e) => Left(e) + case Right(UNION(l, _)) => + tl match { + case LIST(t: REAL) => Right(UNION(t :: l, None)) + case _ => Left(err) + } + case _ => ??? } - case _ => ??? + } flatMap { t => + matchTypes(t, innerTypeParam, knownTypes, argTypeStr, matchingTypeStr) } - } flatMap { - t => matchTypes(t, innerTypeParam, knownTypes, argTypeStr, matchingTypeStr) - } - case (tp @ PARAMETERIZEDLIST(_), _) => Left(err) - case (tp @ PARAMETERIZEDTUPLE(typeParams), TUPLE(types)) => matchTupleTypes(err, typeParams, types, knownTypes) - case (tp @ PARAMETERIZEDTUPLE(_), _) => Left(err) - case (tp @ PARAMETERIZEDUNION(l), _) => + case (PARAMETERIZEDLIST(_), _) => Left(err) + case (PARAMETERIZEDTUPLE(typeParams), TUPLE(types)) => matchTupleTypes(err, typeParams, types, knownTypes) + case (PARAMETERIZEDTUPLE(_), _) => Left(err) + case (PARAMETERIZEDUNION(l), _) => val concretes = UNION.create( l.filter(_.isInstanceOf[REAL]) .map(_.asInstanceOf[REAL]) @@ -116,12 +120,13 @@ object TypeInferrer { case _ => Left(s"Can't resolve correct type for parameterized $placeholder, actual: $argType") } - case (_:REAL, UNION(types, _)) => types.foldLeft(Right(None):Either[String, Option[MatchResult]]) { - (acc, t) => for { - a <- acc - b <- matchTypes(t, placeholder, knownTypes, argTypeStr, matchingTypeStr) - } yield b - } + case (_: REAL, UNION(types, _)) => + types.foldLeft(Right(None): Either[String, Option[MatchResult]]) { (acc, t) => + for { + _ <- acc + b <- matchTypes(t, placeholder, knownTypes, argTypeStr, matchingTypeStr) + } yield b + } case (LIST(tp), LIST(t)) => matchTypes(t, tp, knownTypes, argTypeStr, matchingTypeStr) case (TUPLE(types1), TUPLE(types2)) => matchTupleTypes(err, types1, types2, knownTypes) @@ -144,7 +149,7 @@ object TypeInferrer { .map(_ => None) // match, e.g. many ifs - def findCommonType(list: Seq[FINAL]): FINAL = list match { + def findCommonType(list: List[FINAL]): FINAL = list match { case Nil => NOTHING case one :: Nil => one case head :: tail => @@ -163,9 +168,9 @@ object TypeInferrer { case (NOTHING, t2) => t2 case (t1, t2) if t1 == t2 => t1 - case (r: UNION, a: UNION) => UNION.create((r.typeList.toSet ++ a.typeList.toSet).toSeq) - case (u: UNION, t: FINAL) => if (u.typeList.contains(t)) u else UNION.create(u.typeList :+ t) - case (t: FINAL, u: UNION) => if (u.typeList.contains(t)) u else UNION.create(u.typeList :+ t) + case (r: UNION, a: UNION) => UNION.create((r.typeList.toSet ++ a.typeList.toSet).toSeq) + case (u: UNION, t: FINAL) => if (u.typeList.contains(t)) u else UNION.create(u.typeList :+ t) + case (t: FINAL, u: UNION) => if (u.typeList.contains(t)) u else UNION.create(u.typeList :+ t) case (LIST(it1), LIST(it2)) => LIST(findCommonTypeR(it1, it2, mergeTuples)) case (TUPLE(types1), TUPLE(types2)) if mergeTuples && types1.length == types2.length => diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Types.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Types.scala index fb84dc380a1..59b616e5a6d 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Types.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/Types.scala @@ -1,6 +1,7 @@ package com.wavesplatform.lang.v1.compiler -import cats.implicits._ +import cats.syntax.traverse._ +import cats.instances.list._ object Types { diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/package.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/package.scala index 59b503656ac..747aaf426f3 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/package.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/compiler/package.scala @@ -1,7 +1,7 @@ package com.wavesplatform.lang.v1 import cats.Id -import cats.implicits._ +import cats.syntax.applicative._ import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.lang.v1.task.TaskM import com.wavesplatform.lang.v1.task.imports._ diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/estimator/v2/ScriptEstimatorV2.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/estimator/v2/ScriptEstimatorV2.scala index 23bbc48f8c7..b6a486bc281 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/estimator/v2/ScriptEstimatorV2.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/estimator/v2/ScriptEstimatorV2.scala @@ -1,6 +1,7 @@ package com.wavesplatform.lang.v1.estimator.v2 -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import cats.{Id, Monad} import com.wavesplatform.lang.ExecutionError import com.wavesplatform.lang.v1.FunctionHeader diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/estimator/v3/ScriptEstimatorV3.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/estimator/v3/ScriptEstimatorV3.scala index 19bdd16e6ce..ee15e67f24d 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/estimator/v3/ScriptEstimatorV3.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/estimator/v3/ScriptEstimatorV3.scala @@ -1,6 +1,7 @@ package com.wavesplatform.lang.v1.estimator.v3 -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import cats.{Id, Monad} import com.wavesplatform.lang.ExecutionError import com.wavesplatform.lang.v1.FunctionHeader diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/Contextful.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/Contextful.scala index 59a3c6b8594..5b9ef9195f3 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/Contextful.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/Contextful.scala @@ -1,6 +1,8 @@ package com.wavesplatform.lang.v1.evaluator -import cats.implicits._ +import cats.syntax.functor._ +import cats.syntax.either._ +import cats.syntax.applicative._ import cats.{Eval, Monad} import com.wavesplatform.lang.ExecutionError import com.wavesplatform.lang.v1.compiler.Terms.{EVALUATED, EXPR} diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ContractEvaluator.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ContractEvaluator.scala index 1c4723c126e..a6a8b18f201 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ContractEvaluator.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ContractEvaluator.scala @@ -1,7 +1,7 @@ package com.wavesplatform.lang.v1.evaluator import cats.Id -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.lang.ExecutionError diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/EvaluatorV1.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/EvaluatorV1.scala index 9604cc7ae7b..b3c52507d7c 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/EvaluatorV1.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/EvaluatorV1.scala @@ -1,10 +1,15 @@ package com.wavesplatform.lang.v1.evaluator -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.applicative._ +import cats.syntax.traverse._ +import cats.syntax.functor._ +import cats.instances.either._ +import cats.syntax.bifunctor._ import cats.{Eval, Id, Monad, StackSafeMonad} import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms._ -import com.wavesplatform.lang.v1.compiler.Types.{NOTHING, CASETYPEREF} +import com.wavesplatform.lang.v1.compiler.Types.{CASETYPEREF, NOTHING} import com.wavesplatform.lang.v1.evaluator.ctx.LoggedEvaluationContext.Lenses import com.wavesplatform.lang.v1.evaluator.ctx._ import com.wavesplatform.lang.v1.task.imports._ @@ -14,7 +19,7 @@ import com.wavesplatform.lang.{EvalF, ExecutionError} import scala.collection.mutable.ListBuffer object EvaluatorV1 { - implicit val idEvalFMonad: Monad[EvalF[Id, ?]] = new StackSafeMonad[EvalF[Id, ?]] { + implicit val idEvalFMonad: Monad[EvalF[Id, *]] = new StackSafeMonad[EvalF[Id, *]] { override def flatMap[A, B](fa: Eval[A])(f: A => Eval[B]): Eval[B] = fa.flatMap(f).memoize @@ -26,7 +31,7 @@ object EvaluatorV1 { def apply(): EvaluatorV1[Id, Environment] = evaluator } -class EvaluatorV1[F[_] : Monad, C[_[_]]](implicit ev: Monad[EvalF[F, ?]]) { +class EvaluatorV1[F[_] : Monad, C[_[_]]](implicit ev: Monad[EvalF[F, *]]) { private val lenses = new Lenses[F, C] import lenses._ @@ -68,10 +73,10 @@ class EvaluatorV1[F[_] : Monad, C[_[_]]](implicit ev: Monad[EvalF[F, ?]]) { } private def evalGetter(expr: EXPR, field: String): EvalM[F, C, (EvaluationContext[C, F], EVALUATED)] = { - Monad[EvalM[F, C, ?]].flatMap(evalExprWithCtx(expr)) { case (ctx, exprResult) => + Monad[EvalM[F, C, *]].flatMap(evalExprWithCtx(expr)) { case (ctx, exprResult) => val fields = exprResult.asInstanceOf[CaseObj].fields fields.get(field) match { - case Some(f) => (ctx, f).pure[EvalM[F, C, ?]] + case Some(f) => (ctx, f).pure[EvalM[F, C, *]] case None => raiseError(s"A definition of '$field' not found amongst ${fields.keys}") } } @@ -85,18 +90,18 @@ class EvaluatorV1[F[_] : Monad, C[_[_]]](implicit ev: Monad[EvalF[F, ?]]) { .get(header) .map { case func: UserFunction[C] => - Monad[EvalM[F, C, ?]].flatMap(args.traverse(evalExpr)) { args => + Monad[EvalM[F, C, *]].flatMap(args.traverse(evalExpr)) { args => val letDefsWithArgs = args.zip(func.signature.args).foldLeft(ctx.ec.letDefs) { case (r, (argValue, (argName, _))) => r + (argName -> LazyVal.fromEvaluated(argValue, ctx.l(s"$argName"))) } local { val newState: EvalM[F, C, Unit] = set[F, LoggedEvaluationContext[C, F], ExecutionError](lets.set(ctx)(letDefsWithArgs)).map(_.pure[F]) - Monad[EvalM[F, C, ?]].flatMap(newState)(_ => evalExpr(func.ev(ctx.ec.environment, args))) + Monad[EvalM[F, C, *]].flatMap(newState)(_ => evalExpr(func.ev(ctx.ec.environment, args))) } }: EvalM[F, C, EVALUATED] case func: NativeFunction[C] => - Monad[EvalM[F, C, ?]].flatMap(args.traverse(evalExpr))(args => + Monad[EvalM[F, C, *]].flatMap(args.traverse(evalExpr))(args => liftTER[F, C, EVALUATED](func.eval[F](ctx.ec.environment, args).value) ) } @@ -105,9 +110,9 @@ class EvaluatorV1[F[_] : Monad, C[_[_]]](implicit ev: Monad[EvalF[F, ?]]) { header match { case FunctionHeader.User(typeName, _) => types.get(ctx).get(typeName).collect { - case t @ CASETYPEREF(_, fields, hidden) => + case t @ CASETYPEREF(_, fields, _) => args - .traverse[EvalM[F, C, ?], EVALUATED](evalExpr) + .traverse[EvalM[F, C, *], EVALUATED](evalExpr) .map(values => CaseObj(t, fields.map(_._1).zip(values).toMap): EVALUATED) } case _ => None diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/EvaluatorV2.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/EvaluatorV2.scala index 06a2bf58a20..5545cf65ee4 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/EvaluatorV2.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/EvaluatorV2.scala @@ -1,7 +1,9 @@ package com.wavesplatform.lang.v1.evaluator import cats.Id -import cats.implicits._ +import cats.syntax.either._ +import cats.syntax.foldable._ +import cats.instances.lazyList._ import com.wavesplatform.lang.ExecutionError import com.wavesplatform.lang.directives.values.StdLibVersion import com.wavesplatform.lang.v1.FunctionHeader diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ScriptResult.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ScriptResult.scala index 927f7cab123..95903e868fd 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ScriptResult.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ScriptResult.scala @@ -1,7 +1,9 @@ package com.wavesplatform.lang.v1.evaluator import cats.Id -import cats.implicits._ +import cats.instances.either._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ExecutionError import com.wavesplatform.lang.directives.values.{StdLibVersion, V3, V4, V5} diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/InvariableContext.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/InvariableContext.scala index 2dce27b4cdf..6012894cf86 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/InvariableContext.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/InvariableContext.scala @@ -1,16 +1,17 @@ package com.wavesplatform.lang.v1.evaluator.ctx import cats.Id +import com.wavesplatform.lang.utils.environment import com.wavesplatform.lang.v1.CTX import com.wavesplatform.lang.v1.traits.Environment case class InvariableContext(private val ctx: CTX[Environment]) { - private val constants = ctx.vars.collect { case (k, v) if v._2.isPure => k -> LazyVal.fromEval(v._2(null)) } + private val constants = ctx.vars.collect { case (k, v) if v._2.isPure => k -> LazyVal.fromEval(v._2(environment)) } private def vars(env: Environment[Id]) = ctx.vars.collect { case (k, v) if !v._2.isPure => k -> LazyVal.fromEval(v._2(env)) } private val rawEvaluationContext: EvaluationContext[Environment, Id] = EvaluationContext[Environment, Id]( - null, + environment, ctx.typeDefs, constants, ctx.functionMap diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/LazyVal.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/LazyVal.scala index 87df76f4d17..30484d3fe6d 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/LazyVal.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/LazyVal.scala @@ -1,6 +1,8 @@ package com.wavesplatform.lang.v1.evaluator.ctx -import cats.implicits._ +import cats.instances.either._ +import cats.syntax.applicative._ +import cats.syntax.flatMap._ import cats.{Eval, Monad, ~>} import com.wavesplatform.lang.v1.compiler.Terms.EVALUATED import com.wavesplatform.lang.v1.evaluator.LogCallback @@ -34,7 +36,7 @@ object LazyVal { LazyValImpl(v, _ => Monad[F].unit) def fromEvaluated[F[_] : Monad](v: EVALUATED, lc: LogCallback[F]): LazyVal[F] = - LazyValImpl(v.pure[Either[ExecutionError, ?]].pure[F].pure[Eval], lc) + LazyValImpl(v.pure[Either[ExecutionError, *]].pure[F].pure[Eval], lc) def fromEvaluated[F[_] : Monad](v: EVALUATED): LazyVal[F] = fromEvaluated(v, _ => Monad[F].unit) diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/NativeFunction.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/NativeFunction.scala index 8bb9435dae0..b563e4c00c9 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/NativeFunction.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/NativeFunction.scala @@ -1,7 +1,7 @@ package com.wavesplatform.lang.v1.evaluator.ctx import cats.data.EitherT -import cats.implicits._ +import cats.syntax.applicative._ import cats.{Eval, Monad} import com.wavesplatform.lang.directives.DirectiveDictionary import com.wavesplatform.lang.directives.values.StdLibVersion @@ -43,7 +43,7 @@ case class NativeFunction[C[_[_]]]( @(JSExport @field) args: Seq[String] ) extends BaseFunction[C] { def eval[F[_] : Monad](context: C[F], args: List[EVALUATED]): TrampolinedExecResult[F, EVALUATED] = - EitherT.apply[EvalF[F, ?], ExecutionError, EVALUATED](ev((context, args)).pure[Eval]) + EitherT.apply[EvalF[F, *], ExecutionError, EVALUATED](ev((context, args)).pure[Eval]) } object NativeFunction { diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/CryptoContext.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/CryptoContext.scala index 8511df0bfb6..486dc836811 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/CryptoContext.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/CryptoContext.scala @@ -1,6 +1,6 @@ package com.wavesplatform.lang.v1.evaluator.ctx.impl -import cats.implicits._ +import cats.syntax.semigroup._ import cats.{Id, Monad} import com.wavesplatform.common.merkle.Merkle.createRoot import com.wavesplatform.common.state.ByteStr @@ -136,8 +136,9 @@ object CryptoContext { case 128 => 172 }), (n => { - case CONST_BYTESTR(msg: ByteStr) :: _ => Either.cond(msg.size <= n * 1024, (), s"Invalid message size = ${msg.size} bytes, must be not greater than $n KB") - case xs => notImplemented[Id, Unit](s"sigVerify_${n}Kb(message: ByteVector, sig: ByteVector, pub: ByteVector)", xs) + case CONST_BYTESTR(msg: ByteStr) :: _ => + Either.cond(msg.size <= n * 1024, (), s"Invalid message size = ${msg.size} bytes, must be not greater than $n KB") + case xs => notImplemented[Id, Unit](s"sigVerify_${n}Kb(message: ByteVector, sig: ByteVector, pub: ByteVector)", xs) }), BOOLEAN, ("message", BYTESTR), @@ -166,10 +167,10 @@ object CryptoContext { } def rsaVerify( - digestAlg: CaseObj, - msg: ByteStr, - sig: ByteStr, - pub: ByteStr + digestAlg: CaseObj, + msg: ByteStr, + sig: ByteStr, + pub: ByteStr ) = for { alg <- algFromCO(digestAlg) @@ -211,7 +212,8 @@ object CryptoContext { case 128 => 750 }), (n => { - case _ :: CONST_BYTESTR(msg: ByteStr) :: _ => Either.cond(msg.size <= n * 1024, (), s"Invalid message size = ${msg.size} bytes, must be not greater than $n KB") + case _ :: CONST_BYTESTR(msg: ByteStr) :: _ => + Either.cond(msg.size <= n * 1024, (), s"Invalid message size = ${msg.size} bytes, must be not greater than $n KB") case xs => notImplemented[Id, Unit](s"rsaVerify_${n}Kb(digest: DigestAlgorithmType, message: ByteVector, sig: ByteVector, pub: ByteVector)", xs) }), @@ -234,9 +236,9 @@ object CryptoContext { STRING, ("bytes", BYTESTR) ) { - case CONST_BYTESTR(bytes: ByteStr) :: Nil => global.base58Encode(bytes.arr).flatMap(CONST_STRING(_, reduceLimit = version >= V4)) - case xs => notImplemented[Id, EVALUATED]("toBase58String(bytes: ByteVector)", xs) - } + case CONST_BYTESTR(bytes: ByteStr) :: Nil => global.base58Encode(bytes.arr).flatMap(CONST_STRING(_, reduceLimit = version >= V4)) + case xs => notImplemented[Id, EVALUATED]("toBase58String(bytes: ByteVector)", xs) + } def fromBase58StringF: BaseFunction[NoContext] = NativeFunction( @@ -258,9 +260,9 @@ object CryptoContext { STRING, ("bytes", BYTESTR) ) { - case CONST_BYTESTR(bytes: ByteStr) :: Nil => global.base64Encode(bytes.arr).flatMap(CONST_STRING(_, reduceLimit = version >= V4)) - case xs => notImplemented[Id, EVALUATED]("toBase64String(bytes: ByteVector)", xs) - } + case CONST_BYTESTR(bytes: ByteStr) :: Nil => global.base64Encode(bytes.arr).flatMap(CONST_STRING(_, reduceLimit = version >= V4)) + case xs => notImplemented[Id, EVALUATED]("toBase64String(bytes: ByteVector)", xs) + } def fromBase64StringF: BaseFunction[NoContext] = NativeFunction( @@ -504,9 +506,9 @@ object CryptoContext { val fromV4Ctx = fromV1Ctx |+| CTX[NoContext](v4Types, v4Vars, v4Functions) version match { - case V1 | V2 => fromV1Ctx - case V3 => fromV3Ctx - case v if v >= V4 => fromV4Ctx + case V1 | V2 => fromV1Ctx + case V3 => fromV3Ctx + case V4 | V5 => fromV4Ctx } } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/EnvironmentFunctions.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/EnvironmentFunctions.scala index cefc12fd07b..77533e1c025 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/EnvironmentFunctions.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/EnvironmentFunctions.scala @@ -1,7 +1,7 @@ package com.wavesplatform.lang.v1.evaluator.ctx.impl -import cats.implicits._ import cats.Monad +import cats.syntax.either._ import com.wavesplatform.lang.ExecutionError import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, CONST_STRING, CaseObj} import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.Types diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/PureContext.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/PureContext.scala index 52c99ff843d..e52556605ef 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/PureContext.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/PureContext.scala @@ -1,6 +1,12 @@ package com.wavesplatform.lang.v1.evaluator.ctx.impl -import cats.implicits._ +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.charset.{MalformedInputException, StandardCharsets} +import java.nio.{BufferUnderflowException, ByteBuffer} + +import cats.instances.list._ +import cats.syntax.either._ +import cats.syntax.traverse._ import cats.{Id, Monad} import com.google.common.annotations.VisibleForTesting import com.wavesplatform.common.state.ByteStr @@ -21,9 +27,6 @@ import com.wavesplatform.lang.v1.parser.BinaryOperation import com.wavesplatform.lang.v1.parser.BinaryOperation._ import com.wavesplatform.lang.v1.{BaseGlobal, CTX, FunctionHeader} -import java.nio.charset.StandardCharsets.UTF_8 -import java.nio.charset.{MalformedInputException, StandardCharsets} -import java.nio.{BufferUnderflowException, ByteBuffer} import scala.annotation.tailrec import scala.collection.mutable.ArrayBuffer import scala.util.{Success, Try} @@ -39,12 +42,21 @@ object PureContext { val BigIntMin: BigInt = -BigIntMax - 1 val MaxListLengthV4 = 1000 - lazy val mulLong: BaseFunction[NoContext] = - createTryOp(MUL_OP, LONG, LONG, MUL_LONG)((a, b) => Math.multiplyExact(a, b)) + // As an optimization, JVM might throw an ArithmeticException with empty stack trace and null message. + // The workaround below retrows an exception with the message explicitly set. lazy val divLong: BaseFunction[NoContext] = - createTryOp(DIV_OP, LONG, LONG, DIV_LONG)((a, b) => Math.floorDiv(a, b)) + createTryOp(DIV_OP, LONG, LONG, DIV_LONG) { (a, b) => + try Math.floorDiv(a, b) + catch { case _: ArithmeticException => throw new ArithmeticException("/ by zero") } + } lazy val modLong: BaseFunction[NoContext] = - createTryOp(MOD_OP, LONG, LONG, MOD_LONG)((a, b) => Math.floorMod(a, b)) + createTryOp(MOD_OP, LONG, LONG, MOD_LONG) { (a, b) => + try Math.floorMod(a, b) + catch { case _: ArithmeticException => throw new ArithmeticException("/ by zero") } + } + + lazy val mulLong: BaseFunction[NoContext] = + createTryOp(MUL_OP, LONG, LONG, MUL_LONG)((a, b) => Math.multiplyExact(a, b)) lazy val sumLong: BaseFunction[NoContext] = createTryOp(SUM_OP, LONG, LONG, SUM_LONG)((a, b) => Math.addExact(a, b)) lazy val subLong: BaseFunction[NoContext] = diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/converters/package.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/converters/package.scala index b618ddc5983..b26b54a6132 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/converters/package.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/converters/package.scala @@ -1,6 +1,6 @@ package com.wavesplatform.lang.v1.evaluator.ctx.impl -import cats.implicits._ +import cats.syntax.applicative._ import cats.{Eval, Monad} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/package.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/package.scala index 050a7532d44..9e5dc8a6e0b 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/package.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/package.scala @@ -1,7 +1,8 @@ package com.wavesplatform.lang.v1.evaluator.ctx import cats.Monad -import cats.implicits._ +import cats.syntax.applicative._ +import cats.syntax.either._ import com.wavesplatform.lang.v1.compiler.Terms.CaseObj import com.wavesplatform.lang.v1.compiler.Types.UNIT diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/Functions.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/Functions.scala index 141999741ff..7cf0d608331 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/Functions.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/Functions.scala @@ -1,24 +1,26 @@ package com.wavesplatform.lang.v1.evaluator.ctx.impl.waves +import cats.syntax.applicative._ +import cats.syntax.either._ +import cats.syntax.functor._ import cats.{Id, Monad} -import cats.implicits._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.lang.ExecutionError import com.wavesplatform.lang.directives.values._ -import com.wavesplatform.lang.v1.{BaseGlobal, FunctionHeader} import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.lang.v1.compiler.Types._ -import com.wavesplatform.lang.v1.evaluator.{ContextfulNativeFunction, ContextfulUserFunction} import com.wavesplatform.lang.v1.evaluator.FunctionIds._ -import com.wavesplatform.lang.v1.evaluator.ctx.{BaseFunction, NativeFunction, UserFunction} -import com.wavesplatform.lang.v1.evaluator.ctx.impl.{EnvironmentFunctions, PureContext, notImplemented, unit} import com.wavesplatform.lang.v1.evaluator.ctx.impl.converters._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.Bindings.{scriptTransfer => _, _} import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.Types.{addressOrAliasType, addressType, commonDataEntryType, optionAddress, _} -import com.wavesplatform.lang.v1.traits.{DataType, Environment} +import com.wavesplatform.lang.v1.evaluator.ctx.impl.{EnvironmentFunctions, PureContext, notImplemented, unit} +import com.wavesplatform.lang.v1.evaluator.ctx.{BaseFunction, NativeFunction, UserFunction} +import com.wavesplatform.lang.v1.evaluator.{ContextfulNativeFunction, ContextfulUserFunction} import com.wavesplatform.lang.v1.traits.domain.{Issue, Lease, Recipient} +import com.wavesplatform.lang.v1.traits.{DataType, Environment} +import com.wavesplatform.lang.v1.{BaseGlobal, FunctionHeader} import monix.eval.Coeval import shapeless.Coproduct.unsafeGet @@ -45,7 +47,7 @@ object Functions { .map(_.flatMap { case None => Right(unit) case Some(a) => - a match { + (a: @unchecked) match { case b: ByteStr => CONST_BYTESTR(b) case b: Long => Right(CONST_LONG(b)) case b: String => CONST_STRING(b) @@ -526,7 +528,7 @@ object Functions { } } - def callDAppF(version: StdLibVersion, reentrant: Boolean): BaseFunction[Environment] = { + def callDAppF(reentrant: Boolean): BaseFunction[Environment] = { val (id, name) = if (reentrant) (CALLDAPPREENTRANT, "reentrantInvoke") else (CALLDAPP, "invoke") NativeFunction.withEnvironment[Environment]( name, @@ -558,7 +560,7 @@ object Functions { case a => throw new IllegalArgumentException(s"Unexpected address bytes $a") } case (dApp: CaseObj) :: _ if dApp.caseType == aliasType => - dApp.fields("alias") match { + (dApp.fields("alias"): @unchecked) match { case CONST_STRING(a) => env.resolveAlias(a).map(_.explicitGet().bytes) } case args => throw new IllegalArgumentException(s"Unexpected recipient args $args") @@ -577,9 +579,9 @@ object Functions { args.toList, payments.map { case p: CaseObj if p.caseType == paymentType => - List("assetId", "amount").map(p.fields) match { - case List(CONST_BYTESTR(a), CONST_LONG(v)) => (Some(a.arr), v) - case List(CaseObj(UNIT, _), CONST_LONG(v)) => (None, v) + (List("assetId", "amount").map(p.fields): @unchecked) match { + case CONST_BYTESTR(a) :: CONST_LONG(v) :: Nil => (Some(a.arr), v) + case CaseObj(UNIT, _) :: CONST_LONG(v) :: Nil => (None, v) } case arg => throw new IllegalArgumentException(s"Unexpected payment arg $arg") }, diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/Vals.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/Vals.scala index 1cc6e7c660c..a4364448532 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/Vals.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/Vals.scala @@ -1,6 +1,7 @@ package com.wavesplatform.lang.v1.evaluator.ctx.impl.waves -import cats.implicits._ +import cats.syntax.either._ +import cats.syntax.functor._ import cats.{Eval, Monad} import com.wavesplatform.lang.ExecutionError import com.wavesplatform.lang.directives.values.StdLibVersion diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/WavesContext.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/WavesContext.scala index 648dbc28ba1..dce700cc082 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/WavesContext.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/ctx/impl/waves/WavesContext.scala @@ -1,6 +1,6 @@ package com.wavesplatform.lang.v1.evaluator.ctx.impl.waves -import cats.implicits._ +import cats.syntax.semigroup._ import com.wavesplatform.lang.directives.DirectiveSet import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.Functions.{addressFromStringF, _} @@ -80,8 +80,8 @@ object WavesContext { isDataStorageUntouchedF ) ++ (if (contentType == DApp) Array( - callDAppF(version, reentrant = false), - callDAppF(version, reentrant = true) + callDAppF(reentrant = false), + callDAppF(reentrant = true) ) else Array()) diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/package.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/package.scala index 19fcfde4738..763b7095432 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/package.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/evaluator/package.scala @@ -11,7 +11,7 @@ package object evaluator { implicit class EvalMOps[F[_], C[_[_]], A](ev: EvalM[F, C, A]) { def ter(ctx: LoggedEvaluationContext[C, F]): TrampolinedExecResult[F, A] = - EitherT[EvalF[F, ?], ExecutionError, A](ev.run(ctx).map(_._2)) + EitherT[EvalF[F, *], ExecutionError, A](ev.run(ctx).map(_._2)) } def liftTER[F[_], C[_[_]], A](ter: Eval[F[Either[ExecutionError, A]]]): EvalM[F, C, A] = diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Expressions.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Expressions.scala index 1da6cfedf38..9ca693cecdd 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Expressions.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Expressions.scala @@ -50,7 +50,7 @@ object Expressions { case class VALID[T](position: Pos, v: T) extends PART[T] { override def equals(obj: Any): Boolean = obj match { - case VALID(_, value) => value.equals(this.v) + case VALID(_, value) => value == this.v case _ => false } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Macro.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Macro.scala index 8b228f54889..b6302bf2244 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Macro.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Macro.scala @@ -5,7 +5,8 @@ import com.wavesplatform.lang.v1.parser.Expressions._ object Macro { def unwrapStrict(blockPos: Pos, strictLetDecs: Seq[LET], strictBody: EXPR): EXPR = { - val strictLetDec :: otherLets = strictLetDecs + val strictLetDec = strictLetDecs.head + val otherLets = strictLetDecs.tail val strictPos = strictLetDec.position val strictLetName = strictLetDec.name BLOCK( diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Parser.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Parser.scala index 6370b982e24..b4bfa0f8e83 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Parser.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/Parser.scala @@ -1,6 +1,10 @@ package com.wavesplatform.lang.v1.parser -import cats.implicits._ +import cats.instances.either._ +import cats.instances.list._ +import cats.instances.option._ +import cats.syntax.either._ +import cats.syntax.traverse._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.v1.ContractLimits import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext.MaxListLengthV4 @@ -210,7 +214,7 @@ object Parser { maybeFunctionCallP ) - abstract class Accessor + sealed trait Accessor case class Method(name: PART[String], args: Seq[EXPR]) extends Accessor case class Getter(name: PART[String]) extends Accessor case class ListIndex(index: EXPR) extends Accessor @@ -561,7 +565,7 @@ object Parser { case _ => throw new Exception("Parser error") } case Parsed.Success((s, _), v) => Parsed.Success(s,v) - case Parsed.Failure(m, o, e) => Parsed.Failure(m, o, e) + case f: Parsed.Failure => Parsed.Failure(f.label, f.index, f.extra) } } @@ -572,7 +576,7 @@ object Parser { def parse(str: String): Either[Parsed.Failure, SCRIPT] = parseExpr(str) match { case Parsed.Success(resExpr, _) => Right(SCRIPT(resExpr.position, resExpr)) - case f @ Parsed.Failure(_, _, _) => Left(f) + case f: Parsed.Failure => Left(f) } parseWithError[SCRIPT]( @@ -591,7 +595,7 @@ object Parser { def parse(str: String): Either[Parsed.Failure, DAPP] = parseContract(str) match { case Parsed.Success(resDAPP, _) => Right(resDAPP) - case f @ Parsed.Failure(_, _, _) => Left(f) + case f: Parsed.Failure => Left(f) } parseWithError[DAPP]( diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/ParserV2.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/ParserV2.scala index 638795b626c..c66b5d052dc 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/ParserV2.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/parser/ParserV2.scala @@ -9,7 +9,7 @@ import org.parboiled2.{Rule1, _} import scala.collection.mutable -abstract class Accessor extends Positioned +sealed trait Accessor extends Positioned case class MethodAcc(position: Pos, name: PART[String], args: Seq[EXPR]) extends Accessor case class GetterAcc(position: Pos, name: PART[String]) extends Accessor case class ListIndexAcc(position: Pos, index: EXPR) extends Accessor @@ -123,9 +123,9 @@ class ParserV2(val input: ParserInput) extends Parser { def NEOP: Rule1[BinaryOperation] = rule { "!=" ~ push(NE_OP) } def COMPARE_GROUP_OP: Rule1[BinaryOperation] = rule { GTOP | GEOP | LTOP | LEOP } - def GTOP: Rule1[BinaryOperation] = rule { ">" ~ "=".unary_!() ~ push(GT_OP) } + def GTOP: Rule1[BinaryOperation] = rule { ">" ~ "=".unary_! ~ push(GT_OP) } def GEOP: Rule1[BinaryOperation] = rule { ">=" ~ push(GE_OP) } - def LTOP: Rule1[BinaryOperation] = rule { "<" ~ "=".unary_!() ~ push(LT_OP) } + def LTOP: Rule1[BinaryOperation] = rule { "<" ~ "=".unary_! ~ push(LT_OP) } def LEOP: Rule1[BinaryOperation] = rule { "<=" ~ push(LE_OP) } def CONSOP: Rule1[BinaryOperation] = rule { "::" ~ push(CONS_OP) } @@ -147,10 +147,10 @@ class ParserV2(val input: ParserInput) extends Parser { def ConstAtom: Rule1[EXPR] = rule { IntegerAtom | StringAtom | ByteVectorAtom | BooleanAtom | ListAtom } def IdentifierAtom: Rule1[PART[String]] = rule { - push(cursor) ~ capture((ReservedWords.unary_!() ~ Char ~ zeroOrMore(Char | Digit)) | (ReservedWords ~ (Char | Digit) ~ zeroOrMore(Char | Digit))) ~ push(cursor) ~> parseIdentifierAtom _ + push(cursor) ~ capture((ReservedWords.unary_! ~ Char ~ zeroOrMore(Char | Digit)) | (ReservedWords ~ (Char | Digit) ~ zeroOrMore(Char | Digit))) ~ push(cursor) ~> parseIdentifierAtom _ } def ReferenceAtom: Rule1[EXPR] = rule { - push(cursor) ~ capture((ReservedWords.unary_!() ~ Char ~ zeroOrMore(Char | Digit)) | (ReservedWords ~ (Char | Digit) ~ zeroOrMore(Char | Digit))) ~ push(cursor) ~> parseReferenceAtom _ + push(cursor) ~ capture((ReservedWords.unary_! ~ Char ~ zeroOrMore(Char | Digit)) | (ReservedWords ~ (Char | Digit) ~ zeroOrMore(Char | Digit))) ~ push(cursor) ~> parseReferenceAtom _ } def GenericTypesAtom: Rule1[Seq[(PART[String], Option[PART[String]])]] = rule { oneOrMore(OneGenericTypeAtom).separatedBy(WS ~ "|" ~ WS) } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMT.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMT.scala index 1df15ac52a3..12f34f15b00 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMT.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMT.scala @@ -1,7 +1,8 @@ package com.wavesplatform.lang.v1.task import cats.data.Kleisli -import cats.implicits._ +import cats.syntax.either._ +import cats.syntax.functor._ import cats.{Eval, Functor, Monad} import com.wavesplatform.lang.EvalF import monix.execution.atomic.{Atomic, AtomicBuilder} @@ -32,7 +33,7 @@ trait TaskMT[F[_], S, E, R] { case Left(err) => Left(err) })) - def flatMap[B](f: R => TaskMT[F, S, E, B])(implicit m: Monad[EvalF[F, ?]]): TaskMT[F, S, E, B] = { + def flatMap[B](f: R => TaskMT[F, S, E, B])(implicit m: Monad[EvalF[F, *]]): TaskMT[F, S, E, B] = { TaskMT.fromEvalRef[F, S, E, B] { s => m.flatMap(inner.run(s)) { case Right(v) => f(v).inner.run(s) @@ -41,7 +42,7 @@ trait TaskMT[F[_], S, E, R] { } } - def handleErrorWith(f: E => TaskMT[F, S, E, R])(implicit m: Monad[EvalF[F, ?]]): TaskMT[F, S, E, R] = + def handleErrorWith(f: E => TaskMT[F, S, E, R])(implicit m: Monad[EvalF[F, *]]): TaskMT[F, S, E, R] = TaskMT.fromEvalRef[F, S, E, R] { s => m.flatMap(inner.run(s)) { case Right(v) => m.pure(v.asRight[E]) @@ -49,7 +50,7 @@ trait TaskMT[F[_], S, E, R] { } } - def handleError()(implicit m: Monad[EvalF[F, ?]]): TaskMT[F, S, E, (Option[R], List[E])] = { + def handleError()(implicit m: Monad[EvalF[F, *]]): TaskMT[F, S, E, (Option[R], List[E])] = { TaskMT.fromEvalRef[F, S, E, (Option[R], List[E])] { s => m.flatMap(inner.run(s)) { case Right(v) => m.pure((Some(v), List.empty).asRight[E]) diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMTFunctions.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMTFunctions.scala index b163eb29179..69e2e9d6743 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMTFunctions.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMTFunctions.scala @@ -1,8 +1,9 @@ package com.wavesplatform.lang.v1.task -import cats.{Eval, Monad} import cats.data.Kleisli -import cats.implicits._ +import cats.syntax.applicative._ +import cats.syntax.either._ +import cats.{Eval, Monad} import com.wavesplatform.lang.EvalF trait TaskMTFunctions { @@ -36,9 +37,9 @@ trait TaskMTFunctions { def inspect[F[_] : Monad, S, E, A](f: S => A): TaskMT[F, S, E, A] = get[F, S, E].map(f) - def inspectFlat[F[_] : Monad, S, E, A](f: S => TaskMT[F, S, E, A])(implicit m: Monad[EvalF[F, ?]]): TaskMT[F, S, E, A] = + def inspectFlat[F[_] : Monad, S, E, A](f: S => TaskMT[F, S, E, A])(implicit m: Monad[EvalF[F, *]]): TaskMT[F, S, E, A] = get[F, S, E].flatMap(f) - def modify[F[_] : Monad, S, E](f: S => S)(implicit m: Monad[EvalF[F, ?]]): TaskMT[F, S, E, Unit] = + def modify[F[_] : Monad, S, E](f: S => S)(implicit m: Monad[EvalF[F, *]]): TaskMT[F, S, E, Unit] = get[F, S, E].flatMap(f andThen set[F, S, E]) } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMTInstances.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMTInstances.scala index 57e7ce21e7a..279435b1306 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMTInstances.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/task/TaskMTInstances.scala @@ -8,8 +8,8 @@ trait TaskMTInstances { object TF extends TaskMTFunctions - implicit def monadError[F[_] : Monad, S, E](implicit m: Monad[EvalF[F, ?]]): MonadError[TaskMT[F, S, E, ?], E] = - new MonadError[TaskMT[F, S, E, ?], E] with StackSafeMonad[TaskMT[F, S, E, ?]] { + implicit def monadError[F[_] : Monad, S, E](implicit m: Monad[EvalF[F, *]]): MonadError[TaskMT[F, S, E, *], E] = + new MonadError[TaskMT[F, S, E, *], E] with StackSafeMonad[TaskMT[F, S, E, *]] { override def pure[A](x: A): TaskMT[F, S, E, A] = TF.pure(x) @@ -23,9 +23,9 @@ trait TaskMTInstances { fa.handleErrorWith(f) } - implicit def monadState[F[_]: Monad, S, E](implicit m: Monad[EvalF[F, ?]]): MonadState[TaskMT[F, S, E, ?], S] = - new MonadState[TaskMT[F, S, E, ?], S] { - override val monad: Monad[TaskMT[F, S, E, ?]] = monadError[F, S, E] + implicit def monadState[F[_]: Monad, S, E](implicit m: Monad[EvalF[F, *]]): MonadState[TaskMT[F, S, E, *], S] = + new MonadState[TaskMT[F, S, E, *], S] { + override val monad: Monad[TaskMT[F, S, E, *]] = monadError[F, S, E] override def get: TaskMT[F, S, E, S] = TF.get diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/traits/Environment.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/traits/Environment.scala index 09bbfe5e631..dacc9da0642 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/traits/Environment.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/traits/Environment.scala @@ -10,18 +10,8 @@ import monix.eval.Coeval import shapeless._ object Environment { - import io.circe.{Decoder, HCursor} - case class BalanceDetails(available: Long, regular: Long, generating: Long, effective: Long) - implicit val BalanceDetailsDecoder: Decoder[BalanceDetails] = (c: HCursor) => - for { - available <- c.downField("available").as[Long] - regular <- c.downField("regular").as[Long] - generating <- c.downField("generating").as[Long] - effective <- c.downField("effective").as[Long] - } yield BalanceDetails(available, regular, generating, effective) - type InputEntity = Tx :+: Ord :+: PseudoTx :+: CNil case class AssetId(id: Array[Byte]) diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/traits/domain/Tx.scala b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/traits/domain/Tx.scala index 959b26b77ca..5cf1e14be4f 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/traits/domain/Tx.scala +++ b/lang/shared/src/main/scala/com/wavesplatform/lang/v1/traits/domain/Tx.scala @@ -6,7 +6,7 @@ import com.wavesplatform.lang.v1.traits.domain.{Burn => BurnAction} case class TransferItem(recipient: Recipient, amount: Long) -trait Tx +sealed trait Tx sealed trait PseudoTx object Tx { diff --git a/lang/shared/src/main/scala/com/wavesplatform/utils/Merkle.scala b/lang/shared/src/main/scala/com/wavesplatform/utils/Merkle.scala deleted file mode 100644 index e4a69da802e..00000000000 --- a/lang/shared/src/main/scala/com/wavesplatform/utils/Merkle.scala +++ /dev/null @@ -1,67 +0,0 @@ -package com.wavesplatform.utils - -import com.wavesplatform.lang.v1.BaseGlobal -import scorex.crypto.authds.merkle.MerkleProof -import scorex.crypto.authds.{LeafData, Side} -import scorex.crypto.hash.{CryptographicHash, CryptographicHash32, Digest, Digest32} - -import scala.util.Try - -object Merkle { - - def verify(rootBytes: Array[Byte], proofBytes: Array[Byte], valueBytes: Array[Byte]): Boolean = { - (for { - rootDigest <- parseRoot(rootBytes) - merkleProof <- parseProof(proofBytes, valueBytes) - } yield merkleProof.valid(rootDigest)).getOrElse(false) - } - - def parseRoot(bytes: Array[Byte]): Option[Digest32] = { - if (bytes.length == 32) Some(Digest32 @@ bytes) - else None - } - - private def parseProof(proofBytes: Array[Byte], valueBytes: Array[Byte]): Option[MerkleProof[Digest32]] = - parseMerkleProofLevels(proofBytes).map { data => - MerkleProof[Digest32]( - LeafData @@ valueBytes, - data - )(blakeCH) - }.toOption - - def parseMerkleProofLevels(arr: Array[Byte]): Either[String, List[(Digest, Side)]] = { - def parseHashAndSide(arr: Array[Byte]): Either[String, (Side, Digest, Array[Byte])] = { - val side = - if (arr(0) == MerkleProof.LeftSide) MerkleProof.LeftSide - else MerkleProof.RightSide - val hashLen = arr(1).toInt - lazy val hash = Digest32 @@ arr.slice(2, 2 + hashLen) - - Either - .cond( - hashLen >= 0, - (side, hash, arr.drop(2 + hashLen)), - s"Invalid proof hash length: $hashLen" - ) - } - - def parseLevels(arr: Array[Byte], acc: List[(Digest, Side)]): Either[String, List[(Digest, Side)]] = { - if (arr.nonEmpty) { - parseHashAndSide(arr) - .flatMap { - case (side, hash, rest) => - parseLevels(rest, (hash, side) :: acc) - } - } else Right(acc.reverse) - } - - Try(parseLevels(arr, Nil)) - .getOrElse(Left("Can't parse proof bytes")) - } - - private val global: BaseGlobal = com.wavesplatform.lang.Global - private val blakeCH: CryptographicHash[Digest32] = - new CryptographicHash32 { - override def hash(input: Message): Digest32 = Digest32 @@ global.blake2b256(input) - } -} diff --git a/lang/shared/src/test/scala/com/wavesplatform/common/state/ByteStrTest.scala b/lang/shared/src/test/scala/com/wavesplatform/common/state/ByteStrTest.scala index 0b16aacf42a..2fc819bd93f 100644 --- a/lang/shared/src/test/scala/com/wavesplatform/common/state/ByteStrTest.scala +++ b/lang/shared/src/test/scala/com/wavesplatform/common/state/ByteStrTest.scala @@ -1,9 +1,9 @@ package com.wavesplatform.common.state import com.wavesplatform.common.utils.{Base58, Base64} -import org.scalatest.{Matchers, WordSpecLike} +import org.scalatest._ -class ByteStrTest extends Matchers with WordSpecLike { +class ByteStrTest extends wordspec.AnyWordSpec with matchers.should.Matchers { private def getSeqBytesArr(size: Int, from: Int = 1): Array[Byte] = (from until (from + size) map (_.toByte)).toArray diff --git a/lang/testkit/src/main/scala/com/wavesplatform/lang/Common.scala b/lang/testkit/src/main/scala/com/wavesplatform/lang/Common.scala index cbfded93f3a..ccaceae85db 100644 --- a/lang/testkit/src/main/scala/com/wavesplatform/lang/Common.scala +++ b/lang/testkit/src/main/scala/com/wavesplatform/lang/Common.scala @@ -3,8 +3,8 @@ package com.wavesplatform.lang import cats.Id import cats.kernel.Monoid import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.state.diffs.ProduceError import com.wavesplatform.lang.directives.values._ +import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.CTX import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.lang.v1.compiler.Types._ @@ -13,13 +13,10 @@ import com.wavesplatform.lang.v1.evaluator.EvaluatorV1 import com.wavesplatform.lang.v1.evaluator.EvaluatorV1._ import com.wavesplatform.lang.v1.evaluator.ctx._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.{EnvironmentFunctions, PureContext, _} +import com.wavesplatform.lang.v1.traits.domain.Recipient.Address import com.wavesplatform.lang.v1.traits.domain.{BlockInfo, Recipient, ScriptAssetInfo, Tx} import com.wavesplatform.lang.v1.traits.{DataType, Environment} -import com.wavesplatform.lang.v1.traits.domain.Recipient.Address -import com.wavesplatform.lang.ValidationError -import com.wavesplatform.lang.script.Script import monix.eval.Coeval -import org.scalacheck.ShrinkLowPriority import scala.util.{Left, Right, Try} @@ -36,10 +33,6 @@ object Common { ): Either[ExecutionError, T] = new EvaluatorV1[Id, NoContext]().apply[T](context, expr) - trait NoShrink extends ShrinkLowPriority - - def produce(errorMessage: String): ProduceError = new ProduceError(errorMessage) - val multiplierFunction: NativeFunction[NoContext] = NativeFunction("MULTIPLY", 1L, 10005.toShort, LONG, ("x1", LONG), ("x2", LONG)) { case CONST_LONG(x1: Long) :: CONST_LONG(x2: Long) :: Nil => Try(x1 * x2).map(CONST_LONG).toEither.left.map(_.toString) diff --git a/lang/testkit/src/main/scala/com/wavesplatform/common/state/diffs/ProduceError.scala b/lang/testkit/src/main/scala/com/wavesplatform/test/ProduceError.scala similarity index 81% rename from lang/testkit/src/main/scala/com/wavesplatform/common/state/diffs/ProduceError.scala rename to lang/testkit/src/main/scala/com/wavesplatform/test/ProduceError.scala index 853b2a4cb25..13c8e889feb 100644 --- a/lang/testkit/src/main/scala/com/wavesplatform/common/state/diffs/ProduceError.scala +++ b/lang/testkit/src/main/scala/com/wavesplatform/test/ProduceError.scala @@ -1,4 +1,4 @@ -package com.wavesplatform.common.state.diffs +package com.wavesplatform.test import org.scalatest.matchers.{MatchResult, Matcher} @@ -16,7 +16,3 @@ class ProduceError(errorMessage: String) extends Matcher[Either[_, _]] { } } } - -object ProduceError { - def produce(err: String): Matcher[Either[_, _]] = new ProduceError(err) -} diff --git a/lang/testkit/src/main/scala/com/wavesplatform/test/package.scala b/lang/testkit/src/main/scala/com/wavesplatform/test/package.scala new file mode 100644 index 00000000000..aad2da164ba --- /dev/null +++ b/lang/testkit/src/main/scala/com/wavesplatform/test/package.scala @@ -0,0 +1,11 @@ +package com.wavesplatform + +import org.scalatest.matchers.Matcher + +package object test { + implicit class NumericExt[N](val x: N) extends AnyVal { + def waves(implicit n: Numeric[N]): Long = (BigDecimal(n.toDouble(x)) * 1_0000_0000L).toLong + } + + def produce(err: String): Matcher[Either[_, _]] = new ProduceError(err) +} diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/ContextVersionTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/ContextVersionTest.scala index 9a0cc2b2918..bf729090511 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/ContextVersionTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/ContextVersionTest.scala @@ -2,9 +2,9 @@ package com.wavesplatform.lang import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.Types -import org.scalatest.{FreeSpec, Matchers} +import com.wavesplatform.test.FreeSpec -class ContextVersionTest extends FreeSpec with Matchers { +class ContextVersionTest extends FreeSpec { "InvokeScriptTransaction" - { "exist in lib version 3" in { diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/ContractIntegrationTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/ContractIntegrationTest.scala index 3a836687945..dd524d61d50 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/ContractIntegrationTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/ContractIntegrationTest.scala @@ -1,11 +1,11 @@ package com.wavesplatform.lang import cats.Id -import cats.implicits._ +import cats.syntax.semigroup._ +import cats.syntax.either._ import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.state.diffs.ProduceError._ import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.{NoShrink, sampleTypes} +import com.wavesplatform.lang.Common.sampleTypes import com.wavesplatform.lang.directives.DirectiveSet import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.v1.compiler.Terms._ @@ -15,15 +15,13 @@ import com.wavesplatform.lang.v1.evaluator._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.{Bindings, WavesContext} import com.wavesplatform.lang.v1.parser.Parser -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.traits.domain._ import com.wavesplatform.lang.v1.{CTX, FunctionHeader} -import com.wavesplatform.lang.Global -import org.scalatest.{Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ +import org.scalatest.Inside -class ContractIntegrationTest extends PropSpec with PropertyChecks with ScriptGen with Matchers with NoShrink with Inside { +class ContractIntegrationTest extends PropSpec with Inside { private val ctx: CTX[Environment] = PureContext.build(V3, fixUnicodeFunctions = true).withEnvironment[Environment] |+| diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/ContractParserTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/ContractParserTest.scala index 29be7fd5cc4..b59d4cf83ad 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/ContractParserTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/ContractParserTest.scala @@ -1,20 +1,18 @@ package com.wavesplatform.lang -import com.wavesplatform.lang.Common._ import com.wavesplatform.lang.v1.parser.Expressions.Pos.AnyPos import com.wavesplatform.lang.v1.parser.Expressions._ import com.wavesplatform.lang.v1.parser.{Expressions, Parser} import com.wavesplatform.lang.v1.testing.ScriptGenParser +import com.wavesplatform.test._ import fastparse.Parsed.{Failure, Success} import org.scalatest.exceptions.TestFailedException -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class ContractParserTest extends PropSpec with PropertyChecks with Matchers with ScriptGenParser with NoShrink { +class ContractParserTest extends PropSpec with ScriptGenParser { private def parse(x: String): DAPP = Parser.parseContract(x) match { case Success(r, _) => r - case f@Failure(_, _, _) => throw new TestFailedException(f.msg, 0) + case f: Failure => throw new TestFailedException(f.msg, 0) } private def cleanOffsets(l: LET): LET = diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/ContractSerdeTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/ContractSerdeTest.scala index 32eac798b2d..b9d10db262a 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/ContractSerdeTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/ContractSerdeTest.scala @@ -1,19 +1,17 @@ package com.wavesplatform.lang import com.google.protobuf.ByteString -import com.wavesplatform.common.state.diffs.ProduceError._ import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.NoShrink import com.wavesplatform.lang.contract.DApp._ import com.wavesplatform.lang.contract.{ContractSerDe, DApp} import com.wavesplatform.lang.v1.ContractLimits import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.protobuf.dapp.DAppMeta import com.wavesplatform.protobuf.dapp.DAppMeta.CallableFuncSignature -import org.scalatest.{Assertion, FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ +import org.scalatest.Assertion -class ContractSerdeTest extends FreeSpec with PropertyChecks with Matchers with NoShrink { +class ContractSerdeTest extends FreeSpec { def roundTrip(c: DApp): Assertion = { val bytes = ContractSerDe.serialize(c) diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/DirectiveParserTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/DirectiveParserTest.scala index a6c2ec725f2..897f0a41fe5 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/DirectiveParserTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/DirectiveParserTest.scala @@ -3,10 +3,9 @@ package com.wavesplatform.lang import com.wavesplatform.lang.directives.DirectiveKey._ import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.directives.{Directive, DirectiveParser} -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ -class DirectiveParserTest extends PropSpec with PropertyChecks with Matchers { +class DirectiveParserTest extends PropSpec { def parse(s: String): Either[ExecutionError, List[Directive]] = DirectiveParser(s) diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/EvaluatorV1CaseObjField.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/EvaluatorV1CaseObjField.scala index cd27b735793..8362e162aa9 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/EvaluatorV1CaseObjField.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/EvaluatorV1CaseObjField.scala @@ -11,11 +11,9 @@ import com.wavesplatform.lang.v1.evaluator.ctx.EvaluationContext._ import com.wavesplatform.lang.v1.evaluator.ctx._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext._ -import com.wavesplatform.lang.v1.testing.ScriptGen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class EvaluatorV1CaseObjField extends PropSpec with PropertyChecks with Matchers with ScriptGen with NoShrink { +class EvaluatorV1CaseObjField extends PropSpec { def context(p: CaseObj): EvaluationContext[NoContext, Id] = Monoid.combine(PureContext.build(V1, fixUnicodeFunctions = true).evaluationContext, sampleUnionContext(p)) diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/IntegrationTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/IntegrationTest.scala index 4933d02b1f3..dfe5577d635 100755 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/IntegrationTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/IntegrationTest.scala @@ -1,11 +1,14 @@ package com.wavesplatform.lang +import java.nio.charset.StandardCharsets + import cats.Id -import cats.implicits._ import cats.kernel.Monoid +import cats.syntax.either._ import com.google.common.io.BaseEncoding import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 +import com.wavesplatform.crypto.Keccak256 import com.wavesplatform.lang.Common._ import com.wavesplatform.lang.Testing._ import com.wavesplatform.lang.directives.DirectiveSet @@ -20,21 +23,17 @@ import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.WavesContext import com.wavesplatform.lang.v1.evaluator.ctx.impl.{PureContext, _} import com.wavesplatform.lang.v1.evaluator.{Contextful, ContextfulVal, EvaluatorV2} import com.wavesplatform.lang.v1.parser.Parser -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.traits.domain.Recipient.{Address, Alias} import com.wavesplatform.lang.v1.traits.domain.{Issue, Lease} import com.wavesplatform.lang.v1.{CTX, ContractLimits} -import org.scalatest.{Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ +import org.scalatest.Inside import org.web3j.crypto.Keys -import scorex.crypto.hash.Keccak256 -import scorex.util.encode.Base16 -import java.nio.charset.StandardCharsets import scala.util.{Random, Try} -class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with Matchers with NoShrink with Inside { +class IntegrationTest extends PropSpec with Inside { private def eval[T <: EVALUATED]( code: String, pointInstance: Option[CaseObj] = None, @@ -95,13 +94,13 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M val typed = ExpressionCompiler(ctx.compilerContext, untyped) val loggedCtx = LoggedEvaluationContext[C, Id](_ => _ => (), ctx.evaluationContext(env)) .asInstanceOf[LoggedEvaluationContext[Environment, Id]] - typed.flatMap(v => - Try(new EvaluatorV2(loggedCtx, version).apply(v._1, Int.MaxValue)._1.asInstanceOf[T]) - .toEither - .leftMap(_.getMessage) + typed.flatMap( + v => + Try(new EvaluatorV2(loggedCtx, version).apply(v._1, Int.MaxValue)._1.asInstanceOf[T]).toEither + .leftMap(_.getMessage) ) } - + private val v5Ctx = WavesContext.build(Global, DirectiveSet(V5, Account, DApp).explicitGet()) property("simple let") { @@ -1197,14 +1196,14 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M property("List[Int] median - list with big elements - error") { val src = - s"""[${Long.MaxValue}, ${Long.MaxValue-2}].median()""" - eval(src, version = V4) shouldBe Right(CONST_LONG(Long.MaxValue-1)) + s"""[${Long.MaxValue}, ${Long.MaxValue - 2}].median()""" + eval(src, version = V4) shouldBe Right(CONST_LONG(Long.MaxValue - 1)) } property("List[Int] median - list with MinValue - error") { val src = s"""[0, ${Long.MinValue}].median()""" - eval(src, version = V4) shouldBe Right(CONST_LONG(Long.MinValue/2)) + eval(src, version = V4) shouldBe Right(CONST_LONG(Long.MinValue / 2)) } property("groth16Verify") { @@ -1402,7 +1401,7 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M property("different Issue action constructors") { val script = - """ + """ | Issue("name", "description", 1234567, 100, true) == | Issue("name", "description", 1234567, 100, true, unit, 0) """.stripMargin @@ -1561,7 +1560,7 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M property("ecrecover positive cases") { def hash(message: String): String = { val prefix = "\u0019Ethereum Signed Message:\n" + message.length - Base16.encode(Keccak256.hash((prefix + message).getBytes)) + BaseEncoding.base16().lowerCase().encode(Keccak256.hash((prefix + message).getBytes)) } def recoverPublicKey(message: String, signature: String): Array[Byte] = { @@ -1572,22 +1571,22 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M //source: https://etherscan.io/verifySig/2006 val signature1 = "3b163bbd90556272b57c35d1185b46824f8e16ca229bdb3" + - "6f8dfd5eaaee9420723ef7bc3a6c0236568217aa990617c" + - "f292b1bef1e7d1d936fb2faef3d846c5751b" - val message1 = "what's up jim" + "6f8dfd5eaaee9420723ef7bc3a6c0236568217aa990617c" + + "f292b1bef1e7d1d936fb2faef3d846c5751b" + val message1 = "what's up jim" val expectedAddress1 = "85db9634489b76e238368e4a075cc6e5a56a714c" - Keys.getAddress(recoverPublicKey(message1, signature1)) shouldBe Base16.decode(expectedAddress1).get + Keys.getAddress(recoverPublicKey(message1, signature1)) shouldBe BaseEncoding.base16().lowerCase().decode(expectedAddress1) //source: https://etherscan.io/verifySig/2007 val signature2 = "848ffb6a07e7ce335a2bfe373f1c17573eac320f658ea8" + - "cf07426544f2203e9d52dbba4584b0b6c0ed5333d84074" + - "002878082aa938fdf68c43367946b2f615d01b" - val message2 = "i am the owner" + "cf07426544f2203e9d52dbba4584b0b6c0ed5333d84074" + + "002878082aa938fdf68c43367946b2f615d01b" + val message2 = "i am the owner" val expectedAddress2 = "73f32c743e5928ff800ab8b05a52c73cd485f9c3" - Keys.getAddress(recoverPublicKey(message2, signature2)) shouldBe Base16.decode(expectedAddress2).get + Keys.getAddress(recoverPublicKey(message2, signature2)) shouldBe BaseEncoding.base16().lowerCase().decode(expectedAddress2) } property("ecrecover negative cases") { @@ -1614,16 +1613,16 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M ("unit", "Unit") ) #::: getElement - /* Example for size = 2 - * - * let a = (true, 123) - * func f(x: (Boolean, Int)) == x - * - * let (a1, a2) = a - * a._1 == true && a1 == true && a._2 == 123 && a2 == 123 && - * a == (true, 123) && - * f(a) == a - */ + /* Example for size = 2 + * + * let a = (true, 123) + * func f(x: (Boolean, Int)) == x + * + * let (a1, a2) = a + * a._1 == true && a1 == true && a._2 == 123 && a2 == 123 && + * a == (true, 123) && + * f(a) == a + */ def check(size: Int) = { val valueDefinition = (1 to size).map(i => getElement(i)._1).mkString("(", ", ", ")") val typeDefinition = (1 to size).map(i => getElement(i)._2).mkString("(", ", ", ")") @@ -1737,10 +1736,10 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M ii } val src = lets ++ (if (i != 16) { - s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" - } else { - "bn256Groth16Verify(vk, proof, inputs)" - }) + s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" + } else { + "bn256Groth16Verify(vk, proof, inputs)" + }) eval(src, version = V4) shouldBe Right(CONST_BOOLEAN(false)) } } @@ -1786,10 +1785,10 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M ii } val src = lets ++ (if (i != 16) { - s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" - } else { - "bn256Groth16Verify(vk, proof, inputs)" - }) + s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" + } else { + "bn256Groth16Verify(vk, proof, inputs)" + }) eval(src, version = V4) shouldBe Right(CONST_BOOLEAN(true)) } } @@ -1797,10 +1796,10 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M property("bn256Groth16Verify_*inputs fail if too many inputs") { for ((i, lets) <- bn256GrothsFail ++ bn256GrothsOk if (i > 1)) { val src = lets ++ (if (i <= 16) { - s"bn256Groth16Verify_${i - 1}inputs(vk, proof, inputs)" - } else { - "bn256Groth16Verify(vk, proof, inputs)" - }) + s"bn256Groth16Verify_${i - 1}inputs(vk, proof, inputs)" + } else { + "bn256Groth16Verify(vk, proof, inputs)" + }) eval(src, version = V4) shouldBe Left(s"Invalid inputs size ${i * 32} bytes, must be not greater than ${i * 32 - 32} bytes") } } @@ -1821,17 +1820,17 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M ii } val src = lets ++ (if (i != 16) { - s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" - } else { - "bn256Groth16Verify(vk, proof, inputs)" - }) + s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" + } else { + "bn256Groth16Verify(vk, proof, inputs)" + }) eval(src, version = V4) shouldBe Left(s"Invalid vk size ${n} bytes, must be equal to ${(8 + ii) * 32} bytes for ${ii} inputs") } } property("bn256Groth16Verify_*inputs with invalid proof size") { def lets(proofSize: Int) = - s""" + s""" |let vk = base64'mY//hEITCBCZUJUN/wsOlw1iUSSOESL6PFSbN1abGK80t5jPNICNlPuSorio4mmWpf+4uOyv3gPZe54SYGM4pfhteqJpwFQxdlpwXWyYxMTNaSLDj8VtSn/EJaSu+P6nFmWsda3mTYUPYMZzWE4hMqpDgFPcJhw3prArMThDPbR3Hx7E6NRAAR0LqcrdtsbDqu2T0tto1rpnFILdvHL4PqEUfTmF2mkM+DKj7lKwvvZUbukqBwLrnnbdfyqZJryzGAMIa2JvMEMYszGsYyiPXZvYx6Luk54oWOlOrwEKrCY4NMPwch6DbFq6KpnNSQwOpgRYCz7wpjk57X+NGJmo85tYKc+TNa1rT4/DxG9v6SHkpXmmPeHhzIIW8MOdkFjxB5o6Qn8Fa0c6Tt6br2gzkrGr1eK5/+RiIgEzVhcRrqdY/p7PLmKXqawrEvIv9QZ3ijytPNwinlC8XdRLO/YvP33PjcI9WSMcHV6POP9KPMo1rngaIPMegKgAvTEouNFKp4v3wAXRXX5xEjwXAmM5wyB/SAOaPPCK/emls9kqolHsaj7nuTTbrvSV8bqzUwzQ' |let proof = base64'${ByteStr.fill(proofSize)(1).base64}' |let inputs = base64'aZ8tqrOeEJKt4AMqiRF/WJhIKTDC0HeDTgiJVLZ8OEs=' @@ -1843,10 +1842,10 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M ii } val src = lets(proofSize) ++ (if (i != 16) { - s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" - } else { - "bn256Groth16Verify(vk, proof, inputs)" - }) + s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" + } else { + "bn256Groth16Verify(vk, proof, inputs)" + }) eval(src, version = V4) shouldBe Left(s"Invalid proof size $proofSize bytes, must be equal to 128 bytes") } } @@ -1865,10 +1864,10 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M ii } val src = lets ++ (if (i != 16) { - s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" - } else { - "bn256Groth16Verify(vk, proof, inputs)" - }) + s"bn256Groth16Verify_${i}inputs(vk, proof, inputs)" + } else { + "bn256Groth16Verify(vk, proof, inputs)" + }) eval(src, version = V4) shouldBe Left("Invalid inputs size 33 bytes, must be a multiple of 32 bytes") } } @@ -1905,7 +1904,9 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M } property("Union with multiple List") { - eval("""match (if false then 2 else if true then [3] else ["qqq"]) { case n: Int => n case a => a[0] }""", version = V4) shouldBe Right(CONST_LONG(3)) + eval("""match (if false then 2 else if true then [3] else ["qqq"]) { case n: Int => n case a => a[0] }""", version = V4) shouldBe Right( + CONST_LONG(3) + ) } property("Any type") { @@ -1963,7 +1964,8 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M } property("default type") { - eval("""func f(x: Int| String) = { + eval( + """func f(x: Int| String) = { match x { case i: Int => 1 case v => @@ -1973,7 +1975,9 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M } } } - f("q")""", version = V4) shouldBe Symbol("Left") + f("q")""", + version = V4 + ) shouldBe Symbol("Left") } property("different Lease action constructors") { @@ -1984,8 +1988,8 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M property("calculateLeaseId") { val txId = ByteStr.decodeBase58("aaaa").get - val id1 = Lease.calculateId(Lease(Address(ByteStr.decodeBase58("bbbb").get), 1234567, 123), txId) - val id2 = Lease.calculateId(Lease(Alias("alias"), 9876, 100), txId) + val id1 = Lease.calculateId(Lease(Address(ByteStr.decodeBase58("bbbb").get), 1234567, 123), txId) + val id2 = Lease.calculateId(Lease(Alias("alias"), 9876, 100), txId) val script = s""" | calculateLeaseId(Lease(Address(base58'bbbb'), 1234567, 123)) == base58'$id1' && @@ -1997,8 +2001,8 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M } property("calculateLeaseId restrictions") { - val script1 = s" calculateLeaseId(Lease(Address(base58'${"a"* 36}'), 1234567, 123)) " - val script2 = s""" calculateLeaseId(Lease(Alias("${"a"* 31}"), 1234567, 123)) """ + val script1 = s" calculateLeaseId(Lease(Address(base58'${"a" * 36}'), 1234567, 123)) " + val script2 = s""" calculateLeaseId(Lease(Alias("${"a" * 31}"), 1234567, 123)) """ genericEval[Environment, EVALUATED](script1, ctxt = v5Ctx, version = V5, env = utils.environment) should produce("Address bytes length=27 exceeds limit=26") @@ -2006,7 +2010,7 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M produce("Alias name length=31 exceeds limit=30") } - property("integer case") { + property("integer case") { val sampleScript = """match 2 { | case 1 => 7 @@ -2044,7 +2048,7 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M |} | """.stripMargin - eval[EVALUATED](sampleScript, version=V4) shouldBe evaluated(5) + eval[EVALUATED](sampleScript, version = V4) shouldBe evaluated(5) } property("typed tuple destruct") { @@ -2057,7 +2061,7 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M |} | """.stripMargin - eval[EVALUATED](sampleScript, version=V4) shouldBe evaluated("qqq") + eval[EVALUATED](sampleScript, version = V4) shouldBe evaluated("qqq") } property("caseType destruct") { @@ -2118,11 +2122,15 @@ class IntegrationTest extends PropSpec with PropertyChecks with ScriptGen with M """.stripMargin eval(script2) should produce("value() called on unit value on function 'a' call") - val ctx = WavesContext.build(Global, DirectiveSet(V4, Account, DApp).explicitGet()) + val ctx = WavesContext.build(Global, DirectiveSet(V4, Account, DApp).explicitGet()) val script3 = "SponsorFee(base58'', unit).minSponsoredAssetFee.value()" - genericEval(script3, ctxt = ctx, version = V4, env = utils.environment) should produce("value() called on unit value while accessing field 'minSponsoredAssetFee'") + genericEval(script3, ctxt = ctx, version = V4, env = utils.environment) should produce( + "value() called on unit value while accessing field 'minSponsoredAssetFee'" + ) val script4 = """ getIntegerValue(Address(base58''), "") """ - genericEval(script4, ctxt = ctx, version = V4, env = utils.environment) should produce("value() called on unit value on function 'getInteger' call") + genericEval(script4, ctxt = ctx, version = V4, env = utils.environment) should produce( + "value() called on unit value on function 'getInteger' call" + ) eval("(if (true) then unit else 7).value()") should produce("value() called on unit value after condition evaluation") eval("(let a = 1; if (true) then unit else 7).value()") should produce("value() called on unit value after let block evaluation") diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/ObjectTypesTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/ObjectTypesTest.scala index e9042bb4742..9bf77ede17f 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/ObjectTypesTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/ObjectTypesTest.scala @@ -2,16 +2,14 @@ package com.wavesplatform.lang import com.wavesplatform.DocSource import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.NoShrink import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.directives.{DirectiveDictionary, DirectiveSet} import com.wavesplatform.lang.utils._ import com.wavesplatform.lang.v1.compiler.Types.CASETYPEREF +import com.wavesplatform.test._ import org.scalatest.exceptions.TestFailedException -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class ObjectTypesTest extends PropSpec with PropertyChecks with Matchers with NoShrink { +class ObjectTypesTest extends PropSpec { private val directives: Iterable[DirectiveSet] = DirectiveDictionary[StdLibVersion].all .map(version => DirectiveSet(version, Account, Expression).explicitGet()) diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/ParserV2DAppTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/ParserV2DAppTest.scala index ed2ebca0a7f..4ac5465f3ea 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/ParserV2DAppTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/ParserV2DAppTest.scala @@ -1,15 +1,12 @@ package com.wavesplatform.lang -import com.wavesplatform.lang.Common.NoShrink import com.wavesplatform.lang.v1.parser.Expressions.Pos.AnyPos import com.wavesplatform.lang.v1.parser.Expressions._ import com.wavesplatform.lang.v1.parser.{Expressions, Parser, ParserV2} -import com.wavesplatform.lang.v1.testing.ScriptGenParser +import com.wavesplatform.test._ import org.scalatest.exceptions.TestFailedException -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class ParserV2DAppTest extends PropSpec with PropertyChecks with Matchers with ScriptGenParser with NoShrink { +class ParserV2DAppTest extends PropSpec { private def parse(x: String): DAPP = ParserV2.parseDAPP(x) match { case Right((parsedScript, _)) => parsedScript diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/ParserV2ScriptTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/ParserV2ScriptTest.scala index c1a366c6d8b..472f13c863c 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/ParserV2ScriptTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/ParserV2ScriptTest.scala @@ -1,19 +1,16 @@ package com.wavesplatform.lang import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.lang.Common.NoShrink +import com.wavesplatform.common.utils.Base58 import com.wavesplatform.lang.v1.parser.BinaryOperation._ import com.wavesplatform.lang.v1.parser.Expressions.Pos.AnyPos import com.wavesplatform.lang.v1.parser.Expressions._ import com.wavesplatform.lang.v1.parser.{BinaryOperation, Parser, ParserV2} -import com.wavesplatform.lang.v1.testing.ScriptGenParser +import com.wavesplatform.test._ import fastparse.Parsed.Success import org.scalatest.exceptions.TestFailedException -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -import scorex.util.encode.{Base58 => ScorexBase58} -class ParserV2ScriptTest extends PropSpec with PropertyChecks with Matchers with ScriptGenParser with NoShrink { +class ParserV2ScriptTest extends PropSpec { private def parse(x: String): EXPR = ParserV2.parseExpression(x) match { case Right((parsedScript, _)) => @@ -51,9 +48,9 @@ class ParserV2ScriptTest extends PropSpec with PropertyChecks with Matchers with AnyPos, PART.VALID(AnyPos, "sigVerify"), List( - CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(ScorexBase58.decode("333").get))), - CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(ScorexBase58.decode("222").get))), - CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(ScorexBase58.decode("111").get))) + CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(Base58.decode("333")))), + CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(Base58.decode("222")))), + CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(Base58.decode("111")))) ) ) ) @@ -175,7 +172,10 @@ class ParserV2ScriptTest extends PropSpec with PropertyChecks with Matchers with AnyPos, CONST_LONG(AnyPos, 42), PART.VALID(AnyPos, "q"), - Seq((PART.VALID(AnyPos, "x"), Single(PART.VALID(AnyPos, "Int"), None)), (PART.VALID(AnyPos, "y"), Single(PART.VALID(AnyPos, "Boolean"), None))) + Seq( + (PART.VALID(AnyPos, "x"), Single(PART.VALID(AnyPos, "Int"), None)), + (PART.VALID(AnyPos, "y"), Single(PART.VALID(AnyPos, "Boolean"), None)) + ) ), REF(AnyPos, PART.VALID(AnyPos, "c")) ) @@ -514,7 +514,7 @@ class ParserV2ScriptTest extends PropSpec with PropertyChecks with Matchers with property("crypto functions: sha256") { val text = "❤✓☀★☂♞☯☭☢€☎∞❄♫\u20BD=test message" - val encodedText = ScorexBase58.encode(text.getBytes("UTF-8")) + val encodedText = Base58.encode(text.getBytes("UTF-8")) parse(s"sha256(base58'$encodedText')".stripMargin) shouldBe FUNCTION_CALL( @@ -526,7 +526,7 @@ class ParserV2ScriptTest extends PropSpec with PropertyChecks with Matchers with property("crypto functions: blake2b256") { val text = "❤✓☀★☂♞☯☭☢€☎∞❄♫\u20BD=test message" - val encodedText = ScorexBase58.encode(text.getBytes("UTF-8")) + val encodedText = Base58.encode(text.getBytes("UTF-8")) parse(s"blake2b256(base58'$encodedText')".stripMargin) shouldBe FUNCTION_CALL(AnyPos, PART.VALID(AnyPos, "blake2b256"), List(CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(text.getBytes("UTF-8")))))) @@ -534,7 +534,7 @@ class ParserV2ScriptTest extends PropSpec with PropertyChecks with Matchers with property("crypto functions: keccak256") { val text = "❤✓☀★☂♞☯☭☢€☎∞❄♫\u20BD=test message" - val encodedText = ScorexBase58.encode(text.getBytes("UTF-8")) + val encodedText = Base58.encode(text.getBytes("UTF-8")) parse(s"keccak256(base58'$encodedText')".stripMargin) shouldBe FUNCTION_CALL(AnyPos, PART.VALID(AnyPos, "keccak256"), List(CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(text.getBytes("UTF-8")))))) diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/ScriptParserTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/ScriptParserTest.scala index 26bbf6076e3..1d6b9fa564c 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/ScriptParserTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/ScriptParserTest.scala @@ -1,24 +1,22 @@ package com.wavesplatform.lang import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.lang.Common._ +import com.wavesplatform.common.utils.Base58 import com.wavesplatform.lang.v1.parser.BinaryOperation._ import com.wavesplatform.lang.v1.parser.Expressions.Pos.AnyPos import com.wavesplatform.lang.v1.parser.Expressions._ import com.wavesplatform.lang.v1.parser.{BinaryOperation, Expressions, Parser} import com.wavesplatform.lang.v1.testing.ScriptGenParser +import com.wavesplatform.test._ import fastparse.Parsed.{Failure, Success} import org.scalacheck.Gen import org.scalatest.exceptions.TestFailedException -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -import scorex.util.encode.{Base58 => ScorexBase58} -class ScriptParserTest extends PropSpec with PropertyChecks with Matchers with ScriptGenParser with NoShrink { +class ScriptParserTest extends PropSpec with ScriptGenParser { private def parse(x: String): EXPR = Parser.parseExpr(x) match { case Success(r, _) => r - case f@Failure(_, _, _) => throw new TestFailedException(f.msg, 0) + case f: Failure => throw new TestFailedException(f.msg, 0) } private def cleanOffsets(l: LET): LET = @@ -110,9 +108,9 @@ class ScriptParserTest extends PropSpec with PropertyChecks with Matchers with S AnyPos, PART.VALID(AnyPos, "sigVerify"), List( - CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(ScorexBase58.decode("333").get))), - CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(ScorexBase58.decode("222").get))), - CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(ScorexBase58.decode("111").get))) + CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(Base58.decode("333")))), + CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(Base58.decode("222")))), + CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(Base58.decode("111")))) ) ) ) @@ -573,7 +571,7 @@ class ScriptParserTest extends PropSpec with PropertyChecks with Matchers with S property("crypto functions: sha256") { val text = "❤✓☀★☂♞☯☭☢€☎∞❄♫\u20BD=test message" - val encodedText = ScorexBase58.encode(text.getBytes("UTF-8")) + val encodedText = Base58.encode(text.getBytes("UTF-8")) parse(s"sha256(base58'$encodedText')".stripMargin) shouldBe FUNCTION_CALL( @@ -585,7 +583,7 @@ class ScriptParserTest extends PropSpec with PropertyChecks with Matchers with S property("crypto functions: blake2b256") { val text = "❤✓☀★☂♞☯☭☢€☎∞❄♫\u20BD=test message" - val encodedText = ScorexBase58.encode(text.getBytes("UTF-8")) + val encodedText = Base58.encode(text.getBytes("UTF-8")) parse(s"blake2b256(base58'$encodedText')".stripMargin) shouldBe FUNCTION_CALL(AnyPos, PART.VALID(AnyPos, "blake2b256"), List(CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(text.getBytes("UTF-8")))))) @@ -593,7 +591,7 @@ class ScriptParserTest extends PropSpec with PropertyChecks with Matchers with S property("crypto functions: keccak256") { val text = "❤✓☀★☂♞☯☭☢€☎∞❄♫\u20BD=test message" - val encodedText = ScorexBase58.encode(text.getBytes("UTF-8")) + val encodedText = Base58.encode(text.getBytes("UTF-8")) parse(s"keccak256(base58'$encodedText')".stripMargin) shouldBe FUNCTION_CALL(AnyPos, PART.VALID(AnyPos, "keccak256"), List(CONST_BYTESTR(AnyPos, PART.VALID(AnyPos, ByteStr(text.getBytes("UTF-8")))))) diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/ScriptPreprocessorTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/ScriptPreprocessorTest.scala index 4c5d5fbf7a5..cfd5dee047e 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/ScriptPreprocessorTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/ScriptPreprocessorTest.scala @@ -2,7 +2,6 @@ package com.wavesplatform.lang import cats.Id import cats.kernel.Monoid -import com.wavesplatform.lang.Common.NoShrink import com.wavesplatform.lang.directives.values.V3 import com.wavesplatform.lang.directives.{Directive, DirectiveParser} import com.wavesplatform.lang.script.ScriptPreprocessor @@ -15,10 +14,9 @@ import com.wavesplatform.lang.v1.evaluator.EvaluatorV1._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.lang.v1.testing.ScriptGenParser -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ -class ScriptPreprocessorTest extends PropSpec with PropertyChecks with Matchers with ScriptGenParser with NoShrink { +class ScriptPreprocessorTest extends PropSpec with ScriptGenParser { private val evaluator = new EvaluatorV1[Id, NoContext]() private def processAndEval(src: String, libraries: Map[String, String]): Either[ExecutionError, EVALUATED] = diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/SerdeTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/SerdeTest.scala index 0690e86d5b0..3950a3caa3a 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/SerdeTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/SerdeTest.scala @@ -4,23 +4,21 @@ import java.nio.charset.StandardCharsets import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common._ import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.compiler.Terms._ -import com.wavesplatform.lang.v1.compiler.{ExpressionCompiler, Terms} import com.wavesplatform.lang.v1.compiler.Types.CASETYPEREF +import com.wavesplatform.lang.v1.compiler.{ExpressionCompiler, Terms} import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext import com.wavesplatform.lang.v1.parser.Expressions -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.{FunctionHeader, Serde} +import com.wavesplatform.test._ import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.{Assertion, FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.Assertion import scala.util.Try -class SerdeTest extends FreeSpec with PropertyChecks with Matchers with ScriptGen with NoShrink { +class SerdeTest extends FreeSpec { private val caseObj = CaseObj( CASETYPEREF("Object type", Nil), diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/SmartConstructorTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/SmartConstructorTest.scala index 6803bcaba35..8718eb71013 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/SmartConstructorTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/SmartConstructorTest.scala @@ -3,9 +3,10 @@ package com.wavesplatform.lang import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, CONST_STRING} -import org.scalatest.{Inside, Matchers, PropSpec} +import com.wavesplatform.test.PropSpec +import org.scalatest.Inside -class SmartConstructorTest extends PropSpec with Matchers with Inside { +class SmartConstructorTest extends PropSpec with Inside { property("CONST_BYTESTR size limit") { val allowedBytes = ByteStr.fill(Terms.DataEntryValueMax)(1) inside(CONST_BYTESTR(allowedBytes)) { diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/TypeInferrerTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/TypeInferrerTest.scala index a146d9e150d..064b3eaa6b1 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/TypeInferrerTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/TypeInferrerTest.scala @@ -1,11 +1,10 @@ package com.wavesplatform.lang -import com.wavesplatform.lang.v1.compiler.Types._ -import org.scalatest.{FreeSpec, Matchers} -import Common._ import com.wavesplatform.lang.v1.compiler.TypeInferrer +import com.wavesplatform.lang.v1.compiler.Types._ +import com.wavesplatform.test._ -class TypeInferrerTest extends FreeSpec with Matchers { +class TypeInferrerTest extends FreeSpec { val typeparamT = TYPEPARAM('T') val typeparamG = TYPEPARAM('G') diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerCompactorTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerCompactorTest.scala index b0f59ae206f..cf4da723f70 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerCompactorTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerCompactorTest.scala @@ -1,9 +1,8 @@ package com.wavesplatform.lang.compiler -import cats.implicits._ +import cats.syntax.semigroup._ import com.google.protobuf.ByteString import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.NoShrink import com.wavesplatform.lang.Global import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.contract.DApp._ @@ -17,14 +16,12 @@ import com.wavesplatform.lang.v1.compiler.{ContractScriptCompactor, Terms} import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.{FieldNames, WavesContext} import com.wavesplatform.lang.v1.parser.Parser -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.protobuf.dapp.DAppMeta import com.wavesplatform.protobuf.dapp.DAppMeta.{CallableFuncSignature, CompactNameAndOriginalNamePair} -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ -class ContractCompilerCompactorTest extends PropSpec with PropertyChecks with Matchers with ScriptGen with NoShrink { +class ContractCompilerCompactorTest extends PropSpec { property("contract script compaction - V4, V5") { val script = """ diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerTest.scala index e3a6f9c4c52..9f031c42ab6 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerTest.scala @@ -1,11 +1,10 @@ package com.wavesplatform.lang.compiler -import cats.implicits._ import cats.kernel.Monoid +import cats.syntax.semigroup._ import com.google.protobuf.ByteString import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.{NoShrink, produce} import com.wavesplatform.lang.Global import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.contract.DApp._ @@ -19,15 +18,13 @@ import com.wavesplatform.lang.v1.evaluator.FunctionIds import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.{FieldNames, Types, WavesContext} import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, PureContext} import com.wavesplatform.lang.v1.parser.Parser -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.{ContractLimits, compiler} import com.wavesplatform.protobuf.dapp.DAppMeta import com.wavesplatform.protobuf.dapp.DAppMeta.CallableFuncSignature -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ -class ContractCompilerTest extends PropSpec with PropertyChecks with Matchers with ScriptGen with NoShrink { +class ContractCompilerTest extends PropSpec { private val dAppV3Ctx: CompilerContext = Monoid .combineAll( diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerWithParserV2Test.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerWithParserV2Test.scala index 750f6bdae00..9c328ee1791 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerWithParserV2Test.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ContractCompilerWithParserV2Test.scala @@ -1,16 +1,14 @@ package com.wavesplatform.lang.compiler -import com.wavesplatform.lang.Common.NoShrink import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.directives.values.Imports import com.wavesplatform.lang.directives.{Directive, DirectiveParser} import com.wavesplatform.lang.utils.lazyContexts import com.wavesplatform.lang.v1.compiler.{CompilationError, ContractCompiler} import com.wavesplatform.lang.v1.parser.Expressions -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class ContractCompilerWithParserV2Test extends PropSpec with PropertyChecks with Matchers with NoShrink { +class ContractCompilerWithParserV2Test extends PropSpec { def compile(script: String, saveExprContext: Boolean = false): Either[String, (Option[DApp], Expressions.DAPP, Iterable[CompilationError])] = { diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/DecompilerTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/DecompilerTest.scala index 7adf5e2cf15..53389bebf78 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/DecompilerTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/DecompilerTest.scala @@ -19,10 +19,9 @@ import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.{FunctionHeader, compiler} import com.wavesplatform.protobuf.dapp.DAppMeta -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class DecompilerTest extends PropSpec with PropertyChecks with Matchers { +class DecompilerTest extends PropSpec { val sp = "\\s+".r implicit class StringCmp(s1: String) { diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ErrorTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ErrorTest.scala index a0002f80849..74fc4910506 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ErrorTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ErrorTest.scala @@ -1,16 +1,14 @@ package com.wavesplatform.lang.compiler import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.lang.Common.{NoShrink, multiplierFunction, produce} +import com.wavesplatform.lang.Common.multiplierFunction import com.wavesplatform.lang.v1.compiler.ExpressionCompiler import com.wavesplatform.lang.v1.parser.BinaryOperation.SUM_OP import com.wavesplatform.lang.v1.parser.Expressions import com.wavesplatform.lang.v1.parser.Expressions.Pos.AnyPos -import com.wavesplatform.lang.v1.testing.ScriptGen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ -class ErrorTest extends PropSpec with PropertyChecks with Matchers with ScriptGen with NoShrink { +class ErrorTest extends PropSpec { import com.wavesplatform.lang.v1.parser.Expressions._ diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ExpressionCompilerV1Test.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ExpressionCompilerV1Test.scala index 13c901fe2fe..f43a2365d59 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ExpressionCompilerV1Test.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ExpressionCompilerV1Test.scala @@ -19,16 +19,14 @@ import com.wavesplatform.lang.v1.parser.BinaryOperation.SUM_OP import com.wavesplatform.lang.v1.parser.Expressions.Pos import com.wavesplatform.lang.v1.parser.Expressions.Pos.AnyPos import com.wavesplatform.lang.v1.parser.{Expressions, Parser} -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.{ContractLimits, FunctionHeader, compiler} import com.wavesplatform.lang.{Common, Global} -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ import scala.util.Try -class ExpressionCompilerV1Test extends PropSpec with PropertyChecks with Matchers with ScriptGen with NoShrink { +class ExpressionCompilerV1Test extends PropSpec { property("should infer generic function return type") { import com.wavesplatform.lang.v1.parser.Expressions._ diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ExpressionCompilerWithParserV2Test.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ExpressionCompilerWithParserV2Test.scala index 56e44cd726e..1d109964f30 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ExpressionCompilerWithParserV2Test.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/ExpressionCompilerWithParserV2Test.scala @@ -1,7 +1,6 @@ package com.wavesplatform.lang.compiler import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common._ import com.wavesplatform.lang.directives.values.Imports import com.wavesplatform.lang.directives.{Directive, DirectiveParser} import com.wavesplatform.lang.utils.lazyContexts @@ -10,10 +9,9 @@ import com.wavesplatform.lang.v1.compiler.Types._ import com.wavesplatform.lang.v1.parser.Expressions import com.wavesplatform.lang.v1.parser.Expressions.Pos.AnyPos import com.wavesplatform.lang.v1.parser.Expressions._ -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class ExpressionCompilerWithParserV2Test extends PropSpec with PropertyChecks with Matchers with NoShrink { +class ExpressionCompilerWithParserV2Test extends PropSpec { def compile(script: String, saveExprContext: Boolean = false): Either[String, Expressions.EXPR] = { diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/MetaTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/MetaTest.scala index b3d6ed0d722..363c9c2e117 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/MetaTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/MetaTest.scala @@ -3,7 +3,7 @@ package com.wavesplatform.lang.compiler import cats.kernel.Monoid import com.google.protobuf.ByteString import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.NoShrink +import com.wavesplatform.lang.Global import com.wavesplatform.lang.contract.meta.{MetaMapper, ParsedMeta} import com.wavesplatform.lang.directives.DirectiveSet import com.wavesplatform.lang.directives.values.{Account, V3, V4, DApp => DAppType} @@ -11,14 +11,12 @@ import com.wavesplatform.lang.v1.compiler import com.wavesplatform.lang.v1.compiler.Types._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.WavesContext import com.wavesplatform.lang.v1.parser.Parser -import com.wavesplatform.lang.Global -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.protobuf.dapp.DAppMeta import com.wavesplatform.protobuf.dapp.DAppMeta.CallableFuncSignature -import org.scalatest.{Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ +import org.scalatest.Inside -class MetaTest extends PropSpec with PropertyChecks with Matchers with ScriptGen with NoShrink with Inside { +class MetaTest extends PropSpec with Inside { property("meta v1 with union type parameters") { val ctx = Monoid.combine( compilerContext, diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/names/NameDuplicationTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/names/NameDuplicationTest.scala index c32ece7224a..a5208ebebd1 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/names/NameDuplicationTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/compiler/names/NameDuplicationTest.scala @@ -2,7 +2,7 @@ package com.wavesplatform.lang.compiler.names import cats.kernel.Monoid import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.{NoShrink, produce} +import com.wavesplatform.lang.Global import com.wavesplatform.lang.compiler.compilerContext import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.directives.DirectiveSet @@ -11,13 +11,10 @@ import com.wavesplatform.lang.v1.compiler import com.wavesplatform.lang.v1.compiler.CompilerContext import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.WavesContext import com.wavesplatform.lang.v1.parser.Parser -import com.wavesplatform.lang.Global -import com.wavesplatform.lang.v1.testing.ScriptGen +import com.wavesplatform.test._ import org.scalacheck.Gen -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class NameDuplicationTest extends FreeSpec with PropertyChecks with Matchers with ScriptGen with NoShrink { +class NameDuplicationTest extends FreeSpec { val ctx: CompilerContext = Monoid.combine( diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/doc/DocExportTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/doc/DocExportTest.scala index 1fafee0f69e..1ebba3591c8 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/doc/DocExportTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/doc/DocExportTest.scala @@ -1,6 +1,6 @@ package com.wavesplatform.lang.doc -import cats.implicits._ +import cats.syntax.semigroup._ import com.wavesplatform.DocSource import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.lang.Global @@ -10,10 +10,9 @@ import com.wavesplatform.lang.v1.CTX import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.WavesContext import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, PureContext} import com.wavesplatform.lang.v1.traits.Environment -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ -class DocExportTest extends PropSpec with PropertyChecks with Matchers { +class DocExportTest extends PropSpec { def buildFullContext(ds: DirectiveSet): CTX[Environment] = { val wavesCtx = WavesContext.build(Global, ds) diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/BigIntTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/BigIntTest.scala index ad1f541cfea..972ffa636da 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/BigIntTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/BigIntTest.scala @@ -1,10 +1,10 @@ package com.wavesplatform.lang.evaluator import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.produce import com.wavesplatform.lang.directives.values.{StdLibVersion, V5} import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BIGINT, CONST_BOOLEAN, CONST_LONG, CONST_STRING} import com.wavesplatform.lang.v1.evaluator.ctx.impl.{PureContext, unit} +import com.wavesplatform.test.produce import scala.math.BigDecimal.RoundingMode._ import scala.util.Random diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorSpec.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorSpec.scala index 9a43720ff17..682bfdb1179 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorSpec.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorSpec.scala @@ -1,7 +1,6 @@ package com.wavesplatform.lang.evaluator import com.wavesplatform.lang.Common -import com.wavesplatform.lang.Common.NoShrink import com.wavesplatform.lang.directives.DirectiveDictionary import com.wavesplatform.lang.directives.values.{StdLibVersion, V1} import com.wavesplatform.lang.v1.compiler.ExpressionCompiler @@ -11,11 +10,11 @@ import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext import com.wavesplatform.lang.v1.parser.{Expressions, Parser} import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.traits.Environment -import org.scalatest.{Inside, Matchers, PropSpec} +import com.wavesplatform.test.PropSpec +import org.scalatest.Inside import org.scalatest.exceptions.TestFailedException -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -abstract class EvaluatorSpec extends PropSpec with ScalaCheckPropertyChecks with ScriptGen with Matchers with NoShrink with Inside { +abstract class EvaluatorSpec extends PropSpec with ScriptGen with Inside { def eval(code: String)(implicit startVersion: StdLibVersion = V1, checkNext: Boolean = true): Either[String, EVALUATED] = { val parsedExpr = Parser.parseExpr(code).get.value val results = DirectiveDictionary[StdLibVersion].all diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorV1V2Test.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorV1V2Test.scala index 21be547bf07..c25c2df2c5c 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorV1V2Test.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorV1V2Test.scala @@ -1,12 +1,15 @@ package com.wavesplatform.lang.evaluator +import java.nio.ByteBuffer + import cats.Id import cats.data.EitherT -import cats.implicits._ import cats.kernel.Monoid +import cats.syntax.bifunctor._ import com.google.common.io.BaseEncoding import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, Base64, EitherExt2} +import com.wavesplatform.crypto._ import com.wavesplatform.lang.Common._ import com.wavesplatform.lang.Testing._ import com.wavesplatform.lang.directives.values._ @@ -24,19 +27,15 @@ import com.wavesplatform.lang.v1.evaluator.ctx.impl.converters._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.WavesContext import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, EnvironmentFunctions, PureContext, _} import com.wavesplatform.lang.v1.evaluator.{Contextful, ContextfulVal, EvaluatorV1, EvaluatorV2, FunctionIds, Log} -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.{CTX, ContractLimits, FunctionHeader} import com.wavesplatform.lang.{Common, EvalF, ExecutionError, Global} +import com.wavesplatform.test._ import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -import scorex.crypto.hash.{Blake2b256, Keccak256, Sha256} -import scorex.crypto.signatures.{Curve25519, PublicKey, Signature} +import org.scalatest.EitherValues -import java.nio.ByteBuffer -class EvaluatorV1V2Test extends PropSpec with PropertyChecks with Matchers with ScriptGen with NoShrink with EitherValues { +class EvaluatorV1V2Test extends PropSpec with EitherValues { implicit val version: StdLibVersion = V4 @@ -439,7 +438,7 @@ class EvaluatorV1V2Test extends PropSpec with PropertyChecks with Matchers with val (_, publicKey) = Curve25519.createKeyPair(seed) val bodyBytes = "message".getBytes("UTF-8") - val r = sigVerifyTest(bodyBytes, publicKey, Signature("signature".getBytes("UTF-8"))) + val r = sigVerifyTest(bodyBytes, publicKey, "signature".getBytes("UTF-8")) r.isLeft shouldBe false } @@ -794,7 +793,7 @@ class EvaluatorV1V2Test extends PropSpec with PropertyChecks with Matchers with } } - private def sigVerifyTest(bodyBytes: Array[Byte], publicKey: PublicKey, signature: Signature, lim_n: Option[Short] = None)( + private def sigVerifyTest(bodyBytes: Array[Byte], publicKey: Array[Byte], signature: Array[Byte], lim_n: Option[Short] = None)( implicit version: StdLibVersion ): Either[ExecutionError, Boolean] = { val txType = CASETYPEREF( @@ -861,7 +860,7 @@ class EvaluatorV1V2Test extends PropSpec with PropertyChecks with Matchers with .explicitGet() ._1 ) - case fastparse.Parsed.Failure(_, index, _) => Left(s"Parse error at $index") + case f: fastparse.Parsed.Failure => Left(s"Parse error at ${f.index}") } } @@ -922,8 +921,11 @@ class EvaluatorV1V2Test extends PropSpec with PropertyChecks with Matchers with } property("List weight correct") { - val Right(ARR(Seq(a, b))) = recArrWeight("[[0] ++ [1], 0::1::nil]") - a.weight shouldBe b.weight + val xs = recArrWeight("[[0] ++ [1], 0::1::nil]") + .explicitGet() + .asInstanceOf[ARR] + .xs + xs(0).weight shouldBe xs(1).weight } private def genRCO(cnt: Int) = { @@ -966,11 +968,11 @@ class EvaluatorV1V2Test extends PropSpec with PropertyChecks with Matchers with private def multiSig( bodyBytes: Array[Byte], - senderPK: PublicKey, - alicePK: PublicKey, - bobPK: PublicKey, - aliceProof: Signature, - bobProof: Signature + senderPK: Array[Byte], + alicePK: Array[Byte], + bobPK: Array[Byte], + aliceProof: Array[Byte], + bobProof: Array[Byte] ): Either[(ExecutionError, Log[Id]), (Boolean, Log[Id])] = { val txType = CASETYPEREF( "Transaction", @@ -1030,9 +1032,9 @@ class EvaluatorV1V2Test extends PropSpec with PropertyChecks with Matchers with property("checking a hash of some message by crypto function invoking") { val bodyText = "some text for test" val bodyBytes = bodyText.getBytes("UTF-8") - val hashFunctions = Map(SHA256 -> Sha256, BLAKE256 -> Blake2b256, KECCAK256 -> Keccak256) + val hashFunctions = Map(SHA256 -> Sha256.hash _, BLAKE256 -> Blake2b256.hash _, KECCAK256 -> Keccak256.hash _) - for ((funcName, funcClass) <- hashFunctions) hashFuncTest(bodyBytes, funcName) shouldBe Right(ByteStr(funcClass.hash(bodyText))) + for ((funcName, funcClass) <- hashFunctions) hashFuncTest(bodyBytes, funcName) shouldBe Right(ByteStr(funcClass(bodyBytes))) } private def hashFuncTest(bodyBytes: Array[Byte], funcName: Short): Either[ExecutionError, ByteStr] = { diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorV2Test.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorV2Test.scala index a089a330901..978f4989b42 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorV2Test.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/EvaluatorV2Test.scala @@ -1,9 +1,7 @@ package com.wavesplatform.lang.evaluator -import cats.implicits._ +import cats.syntax.semigroup._ import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.{Common, Global} -import com.wavesplatform.lang.Common.NoShrink import com.wavesplatform.lang.directives.DirectiveSet import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.v1.FunctionHeader @@ -15,16 +13,16 @@ import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.WavesContext import com.wavesplatform.lang.v1.evaluator.{EvaluatorV2, FunctionIds} import com.wavesplatform.lang.v1.parser.Parser -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.traits.Environment +import com.wavesplatform.lang.{Common, Global} +import com.wavesplatform.test._ import org.scalacheck.Gen -import org.scalatest.{Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.Inside import scala.annotation.tailrec import scala.util.Random -class EvaluatorV2Test extends PropSpec with PropertyChecks with ScriptGen with Matchers with NoShrink with Inside { +class EvaluatorV2Test extends PropSpec with Inside { private val version = V4 private val ctx = PureContext.build(version, fixUnicodeFunctions = true).withEnvironment[Environment] |+| diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/FractionIntRoundsTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/FractionIntRoundsTest.scala index 019a1cf6526..dfbef046483 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/FractionIntRoundsTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/FractionIntRoundsTest.scala @@ -1,5 +1,5 @@ package com.wavesplatform.lang.evaluator -import com.wavesplatform.lang.Common.produce +import com.wavesplatform.test._ import com.wavesplatform.lang.directives.DirectiveDictionary import com.wavesplatform.lang.directives.values.{StdLibVersion, V5} import com.wavesplatform.lang.v1.compiler.Terms.CONST_LONG diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/ScriptResultTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/ScriptResultTest.scala index 81a12cb703c..ad99612979a 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/ScriptResultTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/ScriptResultTest.scala @@ -2,9 +2,7 @@ package com.wavesplatform.lang.evaluator import cats.Id import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.state.diffs.ProduceError._ import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.NoShrink import com.wavesplatform.lang.directives.values.V3 import com.wavesplatform.lang.utils import com.wavesplatform.lang.v1.compiler.Terms._ @@ -16,10 +14,9 @@ import com.wavesplatform.lang.v1.evaluator.{ScriptResult, ScriptResultV3} import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.traits.domain.Recipient.Address import com.wavesplatform.lang.v1.traits.domain.{AssetTransfer, DataItem} -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test._ -class ScriptResultTest extends PropSpec with PropertyChecks with Matchers with NoShrink { +class ScriptResultTest extends PropSpec { val pureEvalContext: EvaluationContext[Environment, Id] = PureContext.build(V3, fixUnicodeFunctions = true).withEnvironment[Environment].evaluationContext(utils.environment) diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/StrictWithTupleTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/StrictWithTupleTest.scala index ea95fef4b3c..d55debf9b57 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/StrictWithTupleTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/StrictWithTupleTest.scala @@ -1,6 +1,6 @@ package com.wavesplatform.lang.evaluator -import com.wavesplatform.lang.Common.produce +import com.wavesplatform.test._ import com.wavesplatform.lang.directives.values.{StdLibVersion, V4} import com.wavesplatform.lang.v1.compiler.Terms.CONST_BOOLEAN diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/StringFunctionsTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/StringFunctionsTest.scala index 9dbbd18f117..901054282ae 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/StringFunctionsTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/evaluator/StringFunctionsTest.scala @@ -1,10 +1,10 @@ package com.wavesplatform.lang.evaluator import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.produce import com.wavesplatform.lang.directives.values.{StdLibVersion, V3, V4} import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BOOLEAN, CONST_LONG, CONST_STRING} import com.wavesplatform.lang.v1.evaluator.ctx.impl.unit +import com.wavesplatform.test.produce class StringFunctionsTest extends EvaluatorSpec { property("take") { diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/FunctionComplexityTest.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/FunctionComplexityTest.scala index 56c858e35f6..21c2edfddf8 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/FunctionComplexityTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/FunctionComplexityTest.scala @@ -1,20 +1,18 @@ package com.wavesplatform.lang.v1.estimator import com.wavesplatform.DocSource import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.NoShrink -import com.wavesplatform.lang.directives.{DirectiveDictionary, DirectiveSet} import com.wavesplatform.lang.directives.values._ +import com.wavesplatform.lang.directives.{DirectiveDictionary, DirectiveSet} import com.wavesplatform.lang.utils._ import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.compiler.Terms.FUNCTION_CALL import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.lang.v1.evaluator.ctx.BaseFunction import com.wavesplatform.lang.v1.traits.Environment +import com.wavesplatform.test.PropSpec import org.scalatest.exceptions.TestFailedException -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class FunctionComplexityTest extends PropSpec with PropertyChecks with Matchers with NoShrink { +class FunctionComplexityTest extends PropSpec { val directives: Iterable[DirectiveSet] = DirectiveDictionary[StdLibVersion].all .flatMap( diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/ScriptEstimatorTestBase.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/ScriptEstimatorTestBase.scala index a35cd859068..c22abfd640a 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/ScriptEstimatorTestBase.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/ScriptEstimatorTestBase.scala @@ -2,7 +2,6 @@ package com.wavesplatform.lang.v1.estimator import cats.kernel.Monoid import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common._ import com.wavesplatform.lang.directives.DirectiveSet import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.v1.compiler.ExpressionCompiler @@ -13,20 +12,13 @@ import com.wavesplatform.lang.v1.evaluator.FunctionIds._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.{Types, WavesContext} import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, PureContext} import com.wavesplatform.lang.v1.parser.Parser -import com.wavesplatform.lang.v1.testing.ScriptGen import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.{CTX, FunctionHeader} import com.wavesplatform.lang.{Common, Global, utils} +import com.wavesplatform.test._ import monix.eval.Coeval -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class ScriptEstimatorTestBase(estimators: ScriptEstimator*) - extends PropSpec - with PropertyChecks - with Matchers - with ScriptGen - with NoShrink { +class ScriptEstimatorTestBase(estimators: ScriptEstimator*) extends PropSpec { val Plus = FunctionHeader.Native(SUM_LONG) val Minus = FunctionHeader.Native(SUB_LONG) @@ -37,22 +29,24 @@ class ScriptEstimatorTestBase(estimators: ScriptEstimator*) private val v3FunctionCosts = utils.functionCosts(V3) - implicit val version : StdLibVersion = V3 + implicit val version: StdLibVersion = V3 private def ctx(implicit version: StdLibVersion) = { val transactionType = Types.buildTransferTransactionType(true, version) val tx = CaseObj(transactionType, Map("amount" -> CONST_LONG(100000000L))) Monoid - .combineAll(Seq( - PureContext.build(version, fixUnicodeFunctions = true).withEnvironment[Environment], - CryptoContext.build(Global, version).withEnvironment[Environment], - WavesContext.build(Global, DirectiveSet(version, Account, DApp).explicitGet()), - CTX[NoContext]( - Seq(transactionType), - Map(("tx", (transactionType, ContextfulVal.pure[NoContext](tx)))), - Array.empty - ).withEnvironment[Environment] - )) + .combineAll( + Seq( + PureContext.build(version, fixUnicodeFunctions = true).withEnvironment[Environment], + CryptoContext.build(Global, version).withEnvironment[Environment], + WavesContext.build(Global, DirectiveSet(version, Account, DApp).explicitGet()), + CTX[NoContext]( + Seq(transactionType), + Map(("tx", (transactionType, ContextfulVal.pure[NoContext](tx)))), + Array.empty + ).withEnvironment[Environment] + ) + ) } private val env = Common.emptyBlockchainEnvironment() @@ -65,8 +59,8 @@ class ScriptEstimatorTestBase(estimators: ScriptEstimator*) } protected def estimate( - functionCosts: Map[FunctionHeader, Coeval[Long]] = v3FunctionCosts, - script: EXPR + functionCosts: Map[FunctionHeader, Coeval[Long]] = v3FunctionCosts, + script: EXPR ): Either[String, Long] = { val results = estimators.map(_(lets, functionCosts, script)) if (results.distinct.length == 1) @@ -76,15 +70,16 @@ class ScriptEstimatorTestBase(estimators: ScriptEstimator*) } protected def estimateDelta( - script1: EXPR, - script2: EXPR, - functionCosts: Map[FunctionHeader, Coeval[Long]] = v3FunctionCosts + script1: EXPR, + script2: EXPR, + functionCosts: Map[FunctionHeader, Coeval[Long]] = v3FunctionCosts ): Either[String, Long] = { val results = estimators.map( - e => for { - cost2 <- e(lets, functionCosts, script2) - cost1 <- e(lets, functionCosts, script1) - } yield cost2 - cost1 + e => + for { + cost2 <- e(lets, functionCosts, script2) + cost1 <- e(lets, functionCosts, script1) + } yield cost2 - cost1 ) if (results.distinct.length == 1) results.head diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/ScriptEstimatorV3Test.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/ScriptEstimatorV3Test.scala index 9c746036881..9eb2cbe83d8 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/ScriptEstimatorV3Test.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/ScriptEstimatorV3Test.scala @@ -1,7 +1,7 @@ package com.wavesplatform.lang.v1.estimator import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.Common.produce +import com.wavesplatform.test._ import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.utils.functionCosts import com.wavesplatform.lang.v1.FunctionHeader.Native diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/package.scala b/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/package.scala index 26517e2ac07..a78b75b249c 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/package.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/lang/v1/estimator/package.scala @@ -1,6 +1,6 @@ package com.wavesplatform.lang.v1 -import cats.implicits._ +import cats.syntax.semigroup._ import com.wavesplatform.lang.{Global, Common} import com.wavesplatform.lang.directives.DirectiveSet import com.wavesplatform.lang.directives.values.V3 diff --git a/lang/tests/src/test/scala/com/wavesplatform/test/specs.scala b/lang/tests/src/test/scala/com/wavesplatform/test/specs.scala new file mode 100644 index 00000000000..8fbab9de579 --- /dev/null +++ b/lang/tests/src/test/scala/com/wavesplatform/test/specs.scala @@ -0,0 +1,20 @@ +package com.wavesplatform.test + +import com.wavesplatform.lang.v1.testing.ScriptGen +import org.scalacheck.ShrinkLowPriority +import org.scalatest._ +import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks + +trait BaseSuite extends matchers.should.Matchers with ScalaCheckPropertyChecks with ScriptGen with ShrinkLowPriority { this: Suite => + +} + +abstract class FunSuite extends funsuite.AnyFunSuite with BaseSuite + +abstract class FlatSpec extends flatspec.AnyFlatSpec with BaseSuite + +abstract class FeatureSpec extends featurespec.AnyFeatureSpec with BaseSuite + +abstract class FreeSpec extends freespec.AnyFreeSpec with BaseSuite + +abstract class PropSpec extends propspec.AnyPropSpec with BaseSuite diff --git a/lang/tests/src/test/scala/com/wavesplatform/utils/Base58Test.scala b/lang/tests/src/test/scala/com/wavesplatform/utils/Base58Test.scala index e88d635025e..c8d1b20cc99 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/utils/Base58Test.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/utils/Base58Test.scala @@ -1,12 +1,10 @@ package com.wavesplatform.utils import com.wavesplatform.common.utils.{Base58, FastBase58, StdBase58} +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -import scorex.util.encode.{Base58 => ScorexBase58} -class Base58Test extends PropSpec with PropertyChecks with Matchers { +class Base58Test extends PropSpec { import org.scalacheck.Shrink implicit val noShrink: Shrink[String] = Shrink.shrinkAny @@ -27,18 +25,6 @@ class Base58Test extends PropSpec with PropertyChecks with Matchers { .filter(_.toSet.intersect(IllegalChars.toSet).nonEmpty) } yield chars.mkString - property("works the same as scorex implementation") { - forAll(base58Gen) { s => - val bytes = StdBase58.decode(s) - val scorexBytes = ScorexBase58.decode(s).get - bytes.sameElements(scorexBytes) shouldBe true - - val str = StdBase58.encode(bytes) - val scorexStr = ScorexBase58.encode(bytes) - str shouldBe scorexStr - } - } - property("decodes the same as fast implementation") { forAll(base58Gen) { s => val bytes = StdBase58.decode(s) @@ -62,7 +48,7 @@ class Base58Test extends PropSpec with PropertyChecks with Matchers { property("handles zeroes at start") { val encodedString = "11WH5tQgZH6Djm7RS2guC" - val bytes = ScorexBase58.decode(encodedString).get + val bytes = Base58.decode(encodedString) val stdStr = StdBase58.encode(bytes) val fastStr = FastBase58.encode(bytes) diff --git a/lang/tests/src/test/scala/com/wavesplatform/utils/Base64Test.scala b/lang/tests/src/test/scala/com/wavesplatform/utils/Base64Test.scala index 03f81fcad07..62d8c46a00e 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/utils/Base64Test.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/utils/Base64Test.scala @@ -1,11 +1,10 @@ package com.wavesplatform.utils import com.wavesplatform.common.utils.Base64 +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class Base64Test extends PropSpec with PropertyChecks with Matchers { +class Base64Test extends PropSpec { private val Base64Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/" private val IllegalChars = "!@#$%^&*()_-?/.,<>|\';:`~" diff --git a/lang/tests/src/test/scala/com/wavesplatform/utils/MerkleTest.scala b/lang/tests/src/test/scala/com/wavesplatform/utils/MerkleTest.scala index 31b202fb526..dcc93c7f892 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/utils/MerkleTest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/utils/MerkleTest.scala @@ -4,6 +4,7 @@ import cats.Id import cats.syntax.monoid._ import com.google.common.primitives.Ints import com.wavesplatform.common.merkle.Merkle._ +import com.wavesplatform.common.merkle._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.Base64 import com.wavesplatform.lang.Global @@ -15,107 +16,104 @@ import com.wavesplatform.lang.v1.evaluator.EvaluatorV1 import com.wavesplatform.lang.v1.evaluator.EvaluatorV1._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, PureContext} import com.wavesplatform.lang.v1.parser.Parser -import com.wavesplatform.lang.Common.{NoShrink, produce} +import com.wavesplatform.test._ import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -import scorex.crypto.authds.merkle.{Leaf, MerkleProof, MerkleTree} -import scorex.crypto.authds.{LeafData, Side} -import scorex.crypto.hash.{Blake2b256, CryptographicHash32, Digest, Digest32} +import scala.annotation.tailrec import scala.util.Random -class MerkleTest extends PropSpec with PropertyChecks with Matchers with NoShrink { - - val AMT: Long = 1000000 * 100000000L - - implicit val fastHash = new CryptographicHash32 { - override def hash(input: Message): Digest32 = Blake2b256.hash(input) +class MerkleTest extends PropSpec { + private val EmptyNodeHash = hash(Array[Byte](0)) + + private def mkScryptoLevels(data: Seq[Message]): Seq[Level] = { + if (data.isEmpty) Seq(Seq.empty) + else { + @tailrec + def loop(prevLevel: Seq[Digest], acc: Seq[Level]): Seq[Level] = { + val level = prevLevel + .grouped(2) + .collect { + case Seq(l, r) => hash(ScryptoMerkleProof.InternalNodePrefix +: (l ++ r)) + case Seq(l) => + hash(ScryptoMerkleProof.InternalNodePrefix +: (l ++ EmptyNodeHash)) + } + .toSeq + if (level.size == 1) level +: acc else loop(level, level +: acc) + } + val bottom = data.map(ld => hash(ScryptoMerkleProof.LeafPrefix +: ld)) + loop(bottom, Seq(bottom)) + } } - def testData(): (MerkleTree[Digest32], List[LeafData]) = { - val data: List[LeafData] = - List - .fill(100)(Random.nextInt(10000)) - .distinct - .map(Ints.toByteArray) - .map(LeafData @@ _) - - val tree = MerkleTree[Digest32](data)(fastHash) - - (tree, data) - } + private def testData() = + List + .fill(10)(Random.nextInt(10000)) + .distinct + .map(Ints.toByteArray) property("TRUE on correct proof") { - val (tree, leafs) = testData() - - forAll(Gen.oneOf(leafs)) { leaf => - val proof = tree - .proofByElement(Leaf[Digest32](leaf)(fastHash)) - .get - - eval(scriptSrc(tree.rootHash, proofBytes(proof), leaf)) shouldBe Right(CONST_BOOLEAN(true)) + val leaves = testData() + val tree = mkScryptoLevels(leaves) + + forAll(Gen.oneOf(leaves.zipWithIndex)) { + case (leaf, index) => + val proofs = Merkle.mkProofs(index, tree) + val bytes = proofBytes(index, proofs) + eval(scriptSrc(tree.head.head, bytes, leaf)) shouldBe Right(CONST_BOOLEAN(true)) } } property("FALSE on incorrect proof") { - val (tree, leafs) = testData() + val leaves = testData() + val tree = mkScryptoLevels(leaves) - val twoLeafsGen: Gen[(LeafData, LeafData)] = - for { - l1 <- Gen.oneOf(leafs) - l2 <- Gen.oneOf(leafs).suchThat(_ != l1) - } yield (l1, l2) + val twoLeavesGen = Gen.pick(2, leaves.zipWithIndex) - forAll(twoLeafsGen) { - case (l1, l2) => - val proof = tree - .proofByElement(Leaf[Digest32](l1)(fastHash)) - .get + forAll(twoLeavesGen) { tl => + val (_, i1) = tl(0) + val (l2, i2) = tl(1) - eval(scriptSrc(tree.rootHash, proofBytes(proof), l2)) shouldBe Right(CONST_BOOLEAN(false)) + eval(scriptSrc(tree.head.head, proofBytes(i2, Merkle.mkProofs(i1, tree)), l2)) shouldBe Right(CONST_BOOLEAN(false)) } } property("FALSE on incorrect root") { - val (tree1, leafs) = testData() - val (tree2, _) = testData() + val leaves = testData() + val tree1 = mkScryptoLevels(leaves) - forAll(Gen.oneOf(leafs)) { leaf => - val proof = tree1 - .proofByElement(Leaf[Digest32](leaf)(fastHash)) - .get + val tree2 = mkScryptoLevels(testData()) - eval(scriptSrc(tree2.rootHash, proofBytes(proof), leaf)) shouldBe Right(CONST_BOOLEAN(false)) + forAll(Gen.oneOf(leaves.zipWithIndex)) { + case (leaf, index) => + eval(scriptSrc(tree2.head.head, proofBytes(index, Merkle.mkProofs(index, tree1)), leaf)) shouldBe Right(CONST_BOOLEAN(false)) } } - property("FALSE on incorrect proof bytes") { - val (tree, leafs) = testData() + property("FALSE on arbitrary proof bytes") { + val leaves = testData() + val tree = mkScryptoLevels(leaves) - forAll(Gen.oneOf(leafs), Gen.containerOf[Array, Byte](Arbitrary.arbitrary[Byte])) { (leaf, bytes) => - eval(scriptSrc(tree.rootHash, bytes, leaf)) shouldBe Right(CONST_BOOLEAN(false)) + forAll(Gen.oneOf(leaves), Gen.containerOf[Array, Byte](Arbitrary.arbitrary[Byte])) { (leaf, bytes) => + eval(scriptSrc(tree.head.head, bytes, leaf)) shouldBe Right(CONST_BOOLEAN(false)) } } - property("FALSE on incorrect root bytes") { - val (tree, leafs) = testData() - - forAll(Gen.oneOf(leafs), Gen.containerOf[Array, Byte](Arbitrary.arbitrary[Byte])) { (leaf, bytes) => - val proof = tree - .proofByElement(Leaf[Digest32](leaf)(fastHash)) - .get + property("FALSE on arbitrary root bytes") { + val leaves = testData() + val tree = mkScryptoLevels(leaves) - eval(scriptSrc(bytes, proofBytes(proof), leaf)) shouldBe Right(CONST_BOOLEAN(false)) + forAll(Gen.oneOf(leaves.zipWithIndex), Gen.containerOf[Array, Byte](Arbitrary.arbitrary[Byte])) { + case ((leaf, index), bytes) => + eval(scriptSrc(bytes, proofBytes(index, Merkle.mkProofs(index, tree)), leaf)) shouldBe Right(CONST_BOOLEAN(false)) } } private val evaluator = new EvaluatorV1[Id, NoContext]() private def eval[T <: EVALUATED](code: String, version: StdLibVersion = V3): Either[String, T] = { - val untyped = Parser.parseExpr(code).get.value - val ctx = PureContext.build(version, fixUnicodeFunctions = true) |+| CryptoContext.build(Global, version) - val typed = ExpressionCompiler(ctx.compilerContext, untyped) + val untyped = Parser.parseExpr(code).get.value + val ctx = PureContext.build(version, fixUnicodeFunctions = true) |+| CryptoContext.build(Global, version) + val typed = ExpressionCompiler(ctx.compilerContext, untyped) typed.flatMap(v => evaluator.apply[T](ctx.evaluationContext, v._1)) } @@ -139,25 +137,22 @@ class MerkleTest extends PropSpec with PropertyChecks with Matchers with NoShrin } property("Create root from proof") { - val (_, leafs) = testData() - val levels = mkLevels(leafs) + val leaves = testData() + val levels = Merkle.mkLevels(leaves) - forAll(Gen.oneOf(leafs.zipWithIndex)) { case (leaf, index) => - val proofs = mkProofs(index, levels).reverse + forAll(Gen.oneOf(leaves.zipWithIndex)) { + case (leaf, index) => + val proofs = mkProofs(index, levels).reverse - eval(scriptCreateRootSrc(proofs, hash(leaf), index), V4) shouldBe CONST_BYTESTR(ByteStr(levels.head.head)) - eval(scriptCreateRootSrc(proofs, hash(leaf), index + (1< loop(xs, Array.concat(acc, s +: d.length.toByte +: d)) - case Nil => acc + private def proofBytes(index: Int, proofs: Seq[Array[Byte]]): Array[Byte] = + proofs.reverse + .foldLeft(index -> Array.emptyByteArray) { + case ((index, buf), proof) => (index / 2, buf ++ Array(((index + 0) % 2).toByte, proof.length.toByte) ++ proof) } - } - - loop(mp.levels.toList, Array.emptyByteArray) - } + ._2 } diff --git a/lang/tests/src/test/scala/com/wavesplatform/utils/RSATest.scala b/lang/tests/src/test/scala/com/wavesplatform/utils/RSATest.scala index c794b321b6f..874ec55c6f3 100644 --- a/lang/tests/src/test/scala/com/wavesplatform/utils/RSATest.scala +++ b/lang/tests/src/test/scala/com/wavesplatform/utils/RSATest.scala @@ -6,7 +6,6 @@ import cats.Id import cats.syntax.monoid._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base64, EitherExt2} -import com.wavesplatform.lang.Common.{NoShrink, produce} import com.wavesplatform.lang.Global import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.v1.CTX @@ -21,14 +20,14 @@ import com.wavesplatform.lang.v1.evaluator.ctx.impl.crypto.RSA._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, PureContext} import com.wavesplatform.lang.v1.evaluator.{ContextfulVal, EvaluatorV1} import com.wavesplatform.lang.v1.parser.Parser +import com.wavesplatform.test._ import org.bouncycastle.jce.provider.BouncyCastleProvider import org.scalacheck.{Arbitrary, Gen} import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import scala.util.Random -class RSATest extends PropSpec with PropertyChecks with Matchers with BeforeAndAfterAll with NoShrink { +class RSATest extends PropSpec with BeforeAndAfterAll { lazy val provider = new BouncyCastleProvider diff --git a/node-generator/build.sbt b/node-generator/build.sbt index fc7cfe65f7e..5c7a7ab085e 100644 --- a/node-generator/build.sbt +++ b/node-generator/build.sbt @@ -1,3 +1,3 @@ libraryDependencies ++= Dependencies.console :+ Dependencies.janino :+ Dependencies.asyncHttpClient :+ Dependencies.logback -fork in run := true +run / fork := true diff --git a/node-generator/src/main/scala/com/wavesplatform/generator/GeneratorSettings.scala b/node-generator/src/main/scala/com/wavesplatform/generator/GeneratorSettings.scala index eb769e270d1..5d124e8fcda 100644 --- a/node-generator/src/main/scala/com/wavesplatform/generator/GeneratorSettings.scala +++ b/node-generator/src/main/scala/com/wavesplatform/generator/GeneratorSettings.scala @@ -32,14 +32,14 @@ object GeneratorSettings { implicit val toPrintable: Show[GeneratorSettings] = { x => import x._ - val modeSettings: String = (mode match { + val modeSettings: String = (mode: @unchecked) match { case Mode.NARROW => show"$narrow" case Mode.WIDE => show"$wide" case Mode.DYN_WIDE => show"$dynWide" case Mode.MULTISIG => show"$multisig" case Mode.ORACLE => show"$oracle" case Mode.SWARM => show"$swarm" - }).toString + } s"""network byte: $chainId |rich accounts: 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 01f6c4fbce9..2a99fe6063b 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 @@ -5,6 +5,7 @@ import java.util.concurrent.ThreadLocalRandom import com.wavesplatform.account.{Address, KeyPair, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 +import com.wavesplatform.crypto.Curve25519.KeyLength import com.wavesplatform.generator.utils.Implicits._ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.estimator.ScriptEstimator @@ -16,7 +17,6 @@ import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTran import com.wavesplatform.transaction.transfer._ import com.wavesplatform.utils.LoggerFacade import org.slf4j.LoggerFactory -import scorex.crypto.signatures.Curve25519._ object Gen { private def random = ThreadLocalRandom.current @@ -53,7 +53,7 @@ object Gen { case BooleanDataEntry(key, _) => s"""extract(getBoolean(oracle, "$key"))""" case BinaryDataEntry(key, value) => s"""(extract(getBinary(oracle, "$key")) == $value)""" case StringDataEntry(key, value) => s"""(extract(getString(oracle, "$key")) == "$value")""" - case EmptyDataEntry(_) => ??? + case EmptyDataEntry(_) => ??? } reduce [String] { case (l, r) => s"$l && $r " } val src = @@ -85,10 +85,12 @@ object Gen { s"let accountSigned$i = if(sigVerify(tx.bodyBytes, tx.proofs[$i], accountPK$i)) then 1 else 0" } mkString "\n" - val proofSum = accountsWithIndexes map { - case (_, ind) => - s"accountSigned$ind" - } mkString ("let proofSum = ", " + ", "") + val proofSum = accountsWithIndexes + .map { + case (_, ind) => + s"accountSigned$ind" + } + .mkString("let proofSum = ", " + ", "") val finalStatement = s"proofSum >= $requiredProofsCount" diff --git a/node-it/build.sbt b/node-it/build.sbt index 7c53350bbfd..430d4cde1f4 100644 --- a/node-it/build.sbt +++ b/node-it/build.sbt @@ -3,16 +3,16 @@ enablePlugins(IntegrationTestsPlugin, sbtdocker.DockerPlugin) description := "NODE integration tests" libraryDependencies ++= Dependencies.it -imageNames in docker := Seq(ImageName("com.wavesplatform/node-it")) - -dockerfile in docker := NativeDockerfile(baseDirectory.value.getParentFile / "docker" / "Dockerfile") - -buildOptions in docker := BuildOptions() - -dockerBuildArguments := Map( - "ENABLE_GRPC" -> "true" +inTask(docker)( + Seq( + imageNames := Seq(ImageName("com.wavesplatform/node-it")), + dockerfile := NativeDockerfile(baseDirectory.value.getParentFile / "docker" / "Dockerfile"), + buildOptions := BuildOptions(), + dockerBuildArguments := Map( + "ENABLE_GRPC" -> "true" + ) + ) ) val packageAll = taskKey[Unit]("build all packages") -docker := docker.dependsOn(packageAll in LocalProject("root")).value - +docker := docker.dependsOn(LocalProject("root") / packageAll).value 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 cc44ef2fcb4..8aee359f7b2 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/BaseSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/BaseSuite.scala @@ -3,21 +3,21 @@ package com.wavesplatform.it import java.io.File import com.typesafe.config.{Config, ConfigFactory} +import com.wavesplatform.account.AddressScheme import com.wavesplatform.it.transactions.NodesFromDocker import monix.eval.Coeval import org.scalatest._ -import scala.jdk.CollectionConverters._ import scala.concurrent.ExecutionContext +import scala.jdk.CollectionConverters._ -class BaseSuite - extends FreeSpec - with ReportingTestName +trait BaseSuite + extends ReportingTestName with NodesFromDocker - with Matchers + with matchers.should.Matchers with CancelAfterFailure with BeforeAndAfterAll - with BeforeAndAfterEach { + with BeforeAndAfterEach { this: TestSuite with Nodes => protected implicit val ec: ExecutionContext = ExecutionContext.Implicits.global protected def nodeConfigs: Seq[Config] = @@ -31,10 +31,17 @@ class BaseSuite def notMiner: Node = nodes.last protected def sender: Node = miner + private var isRunning = false + // protected because https://github.com/sbt/zinc/issues/292 protected val theNodes: Coeval[Seq[Node]] = Coeval.evalOnce { + require(isRunning, "Do not attempt to access node instances from suite constructors") Option(System.getProperty("waves.it.config.file")) match { - case None => dockerNodes() + case None => + AddressScheme.current = new AddressScheme { + override val chainId: Byte = 'I' + } + dockerNodes() case Some(filePath) => val defaultConfig = ConfigFactory.load() ConfigFactory @@ -49,7 +56,12 @@ class BaseSuite override protected def nodes: Seq[Node] = theNodes() protected override def beforeAll(): Unit = { + isRunning = true theNodes.run() super.beforeAll() } } + +abstract class BaseFreeSpec extends freespec.AnyFreeSpec with BaseSuite + +abstract class BaseFunSuite extends funsuite.AnyFunSuite with BaseSuite diff --git a/node-it/src/test/scala/com/wavesplatform/it/ExternalNode.scala b/node-it/src/test/scala/com/wavesplatform/it/ExternalNode.scala index a4e4a998d0c..b8d8920d494 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/ExternalNode.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/ExternalNode.scala @@ -7,13 +7,13 @@ import com.typesafe.config.Config class ExternalNode(config: Config) extends Node(config) { override def nodeExternalPort(internalPort: Int): Int = internalPort - override def nodeApiEndpoint = new URL(config.getString("node-api-endpoint")) + override def nodeApiEndpoint: URL = new URL(config.getString("node-api-endpoint")) - override def apiKey = config.getString("api-key") + override def apiKey: String = config.getString("api-key") - override def networkAddress = { - val hostAndPort = "([^:]+)\\:([\\d+])+".r - val hostAndPort(host, port) = config.getString("network-address") + override def networkAddress: InetSocketAddress = { + val hostAndPort = "([^:]+)\\:([\\d+])+".r + @unchecked val hostAndPort(host, port) = config.getString("network-address") new InetSocketAddress(host, port.toInt) } } diff --git a/node-it/src/test/scala/com/wavesplatform/it/GrpcIntegrationSuiteWithThreeAddress.scala b/node-it/src/test/scala/com/wavesplatform/it/GrpcIntegrationSuiteWithThreeAddress.scala index 19469bad2e7..b759d554f6c 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/GrpcIntegrationSuiteWithThreeAddress.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/GrpcIntegrationSuiteWithThreeAddress.scala @@ -4,28 +4,20 @@ import com.google.protobuf.ByteString import com.wavesplatform.account.{Address, KeyPair} import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.SyncGrpcApi._ -import com.wavesplatform.it.util._ +import com.wavesplatform.test.NumericExt import com.wavesplatform.protobuf.transaction.{PBRecipients, PBTransactions, Recipient} import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.utils.ScorexLogging import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures} -import org.scalatest.{BeforeAndAfterAll, Matchers, RecoverMethods, Suite} +import org.scalatest._ trait GrpcIntegrationSuiteWithThreeAddress - extends BeforeAndAfterAll - with Matchers + extends BaseSuite with ScalaFutures with IntegrationPatience with RecoverMethods - with IntegrationTestsScheme - with Nodes with ScorexLogging { - this: Suite => - - def miner: Node = nodes.head - def notMiner: Node = nodes.last - - protected def sender: Node = miner + this: TestSuite with Nodes => protected lazy val firstAcc: KeyPair = KeyPair("first_acc".getBytes("UTF-8")) protected lazy val secondAcc: KeyPair = KeyPair("second_acc".getBytes("UTF-8")) @@ -42,8 +34,8 @@ trait GrpcIntegrationSuiteWithThreeAddress def dumpBalances(node: Node, accounts: Seq[ByteString], label: String): Unit = { accounts.foreach(acc => { - val balance = miner.wavesBalance(acc).available - val eff = miner.wavesBalance(acc).effective + val balance = node.wavesBalance(acc).available + val eff = node.wavesBalance(acc).effective val formatted = s"$acc: balance = $balance, effective = $eff" log.debug(s"$label account balance:\n$formatted") 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 2f8ae891015..e99fad87265 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/IntegrationSuiteWithThreeAddresses.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/IntegrationSuiteWithThreeAddresses.scala @@ -3,7 +3,7 @@ package com.wavesplatform.it import com.wavesplatform.account.KeyPair import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.util._ +import com.wavesplatform.test.NumericExt import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler @@ -12,21 +12,8 @@ import com.wavesplatform.utils.ScorexLogging import org.scalatest._ import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures} -trait IntegrationSuiteWithThreeAddresses - extends BeforeAndAfterAll - with Matchers - with ScalaFutures - with IntegrationPatience - with RecoverMethods - with IntegrationTestsScheme - with Nodes - with ScorexLogging { - this: Suite => - - def miner: Node = nodes.head - def notMiner: Node = nodes.last - - protected def sender: Node = miner +trait IntegrationSuiteWithThreeAddresses extends BaseSuite with ScalaFutures with IntegrationPatience with RecoverMethods with ScorexLogging { + this: TestSuite with Nodes => protected lazy val firstKeyPair: KeyPair = sender.createKeyPair() protected lazy val firstAddress: String = firstKeyPair.toAddress.toString @@ -42,34 +29,16 @@ trait IntegrationSuiteWithThreeAddresses val defaultBalance: Long = 100.waves - def dumpBalances(accounts: Seq[KeyPair], label: String): Unit = - accounts.foreach { acc => - val (balance, eff) = miner.accountBalances(acc.toAddress.toString) - log.debug(s"$label $acc balance: balance = $balance, effective = $eff") - } - 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 = { - nodes.waitForHeight(2) val accounts = Seq(firstKeyPair, secondKeyPair, thirdKeyPair) - dumpBalances(accounts, "initial") - val txs = makeTransfers(accounts) - - val targetHeight = nodes.map(_.height).max + 1 - withClue(s"waitForHeight($targetHeight)") { - nodes.waitForHeight(targetHeight) - } - withClue("waitForTxsToReachAllNodes") { - txs.foreach(nodes.waitForTransaction) + nodes.waitForHeight(makeTransfers(accounts).map(ts => nodes.waitForTransaction(ts).height).max + 1) } - - dumpBalances(accounts, "after transfer") - accounts.foreach(a => miner.assertBalances(a.toAddress.toString, defaultBalance, defaultBalance)) } withClue("beforeAll") { diff --git a/node-it/src/test/scala/com/wavesplatform/it/IntegrationTestsScheme.scala b/node-it/src/test/scala/com/wavesplatform/it/IntegrationTestsScheme.scala deleted file mode 100644 index e37cbfb6ae5..00000000000 --- a/node-it/src/test/scala/com/wavesplatform/it/IntegrationTestsScheme.scala +++ /dev/null @@ -1,9 +0,0 @@ -package com.wavesplatform.it - -import com.wavesplatform.account.AddressScheme - -trait IntegrationTestsScheme { - AddressScheme.current = new AddressScheme { - override val chainId: Byte = 'I' - } -} 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 d3f5cf9ea72..8f5ae825459 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/TransferSending.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/TransferSending.scala @@ -30,10 +30,6 @@ trait TransferSending extends ScorexLogging { import scala.concurrent.ExecutionContext.Implicits.global - AddressScheme.current = new AddressScheme { - override val chainId: Byte = 'I'.toByte - } - def generateTransfersFromAccount(n: Int, accountAddress: String): Seq[Req] = { val fee = 100000 + 400000 // + 400000 for scripted accounts val seedSize = 32 diff --git a/node-it/src/test/scala/com/wavesplatform/it/WaitForHeight2.scala b/node-it/src/test/scala/com/wavesplatform/it/WaitForHeight2.scala index 8ccb2e3ccc8..71165475f76 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/WaitForHeight2.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/WaitForHeight2.scala @@ -1,22 +1,15 @@ package com.wavesplatform.it import com.wavesplatform.it.api.AsyncHttpApi._ -import com.wavesplatform.utils.ScorexLogging import org.scalatest._ -import scala.concurrent.{Await, Future} import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent.Future import scala.concurrent.Future.traverse -import scala.concurrent.duration._ -trait WaitForHeight2 extends BeforeAndAfterAll with ScorexLogging with ReportingTestName with Nodes { +trait WaitForHeight2 extends ReportingTestName with Nodes { this: Suite => - abstract protected override def beforeAll(): Unit = { - super.beforeAll() - Await.result(traverse(nodes)(_.waitForHeight(2)), 2.minute) - } - def waitForTxsToReachAllNodes(nodes: Seq[Node] = nodes, txIds: Seq[String]): Future[_] = { val txNodePairs = for { txId <- txIds 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 020722bbcd3..f5512b5fe02 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 @@ -4,18 +4,18 @@ import com.wavesplatform.account.KeyPair import com.wavesplatform.api.http.ApiError.ScriptExecutionError import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.it.BaseSuite +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync._ -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BOOLEAN, CONST_BYTESTR, CONST_LONG, CONST_STRING} import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, IntegerDataEntry, StringDataEntry} +import com.wavesplatform.test._ import com.wavesplatform.transaction.smart.script.ScriptCompiler case class WriteEntry(ct: String, t: String, v: Any, k: String = "somekey") -class RemoveEntrySuite extends BaseSuite { +class RemoveEntrySuite extends BaseFreeSpec { private val stringTestData = WriteEntry("String", "String", "somevalue") private val integerTestData = WriteEntry("Integer", "Int", 1) diff --git a/node-it/src/test/scala/com/wavesplatform/it/api/AsyncGrpcApi.scala b/node-it/src/test/scala/com/wavesplatform/it/api/AsyncGrpcApi.scala index 66cefd2e6de..e19996e2dc5 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/api/AsyncGrpcApi.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/api/AsyncGrpcApi.scala @@ -45,7 +45,7 @@ object AsyncGrpcApi { def blockAt(height: Int): Future[Block] = { blocks - .getBlock(BlockRequest.of(includeTransactions = true, BlockRequest.Request.Height(height))) + .getBlock(BlockRequest.of(BlockRequest.Request.Height(height), includeTransactions = true)) .map(r => PBBlocks.vanilla(r.getBlock).get.json().as[Block]) } @@ -307,7 +307,7 @@ object AsyncGrpcApi { condition } - def height: Future[Int] = blocks.getCurrentHeight(Empty.of()).map(h => h.value) + def height: Future[Int] = blocks.getCurrentHeight(Empty.of()) def waitForHeight(expectedHeight: Int): Future[Int] = { waitFor[Int](s"height >= $expectedHeight")(_.height, h => h >= expectedHeight, 5.seconds) 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 017a02993a3..8183141bb3f 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 @@ -35,7 +35,7 @@ import org.asynchttpclient.Dsl.{delete => _delete, get => _get, post => _post, p import org.asynchttpclient._ import org.asynchttpclient.util.HttpConstants.ResponseStatusCodes.OK_200 import org.scalactic.source.Position -import org.scalatest.{Assertions, Matchers} +import org.scalatest.{Assertions, matchers} import play.api.libs.json.Json.{stringify, toJson} import play.api.libs.json._ @@ -49,7 +49,7 @@ import scala.util.{Failure, Success} object AsyncHttpApi extends Assertions { //noinspection ScalaStyle - implicit class NodeAsyncHttpApi(val n: Node) extends Assertions with Matchers { + implicit class NodeAsyncHttpApi(val n: Node) extends Assertions with matchers.should.Matchers { def get( path: String, @@ -749,7 +749,6 @@ object AsyncHttpApi extends Assertions { sellMatcherFee: Long, fee: Long, version: Byte, - matcherFeeAssetId: Option[String], amountsAsStrings: Boolean = false, validate: Boolean = true ): Future[Transaction] = { @@ -904,23 +903,6 @@ object AsyncHttpApi extends Assertions { executeRequest } - def once(r: Request): Future[Response] = { - val id = UUID.randomUUID() - n.log.trace(s"[$id] Executing request ${r.getMethod} ${r.getUrl}") - n.client - .executeRequest( - r, - new AsyncCompletionHandler[Response] { - override def onCompleted(response: Response): Response = { - n.log.debug(s"[$id] Response for ${r.getUrl} is ${response.getStatusCode}") - response - } - } - ) - .toCompletableFuture - .toScala - } - def debugStateAt(height: Long): Future[Map[String, Long]] = getWithApiKey(s"/debug/stateWaves/$height").as[Map[String, Long]] def debugBalanceHistory(address: String, amountsAsStrings: Boolean = false): Future[Seq[BalanceHistory]] = { @@ -954,23 +936,20 @@ object AsyncHttpApi extends Assertions { def accountsBalances(height: Option[Int], accounts: Seq[String], asset: Option[String]): Future[Seq[(String, Long)]] = n.balances(height, accounts, asset).map(_.map(b => (b.address, b.balance))) - def accountBalances(acc: String): Future[(Long, Long)] = { - n.balance(acc).map(_.balance).zip(n.effectiveBalance(acc).map(_.balance)) - } + def accountBalances(acc: String): Future[(Long, Long)] = + n.balanceDetails(acc).map(bd => bd.regular -> bd.effective) - def assertBalances(acc: String, balance: Long, effectiveBalance: Long)(implicit pos: Position): Future[Unit] = { + def assertBalances(acc: String, balance: Long, effectiveBalance: Long)(implicit pos: Position): Future[Unit] = for { - newBalance <- accountBalance(acc) - newEffectiveBalance <- accountEffectiveBalance(acc) + newBalance <- balanceDetails(acc) } yield { withClue(s"effective balance of $acc") { - newEffectiveBalance shouldBe effectiveBalance + newBalance.effective shouldBe effectiveBalance } withClue(s"balance of $acc") { - newBalance shouldBe balance + newBalance.regular shouldBe balance } } - } def assertAssetBalance(acc: String, assetIdString: String, balance: Long)(implicit pos: Position): Future[Unit] = { for { @@ -998,7 +977,7 @@ object AsyncHttpApi extends Assertions { } } - implicit class NodesAsyncHttpApi(nodes: Seq[Node]) extends Matchers { + implicit class NodesAsyncHttpApi(nodes: Seq[Node]) extends matchers.should.Matchers { def height: Future[Seq[Int]] = traverse(nodes)(_.height) def waitForHeightAriseAndTxPresent(transactionId: String)(implicit p: Position): Future[Unit] = diff --git a/node-it/src/test/scala/com/wavesplatform/it/api/SyncGrpcApi.scala b/node-it/src/test/scala/com/wavesplatform/it/api/SyncGrpcApi.scala index 727a126a696..def14d4839d 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/api/SyncGrpcApi.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/api/SyncGrpcApi.scala @@ -3,7 +3,6 @@ package com.wavesplatform.it.api import java.util.concurrent.TimeoutException import com.google.protobuf.ByteString -import com.google.protobuf.wrappers.StringValue import com.wavesplatform.account.{AddressScheme, KeyPair} import com.wavesplatform.api.grpc.BalanceResponse.WavesBalances import com.wavesplatform.api.grpc.{TransactionStatus => PBTransactionStatus, _} @@ -74,8 +73,8 @@ object SyncGrpcApi extends Assertions { } def resolveAlias(alias: String): Addr = { - val addr = accounts.resolveAlias(StringValue.of(alias)) - PBRecipients.toAddress(addr.value.toByteArray, AddressScheme.current.chainId).explicitGet() + val addr = accounts.resolveAlias(alias) + PBRecipients.toAddress(addr.toByteArray, AddressScheme.current.chainId).explicitGet() } def stateChanges(txId: String): (VanillaTransaction, StateChangesDetails) = { @@ -212,7 +211,7 @@ object SyncGrpcApi extends Assertions { def waitForTxAndHeightArise(txId: String): Unit = { @tailrec def recWait(): Unit = { - val Seq(status) = getStatuses(TransactionsByIdRequest.of(Seq(ByteString.copyFrom(Base58.decode(txId))))) + val status = getStatuses(TransactionsByIdRequest.of(Seq(ByteString.copyFrom(Base58.decode(txId))))).head val currentHeight = this.height if (status.status.isNotExists) throw new IllegalArgumentException(s"Transaction not exists: $txId") @@ -344,7 +343,7 @@ object SyncGrpcApi extends Assertions { } def getActiveLeases(address: ByteString): List[LeaseResponse] = { - accounts.getActiveLeases(AccountRequest.of(address)).toList + accounts.getActiveLeases(AccountRequest.of(address)).toList } def updateAssetInfo( @@ -366,21 +365,21 @@ object SyncGrpcApi extends Assertions { def assetInfo(assetId: String): AssetInfoResponse = sync(async(n).assetInfo(assetId)) def blockAt(height: Int): VanillaBlock = { - val block = blocks.getBlock(BlockRequest.of(includeTransactions = true, BlockRequest.Request.Height.apply(height))).getBlock + val block = blocks.getBlock(BlockRequest.of(BlockRequest.Request.Height.apply(height), includeTransactions = true)).getBlock PBBlocks.vanilla(block).toEither.explicitGet() } def blockHeaderAt(height: Int): Header = { - blocks.getBlock(BlockRequest.of(includeTransactions = true, BlockRequest.Request.Height.apply(height))).getBlock.getHeader + blocks.getBlock(BlockRequest.of(BlockRequest.Request.Height.apply(height), includeTransactions = true)).getBlock.getHeader } def blockById(blockId: ByteString): VanillaBlock = { - val block = blocks.getBlock(BlockRequest.of(includeTransactions = true, BlockRequest.Request.BlockId.apply(blockId))).getBlock + val block = blocks.getBlock(BlockRequest.of(BlockRequest.Request.BlockId.apply(blockId), includeTransactions = true)).getBlock PBBlocks.vanilla(block).toEither.explicitGet() } def blockSeq(fromHeight: Int, toHeight: Int, filter: BlockRangeRequest.Filter = BlockRangeRequest.Filter.Empty): Seq[VanillaBlock] = { - val blockIter = blocks.getBlockRange(BlockRangeRequest.of(fromHeight, toHeight, includeTransactions = true, filter)) + val blockIter = blocks.getBlockRange(BlockRangeRequest.of(fromHeight, toHeight, filter, includeTransactions = true)) blockIter.map(blockWithHeight => PBBlocks.vanilla(blockWithHeight.getBlock).toEither.explicitGet()).toSeq } 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 7d85fda171b..c6b5ac2f0d3 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 @@ -24,8 +24,7 @@ import com.wavesplatform.transaction.{Asset, TxVersion} import io.grpc.Status.Code import org.asynchttpclient.Response import org.scalactic.source.Position -import org.scalatest.Matchers._ -import org.scalatest.{Assertion, Assertions, Matchers} +import org.scalatest.{Assertion, Assertions, matchers} import play.api.libs.json.Json.parse import play.api.libs.json._ @@ -35,7 +34,7 @@ import scala.concurrent.{Await, Awaitable, Future} import scala.util._ import scala.util.control.NonFatal -object SyncHttpApi extends Assertions { +object SyncHttpApi extends Assertions with matchers.should.Matchers { case class ApiCallException(cause: Throwable) extends Exception("Error in API call", cause) case class ErrorMessage(error: Int, message: String) implicit val errorMessageFormat: Format[ErrorMessage] = Json.format @@ -142,7 +141,7 @@ object SyncHttpApi extends Assertions { } //noinspection ScalaStyle - implicit class NodeExtSync(n: Node) extends Assertions with Matchers { + implicit class NodeExtSync(n: Node) extends Assertions with matchers.should.Matchers { import com.wavesplatform.it.api.AsyncHttpApi.{NodeAsyncHttpApi => async} private def maybeWaitForTransaction(tx: Transaction, wait: Boolean): Transaction = { @@ -408,7 +407,6 @@ object SyncHttpApi extends Assertions { sellMatcherFee: Long, fee: Long, version: Byte = 2, - matcherFeeAssetId: Option[String] = None, waitForTx: Boolean = false, amountsAsStrings: Boolean = false, validate: Boolean = true @@ -425,7 +423,6 @@ object SyncHttpApi extends Assertions { sellMatcherFee, fee, version, - matcherFeeAssetId, amountsAsStrings, validate ) @@ -786,18 +783,16 @@ object SyncHttpApi extends Assertions { def rollback(height: Int, returnToUTX: Boolean = true): Unit = { val combinations = nodes.combinations(2).toSeq - nodes.combinations(2).foreach { - case Seq(n1, n2) => - n1.blacklist(n2.networkAddress) - n2.blacklist(n1.networkAddress) + combinations.foreach { ns => + ns.head.blacklist(ns(1).networkAddress) + ns(1).blacklist(ns.head.networkAddress) } nodes.rollbackWithoutBlacklisting(height, returnToUTX) nodes.foreach(_.clearBlacklist()) - combinations.foreach { - case Seq(n1, n2) => - n1.connect(n2.networkAddress) + combinations.foreach { ns => + ns.head.connect(ns(1).networkAddress) } } 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 5ff4db0e239..12ab8ba7a04 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 @@ -8,19 +8,19 @@ import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.api.{BurnInfoResponse, IssueInfoResponse, ReissueInfoResponse, StateChangesDetails} import com.wavesplatform.it.sync._ import com.wavesplatform.it.sync.grpc.GrpcBaseTransactionSuiteLike -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BOOLEAN, CONST_BYTESTR, CONST_LONG, FUNCTION_CALL} 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.smart.script.ScriptCompiler -import org.scalatest.FreeSpec +import org.scalatest.freespec.AnyFreeSpec import scala.util.Random -class GrpcIssueReissueBurnAssetSuite extends FreeSpec with GrpcBaseTransactionSuiteLike { +class GrpcIssueReissueBurnAssetSuite extends AnyFreeSpec with GrpcBaseTransactionSuiteLike { private val initialWavesBalance = 100.waves private val setScriptPrice = 0.01.waves diff --git a/node-it/src/test/scala/com/wavesplatform/it/asset/GrpcSponsorFeeActionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/asset/GrpcSponsorFeeActionSuite.scala index 7d7e89a3dc3..9d56d57de2b 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/asset/GrpcSponsorFeeActionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/asset/GrpcSponsorFeeActionSuite.scala @@ -6,14 +6,14 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.{IssueInfoResponse, SponsorFeeResponse, StateChangesDetails} import com.wavesplatform.it.sync._ import com.wavesplatform.it.sync.grpc.GrpcBaseTransactionSuiteLike -import com.wavesplatform.it.util._ 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.smart.script.ScriptCompiler -import org.scalatest.FreeSpec +import org.scalatest.freespec.AnyFreeSpec -class GrpcSponsorFeeActionSuite extends FreeSpec with GrpcBaseTransactionSuiteLike { +class GrpcSponsorFeeActionSuite extends AnyFreeSpec with GrpcBaseTransactionSuiteLike { private val initialWavesBalance = 100.waves private val minSponsoredAssetFee = 100 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 da4da6228cb..a8a9d440874 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 @@ -1,25 +1,25 @@ package com.wavesplatform.it.asset -import scala.concurrent.duration._ - import com.typesafe.config.Config import com.wavesplatform.account.KeyPair import com.wavesplatform.api.http.ApiError.{AssetDoesNotExist, TransactionDoesNotExist} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.it.BaseSuite -import com.wavesplatform.it.api.{AssetInfo, BurnInfoResponse, IssueInfoResponse, ReissueInfoResponse, StateChangesDetails, Transaction} +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.it.api.SyncHttpApi._ +import com.wavesplatform.it.api.{AssetInfo, BurnInfoResponse, IssueInfoResponse, ReissueInfoResponse, StateChangesDetails, Transaction} import com.wavesplatform.it.sync._ -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BOOLEAN, CONST_BYTESTR, CONST_LONG} import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ +import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.TxVersion -import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.transaction.Asset.IssuedAsset +import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} + +import scala.concurrent.duration._ -class IssueReissueBurnAssetSuite extends BaseSuite { +class IssueReissueBurnAssetSuite extends BaseFreeSpec { override val nodeConfigs: Seq[Config] = com.wavesplatform.it.NodeConfigs.newBuilder .overrideBase(_.quorum(0)) 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 c69986b6366..59e9b2abcb3 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 @@ -2,17 +2,17 @@ package com.wavesplatform.it.asset import com.wavesplatform.account.KeyPair import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.it.BaseSuite +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.{IssueInfoResponse, SponsorFeeResponse, StateChangesDetails} import com.wavesplatform.it.sync._ -import com.wavesplatform.it.util._ 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.smart.script.ScriptCompiler -class SponsorFeeActionSuite extends BaseSuite { +class SponsorFeeActionSuite extends BaseFreeSpec { private val initialWavesBalance = 100.waves private var sponsoredAssetId: String = "" @@ -543,7 +543,7 @@ class SponsorFeeActionSuite extends BaseSuite { val invokeTx2 = miner.invokeScript(miner.keyPair, dAppAddress, Some("sponsorAsset"), waitForTx = true, fee = smartMinFee + issueFee) miner.debugStateChanges(invokeTx2._1.id).stateChanges.get.sponsorFees.head.assetId shouldBe assetId - nodes.rollback(firstTxHeight, returnToUTX = true) + nodes.rollback(firstTxHeight) nodes.waitForTransaction(invokeTx2._1.id) miner.assetsDetails(assetId).minSponsoredAssetFee shouldBe Some(minSponsoredAssetFee) diff --git a/node-it/src/test/scala/com/wavesplatform/it/async/BlockSizeConstraintsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/async/BlockSizeConstraintsSuite.scala index 3da65ccb25e..05db3bc41ca 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/async/BlockSizeConstraintsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/async/BlockSizeConstraintsSuite.scala @@ -1,27 +1,23 @@ package com.wavesplatform.it.async import com.typesafe.config.{Config, ConfigFactory} +import com.wavesplatform.it._ import com.wavesplatform.it.api.AsyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{LoadTest, NodeConfigs, TransferSending} -import org.scalatest._ import scala.concurrent.Await.result -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.duration._ import scala.concurrent.Future +import scala.concurrent.duration._ @LoadTest -class BlockSizeConstraintsSuite extends FreeSpec with Matchers with TransferSending with NodesFromDocker { +class BlockSizeConstraintsSuite extends BaseFreeSpec with TransferSending { import BlockSizeConstraintsSuite._ override protected val nodeConfigs: Seq[Config] = Seq(ConfigOverrides.withFallback(NodeConfigs.randomMiner)) - private val nodeAddresses = nodeConfigs.map(_.getString("address")).toSet - private def miner = nodes.head + private lazy val nodeAddresses = nodeConfigs.map(_.getString("address")).toSet - val transfers = generateTransfersToRandomAddresses(maxTxsGroup, nodeAddresses) + private lazy val transfers = generateTransfersToRandomAddresses(maxTxsGroup, nodeAddresses) s"Block is limited by size after activation" in result( for { _ <- Future.sequence((0 to maxGroups).map(_ => processRequests(transfers, includeAttachment = true))) diff --git a/node-it/src/test/scala/com/wavesplatform/it/async/MicroblocksFeeTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/async/MicroblocksFeeTestSuite.scala index 7772f6b9805..329c33159a5 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/async/MicroblocksFeeTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/async/MicroblocksFeeTestSuite.scala @@ -1,22 +1,17 @@ package com.wavesplatform.it.async import com.typesafe.config.{Config, ConfigFactory} +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.AsyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.util._ -import com.wavesplatform.utils.ScorexLogging -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers} +import com.wavesplatform.test._ -import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future.traverse import scala.concurrent.duration._ import scala.concurrent.{Await, Future} import scala.util.Random -class MicroblocksFeeTestSuite extends FreeSpec with Matchers with CancelAfterFailure with NodesFromDocker with ScorexLogging { - - private def notMiner = nodes.head +class MicroblocksFeeTestSuite extends BaseFreeSpec { private def firstAddress = nodes(1).address @@ -100,10 +95,10 @@ class MicroblocksFeeTestSuite extends FreeSpec with Matchers with CancelAfterFai """.stripMargin ) - override protected def nodeConfigs: Seq[Config] = Seq( - notMinerConfig.withFallback(Default.head), + override protected val nodeConfigs: Seq[Config] = Seq( + minerConfig.withFallback(Default(0)), notMinerConfig.withFallback(Default(1)), notMinerConfig.withFallback(Default(2)), - minerConfig.withFallback(Default(3)) + notMinerConfig.withFallback(Default(3)) ) } diff --git a/node-it/src/test/scala/com/wavesplatform/it/async/MicroblocksGenerationSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/async/MicroblocksGenerationSuite.scala index dd6e72e27c2..f14a72b6c59 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/async/MicroblocksGenerationSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/async/MicroblocksGenerationSuite.scala @@ -2,15 +2,12 @@ package com.wavesplatform.it.async import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.it.api.AsyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{NodeConfigs, TransferSending} -import org.scalatest._ +import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs, TransferSending} import scala.concurrent.Await.result -import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ -class MicroblocksGenerationSuite extends FreeSpec with Matchers with TransferSending with NodesFromDocker { +class MicroblocksGenerationSuite extends BaseFreeSpec with TransferSending { import MicroblocksGenerationSuite._ override protected val nodeConfigs: Seq[Config] = @@ -18,8 +15,6 @@ class MicroblocksGenerationSuite extends FreeSpec with Matchers with TransferSen private val nodeAddresses = nodeConfigs.map(_.getString("address")).toSet - private def miner = nodes.head - s"Generate transactions and wait for one block with $maxTxs txs" in result( for { uploadedTxs <- processRequests(generateTransfersToRandomAddresses(maxTxs, nodeAddresses)) diff --git a/node-it/src/test/scala/com/wavesplatform/it/async/SmartTransactionsConstraintsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/async/SmartTransactionsConstraintsSuite.scala index a50c31157a2..0e26a1945fe 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/async/SmartTransactionsConstraintsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/async/SmartTransactionsConstraintsSuite.scala @@ -5,22 +5,19 @@ import com.wavesplatform.account.KeyPair import com.wavesplatform.api.http.requests.SignedSetScriptRequest import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.AsyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{NodeConfigs, TransferSending} +import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs, TransferSending} import com.wavesplatform.lang.directives.values.V1 import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.mining.MiningConstraints.MaxScriptRunsInBlock import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.smart.SetScriptTransaction -import org.scalatest._ import play.api.libs.json.{JsNumber, Json} import scala.concurrent.Await.result -import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ -class SmartTransactionsConstraintsSuite extends FreeSpec with Matchers with TransferSending with NodesFromDocker { +class SmartTransactionsConstraintsSuite extends BaseFreeSpec with TransferSending { override protected val nodeConfigs: Seq[Config] = NodeConfigs.newBuilder .overrideBase( @@ -48,7 +45,6 @@ class SmartTransactionsConstraintsSuite extends FreeSpec with Matchers with Tran .withDefault(1) .build(false) - private def miner = nodes.head private val smartPrivateKey = KeyPair.fromSeed(NodeConfigs.Default(1).getString("account-seed")).explicitGet() private val simplePrivateKey = KeyPair.fromSeed(NodeConfigs.Default(2).getString("account-seed")).explicitGet() 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 fb77622a370..2ef4a1f2e21 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 @@ -5,17 +5,14 @@ import java.util.concurrent.TimeoutException import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.it._ import com.wavesplatform.it.api.AsyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker import com.wavesplatform.it.util._ -import org.scalatest._ -import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future.traverse import scala.concurrent.duration._ import scala.concurrent.{Await, Future} @LoadTest -class WideStateGenerationSuite extends FreeSpec with WaitForHeight2 with Matchers with TransferSending with NodesFromDocker { +class WideStateGenerationSuite extends BaseFreeSpec with WaitForHeight2 with TransferSending { override protected def createDocker: Docker = new Docker( suiteConfig = ConfigFactory.parseString( @@ -57,7 +54,8 @@ class WideStateGenerationSuite extends FreeSpec with WaitForHeight2 with Matcher b <- dumpBalances() uploadedTxs <- processRequests( generateTransfersToRandomAddresses(requestsCount / 2, nodeAddresses) ++ - generateTransfersBetweenAccounts(requestsCount / 2, b)) + generateTransfersBetweenAccounts(requestsCount / 2, b) + ) _ <- Await.ready(traverse(nodes)(_.waitFor[Int]("UTX is empty")(_.utxSize, _ == 0, 5.seconds)), 7.minutes) diff --git a/node-it/src/test/scala/com/wavesplatform/it/grpc/BlocksApiSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/grpc/BlocksApiSuite.scala index c4ca29ef5d7..16d99b3ddb4 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/grpc/BlocksApiSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/grpc/BlocksApiSuite.scala @@ -9,9 +9,8 @@ import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.sync.grpc.GrpcBaseTransactionSuite import com.wavesplatform.protobuf.block._ import com.wavesplatform.protobuf.transaction.PBRecipients -import org.scalatest.Matchers -class BlocksApiSuite extends GrpcBaseTransactionSuite with Matchers { +class BlocksApiSuite extends GrpcBaseTransactionSuite { private val BlockV4Height = 3 private val BlockV5Height = 5 override protected def nodeConfigs: Seq[Config] = 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 38fd66b58d2..f016cccd57d 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 @@ -8,7 +8,7 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync._ import com.wavesplatform.it.sync.transactions.{FailedTransactionSuiteLike, OverflowBlock} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.lang.v1.repl.Repl import com.wavesplatform.lang.v1.repl.node.http.NodeConnectionSettings diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/BlacklistTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/BlacklistTestSuite.scala index 3c70e24ada1..bf218dff515 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/BlacklistTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/BlacklistTestSuite.scala @@ -3,12 +3,11 @@ package com.wavesplatform.it.sync import com.typesafe.config.Config import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api._ -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{NodeConfigs, ReportingTestName} -import org.scalatest._ +import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs} + import scala.concurrent.duration._ -class BlacklistTestSuite extends FreeSpec with Matchers with CancelAfterFailure with ReportingTestName with NodesFromDocker { +class BlacklistTestSuite extends BaseFreeSpec { override protected def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder 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 581e7d57ad8..aa94e46171f 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 @@ -5,23 +5,15 @@ import com.wavesplatform.block.Block import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.Base58 import com.wavesplatform.crypto -import com.wavesplatform.it.{NodeConfigs, ReportingTestName} +import com.wavesplatform.crypto.Blake2b256 import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync.activation.ActivationStatusRequest -import com.wavesplatform.it.transactions.NodesFromDocker -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers, OptionValues} -import scorex.crypto.hash.Blake2b256 +import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs} +import org.scalatest._ import scala.concurrent.duration._ -class BlockV5TestSuite - extends FreeSpec - with Matchers - with CancelAfterFailure - with NodesFromDocker - with ActivationStatusRequest - with ReportingTestName - with OptionValues { +class BlockV5TestSuite extends BaseFreeSpec with ActivationStatusRequest with OptionValues { override def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder @@ -37,11 +29,11 @@ class BlockV5TestSuite nodes.head.waitForHeight(nodes.head.height + 2, 2.minute) currentHeight = nodes.head.height - val lastBlockCurrentHeight = nodes.head.lastBlock() - val lastBlockHeadersCurrentHeight = nodes.head.lastBlockHeader() - val blockAtCurrentHeight = nodes.head.blockAt(currentHeight) - val blockHeadersCurrentHeight = nodes.head.blockHeadersAt(currentHeight) - val blockBySignatureCurrentHeight = nodes.head.blockById(blockAtCurrentHeight.id) + val lastBlockCurrentHeight = nodes.head.lastBlock() + val lastBlockHeadersCurrentHeight = nodes.head.lastBlockHeader() + val blockAtCurrentHeight = nodes.head.blockAt(currentHeight) + val blockHeadersCurrentHeight = nodes.head.blockHeadersAt(currentHeight) + val blockBySignatureCurrentHeight = nodes.head.blockById(blockAtCurrentHeight.id) val generationSignatureInBlockJson = ByteStr.decodeBase58(blockAtCurrentHeight.generationSignature.get).get blockAtCurrentHeight.version.value shouldBe Block.ProtoBlockVersion 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 5e8a25683c0..25e7c9c642c 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 @@ -6,7 +6,7 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.state.Sponsorship import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.assets.IssueTransaction @@ -33,7 +33,7 @@ class CustomFeeTransactionSuite extends BaseTransactionSuite with CancelAfterFai nodes.waitForHeightAriseAndTxPresent(issuedAssetId) val sponsorAssetId = notMiner.sponsorAsset(senderKeyPair, issuedAssetId, assetToken, assetFee).id - assert(!sponsorAssetId.isEmpty) + assert(sponsorAssetId.nonEmpty) nodes.waitForHeightAriseAndTxPresent(sponsorAssetId) val fees = 2 * assetFee diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/FairPoSTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/FairPoSTestSuite.scala index 9f09757d4a6..4559b3be51c 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/FairPoSTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/FairPoSTestSuite.scala @@ -1,12 +1,12 @@ package com.wavesplatform.it.sync import com.typesafe.config.{Config, ConfigFactory} -import org.scalatest.{CancelAfterFailure, FunSuite} +import com.wavesplatform.it.BaseFunSuite import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker + import scala.concurrent.duration._ -class FairPoSTestSuite extends FunSuite with CancelAfterFailure with NodesFromDocker { +class FairPoSTestSuite extends BaseFunSuite { import FairPoSTestSuite._ override protected def nodeConfigs: Seq[Config] = Configs diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/ForgeReturnedToUTXSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/ForgeReturnedToUTXSuite.scala index 417a3e970bb..d20085dd8f0 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/ForgeReturnedToUTXSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/ForgeReturnedToUTXSuite.scala @@ -4,9 +4,9 @@ import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.TransactionInfo import com.wavesplatform.it.transactions.NodesFromDocker -import org.scalatest.{CancelAfterFailure, FunSuite, Matchers} +import org.scalatest._ -class ForgeReturnedToUTXSuite extends FunSuite with CancelAfterFailure with NodesFromDocker with Matchers { +class ForgeReturnedToUTXSuite extends funsuite.AnyFunSuite with CancelAfterFailure with NodesFromDocker with matchers.should.Matchers { import ForgeReturnedToUTXSuite._ override protected def nodeConfigs: Seq[Config] = Configs diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/MerkleRootTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/MerkleRootTestSuite.scala index 325bed93fe8..2bf4e73e110 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/MerkleRootTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/MerkleRootTestSuite.scala @@ -4,23 +4,18 @@ import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.api.http.ApiError.{CustomValidationError, InvalidSignature} import com.wavesplatform.block.Block import com.wavesplatform.common.utils.Base58 +import com.wavesplatform.crypto.Blake2b256 import com.wavesplatform.features.BlockchainFeatures -import com.wavesplatform.it.ReportingTestName -import com.wavesplatform.it.sync.activation.ActivationStatusRequest +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers, OptionValues} -import scorex.crypto.hash.Blake2b256 +import com.wavesplatform.it.sync.activation.ActivationStatusRequest +import org.scalatest._ import scala.concurrent.duration._ class MerkleRootTestSuite - extends FreeSpec - with Matchers - with CancelAfterFailure - with NodesFromDocker + extends BaseFreeSpec with ActivationStatusRequest - with ReportingTestName with OptionValues { import MerkleRootTestSuite._ 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 b96eb82c52e..3aaf38a90b4 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,17 +1,13 @@ package com.wavesplatform.it.sync import com.typesafe.config.Config -import com.wavesplatform.it.NodeConfigs import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker +import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs} import com.wavesplatform.state.Sponsorship import com.wavesplatform.state.diffs.FeeValidation import com.wavesplatform.utils.ScorexLogging -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers} -class MicroblocksSponsoredFeeTestSuite extends FreeSpec with Matchers with CancelAfterFailure with NodesFromDocker with ScorexLogging { - - private def notMiner = nodes.head +class MicroblocksSponsoredFeeTestSuite extends BaseFreeSpec with ScorexLogging { private lazy val sponsor = nodes(1) private val Token = 100L diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/MinerStateTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/MinerStateTestSuite.scala index 0e093a15b70..c54f3218eb5 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/MinerStateTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/MinerStateTestSuite.scala @@ -1,21 +1,20 @@ package com.wavesplatform.it.sync import com.typesafe.config.{Config, ConfigFactory} +import com.wavesplatform.it.BaseFunSuite import com.wavesplatform.it.api.State import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.util._ -import org.scalatest.{CancelAfterFailure, FunSuite, Matchers} +import com.wavesplatform.test._ + import scala.concurrent.duration._ -class MinerStateTestSuite extends FunSuite with CancelAfterFailure with NodesFromDocker with Matchers { +class MinerStateTestSuite extends BaseFunSuite { import MinerStateTestSuite._ override protected def nodeConfigs: Seq[Config] = Configs private val transferAmount = 1000.waves - private def miner = nodes.head private def last = nodes.last test("node w/o balance can forge blocks after effective balance increase") { 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 2a546b7638b..83bf296e519 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 @@ -7,14 +7,12 @@ import com.wavesplatform.common.utils._ import com.wavesplatform.it._ import com.wavesplatform.it.api.AsyncHttpApi._ import com.wavesplatform.it.api._ -import com.wavesplatform.it.transactions.BaseTransactionSuiteLike -import com.wavesplatform.it.util._ +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.utils._ -import org.scalatest.FreeSpec import play.api.libs.json._ import scala.concurrent.Future.traverse @@ -22,7 +20,7 @@ import scala.concurrent.duration._ import scala.concurrent.{Await, Future} import scala.util.Random -class NFTBalanceSuite extends FreeSpec with BaseTransactionSuiteLike { +class NFTBalanceSuite extends BaseFreeSpec { import NFTBalanceSuite._ override protected def nodeConfigs: Seq[Config] = 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 15973294b81..180030260da 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,14 +6,12 @@ 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.transactions.NodesFromDocker -import com.wavesplatform.it.util._ -import com.wavesplatform.it.{ReportingTestName, WaitForHeight2} +import com.wavesplatform.it.{BaseFreeSpec, WaitForHeight2} +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer.TransferTransaction -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers} -class NodeRestartTestSuite extends FreeSpec with Matchers with WaitForHeight2 with CancelAfterFailure with ReportingTestName with NodesFromDocker { +class NodeRestartTestSuite extends BaseFreeSpec with WaitForHeight2 { import NodeRestartTestSuite._ override protected def nodeConfigs: Seq[Config] = Configs diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/ObsoleteHandlersSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/ObsoleteHandlersSuite.scala index e71da94c2cc..7476ed773b6 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/ObsoleteHandlersSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/ObsoleteHandlersSuite.scala @@ -1,15 +1,15 @@ package com.wavesplatform.it.sync import com.typesafe.config.Config -import com.wavesplatform.api.http.requests.{CreateAliasRequest, DataRequest, LeaseCancelRequest, LeaseRequest, MassTransferRequest, SponsorFeeRequest, TransferRequest} +import com.wavesplatform.api.http.requests._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.Transaction import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, IntegerDataEntry, StringDataEntry} +import com.wavesplatform.test._ import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer 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 5d65e69f5b1..b178c41b944 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 @@ -11,15 +11,13 @@ 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.transactions.NodesFromDocker -import com.wavesplatform.it.{NodeConfigs, WaitForHeight2} +import com.wavesplatform.it.{BaseFunSuite, NodeConfigs, WaitForHeight2} import com.wavesplatform.network.RawBytes -import org.scalatest.{CancelAfterFailure, FunSuite, Matchers} import play.api.libs.json.{JsSuccess, Json, Reads} import scala.util.Random -class PoSSuite extends FunSuite with Matchers with NodesFromDocker with WaitForHeight2 with CancelAfterFailure { +class PoSSuite extends BaseFunSuite with WaitForHeight2 { private val signerPK = KeyPair.fromSeed(nodeConfigs.last.getString("account-seed")).explicitGet() diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/RewardsTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/RewardsTestSuite.scala index bc0e62a36e6..e56428fdd95 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/RewardsTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/RewardsTestSuite.scala @@ -3,28 +3,19 @@ package com.wavesplatform.it.sync import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.api.http.ApiError.CustomValidationError import com.wavesplatform.features.{BlockchainFeatureStatus, BlockchainFeatures} +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.it.NodeConfigs.Default import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync.activation.ActivationStatusRequest -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{Node, ReportingTestName} -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers, OptionValues} +import org.scalatest.OptionValues import scala.concurrent.duration._ -class RewardsTestSuite - extends FreeSpec - with Matchers - with CancelAfterFailure - with NodesFromDocker - with ActivationStatusRequest - with ReportingTestName - with OptionValues { +class RewardsTestSuite extends BaseFreeSpec with ActivationStatusRequest with OptionValues { import RewardsTestSuite._ override protected def nodeConfigs: Seq[Config] = Configs - val miner: Node = nodes.head lazy val initMinerBalance: Long = miner.balanceAtHeight(miner.address, 1) val InitialAmount = 6400000000000000L diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/RideCreateMerkleRootTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/RideCreateMerkleRootTestSuite.scala index 805bb72a7a1..5b023a34679 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/RideCreateMerkleRootTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/RideCreateMerkleRootTestSuite.scala @@ -8,8 +8,7 @@ import com.wavesplatform.common.utils.{Base58, EitherExt2} import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.Transaction -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{Node, NodeConfigs, ReportingTestName, TransferSending} +import com.wavesplatform.it.{BaseFunSuite, NodeConfigs, TransferSending} import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.state._ @@ -18,15 +17,10 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{Proofs, TxVersion} import org.scalatest.prop.TableDrivenPropertyChecks -import org.scalatest.{CancelAfterFailure, FunSuite, Matchers} class RideCreateMerkleRootTestSuite - extends FunSuite - with CancelAfterFailure + extends BaseFunSuite with TransferSending - with NodesFromDocker - with ReportingTestName - with Matchers with TableDrivenPropertyChecks { override def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder @@ -43,8 +37,6 @@ class RideCreateMerkleRootTestSuite .withDefault(1) .buildNonConflicting() - private def sender: Node = nodes.last - test("Ride createMerkleRoot") { val script = """ |{-# STDLIB_VERSION 4 #-} 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 bac14b0d8ec..3bf0d4ae65c 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,32 +1,26 @@ 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.SyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state.{BooleanDataEntry, IntegerDataEntry, StringDataEntry} -import com.wavesplatform.transaction.TxVersion +import com.wavesplatform.test._ +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, TxVersion} import org.scalatest.prop.TableDrivenPropertyChecks -import org.scalatest.{CancelAfterFailure, FunSuite, Matchers} import scala.concurrent.Await import scala.concurrent.duration._ import scala.util.Random @LoadTest -class RollbackSuite - extends FunSuite - with CancelAfterFailure - with TransferSending - with NodesFromDocker - with ReportingTestName - with Matchers - with TableDrivenPropertyChecks { +class RollbackSuite extends BaseFunSuite with TransferSending with TableDrivenPropertyChecks { override def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder .overrideBase(_.quorum(0)) @@ -35,10 +29,9 @@ class RollbackSuite .withSpecial(1, _.nonMiner) .buildNonConflicting() - private val nodeAddresses = nodeConfigs.map(_.getString("address")).toSet - private def sender: Node = nodes.last - private def miner: Node = nodes.head - private def firstAddress: String = sender.address + private lazy val nodeAddresses = nodeConfigs.map(_.getString("address")).toSet + + private def notMinerAddress: String = notMiner.address test("Apply the same transfer transactions twice with return to UTX") { @@ -91,19 +84,19 @@ class RollbackSuite test("Alias transaction rollback should work fine") { val alias = "test_alias4" - val aliasTxId = sender.createAlias(sender.keyPair, alias, transferAmount).id + val aliasTxId = sender.createAlias(notMiner.keyPair, alias, transferAmount).id nodes.waitForHeightAriseAndTxPresent(aliasTxId) - val txsBefore = sender.transactionsByAddress(firstAddress, 10) + val txsBefore = sender.transactionsByAddress(notMinerAddress, 10) val txHeight = sender.waitForTransaction(aliasTxId).height nodes.rollback(txHeight - 1, returnToUTX = false) nodes.waitForHeight(txHeight + 1) - val secondAliasTxId = sender.createAlias(sender.keyPair, alias, transferAmount).id + val secondAliasTxId = sender.createAlias(notMiner.keyPair, alias, transferAmount).id nodes.waitForHeightAriseAndTxPresent(secondAliasTxId) - sender.transactionsByAddress(firstAddress, 10) shouldNot contain theSameElementsAs txsBefore + sender.transactionsByAddress(notMinerAddress, 10) shouldNot contain theSameElementsAs txsBefore } @@ -112,33 +105,33 @@ class RollbackSuite val entry1 = IntegerDataEntry("1", 0) val entry2 = BooleanDataEntry("2", value = true) val entry3 = IntegerDataEntry("1", 1) - val txsBefore0 = sender.transactionsByAddress(firstAddress, 10) + val txsBefore0 = sender.transactionsByAddress(notMinerAddress, 10) - val tx1 = sender.putData(sender.keyPair, List(entry1), calcDataFee(List(entry1), TxVersion.V1)).id + val tx1 = sender.putData(notMiner.keyPair, List(entry1), calcDataFee(List(entry1), TxVersion.V1)).id nodes.waitForHeightAriseAndTxPresent(tx1) - val txsBefore1 = sender.transactionsByAddress(firstAddress, 10) + val txsBefore1 = sender.transactionsByAddress(notMinerAddress, 10) val tx1height = sender.waitForTransaction(tx1).height - val tx2 = sender.putData(sender.keyPair, List(entry2, entry3), calcDataFee(List(entry2, entry3), TxVersion.V1)).id + val tx2 = sender.putData(notMiner.keyPair, List(entry2, entry3), calcDataFee(List(entry2, entry3), TxVersion.V1)).id nodes.waitForHeightAriseAndTxPresent(tx2) - val data2 = sender.getData(firstAddress) + val data2 = sender.getData(notMinerAddress) assert(data2 == List(entry3, entry2)) nodes.rollback(tx1height, returnToUTX = false) nodes.waitForSameBlockHeadersAt(tx1height) - val data1 = node.getData(firstAddress) + val data1 = node.getData(notMinerAddress) assert(data1 == List(entry1)) - sender.transactionsByAddress(firstAddress, 10) should contain theSameElementsAs txsBefore1 + sender.transactionsByAddress(notMinerAddress, 10) should contain theSameElementsAs txsBefore1 nodes.rollback(tx1height - 1, returnToUTX = false) nodes.waitForSameBlockHeadersAt(tx1height - 1) - val data0 = node.getData(firstAddress) + val data0 = node.getData(notMinerAddress) assert(data0 == List.empty) - sender.transactionsByAddress(firstAddress, 10) should contain theSameElementsAs txsBefore0 + sender.transactionsByAddress(notMinerAddress, 10) should contain theSameElementsAs txsBefore0 } test("Sponsorship transaction rollback") { @@ -146,20 +139,20 @@ class RollbackSuite val sponsorAssetId = sender - .issue(sender.keyPair, "SponsoredAsset", "For test usage", sponsorAssetTotal, reissuable = false, fee = issueFee) + .issue(notMiner.keyPair, "SponsoredAsset", "For test usage", sponsorAssetTotal, reissuable = false, fee = issueFee) .id nodes.waitForHeightAriseAndTxPresent(sponsorAssetId) - val sponsorId = sender.sponsorAsset(sender.keyPair, sponsorAssetId, baseFee = 100L, fee = issueFee).id + val sponsorId = sender.sponsorAsset(notMiner.keyPair, sponsorAssetId, baseFee = 100L, fee = issueFee).id nodes.waitForHeightAriseAndTxPresent(sponsorId) val height = sender.waitForTransaction(sponsorId).height - val txsBefore1 = sender.transactionsByAddress(firstAddress, 10) + val txsBefore1 = sender.transactionsByAddress(notMinerAddress, 10) val assetDetailsBefore = sender.assetsDetails(sponsorAssetId) nodes.waitForHeightArise() - val sponsorSecondId = sender.sponsorAsset(sender.keyPair, sponsorAssetId, baseFee = 2 * 100L, fee = issueFee).id + val sponsorSecondId = sender.sponsorAsset(notMiner.keyPair, sponsorAssetId, baseFee = 2 * 100L, fee = issueFee).id nodes.waitForHeightAriseAndTxPresent(sponsorSecondId) nodes.rollback(height, returnToUTX = false) @@ -169,7 +162,7 @@ class RollbackSuite val assetDetailsAfter = sender.assetsDetails(sponsorAssetId) assert(assetDetailsAfter.minSponsoredAssetFee == assetDetailsBefore.minSponsoredAssetFee) - sender.transactionsByAddress(sender.address, 10) should contain theSameElementsAs txsBefore1 + sender.transactionsByAddress(notMinerAddress, 10) should contain theSameElementsAs txsBefore1 } test("transfer depends from data tx") { @@ -182,7 +175,7 @@ class RollbackSuite case _ => false }""".stripMargin - val pkSwapBC1 = KeyPair.fromSeed(sender.seed(firstAddress)).explicitGet() + val pkSwapBC1 = notMiner.keyPair val script = ScriptCompiler(scriptText, isAssetScript = false, ScriptEstimatorV2).explicitGet()._1 val sc1SetTx = SetScriptTransaction .selfSigned(1.toByte, sender = pkSwapBC1, script = Some(script), fee = setScriptFee, timestamp = System.currentTimeMillis()) @@ -195,11 +188,14 @@ class RollbackSuite nodes.waitForHeightArise() val entry1 = StringDataEntry("oracle", "yes") - val dtx = sender.putData(sender.keyPair, List(entry1), calcDataFee(List(entry1), TxVersion.V1) + smartFee).id + val dtx = sender.putData(sender.keyPair, List(entry1), 0.1.waves).id nodes.waitForHeightAriseAndTxPresent(dtx) - val tx = sender.transfer(sender.keyPair, firstAddress, transferAmount, smartMinFee, waitForTx = true).id - nodes.waitForHeightAriseAndTxPresent(tx) + val transfer = TransferTransaction + .create(2.toByte, pkSwapBC1.publicKey, sender.publicKey.toAddress, Waves, transferAmount, Waves, smartMinFee, ByteStr.empty, System.currentTimeMillis(), Proofs.empty) + .explicitGet() + + nodes.waitForHeightAriseAndTxPresent(sender.signedBroadcast(transfer.json(), waitForTx = true).id) //as rollback is too fast, we should blacklist nodes from each other before rollback sender.blacklist(miner.networkAddress) @@ -213,7 +209,7 @@ class RollbackSuite nodes.waitForHeightArise() assert(sender.findTransactionInfo(dtx).isDefined) - assert(sender.findTransactionInfo(tx).isDefined) + assert(sender.findTransactionInfo(transfer.id().toString).isDefined) } @@ -221,7 +217,7 @@ class RollbackSuite Table( ("num", "name"), (1, "1 of N"), - (nodes.size, "N of N") + (nodeConfigs.size, "N of N") ) ) { (num, name) => test(s"generate more blocks and resynchronise after rollback $name") { 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 6d720da7aa9..b394974f691 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 @@ -4,24 +4,19 @@ 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.Node import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.TransactionInfo -import com.wavesplatform.it.transactions.NodesFromDocker +import com.wavesplatform.it.{BaseFunSuite, Node} import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction -import org.scalatest.{CancelAfterFailure, FunSuite, Matchers} import scala.util.{Random, Try} -class UtxSuite extends FunSuite with CancelAfterFailure with NodesFromDocker with Matchers { - private val miner: Node = nodes.head - private val notMiner: Node = nodes(1) - +class UtxSuite extends BaseFunSuite { private var whitelistedAccount: KeyPair = _ private var whitelistedDAppAccount: KeyPair = _ 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 c0902d7aca5..cc5de84f00e 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 @@ -11,9 +11,9 @@ 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.it.util._ import com.wavesplatform.it.{NTPTime, NodeConfigs} import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.assets.exchange.{AssetPair, Order} @@ -203,7 +203,7 @@ class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTim test("accept invalid by asset script in payment InvokeScriptTransaction to utx and save it as failed after activation height") { sender.setAssetScript(asset, dAppKP, priorityFee, assetScript(true), waitForTx = true) - val invokesCount = MaxTxsInMicroBlock * 2 + val invokesCount = MaxTxsInMicroBlock * 2 val callerBalance = sender.balance(caller).balance val callerAssetBalance = { val balance = sender.assetBalance(caller, asset).balance @@ -406,7 +406,6 @@ class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTim buy.matcherFee, sell.matcherFee, matcherFee + smartFee * 3, - matcherFeeAssetId = Some(feeAsset), version = TxVersion.V3 ) .id @@ -436,7 +435,6 @@ class AcceptFailedScriptActivationSuite extends BaseTransactionSuite with NTPTim buy.matcherFee, sell.matcherFee, matcherFee + smartFee * 3, - matcherFeeAssetId = Some(feeAsset), version = TxVersion.V3 ) .id diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/ActivationStatusRequest.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/ActivationStatusRequest.scala index f364e38177e..5a367aa2b21 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/ActivationStatusRequest.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/ActivationStatusRequest.scala @@ -3,7 +3,7 @@ package com.wavesplatform.it.sync.activation import com.wavesplatform.features.BlockchainFeatureStatus import com.wavesplatform.features.api.{FeatureActivationStatus, NodeFeatureStatus} import org.scalactic.source.Position -import org.scalatest.Matchers +import org.scalatest.matchers.should.Matchers trait ActivationStatusRequest extends Matchers { def assertVotingStatus( 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 c08cbc2ce93..4d0127d15c1 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 @@ -3,18 +3,10 @@ package com.wavesplatform.it.sync.activation import com.typesafe.config.Config import com.wavesplatform.features.api.NodeFeatureStatus import com.wavesplatform.features.{BlockchainFeatureStatus, BlockchainFeatures} -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{NodeConfigs, ReportingTestName} -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers} import com.wavesplatform.it.api.SyncHttpApi._ +import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs, ReportingTestName} -class FeatureActivationTestSuite - extends FreeSpec - with Matchers - with CancelAfterFailure - with NodesFromDocker - with ActivationStatusRequest - with ReportingTestName { +class FeatureActivationTestSuite extends BaseFreeSpec with ActivationStatusRequest with ReportingTestName { private val votingInterval = 12 private val blocksForActivation = 12 // should be even 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 70f4236e8c6..93e5205bd89 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 @@ -3,19 +3,13 @@ package com.wavesplatform.it.sync.activation import com.typesafe.config.Config import com.wavesplatform.features.BlockchainFeatureStatus import com.wavesplatform.features.api.{FeatureActivationStatus, NodeFeatureStatus} -import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.BlockHeader -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{NodeConfigs, ReportingTestName} -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers} +import com.wavesplatform.it.api.SyncHttpApi._ +import com.wavesplatform.it.{BaseFreeSpec, NodeConfigs} class NotActivateFeatureTestSuite - extends FreeSpec - with Matchers - with CancelAfterFailure - with ActivationStatusRequest - with ReportingTestName - with NodesFromDocker { + extends BaseFreeSpec + with ActivationStatusRequest { private val votingInterval = 14 private val blocksForActivation = 14 diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/PreActivatedFeaturesTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/PreActivatedFeaturesTestSuite.scala index 3e8dff69551..c0d75cd0b7c 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/activation/PreActivatedFeaturesTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/activation/PreActivatedFeaturesTestSuite.scala @@ -3,16 +3,9 @@ import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.features.api.NodeFeatureStatus import com.wavesplatform.features.{BlockchainFeatureStatus, BlockchainFeatures} import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{Docker, ReportingTestName} -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers} -class PreActivatedFeaturesTestSuite - extends FreeSpec - with Matchers - with CancelAfterFailure - with NodesFromDocker - with ActivationStatusRequest - with ReportingTestName { +import com.wavesplatform.it.{BaseFreeSpec, Docker} + +class PreActivatedFeaturesTestSuite extends BaseFreeSpec with ActivationStatusRequest { override protected def nodeConfigs: Seq[Config] = PreActivatedFeaturesTestSuite.Configs override protected def beforeAll(): Unit = { diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/block/BlockHeadersTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/block/BlockHeadersTestSuite.scala index edf1d02f22f..e14627e9fec 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/block/BlockHeadersTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/block/BlockHeadersTestSuite.scala @@ -9,10 +9,15 @@ import com.wavesplatform.it.{Node, NodeConfigs, TransferSending} import org.scalactic.source.Position import org.scalatest._ -import scala.concurrent.duration._ import scala.concurrent.Await +import scala.concurrent.duration._ -class BlockHeadersTestSuite extends FunSuite with CancelAfterFailure with TransferSending with NodesFromDocker with Matchers { +class BlockHeadersTestSuite + extends funsuite.AnyFunSuite + with CancelAfterFailure + with TransferSending + with NodesFromDocker + with matchers.should.Matchers { private val activationHeight = 4 private val minerDesiredReward = 750000000 @@ -23,8 +28,9 @@ class BlockHeadersTestSuite extends FunSuite with CancelAfterFailure with Transf override protected def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder - .overrideBase(_.raw( - s"""waves { + .overrideBase( + _.raw( + s"""waves { | blockchain.custom.functionality { | pre-activated-features = { | ${BlockchainFeatures.BlockReward.id} = $activationHeight @@ -39,7 +45,8 @@ class BlockHeadersTestSuite extends FunSuite with CancelAfterFailure with Transf | rewards.desired = $minerDesiredReward | miner.quorum = 1 |}""".stripMargin - )) + ) + ) .withDefault(1) .withSpecial(_.nonMiner) .buildNonConflicting() diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/debug/DebugConfigInfo.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/debug/DebugConfigInfo.scala index 82f59a5f5a5..2c0d22d9ce6 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/debug/DebugConfigInfo.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/debug/DebugConfigInfo.scala @@ -1,12 +1,10 @@ package com.wavesplatform.it.sync.debug import com.typesafe.config.Config -import com.wavesplatform.it.NodeConfigs import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import org.scalatest.FunSuite +import com.wavesplatform.it.{BaseFunSuite, NodeConfigs} -class DebugConfigInfo extends FunSuite with NodesFromDocker { +class DebugConfigInfo extends BaseFunSuite { override protected val nodeConfigs: Seq[Config] = NodeConfigs.newBuilder.withDefault(1).build() diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/debug/DebugPortfoliosSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/debug/DebugPortfoliosSuite.scala index 4b8750f19e0..f3840120aef 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/debug/DebugPortfoliosSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/debug/DebugPortfoliosSuite.scala @@ -1,22 +1,19 @@ package com.wavesplatform.it.sync.debug import com.typesafe.config.Config -import com.wavesplatform.it.{Node, NodeConfigs} import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.util._ import com.wavesplatform.it.sync._ -import org.scalatest.FunSuite +import com.wavesplatform.it.transactions.NodesFromDocker +import com.wavesplatform.it.{BaseFunSuite, NodeConfigs} +import com.wavesplatform.test._ -class DebugPortfoliosSuite extends FunSuite with NodesFromDocker { +class DebugPortfoliosSuite extends BaseFunSuite with NodesFromDocker { override protected def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder .overrideBase(_.quorum(0)) .withDefault(entitiesNumber = 1) .buildNonConflicting() - private def sender: Node = nodes.head - private lazy val firstAcc = sender.createKeyPair() private lazy val secondAcc = sender.createKeyPair() 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 7963e2180eb..82544f2462b 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 @@ -1,18 +1,13 @@ package com.wavesplatform.it.sync.grpc import com.typesafe.config.Config +import com.wavesplatform.it._ import com.wavesplatform.it.sync._ import com.wavesplatform.it.sync.activation.ActivationStatusRequest -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{GrpcIntegrationSuiteWithThreeAddress, NodeConfigs, ReportingTestName} -import org.scalatest.{FreeSpec, Matchers} class AssetsApiGrpcSuite - extends FreeSpec - with Matchers - with NodesFromDocker + extends BaseFreeSpec with ActivationStatusRequest - with ReportingTestName with GrpcIntegrationSuiteWithThreeAddress { "nftList returns all NFT" in { diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/BlockV5GrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/BlockV5GrpcSuite.scala index 6ce0667f8ea..4f722357a66 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/BlockV5GrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/BlockV5GrpcSuite.scala @@ -8,19 +8,14 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.sync.activation.ActivationStatusRequest -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{GrpcIntegrationSuiteWithThreeAddress, NodeConfigs, ReportingTestName} -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers, OptionValues} +import com.wavesplatform.it.{GrpcIntegrationSuiteWithThreeAddress, NodeConfigs} +import org.scalatest._ import scala.concurrent.duration._ class BlockV5GrpcSuite - extends FreeSpec - with Matchers - with CancelAfterFailure - with NodesFromDocker + extends freespec.AnyFreeSpec with ActivationStatusRequest - with ReportingTestName with OptionValues with GrpcIntegrationSuiteWithThreeAddress { diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/CreateAliasTransactionGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/CreateAliasTransactionGrpcSuite.scala index 4e910ed4bad..559b1dc27f9 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/CreateAliasTransactionGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/CreateAliasTransactionGrpcSuite.scala @@ -5,7 +5,7 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.NTPTime import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.sync.{aliasTxSupportedVersions, minFee, transferAmount} -import com.wavesplatform.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.protobuf.transaction.{PBRecipients, Recipient} import io.grpc.Status.Code import org.scalatest.prop.TableDrivenPropertyChecks 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 96e14dfb903..d71e34dc18a 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 @@ -5,7 +5,7 @@ import com.wavesplatform.account.{Address, KeyPair} import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.sync.{dataTxSupportedVersions, minFee} -import com.wavesplatform.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 import com.wavesplatform.protobuf.transaction.DataTransactionData.DataEntry import com.wavesplatform.protobuf.transaction.{DataTransactionData, PBRecipients, PBTransactions, Recipient} 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 e16ee0e4730..982ad9af9d0 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 @@ -4,7 +4,7 @@ import com.wavesplatform.common.utils.{Base64, EitherExt2} import com.wavesplatform.it.NTPTime import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.sync.{matcherFee, minFee, someAssetAmount} -import com.wavesplatform.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.protobuf.transaction.{PBTransactions, Recipient} import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxVersion diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/FailedTransactionGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/FailedTransactionGrpcSuite.scala index 3126d601027..ca0565a653c 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/FailedTransactionGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/FailedTransactionGrpcSuite.scala @@ -10,7 +10,6 @@ import com.wavesplatform.common.utils.{Base58, EitherExt2} import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.sync._ import com.wavesplatform.it.sync.transactions.FailedTransactionSuiteLike -import com.wavesplatform.it.util._ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms @@ -20,6 +19,7 @@ import com.wavesplatform.protobuf.Amount import com.wavesplatform.protobuf.transaction.DataTransactionData.DataEntry import com.wavesplatform.protobuf.transaction.{PBRecipients, PBSignedTransaction, PBTransactions, Recipient} import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, IntegerDataEntry, StringDataEntry} +import com.wavesplatform.test._ import com.wavesplatform.transaction.assets.exchange.AssetPair import com.wavesplatform.transaction.smart.script.ScriptCompiler diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/GrpcBaseTransactionSuiteLike.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/GrpcBaseTransactionSuiteLike.scala index 8e5ce0c1c1c..957e81e5a32 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/GrpcBaseTransactionSuiteLike.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/GrpcBaseTransactionSuiteLike.scala @@ -1,50 +1,11 @@ package com.wavesplatform.it.sync.grpc -import java.io.File - -import com.typesafe.config.{Config, ConfigFactory} -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.{ExternalNode, GrpcIntegrationSuiteWithThreeAddress, GrpcWaitForHeight, Node, NodeConfigs} -import monix.eval.Coeval -import org.scalatest.{BeforeAndAfterAll, FunSuite, Suite} - -import scala.concurrent.ExecutionContext -import scala.jdk.CollectionConverters._ +import com.wavesplatform.it.{GrpcIntegrationSuiteWithThreeAddress, GrpcWaitForHeight, Nodes} +import org.scalatest._ trait GrpcBaseTransactionSuiteLike extends GrpcWaitForHeight - with GrpcIntegrationSuiteWithThreeAddress - with BeforeAndAfterAll - with NodesFromDocker { this: Suite => - - protected implicit val ec: ExecutionContext = ExecutionContext.Implicits.global - - protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() - - // protected because https://github.com/sbt/zinc/issues/292 - protected lazy val theNodes: Coeval[Seq[Node]] = Coeval.evalOnce { - Option(System.getProperty("waves.it.config.file")) match { - case None => dockerNodes() - case Some(filePath) => - val defaultConfig = ConfigFactory.load() - ConfigFactory - .parseFile(new File(filePath)) - .getConfigList("nodes") - .asScala - .toSeq - .map(cfg => new ExternalNode(cfg.withFallback(defaultConfig).resolve())) - } - } - - protected override def beforeAll(): Unit = { - theNodes.run() - super.beforeAll() - } + with GrpcIntegrationSuiteWithThreeAddress { this: TestSuite with Nodes => } -abstract class GrpcBaseTransactionSuite extends FunSuite with GrpcBaseTransactionSuiteLike +abstract class GrpcBaseTransactionSuite extends funsuite.AnyFunSuite with GrpcBaseTransactionSuiteLike diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/InvokeScriptTransactionGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/InvokeScriptTransactionGrpcSuite.scala index a783183bdb8..dcec702b471 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/InvokeScriptTransactionGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/InvokeScriptTransactionGrpcSuite.scala @@ -7,13 +7,13 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.sync._ import com.wavesplatform.it.sync.smartcontract.invokeScrTxSupportedVersions -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, FUNCTION_CALL} import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.protobuf.transaction.DataTransactionData.DataEntry import com.wavesplatform.protobuf.transaction.{PBRecipients, PBTransactions, Recipient} +import com.wavesplatform.test._ import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.smart.script.ScriptCompiler import io.grpc.Status.Code diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/IssueTransactionGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/IssueTransactionGrpcSuite.scala index 0dac6cbf8a3..ae0bd771cbe 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/IssueTransactionGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/IssueTransactionGrpcSuite.scala @@ -4,9 +4,9 @@ import com.wavesplatform.common.utils.{Base64, EitherExt2} import com.wavesplatform.it.NTPTime import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.sync._ -import com.wavesplatform.it.util._ import com.wavesplatform.lang.script.Script import com.wavesplatform.protobuf.transaction.PBTransactions +import com.wavesplatform.test._ import com.wavesplatform.transaction.assets.IssueTransaction import io.grpc.Status.Code import org.scalatest.prop.TableDrivenPropertyChecks diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/LeasingTransactionsGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/LeasingTransactionsGrpcSuite.scala index 872b9defbba..5c3c23b721b 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/LeasingTransactionsGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/LeasingTransactionsGrpcSuite.scala @@ -5,8 +5,8 @@ import com.wavesplatform.api.grpc.LeaseResponse import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.SyncGrpcApi._ import com.wavesplatform.it.sync._ -import com.wavesplatform.it.util._ import com.wavesplatform.protobuf.transaction.{PBRecipients, PBTransactions, Recipient} +import com.wavesplatform.test._ import com.wavesplatform.transaction.Transaction import com.wavesplatform.transaction.lease.LeaseTransaction import io.grpc.Status.Code @@ -183,7 +183,7 @@ class LeasingTransactionsGrpcSuite extends GrpcBaseTransactionSuite { private def toResponse(tx: Transaction, height: Long): LeaseResponse = { val leaseTx = tx.asInstanceOf[LeaseTransaction] - val leaseTxId = ByteString.copyFrom(leaseTx.id.value().arr) + val leaseTxId = ByteString.copyFrom(leaseTx.id().arr) LeaseResponse( leaseId = leaseTxId, originTransactionId = leaseTxId, diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/ReissueTransactionGrpcSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/ReissueTransactionGrpcSuite.scala index d8e02ec7aef..c6b28df3f20 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/ReissueTransactionGrpcSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/grpc/ReissueTransactionGrpcSuite.scala @@ -1,12 +1,11 @@ package com.wavesplatform.it.sync.grpc +import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.NTPTime -import com.wavesplatform.it.sync._ import com.wavesplatform.it.api.SyncGrpcApi._ -import com.wavesplatform.protobuf.transaction.PBTransactions -import com.wavesplatform.it.util._ -import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.protobuf.transaction.Recipient +import com.wavesplatform.it.sync._ +import com.wavesplatform.protobuf.transaction.{PBTransactions, Recipient} +import com.wavesplatform.test._ import io.grpc.Status.Code class ReissueTransactionGrpcSuite extends GrpcBaseTransactionSuite with NTPTime { diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/network/DetectBrokenConnectionsTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/network/DetectBrokenConnectionsTestSuite.scala index 5fc6752a866..83089fd721e 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/network/DetectBrokenConnectionsTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/network/DetectBrokenConnectionsTestSuite.scala @@ -1,15 +1,13 @@ package com.wavesplatform.it.sync.network import com.typesafe.config.{Config, ConfigFactory} +import com.wavesplatform.it.BaseFreeSpec import com.wavesplatform.it.NodeConfigs.Default -import com.wavesplatform.it.ReportingTestName import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.transactions.NodesFromDocker -import org.scalatest.{FreeSpec, Matchers} import scala.concurrent.duration._ -class DetectBrokenConnectionsTestSuite extends FreeSpec with Matchers with ReportingTestName with NodesFromDocker { +class DetectBrokenConnectionsTestSuite extends BaseFreeSpec { override protected def nodeConfigs: Seq[Config] = { val highPriorityConfig = ConfigFactory.parseString("waves.network.break-idle-connections-timeout = 20s") 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 0bc0035da12..ee4250a41b6 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,20 +3,12 @@ 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.transactions.NodesFromDocker -import com.wavesplatform.it.{Node, ReportingTestName, WaitForHeight2} -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers} +import com.wavesplatform.it.{BaseFreeSpec, Node, WaitForHeight2} import scala.concurrent.Await import scala.concurrent.duration._ -class NetworkSeparationTestSuite - extends FreeSpec - with Matchers - with WaitForHeight2 - with CancelAfterFailure - with ReportingTestName - with NodesFromDocker { +class NetworkSeparationTestSuite extends BaseFreeSpec with WaitForHeight2 { import NetworkSeparationTestSuite._ override protected def nodeConfigs: Seq[Config] = Configs diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/network/NetworkUniqueConnectionsTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/network/NetworkUniqueConnectionsTestSuite.scala index d5ee44338bd..bcfb4edb5a9 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/network/NetworkUniqueConnectionsTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/network/NetworkUniqueConnectionsTestSuite.scala @@ -4,13 +4,13 @@ import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.{DockerBased, Node, NodeConfigs, Nodes} import com.wavesplatform.utils.ScorexLogging -import org.scalatest.{FreeSpec, Matchers} +import org.scalatest._ import scala.concurrent._ import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} -class NetworkUniqueConnectionsTestSuite extends FreeSpec with Matchers with DockerBased with ScorexLogging with Nodes { +class NetworkUniqueConnectionsTestSuite extends freespec.AnyFreeSpec with matchers.should.Matchers with DockerBased with ScorexLogging with Nodes { import NetworkUniqueConnectionsTestSuite._ "nodes should up and connect with each other" in { @@ -40,8 +40,8 @@ class NetworkUniqueConnectionsTestSuite extends FreeSpec with Matchers with Dock withClue("Should fail with TimeoutException, because the connectionAttempt should fail") { Try(firstNode.waitForPeers(2, 30.seconds)) match { case Failure(ApiCallException(_: TimeoutException)) => // Pass - case Failure(exception) => fail(exception) - case Success(v) => fail(s"Expected TimeoutException, got $v") + case Failure(exception) => fail(exception) + case Success(v) => fail(s"Expected TimeoutException, got $v") } } } 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 17e35e280ff..9106f10a609 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 @@ -14,11 +14,10 @@ import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.network.{RawBytes, TransactionSpec} import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer._ -import org.scalatest._ import scala.concurrent.duration._ -class SimpleTransactionsSuite extends BaseTransactionSuite with Matchers { +class SimpleTransactionsSuite extends BaseTransactionSuite { override protected def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder .overrideBase(_.quorum(0)) 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 770b3a90802..47ff9d2d0ed 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 @@ -4,11 +4,11 @@ import com.wavesplatform.api.http.ApiError.TransactionNotAllowedByAssetScript import com.wavesplatform.api.http.requests.IssueRequest import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.SyncHttpApi.AssertiveApiError -import com.wavesplatform.it.util._ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.protobuf.transaction.{DataTransactionData, PBTransactions} import com.wavesplatform.state.DataEntry +import com.wavesplatform.test._ import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler 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 b74b924268d..60cc2d7ae51 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 @@ -5,7 +5,7 @@ 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.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.SetScriptTransaction 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 400fa779281..a65151d27cb 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 @@ -6,7 +6,7 @@ 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.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.lease.LeaseTransaction 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 b70631dc86c..87b4fc3b9b9 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 @@ -7,9 +7,8 @@ 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.v2.ScriptEstimatorV2 import com.wavesplatform.state.BinaryDataEntry +import com.wavesplatform.test._ import org.scalatest.CancelAfterFailure import scala.concurrent.duration._ diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/HodlContractTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/HodlContractTransactionSuite.scala index 4b41b950612..f58f318b606 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/HodlContractTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/HodlContractTransactionSuite.scala @@ -5,10 +5,10 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.{PutDataResponse, TransactionInfo} import com.wavesplatform.it.sync.{minFee, setScriptFee} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.compiler.Terms.CONST_LONG import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler 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 3976264062b..bf99e20545d 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 @@ -12,9 +12,9 @@ import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.state.BinaryDataEntry import com.wavesplatform.transaction.smart.script.ScriptCompiler -import org.scalatest.{CancelAfterFailure, Matchers, OptionValues} +import org.scalatest._ -class InvokeCalcIssueSuite extends BaseTransactionSuite with Matchers with CancelAfterFailure with OptionValues { +class InvokeCalcIssueSuite extends BaseTransactionSuite with CancelAfterFailure with OptionValues { import InvokeCalcIssueSuite._ override protected def nodeConfigs: Seq[Config] = diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeMultiplePaymentsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeMultiplePaymentsSuite.scala index 4f8c5a0d829..98360c47a89 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeMultiplePaymentsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeMultiplePaymentsSuite.scala @@ -10,6 +10,7 @@ import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.compiler.Terms.CONST_STRING import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptErrorMsgSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptErrorMsgSuite.scala index 9275e2366be..047a2036669 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptErrorMsgSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptErrorMsgSuite.scala @@ -5,8 +5,8 @@ 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.it.util._ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler 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 e2e17659fd8..2fd2b482cd1 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 @@ -4,10 +4,10 @@ import com.typesafe.config.Config import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.NodeConfigs import com.wavesplatform.it.api.SyncHttpApi._ -import com.wavesplatform.it.sync.smartcontract.RideV4ActivationSuite._ import com.wavesplatform.it.sync._ +import com.wavesplatform.it.sync.smartcontract.RideV4ActivationSuite._ import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer import org.scalatest.CancelAfterFailure diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionStateChangesSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionStateChangesSuite.scala index e3beb55503a..309cb277dda 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionStateChangesSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionStateChangesSuite.scala @@ -5,9 +5,9 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api._ import com.wavesplatform.it.sync._ import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.compiler.Terms.{CONST_LONG, CONST_STRING} import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer import org.scalactic.source.Position diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionStateChangesTransfersSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionStateChangesTransfersSuite.scala index b772b2be502..0154e983360 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionStateChangesTransfersSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptTransactionStateChangesTransfersSuite.scala @@ -4,9 +4,9 @@ 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.it.util._ import com.wavesplatform.lang.v1.compiler.Terms.CONST_LONG import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler 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 c341fd92f2d..6e6c1ce3878 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 @@ -10,11 +10,11 @@ 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.it.util._ import com.wavesplatform.lang.v1.compiler.Terms.CONST_BYTESTR import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.state._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptWithSmartAccountAndAssetSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptWithSmartAccountAndAssetSuite.scala index 4dc6f99f684..be54d90d44b 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptWithSmartAccountAndAssetSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptWithSmartAccountAndAssetSuite.scala @@ -6,8 +6,8 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync.{issueFee, minFee, smartFee, smartMinFee} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptWithSponsorshipSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptWithSponsorshipSuite.scala index 7a3fa38bf5f..06558129a9d 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptWithSponsorshipSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeScriptWithSponsorshipSuite.scala @@ -6,8 +6,8 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync.{minFee, smartMinFee} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeWithTransferSmartassetSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeWithTransferSmartassetSuite.scala index c234f2214d1..13ffccba5fd 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeWithTransferSmartassetSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/InvokeWithTransferSmartassetSuite.scala @@ -4,10 +4,10 @@ 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.it.util._ import com.wavesplatform.lang.v1.compiler.Terms.CONST_STRING import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state.IntegerDataEntry +import com.wavesplatform.test._ import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalatest.CancelAfterFailure diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/LeaseSmartContractsTestSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/LeaseSmartContractsTestSuite.scala index e705c4d6d47..b1edaa3c1b9 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/LeaseSmartContractsTestSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/LeaseSmartContractsTestSuite.scala @@ -6,8 +6,8 @@ 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.it.util._ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} import com.wavesplatform.transaction.smart.script.ScriptCompiler 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 ab7ae74070c..4245484a3b3 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 @@ -7,8 +7,8 @@ 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.it.util._ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalatest.CancelAfterFailure 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 cdbc44117d3..b0d4870eaae 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 @@ -7,8 +7,8 @@ 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.it.util._ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SetScriptTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SetScriptTransactionSuite.scala index 16f896f9461..ea0e850d9b1 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SetScriptTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/smartcontract/SetScriptTransactionSuite.scala @@ -8,8 +8,8 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.TransactionInfo import com.wavesplatform.it.sync.{minFee, setScriptFee, transferAmount} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ 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 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 25f1f20287f..c078ea64320 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,14 +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.transactions.NodesFromDocker -import com.wavesplatform.it.util._ -import com.wavesplatform.it.{ReportingTestName, WaitForHeight2} +import com.wavesplatform.it.{BaseFreeSpec, WaitForHeight2} import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 +import com.wavesplatform.test._ import com.wavesplatform.transaction.smart.script.ScriptCompiler -import org.scalatest.{CancelAfterFailure, FreeSpec, Matchers} -class UTXAllowance extends FreeSpec with Matchers with WaitForHeight2 with CancelAfterFailure with ReportingTestName with NodesFromDocker { +class UTXAllowance extends BaseFreeSpec with WaitForHeight2 { import UTXAllowance._ override protected def nodeConfigs: Seq[Config] = Configs 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 b0e0c06150c..634386bad54 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 @@ -5,7 +5,7 @@ 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.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.CreateAliasTransaction import org.scalatest.prop.TableDrivenPropertyChecks import play.api.libs.json.Json 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 34e171f098f..babc679de1f 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 @@ -1,6 +1,6 @@ package com.wavesplatform.it.sync.transactions -import cats.implicits._ +import cats.syntax.option._ import com.wavesplatform.account.AddressScheme import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils._ 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 d44b53c0774..5d8cb315364 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 @@ -11,7 +11,7 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.{TransactionInfo, UnexpectedStatusCodeException} import com.wavesplatform.it.sync.{calcDataFee, minFee, _} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, DataEntry, EmptyDataEntry, IntegerDataEntry, StringDataEntry} import com.wavesplatform.transaction.smart.script.ScriptCompiler @@ -93,7 +93,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { // can put data val putDataEntries = (1 to 25).flatMap(i => dataEntries(i)).toList val putTxId = sender.putData(sender.keyPair, putDataEntries, calcDataFee(putDataEntries, TxVersion.V1)).id - nodes.waitForHeightAriseAndTxPresent(putTxId) + nodes.waitForTransaction(putTxId) // can put new, update and remove existed in the same transaction val updatedDatEntries = putDataEntries.take(25).map(updateDataEntry) @@ -107,7 +107,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val updateAndRemoveTxId = sender.broadcastData(sender.keyPair, updateAndRemoveDataEntries, calcDataFee(updateAndRemoveDataEntries, TxVersion.V2)).id - nodes.waitForHeightAriseAndTxPresent(updateAndRemoveTxId) + nodes.waitForTransaction(updateAndRemoveTxId) sender.getData(sender.address) should contain theSameElementsAs updatedDatEntries ++ putDataEntries.slice(25, 75) ++ newDataEntries @@ -116,7 +116,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val reuseTxId = sender.broadcastData(sender.keyPair, reusedData, calcDataFee(reusedData, TxVersion.V1), version = TxVersion.V1).id - nodes.waitForHeightAriseAndTxPresent(reuseTxId) + nodes.waitForTransaction(reuseTxId) sender.getData(sender.address) should contain theSameElementsAs updatedDatEntries ++ putDataEntries.slice(25, 75) ++ reusedData ++ newDataEntries @@ -167,7 +167,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val data = List(entry) val dataFee = calcDataFee(data, v) val dataTx = sender.putData(firstKeyPair, data, version = v, fee = dataFee) - nodes.waitForHeightAriseAndTxPresent(dataTx.id) + nodes.waitForTransaction(dataTx.id) if (v > 2) { dataTx.chainId shouldBe Some(AddressScheme.current.chainId) sender.transactionInfo[TransactionInfo](dataTx.id).chainId shouldBe Some(AddressScheme.current.chainId) @@ -182,15 +182,13 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val data = List(BooleanDataEntry("bool", false)) assertBadRequestAndResponse(sender.putData(firstKeyPair, data, balance1 + 1, version = v), "Accounts balance errors") - nodes.waitForHeightArise() miner.assertBalances(firstAddress, balance1, eff1) val leaseAmount = 1.waves val leaseId = sender.lease(firstKeyPair, secondAddress, leaseAmount, minFee).id - nodes.waitForHeightAriseAndTxPresent(leaseId) + nodes.waitForTransaction(leaseId) assertBadRequestAndResponse(sender.putData(firstKeyPair, data, balance1 - leaseAmount, version = v), "Accounts balance errors") - nodes.waitForHeightArise() miner.assertBalances(firstAddress, balance1 - minFee, eff1 - leaseAmount - minFee) } } @@ -232,7 +230,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val data = List.tabulate(26)(n => BinaryDataEntry(key + n.toChar, ByteStr(Array.fill(5599)(n.toByte)))) val fee = calcDataFee(data, TxVersion.V1) val txId = sender.putData(firstKeyPair, data, fee, version = TxVersion.V1).id - nodes.waitForHeightAriseAndTxPresent(txId) + nodes.waitForTransaction(txId) //Max size of transaction V2 val maxKeySizeV2 = 400 @@ -240,7 +238,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val data2 = List.tabulate(5)(n => BinaryDataEntry(key2 + n.toChar, ByteStr(Array.fill(Short.MaxValue)(n.toByte)))) val fee2 = calcDataFee(data2, TxVersion.V2) val txId2 = sender.putData(firstKeyPair, data2, fee2, version = TxVersion.V2).id - nodes.waitForHeightAriseAndTxPresent(txId2) + nodes.waitForTransaction(txId2) } @@ -251,7 +249,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val intEntry = IntegerDataEntry("int", 8) val intList = List(intEntry) val tx1 = sender.putData(txSender, intList, calcDataFee(intList, v), version = v).id - nodes.waitForHeightAriseAndTxPresent(tx1) + nodes.waitForTransaction(tx1) val txSenderAddress = txSender.toAddress.toString sender.getDataByKey(txSenderAddress, "int") shouldBe intEntry @@ -261,13 +259,13 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val boolEntry = BooleanDataEntry("bool", true) val boolList = List(boolEntry) val tx2 = sender.putData(txSender, boolList, calcDataFee(boolList, v), version = v).id - nodes.waitForHeightAriseAndTxPresent(tx2) + nodes.waitForTransaction(tx2) // define string entry val stringEntry = StringDataEntry("str", "AAA") val stringList = List(stringEntry) val txS = sender.putData(txSender, stringList, calcDataFee(stringList, v), version = v).id - nodes.waitForHeightAriseAndTxPresent(txS) + nodes.waitForTransaction(txS) sender.getDataByKey(txSenderAddress, "int") shouldBe intEntry sender.getDataByKey(txSenderAddress, "bool") shouldBe boolEntry @@ -278,7 +276,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val reIntEntry = IntegerDataEntry("int", 10) val reIntList = List(reIntEntry) val tx3 = sender.putData(txSender, reIntList, calcDataFee(reIntList, v), version = v).id - nodes.waitForHeightAriseAndTxPresent(tx3) + nodes.waitForTransaction(tx3) sender.getDataByKey(txSenderAddress, "int") shouldBe reIntEntry sender.getDataByKey(txSenderAddress, "bool") shouldBe boolEntry @@ -294,7 +292,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val dataAllTypes = List(intEntry2, boolEntry2, blobEntry2, stringEntry2, unicodeStringEntry) val fee = calcDataFee(dataAllTypes, v) val txId = sender.putData(txSender, dataAllTypes, fee, version = v).id - nodes.waitForHeightAriseAndTxPresent(txId) + nodes.waitForTransaction(txId) sender.getDataByKey(txSenderAddress, "int") shouldBe intEntry2 sender.getDataByKey(txSenderAddress, "bool") shouldBe boolEntry2 @@ -342,13 +340,13 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val boolData = List(BooleanDataEntry(nonLatinKey, true)) val boolDataFee = calcDataFee(boolData, v) val firstTx = sender.putData(firstKeyPair, boolData, boolDataFee, version = v).id - nodes.waitForHeightAriseAndTxPresent(firstTx) + nodes.waitForTransaction(firstTx) sender.getDataByKey(firstAddress, nonLatinKey) shouldBe boolData.head val longData = List(IntegerDataEntry(nonLatinKey, 100500)) val longDataFee = calcDataFee(longData, v) val secondTx = sender.putData(firstKeyPair, longData, longDataFee, version = v).id - nodes.waitForHeightAriseAndTxPresent(secondTx) + nodes.waitForTransaction(secondTx) sender.getDataByKey(firstAddress, nonLatinKey) shouldBe longData.head } } @@ -423,7 +421,7 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val withProof = request assert((withProof \ "proofs").as[Seq[String]].lengthCompare(1) == 0) sender.postJson("/transactions/broadcast", withProof) - nodes.waitForHeightAriseAndTxPresent(id(withProof)) + nodes.waitForTransaction(id(withProof)) } } @@ -459,26 +457,22 @@ class DataTransactionSuite extends BaseTransactionSuite with EitherValues { val extraValueData = List(BinaryDataEntry("key", ByteStr(Array.fill(maxValueSize + 1)(1.toByte)))) assertBadRequestAndResponse(postDataTxJson(firstKeyPair, extraValueData, 1.waves, version = v), TooBig) - nodes.waitForHeightArise() val largeBinData = List.tabulate(5)(n => BinaryDataEntry(extraKey, ByteStr(Array.fill(maxValueSize)(n.toByte)))) assertBadRequestAndResponse(postDataTxJson(firstKeyPair, largeBinData, 1.waves, version = v), TooBig) - nodes.waitForHeightArise() val largeStrData = List.tabulate(5)(n => StringDataEntry(extraKey, "A" * maxValueSize)) assertBadRequestAndResponse(postDataTxJson(firstKeyPair, largeStrData, 1.waves, version = v), TooBig) - nodes.waitForHeightArise() val tooManyEntriesData = List.fill(maxEntryCount + 1)(IntegerDataEntry("key", 88)) assertBadRequestAndResponse(postDataTxJson(firstKeyPair, tooManyEntriesData, 1.waves, version = v), TooBig) - nodes.waitForHeightArise() } } test("try to put empty data") { for (v <- dataTxSupportedVersions) { val noDataTx = sender.putData(fourthKeyPair, List.empty, calcDataFee(List.empty, v), version = v).id - nodes.waitForHeightAriseAndTxPresent(noDataTx) + nodes.waitForTransaction(noDataTx) sender.getData(fourthAddress) shouldBe List.empty } } 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 c314fc37cd3..f963595d5df 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 @@ -8,8 +8,8 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync._ import com.wavesplatform.it.sync.smartcontract.exchangeTx import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.it.{NTPTime, NodeConfigs} +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxVersion import com.wavesplatform.transaction.assets.IssueTransaction diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/FailedTransactionSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/FailedTransactionSuite.scala index 0e75ae25390..c3a8015c084 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/FailedTransactionSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/FailedTransactionSuite.scala @@ -10,10 +10,10 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.{DebugStateChanges, TransactionStatus} import com.wavesplatform.it.sync._ import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, IntegerDataEntry, StringDataEntry} +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.assets.exchange.AssetPair import com.wavesplatform.transaction.smart.InvokeScriptTransaction 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 056de78c96f..d3406e56255 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 @@ -15,7 +15,7 @@ import com.wavesplatform.transaction.assets.exchange.{AssetPair, ExchangeTransac import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.{Asset, TxVersion} import com.wavesplatform.utils.ScorexLogging -import org.scalatest.Matchers +import org.scalatest.matchers.should.Matchers import play.api.libs.json.JsObject import scala.concurrent.duration._ @@ -43,7 +43,7 @@ trait FailedTransactionSuiteLike[T] extends ScorexLogging { _: Matchers => } object restApi { - import com.wavesplatform.it.api.SyncHttpApi._ + import com.wavesplatform.it.api.SyncHttpApi.{NodeExtSync, assertApiError} /** * Checks that transactions contain failed and returns them. 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 2b3ebf13d19..236c67f0d4b 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 @@ -4,8 +4,8 @@ import com.typesafe.config.Config import com.wavesplatform.account.KeyPair import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.it.{Node, NodeConfigs} +import com.wavesplatform.test._ import org.scalatest.prop.TableDrivenPropertyChecks class IssueNFTSuite extends BaseTransactionSuite with TableDrivenPropertyChecks { 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 b5e21798fc9..3c4c90ecd3f 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 @@ -7,7 +7,7 @@ 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.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.{Proofs, TxVersion} import org.scalatest.prop.TableDrivenPropertyChecks diff --git a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/LeasingTransactionsSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/LeasingTransactionsSuite.scala index f2a5b1d0c65..ae1454a143d 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/LeasingTransactionsSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/transactions/LeasingTransactionsSuite.scala @@ -7,7 +7,7 @@ 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.it.util._ +import com.wavesplatform.test._ import org.scalatest.CancelAfterFailure import play.api.libs.json.Json 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 f16a903a641..ddef9c5a95e 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 @@ -8,7 +8,7 @@ import com.wavesplatform.it.api.MassTransferTransactionInfo 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.test._ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer.MassTransferTransaction.{MaxTransferCount, Transfer} import com.wavesplatform.transaction.transfer.TransferTransaction.MaxAttachmentSize 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 ae4b5f4350f..472a2d23c98 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 @@ -8,7 +8,7 @@ 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.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.assets.ReissueTransaction class ReissueTransactionSuite extends BaseTransactionSuite { 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 7d54d7577e8..fa0c26eed7b 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 @@ -9,8 +9,8 @@ import com.wavesplatform.crypto import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync.{script, someAssetAmount, _} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.assets.SetAssetScriptTransaction 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 b9dbd6b3176..f667065a6e8 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 @@ -9,8 +9,8 @@ import com.wavesplatform.it.NTPTime import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync.{someAssetAmount, _} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ import com.wavesplatform.state._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction._ import com.wavesplatform.transaction.assets.exchange.AssetPair.extractAssetId 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 9d94d4d336e..aa2d75a23cf 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,28 +3,23 @@ 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.it.api.SyncHttpApi._ import com.wavesplatform.it.api.TransactionInfo import com.wavesplatform.it.sync._ -import com.wavesplatform.it.transactions.NodesFromDocker -import com.wavesplatform.it.util._ -import com.wavesplatform.it.{IntegrationSuiteWithThreeAddresses, NodeConfigs, ReportingTestName} +import com.wavesplatform.it.{BaseFreeSpec, IntegrationSuiteWithThreeAddresses, NodeConfigs} 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 org.scalatest.{Assertion, FreeSpec, Matchers} -import com.wavesplatform.common.utils.EitherExt2 +import org.scalatest.Assertion import scala.concurrent.duration._ class SponsorshipSuite - extends FreeSpec - with IntegrationSuiteWithThreeAddresses - with NodesFromDocker - with Matchers - with ReportingTestName - /*with CancelAfterFailure*/ { + extends BaseFreeSpec + with IntegrationSuiteWithThreeAddresses { override def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder 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 4b8700dc017..db3f5544977 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 @@ -8,9 +8,9 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.Transaction import com.wavesplatform.it.sync.{calcMassTransferFee, setScriptFee, _} import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ 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.smart.InvokeScriptTransaction 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 0893684db95..3bdf867becf 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 @@ -7,7 +7,7 @@ import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.TransferTransactionInfo import com.wavesplatform.it.sync._ import com.wavesplatform.it.transactions.BaseTransactionSuite -import com.wavesplatform.it.util._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer._ import org.scalatest.CancelAfterFailure @@ -17,7 +17,9 @@ 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 = TransferTransaction + .selfSigned(2.toByte, sender.keyPair, sender.keyPair.toAddress, Waves, 100L, Waves, minFee, ByteStr.empty, System.currentTimeMillis()) + .explicitGet() 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/utils/TransactionSerializeSuite.scala b/node-it/src/test/scala/com/wavesplatform/it/sync/utils/TransactionSerializeSuite.scala index c0a971559f7..4a691d29262 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/sync/utils/TransactionSerializeSuite.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/sync/utils/TransactionSerializeSuite.scala @@ -2,15 +2,16 @@ package com.wavesplatform.it.sync.utils import com.wavesplatform.account.{Address, PublicKey} 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.it.util._ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.compiler.Terms.TRUE import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, IntegerDataEntry} +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets._ import com.wavesplatform.transaction.assets.exchange._ @@ -20,9 +21,8 @@ import com.wavesplatform.transaction.transfer.MassTransferTransaction.Transfer import com.wavesplatform.transaction.transfer.{MassTransferTransaction, TransferTransaction} import com.wavesplatform.transaction.{CreateAliasTransaction, DataTransaction, Proofs, Transaction, TxVersion} import com.wavesplatform.utils._ -import org.scalatest.prop.TableDrivenPropertyChecks -import com.wavesplatform.common.utils.EitherExt2 import org.scalatest.Informing +import org.scalatest.prop.TableDrivenPropertyChecks class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPropertyChecks with Informing { private val publicKey = PublicKey.fromBase58String("FM5ojNqW7e9cZ9zhPYGkpSP1Pcd8Z3e3MNKYVS5pGJ8Z").explicitGet() @@ -30,7 +30,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro private val tsOrderFrom: Long = 1526992336241L private val tsOrderTo: Long = 1529584336241L - private val buyV2 = Order( + private lazy val buyV2 = Order( TxVersion.V2, PublicKey.fromBase58String("BqeJY8CP3PeUDaByz57iRekVUGtLxoow4XxPvXfHynaZ").explicitGet(), PublicKey.fromBase58String("Fvk5DXmfyWVZqQVBowUBMwYtRAHDtdyZNNeRrwSjt6KP").explicitGet(), @@ -44,7 +44,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro proofs = Proofs(Seq(ByteStr.decodeBase58("2bkuGwECMFGyFqgoHV4q7GRRWBqYmBFWpYRkzgYANR4nN2twgrNaouRiZBqiK2RJzuo9NooB9iRiuZ4hypBbUQs").get)) ) - val buyV1 = Order( + private lazy val buyV1 = Order( TxVersion.V1, PublicKey.fromBase58String("BqeJY8CP3PeUDaByz57iRekVUGtLxoow4XxPvXfHynaZ").explicitGet(), PublicKey.fromBase58String("Fvk5DXmfyWVZqQVBowUBMwYtRAHDtdyZNNeRrwSjt6KP").explicitGet(), @@ -58,7 +58,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro proofs = Proofs(ByteStr.decodeBase58("2bkuGwECMFGyFqgoHV4q7GRRWBqYmBFWpYRkzgYANR4nN2twgrNaouRiZBqiK2RJzuo9NooB9iRiuZ4hypBbUQs").get) ) - private val sell = Order( + private lazy val sell = Order( TxVersion.V1, PublicKey.fromBase58String("7E9Za8v8aT6EyU1sX91CVK7tWUeAetnNYDxzKZsyjyKV").explicitGet(), PublicKey.fromBase58String("Fvk5DXmfyWVZqQVBowUBMwYtRAHDtdyZNNeRrwSjt6KP").explicitGet(), @@ -72,7 +72,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro proofs = Proofs(ByteStr.decodeBase58("2R6JfmNjEnbXAA6nt8YuCzSf1effDS4Wkz8owpCD9BdCNn864SnambTuwgLRYzzeP5CAsKHEviYKAJ2157vdr5Zq").get) ) - private val exV1 = ExchangeTransaction + private lazy val exV1 = ExchangeTransaction .create( TxVersion.V1, buyV1, @@ -87,7 +87,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val exV2 = ExchangeTransaction + private lazy val exV2 = ExchangeTransaction .create( TxVersion.V2, buyV2, @@ -102,7 +102,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val burnV1 = BurnTransaction + private lazy val burnV1 = BurnTransaction .create( 1.toByte, publicKey, @@ -114,7 +114,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val burnV2 = BurnTransaction + private lazy val burnV2 = BurnTransaction .create( 2.toByte, publicKey, @@ -126,7 +126,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val aliasV1 = CreateAliasTransaction + private lazy val aliasV1 = CreateAliasTransaction .create( Transaction.V1, publicKey, @@ -137,7 +137,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val aliasV2 = CreateAliasTransaction + private lazy val aliasV2 = CreateAliasTransaction .create( Transaction.V2, publicKey, @@ -148,7 +148,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val data = DataTransaction + private lazy val data = DataTransaction .create( 1.toByte, publicKey, @@ -159,7 +159,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val issueV1 = IssueTransaction( + private lazy val issueV1 = IssueTransaction( TxVersion.V1, publicKey, "Gigacoin".utf8Bytes, @@ -173,7 +173,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro Proofs(ByteStr.decodeBase58("28kE1uN1pX2bwhzr9UHw5UuB9meTFEDFgeunNgy6nZWpHX4pzkGYotu8DhQ88AdqUG6Yy5wcXgHseKPBUygSgRMJ").get) ) - private val issueV2 = IssueTransaction( + private lazy val issueV2 = IssueTransaction( TxVersion.V2, publicKey, "Gigacoin".utf8Bytes, @@ -187,7 +187,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro Proofs(Seq(ByteStr.decodeBase58("43TCfWBa6t2o2ggsD4bU9FpvH3kmDbSBWKE1Z6B5i5Ax5wJaGT2zAvBihSbnSS3AikZLcicVWhUk1bQAMWVzTG5g").get)) ) - private val leasecancelV1 = LeaseCancelTransaction + private lazy val leasecancelV1 = LeaseCancelTransaction .create( 1.toByte, publicKey, @@ -198,7 +198,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val leasecancelV2 = LeaseCancelTransaction + private lazy val leasecancelV2 = LeaseCancelTransaction .create( 2.toByte, publicKey, @@ -233,7 +233,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - lazy val mass = MassTransferTransaction + private lazy val mass = MassTransferTransaction .create( 1.toByte, publicKey, @@ -248,7 +248,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val reissueV1 = ReissueTransaction + private lazy val reissueV1 = ReissueTransaction .create( 1.toByte, publicKey, @@ -261,7 +261,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val reissueV2 = ReissueTransaction + private lazy val reissueV2 = ReissueTransaction .create( 2.toByte, publicKey, @@ -274,7 +274,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val setasset = SetAssetScriptTransaction + private lazy val setasset = SetAssetScriptTransaction .create( 1.toByte, publicKey, @@ -295,7 +295,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val setscript = SetScriptTransaction + private lazy val setscript = SetScriptTransaction .create( 1.toByte, publicKey, @@ -306,7 +306,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro ) .explicitGet() - private val sponsor = SponsorFeeTransaction + private lazy val sponsor = SponsorFeeTransaction .create( 1.toByte, publicKey, @@ -347,7 +347,7 @@ class TransactionSerializeSuite extends BaseTransactionSuite with TableDrivenPro recipient.chainId ) - private val invokeScript = InvokeScriptTransaction + private lazy val invokeScript = InvokeScriptTransaction .create( 1.toByte, PublicKey.fromBase58String("BqeJY8CP3PeUDaByz57iRekVUGtLxoow4XxPvXfHynaZ").explicitGet(), 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 4c949758cde..f23ca3e271e 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 @@ -1,54 +1,11 @@ package com.wavesplatform.it.transactions -import java.io.File - -import com.typesafe.config.{Config, ConfigFactory} import com.wavesplatform.it._ -import monix.eval.Coeval -import org.scalatest.{BeforeAndAfterAll, FunSuite, Suite} - -import scala.jdk.CollectionConverters._ -import scala.concurrent.ExecutionContext +import org.scalatest._ trait BaseTransactionSuiteLike extends WaitForHeight2 with IntegrationSuiteWithThreeAddresses with BeforeAndAfterAll with NodesFromDocker { - this: Suite => - - protected implicit val ec: ExecutionContext = ExecutionContext.Implicits.global - - protected def nodeConfigs: Seq[Config] = - NodeConfigs.newBuilder - .overrideBase(_.quorum(0)) - .withDefault(1) - .withSpecial(_.nonMiner) - .buildNonConflicting() - - override def miner: Node = nodes.head - - private var istRunning = false - - // protected because https://github.com/sbt/zinc/issues/292 - protected lazy val theNodes: Coeval[Seq[Node]] = Coeval.evalOnce { - require(istRunning, "Do not attempt to access node instances from suite constructors") - Option(System.getProperty("waves.it.config.file")) match { - case None => dockerNodes() - case Some(filePath) => - val defaultConfig = ConfigFactory.load() - ConfigFactory - .parseFile(new File(filePath)) - .getConfigList("nodes") - .asScala - .toSeq - .map(cfg => new ExternalNode(cfg.withFallback(defaultConfig).resolve())) - } - } - - override protected def nodes: Seq[Node] = theNodes() + this: TestSuite with Nodes => - protected override def beforeAll(): Unit = { - istRunning = true - theNodes.run() - super.beforeAll() - } } -abstract class BaseTransactionSuite extends FunSuite with BaseTransactionSuiteLike +abstract class BaseTransactionSuite extends funsuite.AnyFunSuite with BaseTransactionSuiteLike diff --git a/node-it/src/test/scala/com/wavesplatform/it/util/package.scala b/node-it/src/test/scala/com/wavesplatform/it/util/package.scala index 0242a7af97d..3abbe749482 100644 --- a/node-it/src/test/scala/com/wavesplatform/it/util/package.scala +++ b/node-it/src/test/scala/com/wavesplatform/it/util/package.scala @@ -1,6 +1,5 @@ package com.wavesplatform.it -import com.wavesplatform.settings.Constants import com.wavesplatform.state.DataEntry import io.netty.util.Timer @@ -25,9 +24,6 @@ package object util { def retryUntil[A](f: => Future[A], cond: A => Boolean, retryInterval: FiniteDuration)(implicit ec: ExecutionContext): Future[A] = f.flatMap(v => if (cond(v)) Future.successful(v) else schedule(retryUntil(f, cond, retryInterval), retryInterval)) } - implicit class DoubleExt(val d: Double) extends AnyVal { - def waves: Long = (BigDecimal(d) * Constants.UnitsInWave).toLong - } implicit class TypedDataEntry(entry: DataEntry[_]) { def as[T]: T = entry.asInstanceOf[T] } diff --git a/node/build.sbt b/node/build.sbt index 71bb9bd1893..f941d2a341f 100644 --- a/node/build.sbt +++ b/node/build.sbt @@ -7,11 +7,16 @@ import sbtassembly.MergeStrategy enablePlugins(RunApplicationSettings, JavaServerAppPackaging, UniversalDeployPlugin, JDebPackaging, SystemdPlugin, GitVersioning, VersionObject) libraryDependencies ++= Dependencies.node.value -coverageExcludedPackages := "" + +name := "waves" inConfig(Compile)( Seq( PB.targets += scalapb.gen(flatPackage = true) -> sourceManaged.value, + PB.protoSources += PB.externalIncludePath.value, + PB.generate / includeFilter := { (f: File) => + (** / "waves" / "*.proto").matches(f.toPath) + }, PB.deleteTargetDirectory := false, packageDoc / publishArtifact := false, packageSrc / publishArtifact := false @@ -23,9 +28,14 @@ inTask(assembly)( test := {}, assemblyJarName := s"waves-all-${version.value}.jar", assemblyMergeStrategy := { - case "module-info.class" => MergeStrategy.discard - case PathList("META-INF", "io.netty.versions.properties") => MergeStrategy.concat - case other => (assemblyMergeStrategy in assembly).value(other) + case p + if p.endsWith(".proto") || + p.endsWith("module-info.class") || + p.endsWith("io.netty.versions.properties") => + MergeStrategy.discard + case "scala-collection-compat.properties" => MergeStrategy.discard + case PathList("com", "sun", "jna", _*) => MergeStrategy.first + case other => (assembly / assemblyMergeStrategy).value(other) } ) ) @@ -104,23 +114,16 @@ inConfig(Linux)( ) ) -// Variable options are used in different tasks and configs, so we will specify all of them -val nameFix = Seq( - name := "waves", - packageName := s"${name.value}${network.value.packageSuffix}", - normalizedName := s"${name.value}${network.value.packageSuffix}" -) - inConfig(Debian)( Seq( + packageSource := sourceDirectory.value / "package", linuxStartScriptTemplate := (packageSource.value / "systemd.service").toURI.toURL, debianPackageDependencies += "java8-runtime-headless", - serviceAutostart := false, maintainerScripts := maintainerScriptsFromDirectory(packageSource.value / "debian", Seq("preinst", "postinst", "postrm", "prerm")), linuxPackageMappings ++= { val upstartScript = { val src = packageSource.value / "upstart.conf" - val dest = (target in Debian).value / "upstart" / s"${packageName.value}.conf" + val dest = (Debian / target).value / "upstart" / s"${packageName.value}.conf" val result = TemplateWriter.generateScript(src.toURI.toURL, linuxScriptReplacements.value) IO.write(dest, result) dest @@ -136,8 +139,10 @@ inConfig(Debian)( |is_upstart() { | /sbin/init --version | grep upstart >/dev/null 2>&1 |} - |""".stripMargin - ) ++ nameFix + |""".stripMargin, + packageName := s"${name.value}${network.value.packageSuffix}", + normalizedName := s"${name.value}${network.value.packageSuffix}" + ) ) V.scalaPackage := "com.wavesplatform" @@ -146,6 +151,3 @@ V.scalaPackage := "com.wavesplatform" moduleName := s"waves${network.value.packageSuffix}" // waves-*.jar instead of node-*.jar executableScriptName := moduleName.value // bin/waves instead of bin/node - -nameFix -inScope(Global)(nameFix) diff --git a/node/src/main/java/com/sun/jna/Memory.java b/node/src/main/java/com/sun/jna/Memory.java new file mode 100644 index 00000000000..6c3ffd05146 --- /dev/null +++ b/node/src/main/java/com/sun/jna/Memory.java @@ -0,0 +1,1077 @@ +/* + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +package com.sun.jna; + +import java.io.Closeable; +import java.io.IOException; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import java.util.ArrayList; + +/** + * A Pointer to memory obtained from the native heap via a + * call to malloc. + * + *

In some cases it might be necessary to use memory obtained from + * malloc. For example, Memory helps + * accomplish the following idiom: + *

+ *        void *buf = malloc(BUF_LEN * sizeof(char));
+ *        call_some_function(buf);
+ *        free(buf);
+ * 
+ * + *

The {@link #finalize} method will free allocated memory when + * this object is no longer referenced. + * + * @author Sheng Liang, originator + * @author Todd Fast, suitability modifications + * @author Timothy Wall + * @see Pointer + */ +public class Memory extends Pointer { + private final Closeable destructor; + + @SuppressWarnings("deprecation") + private static class Java8Destructor implements Runnable, Closeable { + private static Method CLEANER_CREATE; + + static { + try { + final Class sunCleaner = Class.forName("sun.misc.Cleaner"); + CLEANER_CREATE = sunCleaner.getDeclaredMethod("create", Object.class, Runnable.class); + assert CLEANER_CREATE.isAccessible(); + } catch (Exception e) { + System.err.println("Unable to initialize JNA cleaner"); + e.printStackTrace(); + } + } + + private long peer; + private final LinkedReference reference; + private Object cleaner; + + public static Java8Destructor create(Memory mem) { + final Java8Destructor destructor = new Java8Destructor(mem); + try { + destructor.cleaner = CLEANER_CREATE.invoke(null, mem, destructor); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return destructor; + } + + private Java8Destructor(Memory mem) { + this.peer = mem.peer; + this.reference = mem.reference; + } + + public void close() { + try { + cleaner.getClass().getDeclaredMethod("clean").invoke(cleaner); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public void run() { + try { + free(peer); + } finally { + peer = 0; + if (reference != null) reference.unlink(); + } + } + } + + private static class Java9Destructor implements Runnable, Closeable { + private static Object CLEANER; + + private Object cleanable; + + static { + try { + final Class cleanerClass = Class.forName("java.lang.ref.Cleaner"); + final Method create = cleanerClass.getDeclaredMethod("create"); + Java9Destructor.CLEANER = create.invoke(null); + } catch (Exception e) { + System.err.println("Unable to initialize JNA cleaner"); + e.printStackTrace(); + System.exit(1); + } + } + + private long peer; + private final LinkedReference reference; + + public static Java9Destructor create(Memory mem) { + final Java9Destructor destructor = new Java9Destructor(mem); + try { + final Class sunCleaner = Class.forName("java.lang.ref.Cleaner"); + final Method create = sunCleaner.getDeclaredMethod("register", Object.class, Runnable.class); + destructor.cleanable = create.invoke(CLEANER, mem, destructor); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return destructor; + } + + private Java9Destructor(Memory mem) { + this.peer = mem.peer; + this.reference = mem.reference; + } + + public void close() { + try { + cleanable.getClass().getDeclaredMethod("clean").invoke(cleanable); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public void run() { + try { + free(peer); + } finally { + peer = 0; + if (reference != null) reference.unlink(); + } + } + } + + private static int getJavaVersion() { + String version = System.getProperty("java.version"); + if(version.startsWith("1.")) { + version = version.substring(2, 3); + } else { + int dot = version.indexOf("."); + if(dot != -1) { version = version.substring(0, dot); } + } return Integer.parseInt(version); + } + + + private static Closeable createDestructor(Memory mem) { + if (getJavaVersion() > 8) { + return Java9Destructor.create(mem); + } else { + return Java8Destructor.create(mem); + } + } + + + private static ReferenceQueue QUEUE = new ReferenceQueue(); + private static LinkedReference HEAD; // the head of the doubly linked list used for instance tracking + + /** + * Keep track of all allocated memory so we can dispose of it before + * unloading. This is done using a doubly linked list to enable fast + * removal of tracked instances. + */ + private static class LinkedReference extends WeakReference { + + private LinkedReference next; + private LinkedReference prev; + + private LinkedReference(Memory referent) { + super(referent, QUEUE); + } + + /** + * Add the given {@code instance} to the instance tracking. + * + * @param instance the instance to track + */ + static LinkedReference track(Memory instance) { + // use a different lock here to allow the finialzier to unlink elements too + synchronized (QUEUE) { + LinkedReference stale; + + // handle stale references here to avoid GC overheating when memory is limited + while ((stale = (LinkedReference) QUEUE.poll()) != null) { + stale.unlink(); + } + } + + // keep object allocation outside the syncronized block + LinkedReference entry = new LinkedReference(instance); + + synchronized (LinkedReference.class) { + if (HEAD != null) { + entry.next = HEAD; + HEAD = HEAD.prev = entry; + } else { + HEAD = entry; + } + } + + return entry; + } + + /** + * Remove the related instance from tracking and update the linked list. + */ + private void unlink() { + synchronized (LinkedReference.class) { + LinkedReference next; + + if (HEAD != this) { + if (this.prev == null) { + // this entry was detached before, e.g. disposeAll was called and finalizers are running now + return; + } + + next = this.prev.next = this.next; + } else { + next = HEAD = HEAD.next; + } + + if (next != null) { + next.prev = this.prev; + } + + // set prev to null to detect detached entries + this.prev = null; + } + } + } + + private static final WeakMemoryHolder buffers = new WeakMemoryHolder(); + + /** + * Force cleanup of memory that has associated NIO Buffers which have + * been GC'd. + */ + public static void purge() { + buffers.clean(); + } + + /** + * Dispose of all allocated memory. + */ + public static void disposeAll() { + System.err.println("Skipping com.sun.jna.Memory.disposeAll()"); + return; + +// synchronized (LinkedReference.class) { +// LinkedReference entry; +// +// while ((entry = HEAD) != null) { +// Memory memory = HEAD.get(); +// +// if (memory != null) { +// // dispose does the unlink call internal +// memory.dispose(); +// } else { +// HEAD.unlink(); +// } +// +// if (HEAD == entry) { +// throw new IllegalStateException("the HEAD did not change"); +// } +// } +// } +// +// synchronized (QUEUE) { +// LinkedReference stale; +// +// // try to release as mutch memory as possible +// while ((stale = (LinkedReference) QUEUE.poll()) != null) { +// stale.unlink(); +// } +// } + } + + /** + * Unit-testing only, ensure the doubly linked list is in a good shape. + * + * @return the number of tracked instances + */ + static int integrityCheck() { + synchronized (LinkedReference.class) { + if (HEAD == null) { + return 0; + } + + ArrayList entries = new ArrayList(); + LinkedReference entry = HEAD; + + while (entry != null) { + entries.add(entry); + entry = entry.next; + } + + int index = entries.size() - 1; + entry = entries.get(index); + + while (entry != null) { + if (entries.get(index) != entry) { + throw new IllegalStateException(entries.get(index) + " vs. " + entry + " at index " + index); + } + + entry = entry.prev; + index--; + } + + return entries.size(); + } + } + + private final LinkedReference reference; // used to track the instance + protected long size; // Size of the malloc'ed space + + /** + * Provide a view into the original memory. Keeps an implicit reference + * to the original to prevent GC. + */ + private class SharedMemory extends Memory { + public SharedMemory(long offset, long size) { + this.size = size; + this.peer = Memory.this.peer + offset; + } + + /** + * No need to free memory. + */ + @Override + protected synchronized void dispose() { + this.peer = 0; + } + + /** + * Pass bounds check to parent. + */ + @Override + protected void boundsCheck(long off, long sz) { + Memory.this.boundsCheck(this.peer - Memory.this.peer + off, sz); + } + + @Override + public String toString() { + return super.toString() + " (shared from " + Memory.this.toString() + ")"; + } + } + + /** + * Allocate space in the native heap via a call to C's malloc. + * + * @param size number of bytes of space to allocate + */ + public Memory(long size) { + this.size = size; + if (size <= 0) { + throw new IllegalArgumentException("Allocation size must be greater than zero"); + } + peer = malloc(size); + if (peer == 0) + throw new OutOfMemoryError("Cannot allocate " + size + " bytes"); + + // reference = LinkedReference.track(this); // Removed to optimize syncs + reference = null; + destructor = Memory.createDestructor(this); + } + + protected Memory() { + super(); + + reference = null; + destructor = Memory.createDestructor(this); + } + + /** + * Provide a view of this memory using the given offset as the base address. The + * returned {@link Pointer} will have a size equal to that of the original + * minus the offset. + * + * @throws IndexOutOfBoundsException if the requested memory is outside + * the allocated bounds. + */ + @Override + public Pointer share(long offset) { + return share(offset, size() - offset); + } + + /** + * Provide a view of this memory using the given offset as the base + * address, bounds-limited with the given size. Maintains a reference to + * the original {@link Memory} object to avoid GC as long as the shared + * memory is referenced. + * + * @throws IndexOutOfBoundsException if the requested memory is outside + * the allocated bounds. + */ + @Override + public Pointer share(long offset, long sz) { + boundsCheck(offset, sz); + return new SharedMemory(offset, sz); + } + + /** + * Provide a view onto this structure with the given alignment. + * + * @param byteBoundary Align memory to this number of bytes; should be a + * power of two. + * @throws IndexOutOfBoundsException if the requested alignment can + * not be met. + * @throws IllegalArgumentException if the requested alignment is not + * a positive power of two. + */ + public Memory align(int byteBoundary) { + if (byteBoundary <= 0) { + throw new IllegalArgumentException("Byte boundary must be positive: " + byteBoundary); + } + for (int i = 0; i < 32; i++) { + if (byteBoundary == (1 << i)) { + long mask = ~((long) byteBoundary - 1); + + if ((peer & mask) != peer) { + long newPeer = (peer + byteBoundary - 1) & mask; + long newSize = peer + size - newPeer; + if (newSize <= 0) { + throw new IllegalArgumentException("Insufficient memory to align to the requested boundary"); + } + return (Memory) share(newPeer - peer, newSize); + } + return this; + } + } + throw new IllegalArgumentException("Byte boundary must be a power of two"); + } + + /** Properly dispose of native memory when this object is GC'd. */ +// @Override +// protected void finalize() { +// dispose(); +// } + + /** + * Free the native memory and set peer to zero + */ + protected void dispose() { + if (peer == 0) { + // someone called dispose before, the finalizer will call dispose again + return; + } + + try { + destructor.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Zero the full extent of this memory region. + */ + public void clear() { + clear(size); + } + + /** + * Returns false if the memory has been freed. + */ + public boolean valid() { + return peer != 0; + } + + public long size() { + return size; + } + + /** + * Check that indirection won't cause us to write outside the + * malloc'ed space. + */ + protected void boundsCheck(long off, long sz) { + if (off < 0) { + throw new IndexOutOfBoundsException("Invalid offset: " + off); + } + if (off + sz > size) { + String msg = "Bounds exceeds available space : size=" + + size + ", offset=" + (off + sz); + throw new IndexOutOfBoundsException(msg); + } + } + + ////////////////////////////////////////////////////////////////////////// + // Raw read methods + ////////////////////////////////////////////////////////////////////////// + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.read. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#read(long, byte[], int, int) + */ + @Override + public void read(long bOff, byte[] buf, int index, int length) { + boundsCheck(bOff, length * 1L); + super.read(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.read. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#read(long, short[], int, int) + */ + @Override + public void read(long bOff, short[] buf, int index, int length) { + boundsCheck(bOff, length * 2L); + super.read(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.read. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#read(long, char[], int, int) + */ + @Override + public void read(long bOff, char[] buf, int index, int length) { + boundsCheck(bOff, length * Native.WCHAR_SIZE); + super.read(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.read. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#read(long, int[], int, int) + */ + @Override + public void read(long bOff, int[] buf, int index, int length) { + boundsCheck(bOff, length * 4L); + super.read(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.read. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#read(long, long[], int, int) + */ + @Override + public void read(long bOff, long[] buf, int index, int length) { + boundsCheck(bOff, length * 8L); + super.read(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.read. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#read(long, float[], int, int) + */ + @Override + public void read(long bOff, float[] buf, int index, int length) { + boundsCheck(bOff, length * 4L); + super.read(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.read. But this method performs a bounds checks to + * ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#read(long, double[], int, int) + */ + @Override + public void read(long bOff, double[] buf, int index, int length) { + boundsCheck(bOff, length * 8L); + super.read(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.read. But this method performs a bounds checks to + * ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#read(long, Pointer[], int, int) + */ + @Override + public void read(long bOff, Pointer[] buf, int index, int length) { + boundsCheck(bOff, length * Native.POINTER_SIZE); + super.read(bOff, buf, index, length); + } + + ////////////////////////////////////////////////////////////////////////// + // Raw write methods + ////////////////////////////////////////////////////////////////////////// + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.write. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#write(long, byte[], int, int) + */ + @Override + public void write(long bOff, byte[] buf, int index, int length) { + boundsCheck(bOff, length * 1L); + super.write(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.write. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#write(long, short[], int, int) + */ + @Override + public void write(long bOff, short[] buf, int index, int length) { + boundsCheck(bOff, length * 2L); + super.write(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.write. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#write(long, char[], int, int) + */ + @Override + public void write(long bOff, char[] buf, int index, int length) { + boundsCheck(bOff, length * Native.WCHAR_SIZE); + super.write(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.write. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#write(long, int[], int, int) + */ + @Override + public void write(long bOff, int[] buf, int index, int length) { + boundsCheck(bOff, length * 4L); + super.write(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.write. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#write(long, long[], int, int) + */ + @Override + public void write(long bOff, long[] buf, int index, int length) { + boundsCheck(bOff, length * 8L); + super.write(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.write. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#write(long, float[], int, int) + */ + @Override + public void write(long bOff, float[] buf, int index, int length) { + boundsCheck(bOff, length * 4L); + super.write(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.write. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#write(long, double[], int, int) + */ + @Override + public void write(long bOff, double[] buf, int index, int length) { + boundsCheck(bOff, length * 8L); + super.write(bOff, buf, index, length); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.write. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#write(long, Pointer[], int, int) + */ + @Override + public void write(long bOff, Pointer[] buf, int index, int length) { + boundsCheck(bOff, length * Native.POINTER_SIZE); + super.write(bOff, buf, index, length); + } + + ////////////////////////////////////////////////////////////////////////// + // Java type read methods + ////////////////////////////////////////////////////////////////////////// + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.getByte. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#getByte(long) + */ + @Override + public byte getByte(long offset) { + boundsCheck(offset, 1); + return super.getByte(offset); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.getByte. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#getByte(long) + */ + @Override + public char getChar(long offset) { + boundsCheck(offset, Native.WCHAR_SIZE); + return super.getChar(offset); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.getShort. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#getShort(long) + */ + @Override + public short getShort(long offset) { + boundsCheck(offset, 2); + return super.getShort(offset); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.getInt. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#getInt(long) + */ + @Override + public int getInt(long offset) { + boundsCheck(offset, 4); + return super.getInt(offset); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.getLong. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#getLong(long) + */ + @Override + public long getLong(long offset) { + boundsCheck(offset, 8); + return super.getLong(offset); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.getFloat. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#getFloat(long) + */ + @Override + public float getFloat(long offset) { + boundsCheck(offset, 4); + return super.getFloat(offset); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.getDouble. But this method performs a + * bounds check to ensure that the indirection does not cause memory + * outside the malloced space to be accessed. + * + * @see Pointer#getDouble(long) + */ + @Override + public double getDouble(long offset) { + boundsCheck(offset, 8); + return super.getDouble(offset); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.getPointer. But this method performs + * a bounds checks to ensure that the indirection does not cause memory + * outside the malloced space to be accessed. + * + * @see Pointer#getPointer(long) + */ + @Override + public Pointer getPointer(long offset) { + boundsCheck(offset, Native.POINTER_SIZE); + return shareReferenceIfInBounds(super.getPointer(offset)); + } + + /** + * Get a ByteBuffer mapped to a portion of this memory. + * We keep a weak reference to all ByteBuffers provided so that this + * memory object is not GC'd while there are still implicit outstanding + * references to it (it'd be nice if we could attach our own reference to + * the ByteBuffer, but the VM generates the object so we have no control + * over it). + * + * @param offset byte offset from pointer to start the buffer + * @param length Length of ByteBuffer + * @return a direct ByteBuffer that accesses the memory being pointed to, + */ + @Override + public ByteBuffer getByteBuffer(long offset, long length) { + boundsCheck(offset, length); + ByteBuffer b = super.getByteBuffer(offset, length); + // Ensure this Memory object will not be GC'd (and its memory freed) + // if the Buffer is still extant. + buffers.put(b, this); + return b; + } + + @Override + public String getString(long offset, String encoding) { + // NOTE: we only make sure the start of the string is within bounds + boundsCheck(offset, 0); + return super.getString(offset, encoding); + } + + @Override + public String getWideString(long offset) { + // NOTE: we only make sure the start of the string is within bounds + boundsCheck(offset, 0); + return super.getWideString(offset); + } + + ////////////////////////////////////////////////////////////////////////// + // Java type write methods + ////////////////////////////////////////////////////////////////////////// + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.setByte. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#setByte + */ + @Override + public void setByte(long offset, byte value) { + boundsCheck(offset, 1); + super.setByte(offset, value); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.setChar. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#setChar + */ + @Override + public void setChar(long offset, char value) { + boundsCheck(offset, Native.WCHAR_SIZE); + super.setChar(offset, value); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.setShort. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#setShort + */ + @Override + public void setShort(long offset, short value) { + boundsCheck(offset, 2); + super.setShort(offset, value); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.setInt. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#setInt + */ + @Override + public void setInt(long offset, int value) { + boundsCheck(offset, 4); + super.setInt(offset, value); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.setLong. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#setLong + */ + @Override + public void setLong(long offset, long value) { + boundsCheck(offset, 8); + super.setLong(offset, value); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.setFloat. But this method performs a bounds + * checks to ensure that the indirection does not cause memory outside the + * malloced space to be accessed. + * + * @see Pointer#setFloat + */ + @Override + public void setFloat(long offset, float value) { + boundsCheck(offset, 4); + super.setFloat(offset, value); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.setDouble. But this method performs a + * bounds checks to ensure that the indirection does not cause memory + * outside the malloced space to be accessed. + * + * @see Pointer#setDouble + */ + @Override + public void setDouble(long offset, double value) { + boundsCheck(offset, 8); + super.setDouble(offset, value); + } + + /** + * Indirect the native pointer to malloc space, a la + * Pointer.setPointer. But this method performs + * a bounds checks to ensure that the indirection does not cause memory + * outside the malloced space to be accessed. + * + * @see Pointer#setPointer + */ + @Override + public void setPointer(long offset, Pointer value) { + boundsCheck(offset, Native.POINTER_SIZE); + super.setPointer(offset, value); + } + + @Override + public void setString(long offset, String value, String encoding) { + boundsCheck(offset, Native.getBytes(value, encoding).length + 1L); + super.setString(offset, value, encoding); + } + + @Override + public void setWideString(long offset, String value) { + boundsCheck(offset, (value.length() + 1L) * Native.WCHAR_SIZE); + super.setWideString(offset, value); + } + + @Override + public String toString() { + return "allocated@0x" + Long.toHexString(peer) + " (" + size + " bytes)"; + } + + protected static void free(long p) { + // free(0) is a no-op, so avoid the overhead of the call + if (p != 0) { + Native.free(p); + } + } + + protected static long malloc(long size) { + return Native.malloc(size); + } + + /** + * Dumps the contents of this memory object. + */ + public String dump() { + return dump(0, (int) size()); + } + + /** + * Check whether the supplied Pointer object points into the memory region + * backed by this memory object. The intention is to prevent premature GC + * of the Memory object. + * + * @param target Pointer to check + * @return {@code target} if target does not point into the region covered + * by this memory object, a newly {@code SharedMemory} object, if the pointer + * points to memory backed by this Memory object. + */ + private Pointer shareReferenceIfInBounds(Pointer target) { + if (target == null) { + return null; + } + long offset = target.peer - this.peer; + if (offset >= 0 && offset < this.size) { + return this.share(offset); + } else { + return target; + } + } +} diff --git a/node/src/main/scala/com/wavesplatform/Application.scala b/node/src/main/scala/com/wavesplatform/Application.scala index 08a3c16342a..b50ed4103a0 100644 --- a/node/src/main/scala/com/wavesplatform/Application.scala +++ b/node/src/main/scala/com/wavesplatform/Application.scala @@ -13,8 +13,9 @@ import scala.util.{Failure, Success, Try} import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.Http.ServerBinding -import cats.instances.all._ import cats.syntax.option._ +import cats.instances.bigInt._ +import cats.instances.int._ import com.typesafe.config._ import com.wavesplatform.account.{Address, AddressScheme} import com.wavesplatform.actor.RootActorSystem @@ -207,8 +208,8 @@ class Application(val actorSystem: ActorSystem, val settings: WavesSettings, con ) override val blocksApi: CommonBlocksApi = CommonBlocksApi(blockchainUpdater, loadBlockMetaAt(db, blockchainUpdater), loadBlockInfoAt(db, blockchainUpdater)) - override val accountsApi: CommonAccountsApi = CommonAccountsApi(blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), db, blockchainUpdater) - override val assetsApi: CommonAssetsApi = CommonAssetsApi(blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), db, blockchainUpdater) + override val accountsApi: CommonAccountsApi = CommonAccountsApi(() => blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), db, blockchainUpdater) + override val assetsApi: CommonAssetsApi = CommonAssetsApi(() => blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), db, blockchainUpdater) } extensions = settings.extensions.map { extensionClassName => @@ -367,7 +368,7 @@ class Application(val actorSystem: ActorSystem, val settings: WavesSettings, con ) val httpService = CompositeHttpService(apiRoutes, settings.restAPISettings) - val httpFuture = Http().bindAndHandle(httpService.loggingCompositeRoute, settings.restAPISettings.bindAddress, settings.restAPISettings.port) + val httpFuture = Http().newServerAt(settings.restAPISettings.bindAddress, settings.restAPISettings.port).bindFlow(httpService.loggingCompositeRoute) serverBinding = Await.result(httpFuture, 20.seconds) serverBinding.whenTerminated.foreach(_ => httpService.scheduler.shutdown()) log.info(s"REST API was bound on ${settings.restAPISettings.bindAddress}:${settings.restAPISettings.port}") diff --git a/node/src/main/scala/com/wavesplatform/Explorer.scala b/node/src/main/scala/com/wavesplatform/Explorer.scala index c58c6169eef..c03d68a44da 100644 --- a/node/src/main/scala/com/wavesplatform/Explorer.scala +++ b/node/src/main/scala/com/wavesplatform/Explorer.scala @@ -43,7 +43,7 @@ object Explorer extends ScorexLogging { @tailrec def parseArgs(buffer: Seq[String], args: Seq[String] = Nil, flags: Map[String, String] = Map.empty): (Seq[String], Map[String, String]) = - buffer match { + (buffer: @unchecked) match { case flag +: value +: rest if flag.startsWith("-") => parseArgs(rest, args, flags + (flag -> value)) diff --git a/node/src/main/scala/com/wavesplatform/Importer.scala b/node/src/main/scala/com/wavesplatform/Importer.scala index dc7a964f122..d4f145e85e7 100644 --- a/node/src/main/scala/com/wavesplatform/Importer.scala +++ b/node/src/main/scala/com/wavesplatform/Importer.scala @@ -142,9 +142,9 @@ object Importer extends ScorexLogging { override def blocksApi: CommonBlocksApi = CommonBlocksApi(blockchainUpdater, Application.loadBlockMetaAt(db, blockchainUpdater), Application.loadBlockInfoAt(db, blockchainUpdater)) override def accountsApi: CommonAccountsApi = - CommonAccountsApi(blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), db, blockchainUpdater) + CommonAccountsApi(() => blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), db, blockchainUpdater) override def assetsApi: CommonAssetsApi = - CommonAssetsApi(blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), db, blockchainUpdater) + CommonAssetsApi(() => blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), db, blockchainUpdater) } } diff --git a/node/src/main/scala/com/wavesplatform/account/Address.scala b/node/src/main/scala/com/wavesplatform/account/Address.scala index e95e133e40a..e0edce48576 100644 --- a/node/src/main/scala/com/wavesplatform/account/Address.scala +++ b/node/src/main/scala/com/wavesplatform/account/Address.scala @@ -68,7 +68,8 @@ object Address extends ScorexLogging { ) .flatMap { _ => - val Array(version, network, _*) = addressBytes + val version = addressBytes(0) + val network = addressBytes(1) (for { _ <- Either.cond(version == AddressVersion, (), s"Unknown address version: $version") diff --git a/node/src/main/scala/com/wavesplatform/account/KeyPair.scala b/node/src/main/scala/com/wavesplatform/account/KeyPair.scala index d6040fb55bb..663a210cca1 100644 --- a/node/src/main/scala/com/wavesplatform/account/KeyPair.scala +++ b/node/src/main/scala/com/wavesplatform/account/KeyPair.scala @@ -4,14 +4,16 @@ import java.util import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.Base58 +import com.wavesplatform.crypto.Curve25519 import com.wavesplatform.transaction.TxValidationError.GenericError -import com.wavesplatform.{crypto, utils} +import com.wavesplatform.utils import play.api.libs.json.{Format, Json, Writes} import scala.util.{Failure, Success} final class KeyPair(val seed: Array[Byte]) { - lazy val (PrivateKey(privateKey), PublicKey(publicKey)) = crypto.createKeyPair(seed) + lazy val privateKey: PrivateKey = PrivateKey(Curve25519.privateKeyFromSeed(seed)) + lazy val publicKey: PublicKey = PublicKey(Curve25519.publicKeyFromPrivateKey(privateKey.arr)) override def equals(obj: Any): Boolean = obj match { case kp: KeyPair => util.Arrays.equals(kp.seed, seed) diff --git a/node/src/main/scala/com/wavesplatform/account/PrivateKey.scala b/node/src/main/scala/com/wavesplatform/account/PrivateKey.scala index a8c0f734c97..5634d33cbcc 100644 --- a/node/src/main/scala/com/wavesplatform/account/PrivateKey.scala +++ b/node/src/main/scala/com/wavesplatform/account/PrivateKey.scala @@ -1,9 +1,10 @@ package com.wavesplatform.account import com.wavesplatform.common.state.ByteStr +import com.wavesplatform.crypto.KeyLength import play.api.libs.json.{Format, Writes} import supertagged._ -import com.wavesplatform.crypto.KeyLength +import supertagged.postfix._ object PrivateKey extends TaggedType[ByteStr] { def apply(privateKey: ByteStr): PrivateKey = { diff --git a/node/src/main/scala/com/wavesplatform/account/PublicKey.scala b/node/src/main/scala/com/wavesplatform/account/PublicKey.scala index 68b1f68642f..ee2cfdef549 100644 --- a/node/src/main/scala/com/wavesplatform/account/PublicKey.scala +++ b/node/src/main/scala/com/wavesplatform/account/PublicKey.scala @@ -8,6 +8,7 @@ import com.wavesplatform.transaction.TxValidationError.InvalidAddress import com.wavesplatform.utils.base58Length import play.api.libs.json.{Format, Writes} import supertagged._ +import supertagged.postfix._ object PublicKey extends TaggedType[ByteStr] { private[this] val interner = Interners.newWeakInterner[PublicKey]() 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 65124fb60c7..9a7812ed9ec 100644 --- a/node/src/main/scala/com/wavesplatform/api/common/AddressTransactions.scala +++ b/node/src/main/scala/com/wavesplatform/api/common/AddressTransactions.scala @@ -3,9 +3,8 @@ package com.wavesplatform.api.common import com.wavesplatform.account.Address import com.wavesplatform.api.common.CommonTransactionsApi.TransactionMeta import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.database.{DBExt, DBResource, Keys, protobuf => pb} +import com.wavesplatform.database.{DBExt, DBResource, Keys} import com.wavesplatform.state.{Diff, Height, InvokeScriptResult, NewTransactionInfo, TransactionId, TxNum} -import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.{Authorized, GenesisTransaction, Transaction} import monix.eval.Task import monix.reactive.Observable @@ -43,8 +42,8 @@ object AddressTransactions { private def loadInvokeScriptResult(resource: DBResource, txId: ByteStr): Option[InvokeScriptResult] = for { - pb.TransactionMeta(h, txNum, InvokeScriptTransaction.typeId, _) <- resource.get(Keys.transactionMetaById(TransactionId(txId))) - scriptResult <- resource.get(Keys.invokeScriptResult(h, TxNum(txNum.toShort))) + tm <- resource.get(Keys.transactionMetaById(TransactionId(txId))) + scriptResult <- resource.get(Keys.invokeScriptResult(tm.height, TxNum(tm.num.toShort))) } yield scriptResult def loadInvokeScriptResult(db: DB, txId: ByteStr): Option[InvokeScriptResult] = 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 5bf5efff1ce..bc9f25e04c9 100644 --- a/node/src/main/scala/com/wavesplatform/api/common/CommonAccountsApi.scala +++ b/node/src/main/scala/com/wavesplatform/api/common/CommonAccountsApi.scala @@ -55,7 +55,7 @@ object CommonAccountsApi extends ScorexLogging { final case class BalanceDetails(regular: Long, generating: Long, available: Long, effective: Long, leaseIn: Long, leaseOut: Long) - def apply(diff: => Diff, db: DB, blockchain: Blockchain): CommonAccountsApi = new CommonAccountsApi { + def apply(diff: () => Diff, db: DB, blockchain: Blockchain): CommonAccountsApi = new CommonAccountsApi { override def balance(address: Address, confirmations: Int = 0): Long = { blockchain.balance(address, blockchain.height, confirmations) @@ -79,14 +79,19 @@ object CommonAccountsApi extends ScorexLogging { override def assetBalance(address: Address, asset: IssuedAsset): Long = blockchain.balance(address, asset) - override def portfolio(address: Address): Observable[(IssuedAsset, Long)] = - db.resourceObservable.flatMap { resource => - Observable.fromIterator(Task(assetBalanceIterator(resource, address, diff, includeNft(blockchain)))) + override def portfolio(address: Address): Observable[(IssuedAsset, Long)] = { + val currentDiff = diff() + db.resourceObservable.flatMap { resource => + Observable.fromIterator(Task(assetBalanceIterator(resource, address, currentDiff, includeNft(blockchain)))) + } } override def nftList(address: Address, after: Option[IssuedAsset]): Observable[(IssuedAsset, AssetDescription)] = - db.resourceObservable.flatMap { resource => - Observable.fromIterator(Task(nftIterator(resource, address, diff, after, blockchain.assetDescription))) + { + val currentDiff = diff() + db.resourceObservable.flatMap { resource => + Observable.fromIterator(Task(nftIterator(resource, address, currentDiff, after, blockchain.assetDescription))) + } } override def script(address: Address): Option[AccountScriptInfo] = blockchain.accountScript(address) @@ -96,7 +101,8 @@ object CommonAccountsApi extends ScorexLogging { override def dataStream(address: Address, regex: Option[String]): Observable[DataEntry[_]] = Observable.defer { val pattern = regex.map(_.r.pattern) - val entriesFromDiff = diff.accountData + val entriesFromDiff = diff() + .accountData .get(address) .fold[Map[String, DataEntry[_]]](Map.empty)(_.data.filter { case (k, _) => pattern.forall(_.matcher(k).matches()) }) @@ -124,7 +130,7 @@ object CommonAccountsApi extends ScorexLogging { override def activeLeases(address: Address): Observable[LeaseInfo] = addressTransactions( db, - Some(Height(blockchain.height) -> diff), + Some(Height(blockchain.height) -> diff()), address, None, Set(LeaseTransaction.typeId, InvokeScriptTransaction.typeId), diff --git a/node/src/main/scala/com/wavesplatform/api/common/CommonAssetsApi.scala b/node/src/main/scala/com/wavesplatform/api/common/CommonAssetsApi.scala index f350da643ee..56678a14b3c 100644 --- a/node/src/main/scala/com/wavesplatform/api/common/CommonAssetsApi.scala +++ b/node/src/main/scala/com/wavesplatform/api/common/CommonAssetsApi.scala @@ -23,10 +23,9 @@ trait CommonAssetsApi { object CommonAssetsApi { final case class AssetInfo(description: AssetDescription, issueTransaction: Option[IssueTransaction], sponsorBalance: Option[Long]) - def apply(diff: => Diff, db: DB, blockchain: Blockchain): CommonAssetsApi = new CommonAssetsApi { - def description(assetId: IssuedAsset): Option[AssetDescription] = { + def apply(diff: () => Diff, db: DB, blockchain: Blockchain): CommonAssetsApi = new CommonAssetsApi { + def description(assetId: IssuedAsset): Option[AssetDescription] = blockchain.assetDescription(assetId) - } def fullInfo(assetId: IssuedAsset): Option[AssetInfo] = for { @@ -39,7 +38,7 @@ object CommonAssetsApi { db, height, after, - if (height == blockchain.height) diff.portfolios else Map.empty[Address, Portfolio], + if (height == blockchain.height) diff().portfolios else Map.empty[Address, Portfolio], KeyTags.WavesBalance.prefixBytes, bs => AddressId.fromByteArray(bs.slice(2, bs.length - 4)), _.balance @@ -50,7 +49,7 @@ object CommonAssetsApi { db, height, after, - if (height == blockchain.height) diff.portfolios else Map.empty[Address, Portfolio], + if (height == blockchain.height) diff().portfolios else Map.empty[Address, Portfolio], KeyTags.AssetBalance.prefixBytes ++ asset.id.arr, bs => AddressId.fromByteArray(bs.slice(2 + crypto.DigestLength, bs.length - 4)), _.assets.getOrElse(asset, 0L) diff --git a/node/src/main/scala/com/wavesplatform/api/http/AddressApiRoute.scala b/node/src/main/scala/com/wavesplatform/api/http/AddressApiRoute.scala index 6f4e0cc1376..5ec905f8877 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/AddressApiRoute.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/AddressApiRoute.scala @@ -1,6 +1,8 @@ package com.wavesplatform.api.http import akka.NotUsed +import cats.syntax.traverse._ +import cats.instances.option._ import akka.http.scaladsl.marshalling.{ToResponseMarshallable, ToResponseMarshaller} import akka.http.scaladsl.server.{Directive0, Route} import akka.stream.scaladsl.Source @@ -113,7 +115,7 @@ case class AddressApiRoute( complete(balanceJson(address)) } - def balances: Route = (path("balance") & get & parameters(("height".as[Int].?, "address".as[String].*, "asset".?))) { + def balances: Route = (path("balance") & get & parameters("height".as[Int].?, "address".as[String].*, "asset".?)) { (maybeHeight, addresses, assetId) => val height = maybeHeight.getOrElse(blockchain.height) validateBalanceDepth(height)( @@ -247,7 +249,6 @@ case class AddressApiRoute( private def balanceJson(acc: Address) = Balance(acc.stringRepr, 0, commonAccountsApi.balance(acc)) private def scriptMetaJson(account: Address): Either[ValidationError.ScriptParseError, AccountScriptMeta] = { - import cats.implicits._ val accountScript = blockchain.accountScript(account) accountScript diff --git a/node/src/main/scala/com/wavesplatform/api/http/ApiError.scala b/node/src/main/scala/com/wavesplatform/api/http/ApiError.scala index 05299d19696..f30cfd7cf22 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/ApiError.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/ApiError.scala @@ -208,7 +208,7 @@ object ApiError { override val id: Int = AliasDoesNotExist.Id override val code = StatusCodes.NotFound - private[this] lazy val msgReason = aoa match { + private[this] lazy val msgReason = (aoa: @unchecked) match { case a: Address => s"for address '${a.stringRepr}'" case a: Alias => s"'${a.stringRepr}'" } diff --git a/node/src/main/scala/com/wavesplatform/api/http/ApiRoute.scala b/node/src/main/scala/com/wavesplatform/api/http/ApiRoute.scala index de8e8d9a78d..b4c51affcc7 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/ApiRoute.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/ApiRoute.scala @@ -17,10 +17,10 @@ trait AuthRoute { this: ApiRoute => protected lazy val apiKeyHash: Option[Array[Byte]] = Base58.tryDecode(settings.apiKeyHash).toOption def withAuth: Directive0 = apiKeyHash.fold[Directive0](complete(ApiKeyNotValid)) { hashFromSettings => - optionalHeaderValueByType[`X-Api-Key`](()).flatMap { + optionalHeaderValueByType(`X-Api-Key`).flatMap { case Some(k) if java.util.Arrays.equals(crypto.secureHash(k.value.utf8Bytes), hashFromSettings) => pass case _ => - optionalHeaderValueByType[api_key](()).flatMap { + optionalHeaderValueByType(api_key).flatMap { case Some(k) if java.util.Arrays.equals(crypto.secureHash(k.value.utf8Bytes), hashFromSettings) => pass case _ => complete(ApiKeyNotValid) } diff --git a/node/src/main/scala/com/wavesplatform/api/http/CustomJson.scala b/node/src/main/scala/com/wavesplatform/api/http/CustomJson.scala index 5058462c534..91e07e69980 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/CustomJson.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/CustomJson.scala @@ -40,11 +40,11 @@ object NumberAsStringSerializer extends JsonSerializer[JsValue] { "value" ) - override def serialize(value: JsValue, json: JsonGenerator, provider: SerializerProvider): Unit = { + override def serialize(value: JsValue, json: JsonGenerator, provider: SerializerProvider): Unit = value match { case JsNumber(v) => json.writeNumber(v.bigDecimal) case JsString(v) => json.writeString(v) - case JsBoolean(v) => json.writeBoolean(v) + case v: JsBoolean => json.writeBoolean(v.value) case JsArray(elements) => json.writeStartArray() @@ -66,7 +66,6 @@ object NumberAsStringSerializer extends JsonSerializer[JsValue] { case JsNull => json.writeNull() } - } } object CustomJson { 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 9df87f299c0..eda7cfffe1e 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/DebugApiRoute.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/DebugApiRoute.scala @@ -3,33 +3,28 @@ package com.wavesplatform.api.http import java.net.{InetAddress, InetSocketAddress, URI} import java.util.concurrent.ConcurrentMap -import scala.concurrent.{ExecutionContext, Future} -import scala.concurrent.duration._ -import scala.util.{Failure, Success} -import scala.util.control.NonFatal - import akka.http.scaladsl.common.{EntityStreamingSupport, JsonEntityStreamingSupport} import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.headers.Accept import akka.http.scaladsl.server.Route import akka.stream.scaladsl.Source -import cats.implicits._ import cats.kernel.Monoid +import cats.syntax.either._ import com.typesafe.config.{ConfigObject, ConfigRenderOptions} import com.wavesplatform.account.Address -import com.wavesplatform.api.common.{CommonAccountsApi, CommonAssetsApi, CommonTransactionsApi} import com.wavesplatform.api.common.CommonTransactionsApi.TransactionMeta +import com.wavesplatform.api.common.{CommonAccountsApi, CommonAssetsApi, CommonTransactionsApi} import com.wavesplatform.api.http.TransactionsApiRoute.TransactionJsonSerializer import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.mining.{Miner, MinerDebugInfo} import com.wavesplatform.network.{PeerDatabase, PeerInfo, _} import com.wavesplatform.settings.{RestAPISettings, WavesSettings} -import com.wavesplatform.state.{Blockchain, LeaseBalance, NG, Portfolio, StateHash} import com.wavesplatform.state.diffs.TransactionDiffer -import com.wavesplatform.transaction._ +import com.wavesplatform.state.{Blockchain, LeaseBalance, NG, Portfolio, StateHash} import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.TxValidationError.{GenericError, InvalidRequestSignature} +import com.wavesplatform.transaction._ import com.wavesplatform.transaction.smart.script.trace.TracedResult import com.wavesplatform.utils.{ScorexLogging, Time} import com.wavesplatform.utx.UtxPool @@ -37,8 +32,13 @@ import com.wavesplatform.wallet.Wallet import io.netty.channel.Channel import monix.eval.{Coeval, Task} import monix.execution.Scheduler -import play.api.libs.json._ import play.api.libs.json.Json.JsValueWrapper +import play.api.libs.json._ + +import scala.concurrent.duration._ +import scala.concurrent.{ExecutionContext, Future} +import scala.util.control.NonFatal +import scala.util.{Failure, Success} case class DebugApiRoute( ws: WavesSettings, @@ -106,7 +106,7 @@ case class DebugApiRoute( })) } - private def distribution(height: Int): Route = optionalHeaderValueByType[Accept](()) { accept => + private def distribution(height: Int): Route = optionalHeaderValueByType(Accept) { accept => extractScheduler { implicit s => complete( assetsApi diff --git a/node/src/main/scala/com/wavesplatform/api/http/UtilsApiRoute.scala b/node/src/main/scala/com/wavesplatform/api/http/UtilsApiRoute.scala index 3be4297a1e1..a7999a844f5 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/UtilsApiRoute.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/UtilsApiRoute.scala @@ -1,7 +1,10 @@ package com.wavesplatform.api.http +import java.security.SecureRandom + import akka.http.scaladsl.server.{PathMatcher1, Route} -import cats.implicits._ +import cats.syntax.either._ +import cats.syntax.semigroup._ import com.wavesplatform.account.{Address, AddressScheme, PublicKey} import com.wavesplatform.api.http.ApiError.{CustomValidationError, ScriptCompilerError, TooBigArrayAllocation} import com.wavesplatform.api.http.requests.{ScriptWithImportsRequest, byteStrFormat} @@ -38,8 +41,6 @@ import monix.execution.Scheduler import play.api.libs.json._ import shapeless.Coproduct -import java.security.SecureRandom - case class UtilsApiRoute( timeService: Time, settings: RestAPISettings, diff --git a/node/src/main/scala/com/wavesplatform/api/http/assets/AssetsApiRoute.scala b/node/src/main/scala/com/wavesplatform/api/http/assets/AssetsApiRoute.scala index 2f3720ec7fa..693a53d9bf1 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/assets/AssetsApiRoute.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/assets/AssetsApiRoute.scala @@ -98,7 +98,7 @@ case class AssetsApiRoute( } } } ~ pathPrefix("details") { - (pathEndOrSingleSlash & parameters(("id".as[String].*, "full".as[Boolean] ? false))) { (ids, full) => + (pathEndOrSingleSlash & parameters("id".as[String].*, "full".as[Boolean] ? false)) { (ids, full) => multipleDetailsGet(ids.toSeq.reverse, full) } ~ (path(AssetId) & parameter("full".as[Boolean] ? false)) { (assetId, full) => singleDetails(assetId, full) @@ -181,7 +181,7 @@ case class AssetsApiRoute( } def balanceDistributionAtHeight(assetId: IssuedAsset, heightParam: Int, limitParam: Int, afterParam: Option[String]): Route = - optionalHeaderValueByType[Accept](()) { accept => + optionalHeaderValueByType(Accept) { accept => val paramsEi: Either[ValidationError, DistributionParams] = AssetsApiRoute .validateDistributionParams(blockchain, heightParam, limitParam, settings.distributionAddressLimit, afterParam, maxDistributionDepth) 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 aa883650d0a..08e9ff97fe6 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/package.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/package.scala @@ -61,7 +61,7 @@ package object http extends ApiMarshallers with ScorexLogging { TransactionParsers.by(typeId, version) match { case None => Left(GenericError(s"Bad transaction type ($typeId) and version ($version)")) case Some(x) => - x match { + (x: @unchecked) match { case TransferTransaction => txJson.as[TransferRequest].toTxFrom(senderPk) case CreateAliasTransaction => txJson.as[CreateAliasRequest].toTxFrom(senderPk) case LeaseTransaction => txJson.as[LeaseRequest].toTxFrom(senderPk) @@ -147,7 +147,7 @@ package object http extends ApiMarshallers with ScorexLogging { jsonPostD[A].apply(obj => complete(f(obj))) ~ get(complete(StatusCodes.MethodNotAllowed)) def jsonPostD[A: Reads]: Directive1[A] = - (post & handleExceptions(jsonExceptionHandler) & handleRejections(jsonRejectionHandler) & entity(as[A])) + post & handleExceptions(jsonExceptionHandler) & handleRejections(jsonRejectionHandler) & entity(as[A]) def extractScheduler: Directive1[Scheduler] = extractExecutionContext.map(ec => Scheduler(ec)) 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 073ef35557c..9d7b416b90a 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 @@ -1,6 +1,8 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.either._ +import cats.syntax.traverse._ import com.wavesplatform.account.{AddressOrAlias, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError 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 index 9fa9dc25cc1..202d0769861 100644 --- a/node/src/main/scala/com/wavesplatform/api/http/requests/SignedUpdateAssetInfoRequest.scala +++ b/node/src/main/scala/com/wavesplatform/api/http/requests/SignedUpdateAssetInfoRequest.scala @@ -1,6 +1,7 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +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} 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 007bdba8b09..51a78bb7b80 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 @@ -1,6 +1,7 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +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} diff --git a/node/src/main/scala/com/wavesplatform/block/serialization/package.scala b/node/src/main/scala/com/wavesplatform/block/serialization/package.scala index 728f9c929b6..8e4f7226553 100644 --- a/node/src/main/scala/com/wavesplatform/block/serialization/package.scala +++ b/node/src/main/scala/com/wavesplatform/block/serialization/package.scala @@ -22,7 +22,7 @@ package object serialization { } private[block] def readTransactionData(version: Byte, buf: ByteBuffer): Seq[Transaction] = { - val txCount = version match { + val txCount = (version: @unchecked) match { case GenesisBlockVersion | PlainBlockVersion => buf.getByte case NgBlockVersion | RewardBlockVersion | ProtoBlockVersion => buf.getInt } @@ -46,7 +46,7 @@ package object serialization { generationSignature.arr ) - def mkTxsCountBytes(version: Byte, txsCount: Int): Array[Byte] = version match { + def mkTxsCountBytes(version: Byte, txsCount: Int): Array[Byte] = (version: @unchecked) match { case GenesisBlockVersion | PlainBlockVersion => Array(txsCount.toByte) case NgBlockVersion | RewardBlockVersion | ProtoBlockVersion => Ints.toByteArray(txsCount) } diff --git a/node/src/main/scala/com/wavesplatform/crypto/package.scala b/node/src/main/scala/com/wavesplatform/crypto/package.scala index d3b72db7699..b0b28bdf91a 100644 --- a/node/src/main/scala/com/wavesplatform/crypto/package.scala +++ b/node/src/main/scala/com/wavesplatform/crypto/package.scala @@ -8,8 +8,6 @@ import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.TxValidationError.GenericError import com.wavesplatform.utils._ import org.whispersystems.curve25519.OpportunisticCurve25519Provider -import scorex.crypto.hash.{Blake2b256, Keccak256} -import scorex.crypto.signatures.{Curve25519, Signature, PrivateKey => SPrivateKey, PublicKey => SPublicKey} import scala.util.Try @@ -37,20 +35,18 @@ package object crypto extends ScorexLogging { // Signatures def sign(account: PrivateKey, message: Array[Byte]): ByteStr = - ByteStr(Curve25519.sign(SPrivateKey(account.arr), message)) + ByteStr(Curve25519.sign(account.arr, message)) def signVRF(account: PrivateKey, message: Array[Byte]): ByteStr = ByteStr(provider.calculateVrfSignature(provider.getRandom(DigestLength), account.arr, message)) def verify(signature: ByteStr, message: Array[Byte], publicKey: PublicKey): Boolean = - Curve25519.verify(Signature(signature.arr), message, SPublicKey(publicKey.arr)) + Curve25519.verify(signature.arr, message, publicKey.arr) def verifyVRF(signature: ByteStr, message: Array[Byte], publicKey: PublicKey): Either[ValidationError, ByteStr] = Try(ByteStr(provider.verifyVrfSignature(publicKey.arr, message, signature.arr))).toEither.left .map(_ => GenericError("Could not verify VRF proof")) - def createKeyPair(seed: Array[Byte]): (Array[Byte], Array[Byte]) = Curve25519.createKeyPair(seed) - // see // https://github.com/jedisct1/libsodium/blob/ab4ab23d5744a8e060864a7cec1a7f9b059f9ddd/src/libsodium/crypto_scalarmult/curve25519/ref10/x25519_ref10.c#L17 // https://boringssl.googlesource.com/boringssl/+/master/third_party/wycheproof_testvectors/x25519_test.json diff --git a/node/src/main/scala/com/wavesplatform/database/Key.scala b/node/src/main/scala/com/wavesplatform/database/Key.scala index 44cafc79b5e..dafe70a490f 100644 --- a/node/src/main/scala/com/wavesplatform/database/Key.scala +++ b/node/src/main/scala/com/wavesplatform/database/Key.scala @@ -1,5 +1,7 @@ package com.wavesplatform.database +import scala.collection.concurrent.TrieMap + import com.google.common.base.CaseFormat import com.google.common.io.BaseEncoding import com.google.common.primitives.{Bytes, Shorts} @@ -20,10 +22,18 @@ abstract class Key[V](prefix: Short, val name: String, val suffix: Array[Byte]) } object Key { - private[this] val converter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_HYPHEN) + // Optimisation due to synchronization block in scala.Enumeration#nameOf + private[this] object KeyToString { + private[this] val converter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_HYPHEN) + private[this] val cache = TrieMap.empty[KeyTags.KeyTag, String] + + def toString(keyTag: KeyTags.KeyTag): String = { + cache.getOrElseUpdate(keyTag, converter.convert(keyTag.toString)) + } + } def apply[V](keyTag: KeyTags.KeyTag, keySuffix: Array[Byte], parser: Array[Byte] => V, encoder: V => Array[Byte]): Key[V] = - new Key[V](keyTag.id.toShort, converter.convert(keyTag.toString), keySuffix) { + new Key[V](keyTag.id.toShort, KeyToString.toString(keyTag), keySuffix) { override def parse(bytes: Array[Byte]): V = parser(bytes) override def encode(v: V): Array[Byte] = encoder(v) } diff --git a/node/src/main/scala/com/wavesplatform/database/LevelDBWriter.scala b/node/src/main/scala/com/wavesplatform/database/LevelDBWriter.scala index 2a7c24e4599..aee9669a74f 100644 --- a/node/src/main/scala/com/wavesplatform/database/LevelDBWriter.scala +++ b/node/src/main/scala/com/wavesplatform/database/LevelDBWriter.scala @@ -2,21 +2,16 @@ package com.wavesplatform.database import java.nio.ByteBuffer -import scala.annotation.tailrec -import scala.collection.mutable.{ArrayBuffer, ListBuffer} -import scala.jdk.CollectionConverters._ -import scala.util.Try -import scala.util.control.NonFatal - import cats.data.Ior -import cats.implicits._ +import cats.syntax.option._ +import cats.syntax.semigroup._ import com.google.common.cache.CacheBuilder import com.google.common.collect.MultimapBuilder import com.google.common.primitives.{Ints, Shorts} import com.wavesplatform.account.{Address, Alias} import com.wavesplatform.api.BlockMeta -import com.wavesplatform.block.{Block, SignedBlockHeader} import com.wavesplatform.block.Block.BlockId +import com.wavesplatform.block.{Block, SignedBlockHeader} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils._ import com.wavesplatform.database @@ -26,11 +21,11 @@ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.ValidationError import com.wavesplatform.protobuf.transaction.PBTransactions import com.wavesplatform.settings.{BlockchainSettings, DBSettings, WavesSettings} -import com.wavesplatform.state.{TxNum, _} import com.wavesplatform.state.reader.LeaseDetails -import com.wavesplatform.transaction._ +import com.wavesplatform.state.{TxNum, _} import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError.{AliasDoesNotExist, AliasIsDisabled} +import com.wavesplatform.transaction._ import com.wavesplatform.transaction.assets._ import com.wavesplatform.transaction.assets.exchange.ExchangeTransaction import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} @@ -41,6 +36,12 @@ import monix.reactive.Observer import org.iq80.leveldb.DB import org.slf4j.LoggerFactory +import scala.annotation.tailrec +import scala.collection.mutable.{ArrayBuffer, ListBuffer} +import scala.jdk.CollectionConverters._ +import scala.util.Try +import scala.util.control.NonFatal + object LevelDBWriter extends ScorexLogging { /** {{{ @@ -559,8 +560,8 @@ abstract class LevelDBWriter private[database] ( val (txHeight, txNum) = transactions .get(TransactionId(txId)) .map { case (_, txNum, _) => (height, txNum) } - .orElse(rw.get(Keys.transactionMetaById(TransactionId(txId))).map { - case TransactionMeta(height, txNum, _, _) => (height, TxNum(txNum.toShort)) + .orElse(rw.get(Keys.transactionMetaById(TransactionId(txId))).map { tm => + (tm.height, TxNum(tm.num.toShort)) }) .getOrElse(throw new IllegalArgumentException(s"Couldn't find transaction height and num: $txId")) @@ -687,7 +688,7 @@ abstract class LevelDBWriter private[database] ( transactions.foreach { case (num, tx) => forgetTransaction(tx.id()) - tx match { + (tx: @unchecked) match { case _: GenesisTransaction => // genesis transaction can not be rolled back case _: PaymentTransaction | _: TransferTransaction | _: MassTransferTransaction => // balances already restored @@ -803,23 +804,24 @@ abstract class LevelDBWriter private[database] ( override def transferById(id: ByteStr): Option[(Int, TransferTransaction)] = readOnly { db => for { - TransactionMeta(height, num, TransferTransaction.typeId, _) <- db.get(Keys.transactionMetaById(TransactionId @@ id)) - tx <- db.get(Keys.transactionAt(Height(height), TxNum(num.toShort))).collect { case (t: TransferTransaction, true) => t } + tm <- db.get(Keys.transactionMetaById(TransactionId @@ id)) + if tm.`type` == TransferTransaction.typeId + tx <- db.get(Keys.transactionAt(Height(tm.height), TxNum(tm.num.toShort))).collect { case (t: TransferTransaction, true) => t } } yield (height, tx) } override def transactionInfo(id: ByteStr): Option[(Int, Transaction, Boolean)] = readOnly(transactionInfo(id, _)) - protected def transactionInfo(id: ByteStr, db: ReadOnlyDB): Option[(Int, Transaction, Boolean)] = { - val txId = TransactionId(id) + protected def transactionInfo(id: ByteStr, db: ReadOnlyDB): Option[(Int, Transaction, Boolean)] = for { - TransactionMeta(height, num, _, failed) <- db.get(Keys.transactionMetaById(txId)) - (tx, _) <- db.get(Keys.transactionAt(Height(height), TxNum(num.toShort))) - } yield (height, tx, !failed) - } + tm <- db.get(Keys.transactionMetaById(TransactionId(id))) + (tx, _) <- db.get(Keys.transactionAt(Height(tm.height), TxNum(tm.num.toShort))) + } yield (tm.height, tx, !tm.failed) override def transactionMeta(id: ByteStr): Option[(Int, Boolean)] = readOnly { db => - db.get(Keys.transactionMetaById(TransactionId(id))).map { case TransactionMeta(height, _, _, failed) => (height, !failed) } + db.get(Keys.transactionMetaById(TransactionId(id))).map { tm => + (tm.height, !tm.failed) + } } override def resolveAlias(alias: Alias): Either[ValidationError, Address] = readOnly { db => @@ -838,8 +840,15 @@ abstract class LevelDBWriter private[database] ( isActive => transactionInfo(leaseId, db).collect { case (leaseHeight, lt: LeaseTransaction, _) => - LeaseDetails(lt.sender, lt.recipient, lt.amount, if (isActive) LeaseDetails.Status.Active - else LeaseDetails.Status.Cancelled(h, None), leaseId, leaseHeight) + LeaseDetails( + lt.sender, + lt.recipient, + lt.amount, + if (isActive) LeaseDetails.Status.Active + else LeaseDetails.Status.Cancelled(h, None), + leaseId, + leaseHeight + ) }, Some(_) ) diff --git a/node/src/main/scala/com/wavesplatform/database/package.scala b/node/src/main/scala/com/wavesplatform/database/package.scala index 474d829d96f..688eaa2eaec 100644 --- a/node/src/main/scala/com/wavesplatform/database/package.scala +++ b/node/src/main/scala/com/wavesplatform/database/package.scala @@ -131,7 +131,7 @@ package object database extends ScorexLogging { val ids = List.newBuilder[ByteStr] while (b.remaining() > 0) { - val buffer = b.get() match { + val buffer = (b.get(): @unchecked) match { case crypto.DigestLength => new Array[Byte](crypto.DigestLength) case crypto.SignatureLength => new Array[Byte](crypto.SignatureLength) } @@ -146,7 +146,7 @@ package object database extends ScorexLogging { ids .foldLeft(ByteBuffer.allocate(ids.map(_.arr.length + 1).sum)) { case (b, id) => - b.put(id.arr.length match { + b.put((id.arr.length: @unchecked) match { case crypto.DigestLength => crypto.DigestLength.toByte case crypto.SignatureLength => crypto.SignatureLength.toByte }) @@ -219,8 +219,8 @@ package object database extends ScorexLogging { d.amount, d.status match { case pb.LeaseDetails.Status.Active(_) => LeaseDetails.Status.Active - case pb.LeaseDetails.Status.Expired(pb.LeaseDetails.Expired(height)) => LeaseDetails.Status.Expired(height) - case pb.LeaseDetails.Status.Cancelled(pb.LeaseDetails.Cancelled(height, transactionId)) => + case pb.LeaseDetails.Status.Expired(pb.LeaseDetails.Expired(height, _)) => LeaseDetails.Status.Expired(height) + case pb.LeaseDetails.Status.Cancelled(pb.LeaseDetails.Cancelled(height, transactionId, _)) => LeaseDetails.Status.Cancelled(height, Some(transactionId.toByteStr).filter(!_.isEmpty)) case pb.LeaseDetails.Status.Empty => ??? }, @@ -561,7 +561,7 @@ package object database extends ScorexLogging { case _: PaymentTransaction => LegacyBytes(ByteString.copyFrom(tx.bytes())) case _ => NewTransaction(PBTransactions.protobuf(tx)) } - pb.TransactionData(!succeeded, ptx).toByteArray + pb.TransactionData(ptx, !succeeded).toByteArray } /** Returns status (succeed - true, failed -false) and bytes (left - legacy format bytes, right - new format bytes) */ @@ -645,8 +645,8 @@ package object database extends ScorexLogging { id <- loadLeaseIds(r, fromHeight, toHeight, includeCancelled = false) details <- fromHistory(r, Keys.leaseDetailsHistory(id), Keys.leaseDetails(id)) if details.exists(_.fold(identity, _.isActive)) - pb.TransactionMeta(h, n, _, _) <- r.get(Keys.transactionMetaById(TransactionId(id))) - tx <- r.get(Keys.transactionAt(Height(h), TxNum(n.toShort))) + tm <- r.get(Keys.transactionMetaById(TransactionId(id))) + tx <- r.get(Keys.transactionAt(Height(tm.height), TxNum(tm.num.toShort))) } yield tx).collect { case (lt: LeaseTransaction, true) => lt }.toSeq diff --git a/node/src/main/scala/com/wavesplatform/mining/Miner.scala b/node/src/main/scala/com/wavesplatform/mining/Miner.scala index b47f6c956ee..fca2c8b81b2 100644 --- a/node/src/main/scala/com/wavesplatform/mining/Miner.scala +++ b/node/src/main/scala/com/wavesplatform/mining/Miner.scala @@ -2,12 +2,10 @@ package com.wavesplatform.mining import java.time.LocalTime -import scala.concurrent.duration._ - -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.account.KeyPair -import com.wavesplatform.block.{Block, BlockHeader, SignedBlockHeader} import com.wavesplatform.block.Block._ +import com.wavesplatform.block.{Block, BlockHeader, SignedBlockHeader} import com.wavesplatform.consensus.PoSSelector import com.wavesplatform.consensus.nxt.NxtLikeConsensusBlockData import com.wavesplatform.features.BlockchainFeatures @@ -17,8 +15,8 @@ import com.wavesplatform.network._ import com.wavesplatform.settings.WavesSettings import com.wavesplatform.state._ import com.wavesplatform.state.appender.BlockAppender -import com.wavesplatform.transaction._ import com.wavesplatform.transaction.TxValidationError.BlockFromFuture +import com.wavesplatform.transaction._ import com.wavesplatform.utils.{ScorexLogging, Time} import com.wavesplatform.utx.UtxPool.PackStrategy import com.wavesplatform.utx.UtxPoolImpl @@ -29,6 +27,8 @@ import monix.eval.Task import monix.execution.cancelables.{CompositeCancelable, SerialCancelable} import monix.execution.schedulers.SchedulerService +import scala.concurrent.duration._ + trait Miner { def scheduleMining(blockchain: Option[Blockchain] = None): Unit } diff --git a/node/src/main/scala/com/wavesplatform/mining/microblocks/MicroBlockMinerImpl.scala b/node/src/main/scala/com/wavesplatform/mining/microblocks/MicroBlockMinerImpl.scala index 21fea0dbf64..8557cbe59e6 100644 --- a/node/src/main/scala/com/wavesplatform/mining/microblocks/MicroBlockMinerImpl.scala +++ b/node/src/main/scala/com/wavesplatform/mining/microblocks/MicroBlockMinerImpl.scala @@ -1,11 +1,11 @@ package com.wavesplatform.mining.microblocks -import scala.concurrent.duration._ - -import cats.implicits._ +import cats.syntax.applicativeError._ +import cats.syntax.bifunctor._ +import cats.syntax.either._ import com.wavesplatform.account.KeyPair -import com.wavesplatform.block.{Block, MicroBlock} import com.wavesplatform.block.Block.BlockId +import com.wavesplatform.block.{Block, MicroBlock} import com.wavesplatform.metrics._ import com.wavesplatform.mining._ import com.wavesplatform.mining.microblocks.MicroBlockMinerImpl._ @@ -22,6 +22,8 @@ import kamon.Kamon import monix.eval.Task import monix.execution.schedulers.SchedulerService +import scala.concurrent.duration._ + class MicroBlockMinerImpl( setDebugState: MinerDebugInfo.State => Unit, allChannels: ChannelGroup, diff --git a/node/src/main/scala/com/wavesplatform/network/HandshakeHandler.scala b/node/src/main/scala/com/wavesplatform/network/HandshakeHandler.scala index b2fb440eefc..765929e0772 100644 --- a/node/src/main/scala/com/wavesplatform/network/HandshakeHandler.scala +++ b/node/src/main/scala/com/wavesplatform/network/HandshakeHandler.scala @@ -202,7 +202,7 @@ object HandshakeHandler extends ScorexLogging { super.channelRead(ctx, msg) } - override protected def channelActive(ctx: ChannelHandlerContext): Unit = { + override def channelActive(ctx: ChannelHandlerContext): Unit = { sendLocalHandshake(ctx) ctx.channel().attr(ConnectionStartAttributeKey).set(System.currentTimeMillis()) super.channelActive(ctx) diff --git a/node/src/main/scala/com/wavesplatform/network/InvalidBlockStorage.scala b/node/src/main/scala/com/wavesplatform/network/InvalidBlockStorage.scala index c58d3b6e9a9..adf5b3b29e9 100644 --- a/node/src/main/scala/com/wavesplatform/network/InvalidBlockStorage.scala +++ b/node/src/main/scala/com/wavesplatform/network/InvalidBlockStorage.scala @@ -13,6 +13,13 @@ trait InvalidBlockStorage { def find(blockId: ByteStr): Option[ValidationError] } +object InvalidBlockStorage { + object NoOp extends InvalidBlockStorage { + override def add(blockId: ByteStr, validationError: ValidationError): Unit = {} + override def find(blockId: ByteStr): Option[ValidationError] = None + } +} + class InvalidBlockStorageImpl(settings: InvalidBlockStorageSettings) extends InvalidBlockStorage { private val cache = CacheBuilder .newBuilder() diff --git a/node/src/main/scala/com/wavesplatform/network/LegacyFrameCodec.scala b/node/src/main/scala/com/wavesplatform/network/LegacyFrameCodec.scala index 34b749cb61f..394538ff0d6 100644 --- a/node/src/main/scala/com/wavesplatform/network/LegacyFrameCodec.scala +++ b/node/src/main/scala/com/wavesplatform/network/LegacyFrameCodec.scala @@ -71,7 +71,7 @@ class LegacyFrameCodec(peerDatabase: PeerDatabase, receivedTxsCacheTimeout: Fini } override def encode(ctx: ChannelHandlerContext, msg1: Any, out: ByteBuf): Unit = { - val msg = msg1 match { + val msg = (msg1: @unchecked) match { case rb: RawBytes => rb case tx: Transaction => RawBytes.fromTransaction(tx) case block: Block => RawBytes.fromBlock(block) diff --git a/node/src/main/scala/com/wavesplatform/network/PeerDatabase.scala b/node/src/main/scala/com/wavesplatform/network/PeerDatabase.scala index 175c9810898..1ff539e00a0 100644 --- a/node/src/main/scala/com/wavesplatform/network/PeerDatabase.scala +++ b/node/src/main/scala/com/wavesplatform/network/PeerDatabase.scala @@ -36,7 +36,7 @@ trait PeerDatabase extends AutoCloseable { object PeerDatabase extends ScorexLogging { - trait NoOp extends PeerDatabase { + object NoOp extends PeerDatabase { override def addCandidate(socketAddress: InetSocketAddress): Boolean = true override def touch(socketAddress: InetSocketAddress): Unit = {} @@ -65,7 +65,4 @@ object PeerDatabase extends ScorexLogging { override def close(): Unit = {} } - - object NoOp extends NoOp - } diff --git a/node/src/main/scala/com/wavesplatform/network/RxScoreObserver.scala b/node/src/main/scala/com/wavesplatform/network/RxScoreObserver.scala index a43a6b3026f..38d664fea50 100644 --- a/node/src/main/scala/com/wavesplatform/network/RxScoreObserver.scala +++ b/node/src/main/scala/com/wavesplatform/network/RxScoreObserver.scala @@ -3,7 +3,8 @@ package com.wavesplatform.network import java.util.concurrent.TimeUnit import cats._ -import cats.implicits._ +import cats.instances.bigInt._ +import cats.instances.tuple._ import com.google.common.cache.CacheBuilder import com.wavesplatform.utils.ScorexLogging import io.netty.channel._ @@ -11,8 +12,8 @@ import monix.eval.Coeval import monix.execution.Scheduler import monix.reactive.Observable -import scala.jdk.CollectionConverters._ import scala.concurrent.duration.FiniteDuration +import scala.jdk.CollectionConverters._ case class BestChannel(channel: Channel, score: BigInt) { override def toString: String = s"BestChannel(${id(channel)},$score)" @@ -44,14 +45,16 @@ object RxScoreObserver extends ScorexLogging { } else None } - def apply(scoreTtl: FiniteDuration, - remoteScoreDebounce: FiniteDuration, - initalLocalScore: BigInt, - localScores: Observable[BigInt], - remoteScores: ChannelObservable[BigInt], - channelClosed: Observable[Channel], - channelTimeout: Observable[Channel], - scheduler: Scheduler): (Observable[ChannelClosedAndSyncWith], Coeval[Stats]) = { + def apply( + scoreTtl: FiniteDuration, + remoteScoreDebounce: FiniteDuration, + initalLocalScore: BigInt, + localScores: Observable[BigInt], + remoteScores: ChannelObservable[BigInt], + channelClosed: Observable[Channel], + channelTimeout: Observable[Channel], + scheduler: Scheduler + ): (Observable[ChannelClosedAndSyncWith], Coeval[Stats]) = { var localScore: BigInt = initalLocalScore var currentBestChannel: Option[Channel] = None @@ -78,8 +81,10 @@ object RxScoreObserver extends ScorexLogging { remoteScores .observeOn(scheduler) .groupBy(_._1) - .map(_.distinctUntilChanged - .debounce(remoteScoreDebounce)) + .map( + _.distinctUntilChanged + .debounce(remoteScoreDebounce) + ) .merge .collect { case (ch, score) if ch.isOpen => 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 87fb838449e..0dd404df224 100644 --- a/node/src/main/scala/com/wavesplatform/protobuf/transaction/PBTransactions.scala +++ b/node/src/main/scala/com/wavesplatform/protobuf/transaction/PBTransactions.scala @@ -20,6 +20,7 @@ import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTran import com.wavesplatform.transaction.{Proofs, TxValidationError} import com.wavesplatform.utils.StringBytes import com.wavesplatform.{transaction => vt} +import scalapb.UnknownFieldSet.empty import scala.util.Try @@ -108,19 +109,19 @@ object PBTransactions { val signature = proofs.toSignature val result: Either[ValidationError, VanillaTransaction] = data match { - case Data.Genesis(GenesisTransactionData(recipient, amount)) => + case Data.Genesis(GenesisTransactionData(recipient, amount, `empty`)) => for { addr <- PBRecipients.toAddress(recipient.toByteArray, chainId) tx <- vt.GenesisTransaction.create(addr, amount, timestamp) } yield tx - case Data.Payment(PaymentTransactionData(recipient, amount)) => + case Data.Payment(PaymentTransactionData(recipient, amount, `empty`)) => for { addr <- PBRecipients.toAddress(recipient.toByteArray, chainId) tx <- vt.PaymentTransaction.create(sender, addr, amount, feeAmount, timestamp, signature) } yield tx - case Data.Transfer(TransferTransactionData(Some(recipient), Some(amount), attachment)) => + case Data.Transfer(TransferTransactionData(Some(recipient), Some(amount), attachment, `empty`)) => for { address <- recipient.toAddressOrAlias(chainId) tx <- vt.transfer.TransferTransaction.create( @@ -137,12 +138,12 @@ object PBTransactions { ) } yield tx - case Data.CreateAlias(CreateAliasTransactionData(alias)) => + case Data.CreateAlias(CreateAliasTransactionData(alias, _)) => for { tx <- vt.CreateAliasTransaction.create(version.toByte, sender, alias, feeAmount, timestamp, Proofs(Seq(signature)), chainId) } yield tx - case Data.Issue(IssueTransactionData(name, description, quantity, decimals, reissuable, script)) => + case Data.Issue(IssueTransactionData(name, description, quantity, decimals, reissuable, script, `empty`)) => vt.assets.IssueTransaction.create( version.toByte, sender, @@ -158,7 +159,7 @@ object PBTransactions { chainId ) - case Data.Reissue(ReissueTransactionData(Some(Amount(assetId, amount)), reissuable)) => + case Data.Reissue(ReissueTransactionData(Some(Amount(assetId, amount, `empty`)), reissuable, `empty`)) => vt.assets.ReissueTransaction.create( version.toByte, sender, @@ -171,10 +172,10 @@ object PBTransactions { chainId ) - case Data.Burn(BurnTransactionData(Some(Amount(assetId, amount)))) => + case Data.Burn(BurnTransactionData(Some(Amount(assetId, amount, `empty`)), `empty`)) => vt.assets.BurnTransaction.create(version.toByte, sender, IssuedAsset(assetId.toByteStr), amount, feeAmount, timestamp, proofs, chainId) - case Data.SetAssetScript(SetAssetScriptTransactionData(assetId, script)) => + case Data.SetAssetScript(SetAssetScriptTransactionData(assetId, script, `empty`)) => vt.assets.SetAssetScriptTransaction.create( version.toByte, sender, @@ -186,7 +187,7 @@ object PBTransactions { chainId ) - case Data.SetScript(SetScriptTransactionData(script)) => + case Data.SetScript(SetScriptTransactionData(script, `empty`)) => vt.smart.SetScriptTransaction.create( version.toByte, sender, @@ -197,16 +198,16 @@ object PBTransactions { chainId ) - case Data.Lease(LeaseTransactionData(Some(recipient), amount)) => + case Data.Lease(LeaseTransactionData(Some(recipient), amount, `empty`)) => for { address <- recipient.toAddressOrAlias(chainId) tx <- vt.lease.LeaseTransaction.create(version.toByte, sender, address, amount, feeAmount, timestamp, proofs) } yield tx - case Data.LeaseCancel(LeaseCancelTransactionData(leaseId)) => + case Data.LeaseCancel(LeaseCancelTransactionData(leaseId, `empty`)) => vt.lease.LeaseCancelTransaction.create(version.toByte, sender, leaseId.toByteStr, feeAmount, timestamp, proofs, chainId) - case Data.Exchange(ExchangeTransactionData(amount, price, buyMatcherFee, sellMatcherFee, Seq(order1, order2))) => + case Data.Exchange(ExchangeTransactionData(amount, price, buyMatcherFee, sellMatcherFee, Seq(order1, order2), `empty`)) => vt.assets.exchange.ExchangeTransaction.create( version.toByte, PBOrders.vanilla(order1), @@ -237,7 +238,7 @@ object PBTransactions { chainId ) - case Data.SponsorFee(SponsorFeeTransactionData(Some(Amount(assetId, minFee)))) => + case Data.SponsorFee(SponsorFeeTransactionData(Some(Amount(assetId, minFee, `empty`)), `empty`)) => vt.assets.SponsorFeeTransaction.create( version.toByte, sender, @@ -249,7 +250,7 @@ object PBTransactions { chainId ) - case Data.InvokeScript(InvokeScriptTransactionData(Some(dappAddress), functionCall, payments)) => + case Data.InvokeScript(InvokeScriptTransactionData(Some(dappAddress), functionCall, payments, `empty`)) => import cats.instances.either._ import cats.instances.option._ import cats.syntax.traverse._ @@ -283,7 +284,7 @@ object PBTransactions { ) } yield tx - case Data.UpdateAssetInfo(UpdateAssetInfoTransactionData(assetId, name, description)) => + case Data.UpdateAssetInfo(UpdateAssetInfoTransactionData(assetId, name, description, `empty`)) => UpdateAssetInfoTransaction.create( version.toByte, sender, @@ -318,10 +319,10 @@ object PBTransactions { val signature = proofs.toSignature data match { - case Data.Genesis(GenesisTransactionData(recipient, amount)) => + case Data.Genesis(GenesisTransactionData(recipient, amount, `empty`)) => vt.GenesisTransaction(PBRecipients.toAddress(recipient.toByteArray, chainId).explicitGet(), amount, timestamp, signature, chainId) - case Data.Payment(PaymentTransactionData(recipient, amount)) => + case Data.Payment(PaymentTransactionData(recipient, amount, `empty`)) => vt.PaymentTransaction( sender, PBRecipients.toAddress(recipient.toByteArray, chainId).explicitGet(), @@ -332,7 +333,7 @@ object PBTransactions { chainId ) - case Data.Transfer(TransferTransactionData(Some(recipient), Some(amount), attachment)) => + case Data.Transfer(TransferTransactionData(Some(recipient), Some(amount), attachment, `empty`)) => vt.transfer.TransferTransaction( version.toByte, sender, @@ -347,7 +348,7 @@ object PBTransactions { chainId ) - case Data.CreateAlias(CreateAliasTransactionData(alias)) => + case Data.CreateAlias(CreateAliasTransactionData(alias, `empty`)) => vt.CreateAliasTransaction( version.toByte, sender, @@ -358,7 +359,7 @@ object PBTransactions { chainId ) - case Data.Issue(IssueTransactionData(name, description, quantity, decimals, reissuable, script)) => + case Data.Issue(IssueTransactionData(name, description, quantity, decimals, reissuable, script, `empty`)) => vt.assets.IssueTransaction( version.toByte, sender, @@ -374,7 +375,7 @@ object PBTransactions { chainId ) - case Data.Reissue(ReissueTransactionData(Some(Amount(assetId, amount)), reissuable)) => + case Data.Reissue(ReissueTransactionData(Some(Amount(assetId, amount, `empty`)), reissuable, `empty`)) => vt.assets.ReissueTransaction( version.toByte, sender, @@ -387,10 +388,10 @@ object PBTransactions { chainId ) - case Data.Burn(BurnTransactionData(Some(Amount(assetId, amount)))) => + case Data.Burn(BurnTransactionData(Some(Amount(assetId, amount, `empty`)), `empty`)) => vt.assets.BurnTransaction(version.toByte, sender, IssuedAsset(assetId.toByteStr), amount, feeAmount, timestamp, proofs, chainId) - case Data.SetAssetScript(SetAssetScriptTransactionData(assetId, script)) => + case Data.SetAssetScript(SetAssetScriptTransactionData(assetId, script, `empty`)) => vt.assets.SetAssetScriptTransaction( version.toByte, sender, @@ -402,7 +403,7 @@ object PBTransactions { chainId ) - case Data.SetScript(SetScriptTransactionData(script)) => + case Data.SetScript(SetScriptTransactionData(script, `empty`)) => vt.smart.SetScriptTransaction( version.toByte, sender, @@ -413,7 +414,7 @@ object PBTransactions { chainId ) - case Data.Lease(LeaseTransactionData(Some(recipient), amount)) => + case Data.Lease(LeaseTransactionData(Some(recipient), amount, `empty`)) => vt.lease.LeaseTransaction( version.toByte, sender, @@ -425,10 +426,10 @@ object PBTransactions { chainId ) - case Data.LeaseCancel(LeaseCancelTransactionData(leaseId)) => + case Data.LeaseCancel(LeaseCancelTransactionData(leaseId, `empty`)) => vt.lease.LeaseCancelTransaction(version.toByte, sender, leaseId.toByteStr, feeAmount, timestamp, proofs, chainId) - case Data.Exchange(ExchangeTransactionData(amount, price, buyMatcherFee, sellMatcherFee, Seq(buyOrder, sellOrder))) => + case Data.Exchange(ExchangeTransactionData(amount, price, buyMatcherFee, sellMatcherFee, Seq(buyOrder, sellOrder), `empty`)) => vt.assets.exchange.ExchangeTransaction( version.toByte, PBOrders.vanilla(buyOrder), @@ -459,7 +460,7 @@ object PBTransactions { chainId ) - case Data.SponsorFee(SponsorFeeTransactionData(Some(Amount(assetId, minFee)))) => + case Data.SponsorFee(SponsorFeeTransactionData(Some(Amount(assetId, minFee, `empty`)), `empty`)) => vt.assets.SponsorFeeTransaction( version.toByte, sender, @@ -471,7 +472,7 @@ object PBTransactions { chainId ) - case Data.InvokeScript(InvokeScriptTransactionData(Some(dappAddress), functionCall, payments)) => + case Data.InvokeScript(InvokeScriptTransactionData(Some(dappAddress), functionCall, payments, `empty`)) => import com.wavesplatform.lang.v1.Serde import com.wavesplatform.lang.v1.compiler.Terms.FUNCTION_CALL @@ -490,7 +491,7 @@ object PBTransactions { chainId ) - case Data.UpdateAssetInfo(UpdateAssetInfoTransactionData(assetId, name, description)) => + case Data.UpdateAssetInfo(UpdateAssetInfoTransactionData(assetId, name, description, `empty`)) => vt.assets.UpdateAssetInfoTransaction( version.toByte, sender, diff --git a/node/src/main/scala/com/wavesplatform/protobuf/utils/PBUtils.scala b/node/src/main/scala/com/wavesplatform/protobuf/utils/PBUtils.scala index aaa5d50a69a..1b37027b2ed 100644 --- a/node/src/main/scala/com/wavesplatform/protobuf/utils/PBUtils.scala +++ b/node/src/main/scala/com/wavesplatform/protobuf/utils/PBUtils.scala @@ -1,6 +1,6 @@ package com.wavesplatform.protobuf.utils -import cats.implicits._ +import cats.syntax.applicativeError._ import com.google.protobuf.CodedOutputStream import com.wavesplatform.common.state.ByteStr import scalapb.{GeneratedMessage, GeneratedMessageCompanion} @@ -24,7 +24,7 @@ object PBUtils { outArray } - def decode[A <: GeneratedMessage with scalapb.Message[A]](msg: Array[Byte], cmp: GeneratedMessageCompanion[A]): Either[Throwable, A] = + def decode[A <: GeneratedMessage](msg: Array[Byte], cmp: GeneratedMessageCompanion[A]): Either[Throwable, A] = cmp .validate(msg) .toEither diff --git a/node/src/main/scala/com/wavesplatform/serialization/ScriptValuesJson.scala b/node/src/main/scala/com/wavesplatform/serialization/ScriptValuesJson.scala index 5949ec3128d..1378b3ffd74 100644 --- a/node/src/main/scala/com/wavesplatform/serialization/ScriptValuesJson.scala +++ b/node/src/main/scala/com/wavesplatform/serialization/ScriptValuesJson.scala @@ -5,7 +5,7 @@ import com.wavesplatform.lang.v1.compiler.Terms._ import play.api.libs.json.{JsObject, Json} object ScriptValuesJson { - def serializeValue(e: EVALUATED): JsObject = e match { + def serializeValue(e: EVALUATED): JsObject = (e: @unchecked) match { case CONST_LONG(num) => Json.obj("type" -> "Int", "value" -> num) case CONST_BYTESTR(bs) => Json.obj("type" -> "ByteVector", "value" -> bs.toString) case CONST_STRING(str) => Json.obj("type" -> "String", "value" -> str) diff --git a/node/src/main/scala/com/wavesplatform/settings/utils/ConfigSettingsValidator.scala b/node/src/main/scala/com/wavesplatform/settings/utils/ConfigSettingsValidator.scala index e21b88b18e4..ccb5225bf54 100644 --- a/node/src/main/scala/com/wavesplatform/settings/utils/ConfigSettingsValidator.scala +++ b/node/src/main/scala/com/wavesplatform/settings/utils/ConfigSettingsValidator.scala @@ -1,7 +1,9 @@ package com.wavesplatform.settings.utils import cats.data.{NonEmptyList, Validated, ValidatedNel} -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.foldable._ +import cats.syntax.traverse._ import com.typesafe.config.{Config, ConfigException} import com.wavesplatform.transaction.assets.exchange.AssetPair import net.ceedubs.ficus.Ficus._ diff --git a/node/src/main/scala/com/wavesplatform/state/Blockchain.scala b/node/src/main/scala/com/wavesplatform/state/Blockchain.scala index 3a886721c53..8d0fba04749 100644 --- a/node/src/main/scala/com/wavesplatform/state/Blockchain.scala +++ b/node/src/main/scala/com/wavesplatform/state/Blockchain.scala @@ -94,7 +94,7 @@ object Blockchain { def lastBlockIds(howMany: Int): Seq[ByteStr] = (blockchain.height to blockchain.height - howMany by -1).flatMap(blockId) def resolveAlias(aoa: AddressOrAlias): Either[ValidationError, Address] = - aoa match { + (aoa: @unchecked) match { case a: Address => Right(a) case a: Alias => blockchain.resolveAlias(a) } diff --git a/node/src/main/scala/com/wavesplatform/state/BlockchainUpdaterImpl.scala b/node/src/main/scala/com/wavesplatform/state/BlockchainUpdaterImpl.scala index 9e1d07cb068..b103c8f3a72 100644 --- a/node/src/main/scala/com/wavesplatform/state/BlockchainUpdaterImpl.scala +++ b/node/src/main/scala/com/wavesplatform/state/BlockchainUpdaterImpl.scala @@ -2,8 +2,10 @@ package com.wavesplatform.state import java.util.concurrent.locks.{Lock, ReentrantReadWriteLock} -import cats.implicits._ +import cats.instances.map._ import cats.kernel.Monoid +import cats.syntax.either._ +import cats.syntax.option._ import com.wavesplatform.account.{Address, Alias} import com.wavesplatform.api.BlockMeta import com.wavesplatform.block.Block.BlockId @@ -580,7 +582,7 @@ class BlockchainUpdaterImpl( innerVotes :+ ng.base.header.rewardVote else innerVotes } - case None => Seq() + case _ => Seq() } } diff --git a/node/src/main/scala/com/wavesplatform/state/Diff.scala b/node/src/main/scala/com/wavesplatform/state/Diff.scala index eca0ad78af2..3a071447681 100755 --- a/node/src/main/scala/com/wavesplatform/state/Diff.scala +++ b/node/src/main/scala/com/wavesplatform/state/Diff.scala @@ -1,10 +1,9 @@ package com.wavesplatform.state -import scala.collection.immutable.VectorMap - import cats.data.Ior -import cats.implicits._ +import cats.instances.map._ import cats.kernel.{Monoid, Semigroup} +import cats.syntax.semigroup._ import com.google.protobuf.ByteString import com.wavesplatform.account.{Address, AddressOrAlias, Alias, PublicKey} import com.wavesplatform.common.state.ByteStr @@ -12,8 +11,10 @@ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.script.Script import com.wavesplatform.state.diffs.FeeValidation import com.wavesplatform.state.reader.LeaseDetails -import com.wavesplatform.transaction.{Asset, Transaction} import com.wavesplatform.transaction.Asset.IssuedAsset +import com.wavesplatform.transaction.{Asset, Transaction} + +import scala.collection.immutable.VectorMap case class LeaseBalance(in: Long, out: Long) @@ -178,7 +179,7 @@ object Diff { assetScripts = older.assetScripts ++ newer.assetScripts, accountData = older.accountData.combine(newer.accountData), sponsorship = older.sponsorship.combine(newer.sponsorship), - scriptsRun = older.scriptsRun.combine(newer.scriptsRun), + scriptsRun = older.scriptsRun + newer.scriptsRun, scriptResults = older.scriptResults.combine(newer.scriptResults), scriptsComplexity = older.scriptsComplexity + newer.scriptsComplexity ) diff --git a/node/src/main/scala/com/wavesplatform/state/InvokeScriptResult.scala b/node/src/main/scala/com/wavesplatform/state/InvokeScriptResult.scala index dc087e5a447..6b07d4a4103 100644 --- a/node/src/main/scala/com/wavesplatform/state/InvokeScriptResult.scala +++ b/node/src/main/scala/com/wavesplatform/state/InvokeScriptResult.scala @@ -192,14 +192,9 @@ object InvokeScriptResult { val transfers = actions.collect { case t: lang.AssetTransfer => langTransferToPayment(t) } val leases = actions.collect { case l: lang.Lease => langLeaseToLease(l) } val leaseCancels = actions.collect { case l: lang.LeaseCancel => l } - val invokes = result.invokes.map { - case (dApp, fname, args, payments, r) => - Invocation( - langAddressToAddress(dApp), - Call(fname, args), - (payments.map { - case CaseObj(t, fields) => - (fields("assetId"), fields("amount")) match { + val invokes = result.invokes.map { + case (dApp, fname, args, payments, r) => Invocation(langAddressToAddress(dApp), Call(fname, args), (payments.map { case CaseObj(t, fields) => + ((fields("assetId"), fields("amount")): @unchecked) match { case (CONST_BYTESTR(b), CONST_LONG(a)) => InvokeScriptResult.AttachedPayment(IssuedAsset(b), a) case (_, CONST_LONG(a)) => InvokeScriptResult.AttachedPayment(Waves, a) } diff --git a/node/src/main/scala/com/wavesplatform/state/Portfolio.scala b/node/src/main/scala/com/wavesplatform/state/Portfolio.scala index 990539d76d4..e7e62c8da04 100644 --- a/node/src/main/scala/com/wavesplatform/state/Portfolio.scala +++ b/node/src/main/scala/com/wavesplatform/state/Portfolio.scala @@ -1,7 +1,8 @@ package com.wavesplatform.state -import cats._ -import cats.kernel.instances.map._ +import cats.Monoid +import cats.instances.map._ +import cats.kernel.CommutativeSemigroup import com.wavesplatform.state.diffs.BlockDiffer.Fraction import com.wavesplatform.transaction.Asset import com.wavesplatform.transaction.Asset._ @@ -32,7 +33,7 @@ object Portfolio { val empty: Portfolio = Portfolio() - implicit val longSemigroup: Semigroup[Long] = (x: Long, y: Long) => safeSum(x, y) + implicit val longSemigroup: CommutativeSemigroup[Long] = (x: Long, y: Long) => safeSum(x, y) implicit val monoid: Monoid[Portfolio] = new Monoid[Portfolio] { override val empty: Portfolio = Portfolio.empty diff --git a/node/src/main/scala/com/wavesplatform/state/appender/BlockAppender.scala b/node/src/main/scala/com/wavesplatform/state/appender/BlockAppender.scala index 710ae4ed0b0..67bd3fe556b 100644 --- a/node/src/main/scala/com/wavesplatform/state/appender/BlockAppender.scala +++ b/node/src/main/scala/com/wavesplatform/state/appender/BlockAppender.scala @@ -21,7 +21,6 @@ import monix.eval.Task import monix.execution.Scheduler import scala.util.Right -import scala.util.control.NonFatal object BlockAppender extends ScorexLogging { def apply( @@ -88,9 +87,7 @@ object BlockAppender extends ScorexLogging { } handle - .onErrorHandle { - case NonFatal(e) => log.warn("Error happened after block appending", e) - } + .onErrorHandle(e => log.warn("Error happened after block appending", e)) } //noinspection TypeAnnotation,ScalaStyle diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/BlockDiffer.scala b/node/src/main/scala/com/wavesplatform/state/diffs/BlockDiffer.scala index e9efd49d2c3..e64cf1887a0 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/BlockDiffer.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/BlockDiffer.scala @@ -1,8 +1,8 @@ package com.wavesplatform.state.diffs -import cats.implicits._ import cats.kernel.Monoid import cats.syntax.either.catsSyntaxEitherId +import cats.syntax.semigroup._ import com.wavesplatform.block.{Block, MicroBlock} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.features.BlockchainFeatures diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/CommonValidation.scala b/node/src/main/scala/com/wavesplatform/state/diffs/CommonValidation.scala index f9ac73b227c..8fe1f55c464 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/CommonValidation.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/CommonValidation.scala @@ -145,7 +145,7 @@ object CommonValidation { case V5 => v5Activation } - def scriptTypeActivation(sc: Script): Either[ActivationError, T] = sc match { + def scriptTypeActivation(sc: Script): Either[ActivationError, T] = (sc: @unchecked) match { case _: ExprScript => Right(tx) case _: ContractScript.ContractScriptImpl => v3Activation } diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/DiffsCommon.scala b/node/src/main/scala/com/wavesplatform/state/diffs/DiffsCommon.scala index d2660146839..5d031060ad7 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/DiffsCommon.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/DiffsCommon.scala @@ -1,6 +1,12 @@ package com.wavesplatform.state.diffs -import cats.implicits._ +import cats.instances.map._ +import cats.instances.option._ +import cats.syntax.apply._ +import cats.syntax.either._ +import cats.syntax.ior._ +import cats.syntax.semigroup._ +import cats.syntax.traverse._ import com.wavesplatform.account.{Address, AddressOrAlias, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.features.BlockchainFeatures @@ -11,8 +17,8 @@ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.lang.v1.traits.domain._ -import com.wavesplatform.state.{AssetVolumeInfo, Blockchain, Diff, LeaseBalance, Portfolio, SponsorshipValue} import com.wavesplatform.state.reader.LeaseDetails +import com.wavesplatform.state.{AssetVolumeInfo, Blockchain, Diff, LeaseBalance, Portfolio, SponsorshipValue} import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.ProvenTransaction import com.wavesplatform.transaction.TxValidationError.GenericError diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiff.scala b/node/src/main/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiff.scala index 862b4ec6b22..9f1c85319d6 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiff.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiff.scala @@ -1,7 +1,8 @@ package com.wavesplatform.state.diffs -import cats._ -import cats.implicits._ +import cats.instances.map._ +import cats.kernel.Monoid +import cats.syntax.either._ import com.wavesplatform.account.Address import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.ValidationError 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 46ff2214f1b..d8f31baa6f1 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/FeeValidation.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/FeeValidation.scala @@ -1,7 +1,7 @@ package com.wavesplatform.state.diffs import cats.data.Chain -import cats.implicits._ +import cats.syntax.foldable._ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.ValidationError import com.wavesplatform.settings.Constants diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/MassTransferTransactionDiff.scala b/node/src/main/scala/com/wavesplatform/state/diffs/MassTransferTransactionDiff.scala index fb4e8c7f68a..dce6fd9c6f1 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/MassTransferTransactionDiff.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/MassTransferTransactionDiff.scala @@ -1,6 +1,9 @@ package com.wavesplatform.state.diffs -import cats.implicits._ +import cats.instances.list._ +import cats.instances.map._ +import cats.syntax.semigroup._ +import cats.syntax.traverse._ import com.wavesplatform.account.Address import com.wavesplatform.lang.ValidationError import com.wavesplatform.state._ diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/PaymentTransactionDiff.scala b/node/src/main/scala/com/wavesplatform/state/diffs/PaymentTransactionDiff.scala index 2ca160404e2..cc071abf0ed 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/PaymentTransactionDiff.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/PaymentTransactionDiff.scala @@ -1,6 +1,7 @@ package com.wavesplatform.state.diffs -import cats.implicits._ +import cats.instances.map._ +import cats.syntax.semigroup._ import com.wavesplatform.account.Address import com.wavesplatform.lang.ValidationError import com.wavesplatform.state.{Blockchain, Diff, LeaseBalance, Portfolio} diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiff.scala b/node/src/main/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiff.scala index 594386ae152..3f035b8cab0 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiff.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiff.scala @@ -1,8 +1,10 @@ package com.wavesplatform.state.diffs -import cats.implicits._ -import com.wavesplatform.features.EstimatorProvider._ +import cats.instances.list._ +import cats.syntax.either._ +import cats.syntax.traverse._ import com.wavesplatform.features.ComplexityCheckPolicyProvider._ +import com.wavesplatform.features.EstimatorProvider._ import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.directives.values.StdLibVersion diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/TransferTransactionDiff.scala b/node/src/main/scala/com/wavesplatform/state/diffs/TransferTransactionDiff.scala index 8073b155d06..07b791326be 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/TransferTransactionDiff.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/TransferTransactionDiff.scala @@ -1,6 +1,7 @@ package com.wavesplatform.state.diffs -import cats.implicits._ +import cats.instances.map._ +import cats.syntax.semigroup._ import com.wavesplatform.account.Address import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.ValidationError diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/invoke/CachedDAppCTX.scala b/node/src/main/scala/com/wavesplatform/state/diffs/invoke/CachedDAppCTX.scala index fb65e9181e5..8b1b80490ff 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/invoke/CachedDAppCTX.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/invoke/CachedDAppCTX.scala @@ -1,6 +1,6 @@ package com.wavesplatform.state.diffs.invoke -import cats.implicits.catsSyntaxSemigroup +import cats.syntax.semigroup._ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.Global diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeDiffsCommon.scala b/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeDiffsCommon.scala index a85bb2e23ca..40dc56626f7 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeDiffsCommon.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeDiffsCommon.scala @@ -1,8 +1,8 @@ package com.wavesplatform.state.diffs.invoke -import scala.util.{Failure, Right, Success, Try} - -import cats.implicits._ +import cats.instances.map._ +import cats.syntax.either._ +import cats.syntax.semigroup._ import com.google.common.base.Throwables import com.google.protobuf.ByteString import com.wavesplatform.account.{Address, AddressOrAlias, PublicKey} @@ -19,26 +19,28 @@ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.ContractLimits import com.wavesplatform.lang.v1.compiler.Terms.{FUNCTION_CALL, _} import com.wavesplatform.lang.v1.traits.Environment -import com.wavesplatform.lang.v1.traits.domain.{AssetTransfer, _} import com.wavesplatform.lang.v1.traits.domain.Tx.{BurnPseudoTx, ReissuePseudoTx, ScriptTransfer, SponsorFeePseudoTx} +import com.wavesplatform.lang.v1.traits.domain.{AssetTransfer, _} import com.wavesplatform.settings.Constants import com.wavesplatform.state._ import com.wavesplatform.state.diffs.DiffsCommon import com.wavesplatform.state.diffs.FeeValidation._ import com.wavesplatform.state.reader.CompositeBlockchain -import com.wavesplatform.transaction.{Asset, AssetIdLength} import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError._ import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart._ import com.wavesplatform.transaction.smart.script.ScriptRunner import com.wavesplatform.transaction.smart.script.ScriptRunner.TxOrd -import com.wavesplatform.transaction.smart.script.trace.{AssetVerifierTrace, TracedResult} import com.wavesplatform.transaction.smart.script.trace.AssetVerifierTrace.AssetContext +import com.wavesplatform.transaction.smart.script.trace.{AssetVerifierTrace, TracedResult} import com.wavesplatform.transaction.validation.impl.{LeaseCancelTxValidator, LeaseTxValidator, SponsorFeeTxValidator} +import com.wavesplatform.transaction.{Asset, AssetIdLength} import com.wavesplatform.utils._ import shapeless.Coproduct +import scala.util.{Failure, Right, Success, Try} + object InvokeDiffsCommon { def txFeeDiff(blockchain: Blockchain, tx: InvokeScriptTransaction): Either[GenericError, (Long, Map[Address, Portfolio])] = { val attachedFee = tx.fee diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeScriptDiff.scala b/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeScriptDiff.scala index a7333b31a15..665ace3b236 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeScriptDiff.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeScriptDiff.scala @@ -1,7 +1,10 @@ package com.wavesplatform.state.diffs.invoke import cats.Id -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.either._ +import cats.syntax.semigroup._ +import cats.syntax.traverseFilter._ import com.wavesplatform.account._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.features.EstimatorProvider.EstimatorBlockchainExt diff --git a/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeScriptTransactionDiff.scala b/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeScriptTransactionDiff.scala index 0f19be8980c..547d532363e 100644 --- a/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeScriptTransactionDiff.scala +++ b/node/src/main/scala/com/wavesplatform/state/diffs/invoke/InvokeScriptTransactionDiff.scala @@ -1,9 +1,8 @@ package com.wavesplatform.state.diffs.invoke -import scala.util.Right - import cats.Id -import cats.implicits._ +import cats.syntax.either._ +import cats.syntax.semigroup._ import com.wavesplatform.account._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 @@ -22,18 +21,20 @@ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.lang.v1.evaluator._ import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.traits.domain._ -import com.wavesplatform.metrics.{TxProcessingStats => Stats} import com.wavesplatform.metrics.TxProcessingStats.TxTimerExt +import com.wavesplatform.metrics.{TxProcessingStats => Stats} import com.wavesplatform.state._ import com.wavesplatform.state.reader.CompositeBlockchain import com.wavesplatform.transaction.Transaction import com.wavesplatform.transaction.TxValidationError._ -import com.wavesplatform.transaction.smart.{DApp => DAppTarget, _} import com.wavesplatform.transaction.smart.script.ScriptRunner.TxOrd import com.wavesplatform.transaction.smart.script.trace.{InvokeScriptTrace, TracedResult} +import com.wavesplatform.transaction.smart.{DApp => DAppTarget, _} import monix.eval.Coeval import shapeless.Coproduct +import scala.util.Right + object InvokeScriptTransactionDiff { private[this] def allIssues(r: InvokeScriptResult): Seq[Issue] = { diff --git a/node/src/main/scala/com/wavesplatform/state/reader/CompositeBlockchain.scala b/node/src/main/scala/com/wavesplatform/state/reader/CompositeBlockchain.scala index f4a2d64d884..02669bb914d 100644 --- a/node/src/main/scala/com/wavesplatform/state/reader/CompositeBlockchain.scala +++ b/node/src/main/scala/com/wavesplatform/state/reader/CompositeBlockchain.scala @@ -1,20 +1,21 @@ package com.wavesplatform.state.reader import cats.data.Ior -import cats.implicits._ +import cats.syntax.option._ +import cats.syntax.semigroup._ import com.google.protobuf.ByteString import com.wavesplatform.account.{Address, Alias} -import com.wavesplatform.block.{Block, SignedBlockHeader} import com.wavesplatform.block.Block.BlockId +import com.wavesplatform.block.{Block, SignedBlockHeader} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.settings.BlockchainSettings import com.wavesplatform.state._ -import com.wavesplatform.transaction.{Asset, Transaction} import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError.{AliasDoesNotExist, AliasIsDisabled} import com.wavesplatform.transaction.assets.UpdateAssetInfoTransaction import com.wavesplatform.transaction.transfer.TransferTransaction +import com.wavesplatform.transaction.{Asset, Transaction} final class CompositeBlockchain private ( inner: Blockchain, diff --git a/node/src/main/scala/com/wavesplatform/transaction/TxValidationError.scala b/node/src/main/scala/com/wavesplatform/transaction/TxValidationError.scala index a6f94170dd8..fcd665d7f50 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/TxValidationError.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/TxValidationError.scala @@ -135,10 +135,10 @@ object TxValidationError { def isAssetScript: Boolean = assetId.isDefined private val target: String = assetId.fold("Account")(_ => "Asset") override def toString: String = - if (error.startsWith("ScriptExecutionError")) + if (String.valueOf(error).startsWith("ScriptExecutionError")) error else - s"ScriptExecutionError(error = $error, type = $target, log =${logToString(log)})" + s"ScriptExecutionError(error = $error, type = $target, log = ${logToString(log)})" } object ScriptExecutionError { diff --git a/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/CreateAliasTxSerializer.scala b/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/CreateAliasTxSerializer.scala index 8711a4d3c11..3823263d070 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/CreateAliasTxSerializer.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/CreateAliasTxSerializer.scala @@ -40,7 +40,7 @@ object CreateAliasTxSerializer { def parseBytes(bytes: Array[Byte]): Try[CreateAliasTransaction] = Try { require(bytes.length > 3, "buffer underflow while parsing transaction") - bytes.take(3) match { + (bytes.take(3): @unchecked) match { case Array(CreateAliasTransaction.typeId, _, _) => val buf = ByteBuffer.wrap(bytes, 1, bytes.length - 1) val sender = buf.getPublicKey diff --git a/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/OrderSerializer.scala b/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/OrderSerializer.scala index e68fef47f19..4680677e122 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/OrderSerializer.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/OrderSerializer.scala @@ -86,7 +86,7 @@ object OrderSerializer { def toBytes(ord: Order): Array[Byte] = { import ord._ - version match { + (version: @unchecked) match { case Order.V1 => Bytes.concat(this.bodyBytes(ord), proofs.toSignature.arr) case Order.V2 | Order.V3 => Bytes.concat(this.bodyBytes(ord), proofs.bytes()) } diff --git a/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/PBTransactionSerializer.scala b/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/PBTransactionSerializer.scala index d5c9fe5979a..edad1afeb39 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/PBTransactionSerializer.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/serialization/impl/PBTransactionSerializer.scala @@ -1,6 +1,6 @@ package com.wavesplatform.transaction.serialization.impl -import cats.implicits._ +import cats.syntax.applicativeError._ import com.wavesplatform.protobuf.transaction.{PBTransactions, SignedTransaction => PBSignedTransaction} import com.wavesplatform.protobuf.utils.PBUtils import com.wavesplatform.transaction.{PBParsingError, Transaction} diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/AttachedPaymentExtractor.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/AttachedPaymentExtractor.scala index cb12e3ba5d5..5ff78fde141 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/AttachedPaymentExtractor.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/AttachedPaymentExtractor.scala @@ -38,7 +38,7 @@ object AttachedPaymentExtractor { Right(AttachedPayments.Multi(tx.payments.map(p => (p.amount, p.assetId.compatId)))) private def scriptErrorMessage(apt: AttachedPaymentTarget, version: StdLibVersion): String = { - val name = apt match { + val name = (apt: @unchecked) match { case DApp => "DApp" case InvokerScript => "Invoker script" case AssetScript(id) => s"Attached asset script id=$id" diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/BlockchainContext.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/BlockchainContext.scala index 5a8d8568ac3..00976120c22 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/BlockchainContext.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/BlockchainContext.scala @@ -1,7 +1,9 @@ package com.wavesplatform.transaction.smart +import java.util + import cats.Id -import cats.implicits._ +import cats.syntax.semigroup._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.directives.DirectiveSet @@ -15,8 +17,6 @@ import com.wavesplatform.lang.{ExecutionError, Global} import com.wavesplatform.state._ import monix.eval.Coeval -import java.util - object BlockchainContext { type In = WavesEnvironment.In diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/RealTransactionWrapper.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/RealTransactionWrapper.scala index 5cf49f62f71..4b45582de8e 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/RealTransactionWrapper.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/RealTransactionWrapper.scala @@ -1,6 +1,6 @@ package com.wavesplatform.transaction.smart -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.account.{Address, AddressOrAlias, Alias} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ExecutionError @@ -56,7 +56,7 @@ object RealTransactionWrapper { matcherFeeAssetId = o.matcherFeeAssetId.compatId ) - implicit def aoaToRecipient(aoa: AddressOrAlias): Recipient = aoa match { + implicit def aoaToRecipient(aoa: AddressOrAlias): Recipient = (aoa: @unchecked) match { case a: Address => Recipient.Address(ByteStr(a.bytes)) case a: Alias => Recipient.Alias(a.name) } @@ -67,7 +67,7 @@ object RealTransactionWrapper { stdLibVersion: StdLibVersion, target: AttachedPaymentTarget ): Either[ExecutionError, Tx] = - tx match { + (tx: @unchecked) match { case g: GenesisTransaction => Tx.Genesis(header(g), g.amount, g.recipient).asRight case t: TransferTransaction => mapTransferTx(t).asRight case i: IssueTransaction => 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 46df45faf4e..8ff2de29dab 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/Verifier.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/Verifier.scala @@ -1,7 +1,8 @@ package com.wavesplatform.transaction.smart import cats.Id -import cats.implicits._ +import cats.syntax.either._ +import cats.syntax.functor._ import com.google.common.base.Throwables import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto @@ -39,7 +40,7 @@ object Verifier extends ScorexLogging { type ValidationResult[T] = Either[ValidationError, T] - def apply(blockchain: Blockchain, limitedExecution: Boolean = false)(tx: Transaction): TracedResult[ValidationError, Int] = tx match { + def apply(blockchain: Blockchain, limitedExecution: Boolean = false)(tx: Transaction): TracedResult[ValidationError, Int] = (tx: @unchecked) match { case _: GenesisTransaction => Right(0) case pt: ProvenTransaction => (pt, blockchain.accountScript(pt.sender.toAddress)) match { diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/WavesEnvironment.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/WavesEnvironment.scala index 954a60b02cf..1eff2117006 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/WavesEnvironment.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/WavesEnvironment.scala @@ -1,6 +1,7 @@ package com.wavesplatform.transaction.smart -import cats.implicits._ +import cats.syntax.either._ +import cats.syntax.semigroup._ import com.wavesplatform.account import com.wavesplatform.account.AddressOrAlias import com.wavesplatform.block.BlockHeader @@ -14,12 +15,11 @@ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.FunctionHeader.User import com.wavesplatform.lang.v1.compiler.Terms.{EVALUATED, FUNCTION_CALL} import com.wavesplatform.lang.v1.traits._ -import com.wavesplatform.lang.v1.traits.domain._ import com.wavesplatform.lang.v1.traits.domain.Recipient._ +import com.wavesplatform.lang.v1.traits.domain._ import com.wavesplatform.state._ import com.wavesplatform.state.diffs.invoke.{InvokeScript, InvokeScriptDiff} import com.wavesplatform.state.reader.CompositeBlockchain -import com.wavesplatform.transaction.{Asset, Transaction} import com.wavesplatform.transaction.Asset._ import com.wavesplatform.transaction.TxValidationError.{FailedTransactionError, GenericError} import com.wavesplatform.transaction.assets.exchange.Order @@ -27,6 +27,7 @@ import com.wavesplatform.transaction.serialization.impl.PBTransactionSerializer import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.trace.CoevalR.traced import com.wavesplatform.transaction.transfer.TransferTransaction +import com.wavesplatform.transaction.{Asset, Transaction} import monix.eval.Coeval import shapeless._ diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/package.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/package.scala index 3d5b0933a83..96440fc3ee0 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/package.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/package.scala @@ -1,6 +1,6 @@ package com.wavesplatform.transaction -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ExecutionError import com.wavesplatform.lang.directives.DirectiveSet diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/script/ScriptRunner.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/script/ScriptRunner.scala index a5eaa9c5ea1..76de7834736 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/script/ScriptRunner.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/script/ScriptRunner.scala @@ -1,7 +1,7 @@ package com.wavesplatform.transaction.smart.script import cats.Id -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.account.AddressScheme import com.wavesplatform.common.state.ByteStr import com.wavesplatform.features.BlockchainFeatures diff --git a/node/src/main/scala/com/wavesplatform/transaction/smart/script/trace/TracedResult.scala b/node/src/main/scala/com/wavesplatform/transaction/smart/script/trace/TracedResult.scala index 2511c410a74..529221ec1df 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/smart/script/trace/TracedResult.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/smart/script/trace/TracedResult.scala @@ -1,7 +1,11 @@ package com.wavesplatform.transaction.smart.script.trace -import cats.implicits._ +import cats.instances.either._ +import cats.instances.list._ import cats.kernel.Semigroup +import cats.syntax.either._ +import cats.syntax.semigroup._ +import cats.syntax.semigroupal._ import cats.{Applicative, Apply, Functor} import com.wavesplatform.api.http.ApiError import com.wavesplatform.transaction.Transaction @@ -62,16 +66,17 @@ object TracedResult { a.trace |+| b.trace ) - implicit def applicativeTracedResult[L]: Applicative[TracedResult[L, ?]] with Apply[TracedResult[L, ?]] with Functor[TracedResult[L, ?]] = new Applicative[TracedResult[L, ?]] { - def pure[A](v:A) = wrapValue[A, L](v) - def ap[A,B](fb: TracedResult[L, A=>B])(fa: TracedResult[L, A]) : TracedResult[L, B] = { - TracedResult(fa.resultE ap fb.resultE, fa.trace ++ fb.trace) + implicit def applicativeTracedResult[L]: Applicative[TracedResult[L, *]] with Apply[TracedResult[L, *]] with Functor[TracedResult[L, *]] = + new Applicative[TracedResult[L, *]] { + def pure[A](v: A) = wrapValue[A, L](v) + def ap[A, B](fb: TracedResult[L, A => B])(fa: TracedResult[L, A]): TracedResult[L, B] = { + TracedResult(fa.resultE ap fb.resultE, fa.trace ++ fb.trace) + } + override def product[A, B](fa: TracedResult[L, A], fb: TracedResult[L, B]): TracedResult[L, (A, B)] = { + TracedResult(fa.resultE product fb.resultE, fa.trace ++ fb.trace) + } + override def map[A, B](x: TracedResult[L, A])(f: A => B): TracedResult[L, B] = { + TracedResult[L, B](x.resultE map f, x.trace) + } } - override def product[A,B](fa: TracedResult[L, A], fb: TracedResult[L, B]) : TracedResult[L, (A,B)] = { - TracedResult(fa.resultE product fb.resultE, fa.trace ++ fb.trace) - } - override def map[A,B](x: TracedResult[L, A])(f: A=>B) : TracedResult[L, B] = { - TracedResult[L,B](x.resultE map f, x.trace) - } - } } 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 679dc548671..4ff5ed6babb 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/transfer/MassTransferTransaction.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/transfer/MassTransferTransaction.scala @@ -1,6 +1,7 @@ package com.wavesplatform.transaction.transfer -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.account._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto diff --git a/node/src/main/scala/com/wavesplatform/transaction/validation/impl/InvokeScriptTxValidator.scala b/node/src/main/scala/com/wavesplatform/transaction/validation/impl/InvokeScriptTxValidator.scala index aff53c25eb5..61bf1997a6d 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/validation/impl/InvokeScriptTxValidator.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/validation/impl/InvokeScriptTxValidator.scala @@ -2,7 +2,7 @@ package com.wavesplatform.transaction.validation.impl import cats.data.NonEmptyList import cats.data.Validated.{Invalid, Valid} -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.lang.v1.compiler.Terms.FUNCTION_CALL import com.wavesplatform.lang.v1.{ContractLimits, FunctionHeader} import com.wavesplatform.protobuf.transaction.PBTransactions diff --git a/node/src/main/scala/com/wavesplatform/transaction/validation/impl/LeaseCancelTxValidator.scala b/node/src/main/scala/com/wavesplatform/transaction/validation/impl/LeaseCancelTxValidator.scala index 019fb4a35f4..f44cfb8b45d 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/validation/impl/LeaseCancelTxValidator.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/validation/impl/LeaseCancelTxValidator.scala @@ -1,7 +1,7 @@ package com.wavesplatform.transaction.validation.impl import cats.data.ValidatedNel -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto import com.wavesplatform.lang.ValidationError diff --git a/node/src/main/scala/com/wavesplatform/transaction/validation/impl/LeaseTxValidator.scala b/node/src/main/scala/com/wavesplatform/transaction/validation/impl/LeaseTxValidator.scala index e8bd4349e40..ea93a486bb2 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/validation/impl/LeaseTxValidator.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/validation/impl/LeaseTxValidator.scala @@ -1,7 +1,7 @@ package com.wavesplatform.transaction.validation.impl import cats.data.ValidatedNel -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.lease.LeaseTransaction import com.wavesplatform.transaction.validation.TxValidator diff --git a/node/src/main/scala/com/wavesplatform/transaction/validation/impl/SponsorFeeTxValidator.scala b/node/src/main/scala/com/wavesplatform/transaction/validation/impl/SponsorFeeTxValidator.scala index a367acd8bf1..ab30cf068f9 100644 --- a/node/src/main/scala/com/wavesplatform/transaction/validation/impl/SponsorFeeTxValidator.scala +++ b/node/src/main/scala/com/wavesplatform/transaction/validation/impl/SponsorFeeTxValidator.scala @@ -1,6 +1,6 @@ package com.wavesplatform.transaction.validation.impl -import cats.implicits._ +import cats.syntax.either._ import com.wavesplatform.transaction.TxAmount import com.wavesplatform.transaction.TxValidationError.NegativeMinFee import com.wavesplatform.transaction.assets.SponsorFeeTransaction diff --git a/node/src/main/scala/com/wavesplatform/utils/package.scala b/node/src/main/scala/com/wavesplatform/utils/package.scala index 63f2b4cf8b1..c0e8e080ef4 100644 --- a/node/src/main/scala/com/wavesplatform/utils/package.scala +++ b/node/src/main/scala/com/wavesplatform/utils/package.scala @@ -83,7 +83,7 @@ package object utils extends ScorexLogging { implicit val evaluatedWrites: Writes[EVALUATED] = new Writes[EVALUATED] { import com.wavesplatform.api.http.ApiError - override def writes(o: EVALUATED): JsValue = o match { + override def writes(o: EVALUATED): JsValue = (o: @unchecked) match { case CONST_LONG(num) => Json.obj("type" -> "Int", "value" -> num) case CONST_BYTESTR(bs) => Json.obj("type" -> "ByteVector", "value" -> bs.toString) case CONST_STRING(str) => Json.obj("type" -> "String", "value" -> str) diff --git a/node/src/main/scala/com/wavesplatform/utx/UtxPriorityPool.scala b/node/src/main/scala/com/wavesplatform/utx/UtxPriorityPool.scala index 7813f394578..4f16d960d0b 100644 --- a/node/src/main/scala/com/wavesplatform/utx/UtxPriorityPool.scala +++ b/node/src/main/scala/com/wavesplatform/utx/UtxPriorityPool.scala @@ -97,7 +97,7 @@ final class UtxPriorityPool(base: Blockchain) extends ScorexLogging with Optimis def nextMicroBlockSize(limit: Int): Int = { @tailrec - def nextMicroBlockSizeRec(last: Int, diffs: Seq[Diff]): Int = diffs match { + def nextMicroBlockSizeRec(last: Int, diffs: Seq[Diff]): Int = (diffs: @unchecked) match { case Nil => last.max(limit) case diff +: _ if last + diff.transactions.size > limit => if (last == 0) diff.transactions.size // First micro diff --git a/node/src/test/scala/com/wavesplatform/BlockchainStubHelpers.scala b/node/src/test/scala/com/wavesplatform/BlockchainStubHelpers.scala index 919d79769bb..7f92076bdb1 100644 --- a/node/src/test/scala/com/wavesplatform/BlockchainStubHelpers.scala +++ b/node/src/test/scala/com/wavesplatform/BlockchainStubHelpers.scala @@ -8,7 +8,7 @@ import com.wavesplatform.settings.WavesSettings import com.wavesplatform.state.diffs.TransactionDiffer import com.wavesplatform.state.{Blockchain, LeaseBalance, NG, VolumeAndFee} import com.wavesplatform.transaction.Asset.Waves -import com.wavesplatform.transaction.{Transaction, TxHelpers} +import com.wavesplatform.transaction.TxHelpers import org.scalamock.MockFactoryBase import scala.concurrent.Future @@ -44,14 +44,7 @@ trait BlockchainStubHelpers { self: MockFactoryBase => blockchain } - def createTxPublisherStub(blockchain: Blockchain): TransactionPublisher = { - val publisher = stub[TransactionPublisher] - (publisher.validateAndBroadcast _).when(*, *).onCall { - case (transaction: Transaction, _) => - val differ = TransactionDiffer(blockchain.lastBlockTimestamp, System.currentTimeMillis())(blockchain, _) - val result = differ(transaction) - Future.successful(result.map(_ => true)) - } - publisher + def createTxPublisherStub(blockchain: Blockchain): TransactionPublisher = { (transaction, _) => + Future.successful(TransactionDiffer(blockchain.lastBlockTimestamp, System.currentTimeMillis())(blockchain, transaction).map(_ => true)) } } diff --git a/node/src/test/scala/com/wavesplatform/DeserializationTests.scala b/node/src/test/scala/com/wavesplatform/DeserializationTests.scala index b4f54bf9627..99ae357fd23 100644 --- a/node/src/test/scala/com/wavesplatform/DeserializationTests.scala +++ b/node/src/test/scala/com/wavesplatform/DeserializationTests.scala @@ -1,9 +1,9 @@ package com.wavesplatform import com.wavesplatform.serialization.Deser -import org.scalatest.{FreeSpec, Matchers} +import com.wavesplatform.test.FreeSpec -class DeserializationTests extends FreeSpec with Matchers { +class DeserializationTests extends FreeSpec { "serializeArray" - { "works with arrays < 32k" in { diff --git a/node/src/test/scala/com/wavesplatform/NoShrink.scala b/node/src/test/scala/com/wavesplatform/NoShrink.scala deleted file mode 100644 index b224ea4bd7a..00000000000 --- a/node/src/test/scala/com/wavesplatform/NoShrink.scala +++ /dev/null @@ -1,5 +0,0 @@ -package com.wavesplatform - -import org.scalacheck.ShrinkLowPriority - -trait NoShrink extends ShrinkLowPriority diff --git a/node/src/test/scala/com/wavesplatform/TransactionGen.scala b/node/src/test/scala/com/wavesplatform/TransactionGen.scala index 237f70234b0..cfd17a14e41 100644 --- a/node/src/test/scala/com/wavesplatform/TransactionGen.scala +++ b/node/src/test/scala/com/wavesplatform/TransactionGen.scala @@ -729,13 +729,13 @@ trait TransactionGenBase extends ScriptGen with TypedScriptGen with NTPTime { _: sellMatcherFeeAssetId: Asset = Waves, fixedMatcher: Option[KeyPair] = None ): Gen[ExchangeTransaction] = { - def mkBuyOrder(version: TxVersion): OrderConstructor = version match { + def mkBuyOrder(version: TxVersion): OrderConstructor = (version: @unchecked) match { case Order.V1 => Order.buy(Order.V1, _, _, _, _, _, _, _, _) case Order.V2 => Order.buy(Order.V2, _, _, _, _, _, _, _, _) case Order.V3 => Order.buy(Order.V3, _, _, _, _, _, _, _, _, buyMatcherFeeAssetId) } - def mkSellOrder(version: TxVersion): OrderConstructor = version match { + def mkSellOrder(version: TxVersion): OrderConstructor = (version: @unchecked) match { case Order.V1 => Order.sell(Order.V1, _, _, _, _, _, _, _, _) case Order.V2 => Order.sell(Order.V2, _, _, _, _, _, _, _, _) case Order.V3 => Order.sell(Order.V3, _, _, _, _, _, _, _, _, sellMatcherFeeAssetId) diff --git a/node/src/test/scala/com/wavesplatform/account/AccountOrAliasSpecification.scala b/node/src/test/scala/com/wavesplatform/account/AccountOrAliasSpecification.scala index 1e723f26885..850b95460c4 100644 --- a/node/src/test/scala/com/wavesplatform/account/AccountOrAliasSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/account/AccountOrAliasSpecification.scala @@ -1,11 +1,9 @@ package com.wavesplatform.account -import com.wavesplatform.TransactionGen import com.wavesplatform.common.utils.EitherExt2 -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class AccountOrAliasSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class AccountOrAliasSpecification extends PropSpec { property("Account serialization round trip") { forAll(accountGen) { account => diff --git a/node/src/test/scala/com/wavesplatform/account/AccountOrAliasTests.scala b/node/src/test/scala/com/wavesplatform/account/AccountOrAliasTests.scala index 3ff5d40cb54..4c0949467d1 100644 --- a/node/src/test/scala/com/wavesplatform/account/AccountOrAliasTests.scala +++ b/node/src/test/scala/com/wavesplatform/account/AccountOrAliasTests.scala @@ -1,11 +1,10 @@ package com.wavesplatform.account -import com.wavesplatform.EitherMatchers import com.wavesplatform.common.utils.EitherExt2 -import org.scalatest.{Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec +import org.scalatest.Inside -class AccountOrAliasTests extends PropSpec with PropertyChecks with Matchers with EitherMatchers with Inside { +class AccountOrAliasTests extends PropSpec with Inside { property("Account should get parsed correctly") { AddressOrAlias.fromString("3My3KZgFQ3CrVHgz6vGRt8687sH4oAA1qp8").explicitGet() shouldBe an[Address] diff --git a/node/src/test/scala/com/wavesplatform/account/AccountSpecification.scala b/node/src/test/scala/com/wavesplatform/account/AccountSpecification.scala index 05ce5d313b2..8ff6748da8d 100644 --- a/node/src/test/scala/com/wavesplatform/account/AccountSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/account/AccountSpecification.scala @@ -1,11 +1,10 @@ package com.wavesplatform.account import com.wavesplatform.common.utils.Base58 -import com.wavesplatform.{NoShrink, crypto} -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec -class AccountSpecification extends PropSpec with PropertyChecks with Matchers with NoShrink { +class AccountSpecification extends PropSpec { property("Account.isValidAddress should return false for another address version") { forAll { (data: Array[Byte], AddressVersion2: Byte) => diff --git a/node/src/test/scala/com/wavesplatform/account/AliasSpecification.scala b/node/src/test/scala/com/wavesplatform/account/AliasSpecification.scala index c6cc6cbbe07..734f5ab6884 100644 --- a/node/src/test/scala/com/wavesplatform/account/AliasSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/account/AliasSpecification.scala @@ -1,10 +1,8 @@ package com.wavesplatform.account -import com.wavesplatform.{EitherMatchers, NoShrink, TransactionGen} -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class AliasSpecification extends PropSpec with PropertyChecks with Matchers with EitherMatchers with TransactionGen with NoShrink with EitherValues { +class AliasSpecification extends PropSpec { property("Correct alias should be valid") { forAll(validAliasStringGen) { s => diff --git a/node/src/test/scala/com/wavesplatform/api/common/AddressTransactionsSpec.scala b/node/src/test/scala/com/wavesplatform/api/common/AddressTransactionsSpec.scala index f83af07c083..a0b67ecef28 100644 --- a/node/src/test/scala/com/wavesplatform/api/common/AddressTransactionsSpec.scala +++ b/node/src/test/scala/com/wavesplatform/api/common/AddressTransactionsSpec.scala @@ -1,9 +1,8 @@ package com.wavesplatform.api.common -import com.wavesplatform.WithDB -import org.scalatest.FreeSpec +import com.wavesplatform.test.FreeSpec -class AddressTransactionsSpec extends FreeSpec with WithDB { +class AddressTransactionsSpec extends FreeSpec { "addressTransactions" - { "without pagination" in pending diff --git a/node/src/test/scala/com/wavesplatform/api/common/CommonAccountApiSpec.scala b/node/src/test/scala/com/wavesplatform/api/common/CommonAccountApiSpec.scala index 55e23369f2f..c3475d5eee4 100644 --- a/node/src/test/scala/com/wavesplatform/api/common/CommonAccountApiSpec.scala +++ b/node/src/test/scala/com/wavesplatform/api/common/CommonAccountApiSpec.scala @@ -1,6 +1,5 @@ package com.wavesplatform.api.common -import com.wavesplatform.{history, BlocksTransactionsHelpers, TransactionGen} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils._ import com.wavesplatform.db.WithDomain @@ -9,19 +8,16 @@ 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.{diffs, DataEntry, Diff, EmptyDataEntry, StringDataEntry} +import com.wavesplatform.state.{DataEntry, Diff, EmptyDataEntry, StringDataEntry, diffs} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction, TxHelpers} +import com.wavesplatform.{BlocksTransactionsHelpers, history} import monix.execution.Scheduler.Implicits.global -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks class CommonAccountApiSpec extends FreeSpec - with Matchers with WithDomain - with TransactionGen - with BlocksTransactionsHelpers - with ScalaCheckDrivenPropertyChecks { + with BlocksTransactionsHelpers { "Data stream" - { "handles non-existent address" in { @@ -55,7 +51,7 @@ class CommonAccountApiSpec ) ) ) { d => - val commonAccountsApi = CommonAccountsApi(d.blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), d.db, d.blockchainUpdater) + val commonAccountsApi = CommonAccountsApi(() => d.blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), d.db, d.blockchainUpdater) def dataList(): Set[DataEntry[_]] = commonAccountsApi.dataStream(acc.toAddress, None).toListL.runSyncUnsafe().toSet d.appendBlock(block1) @@ -93,7 +89,7 @@ class CommonAccountApiSpec forAll(preconditions) { case (acc, block1, mb1, block2, mb2) => withDomain(domainSettingsWithFS(TestFunctionalitySettings.withFeatures(BlockchainFeatures.NG, BlockchainFeatures.DataTransaction))) { d => - val commonAccountsApi = CommonAccountsApi(d.blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), d.db, d.blockchainUpdater) + val commonAccountsApi = CommonAccountsApi(() => d.blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), d.db, d.blockchainUpdater) def dataList(): Set[DataEntry[_]] = commonAccountsApi.dataStream(acc.toAddress, Some("test_.*")).toListL.runSyncUnsafe().toSet d.appendBlock(block1) @@ -168,7 +164,7 @@ class CommonAccountApiSpec invoke ) - val api = CommonAccountsApi(Diff.empty, d.db, d.blockchain) + val api = CommonAccountsApi(() => Diff.empty, d.db, d.blockchain) val leaseId = Lease.calculateId( Lease( Recipient.Address(ByteStr(TxHelpers.defaultAddress.bytes)), diff --git a/node/src/test/scala/com/wavesplatform/api/common/CommonTransactionsApiSpec.scala b/node/src/test/scala/com/wavesplatform/api/common/CommonTransactionsApiSpec.scala index 9e1687bb4b3..3ecb0b1ca34 100644 --- a/node/src/test/scala/com/wavesplatform/api/common/CommonTransactionsApiSpec.scala +++ b/node/src/test/scala/com/wavesplatform/api/common/CommonTransactionsApiSpec.scala @@ -1,6 +1,7 @@ package com.wavesplatform.api.common -import org.scalatest.FreeSpec +import com.wavesplatform.test.FreeSpec + class CommonTransactionsApiSpec extends FreeSpec { "Merkle Tree" - { diff --git a/node/src/test/scala/com/wavesplatform/api/http/CustomJsonMarshallerSpec.scala b/node/src/test/scala/com/wavesplatform/api/http/CustomJsonMarshallerSpec.scala index e60cf1e47e2..db524051d5c 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/CustomJsonMarshallerSpec.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/CustomJsonMarshallerSpec.scala @@ -1,32 +1,31 @@ package com.wavesplatform.api.http -import scala.reflect.ClassTag - import akka.http.scaladsl.model.HttpRequest import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.model.headers.Accept import akka.http.scaladsl.server.Route import akka.http.scaladsl.testkit.ScalatestRouteTest -import com.wavesplatform.{NoShrink, NTPTime, TestWallet, TransactionGen} -import com.wavesplatform.api.common.{CommonAccountsApi, CommonAssetsApi, CommonTransactionsApi} import com.wavesplatform.api.common.CommonTransactionsApi.TransactionMeta +import com.wavesplatform.api.common.{CommonAccountsApi, CommonAssetsApi, CommonTransactionsApi} import com.wavesplatform.api.http.assets.AssetsApiRoute import com.wavesplatform.common.state.ByteStr import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.DefaultBlockchainSettings import com.wavesplatform.http.{ApiErrorMatchers, RestAPISettingsHelper} import com.wavesplatform.network.TransactionPublisher -import com.wavesplatform.state.{Blockchain, Height} import com.wavesplatform.state.reader.LeaseDetails +import com.wavesplatform.state.{Blockchain, Height} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.utx.UtxPool +import com.wavesplatform.{NTPTime, TestWallet} import org.scalactic.source.Position import org.scalamock.scalatest.PathMockFactory -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import play.api.libs.json._ +import scala.reflect.ClassTag + class CustomJsonMarshallerSpec extends PropSpec with RestAPISettingsHelper @@ -34,11 +33,7 @@ class CustomJsonMarshallerSpec with TestWallet with NTPTime with ScalatestRouteTest - with Matchers - with ApiErrorMatchers - with NoShrink - with ScalaCheckPropertyChecks - with TransactionGen { + with ApiErrorMatchers { private val blockchain = mock[Blockchain] private val utx = mock[UtxPool] private val publisher = mock[TransactionPublisher] diff --git a/node/src/test/scala/com/wavesplatform/api/http/TraceResultJsonTest.scala b/node/src/test/scala/com/wavesplatform/api/http/TraceResultJsonTest.scala index 20b16dea77a..cb9276cb2c1 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/TraceResultJsonTest.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/TraceResultJsonTest.scala @@ -9,14 +9,14 @@ import com.wavesplatform.lang.v1.compiler.Terms.{CONST_LONG, CONST_STRING, FUNCT import com.wavesplatform.lang.v1.evaluator.ScriptResultV3 import com.wavesplatform.lang.v1.traits.domain.DataItem.Lng import com.wavesplatform.lang.v1.traits.domain.{AssetTransfer, Recipient} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.script.trace.{InvokeScriptTrace, TracedResult} import com.wavesplatform.transaction.{Proofs, TxValidationError} -import org.scalatest.{Matchers, PropSpec} import play.api.libs.json.Json -class TraceResultJsonTest extends PropSpec with Matchers { +class TraceResultJsonTest extends PropSpec { private val tx = ( for { publicKey <- PublicKey.fromBase58String("9utotH1484Hb1WdAHuAKLjuGAmocPZg7jZDtnc35MuqT") @@ -44,7 +44,7 @@ class TraceResultJsonTest extends PropSpec with Matchers { val recipient = Recipient.Address(ByteStr(tx.dAppAddressOrAlias.bytes)) val trace = List( InvokeScriptTrace( - tx.id.value(), + tx.id(), tx.dAppAddressOrAlias, tx.funcCall, Right( @@ -221,7 +221,7 @@ class TraceResultJsonTest extends PropSpec with Matchers { val trace = List( InvokeScriptTrace( - tx.id.value(), + tx.id(), tx.dAppAddressOrAlias, tx.funcCall, Left(TxValidationError.ScriptExecutionError(reason, vars, None)), diff --git a/node/src/test/scala/com/wavesplatform/api/http/requests/RequestsSpec.scala b/node/src/test/scala/com/wavesplatform/api/http/requests/RequestsSpec.scala index e3226c1d47e..481dabafe1b 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/requests/RequestsSpec.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/requests/RequestsSpec.scala @@ -2,14 +2,13 @@ package com.wavesplatform.api.http.requests import com.wavesplatform.account.KeyPair import com.wavesplatform.common.utils.EitherExt2 +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{FreeSpec, Matchers, OptionValues} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import org.scalatest.OptionValues import play.api.libs.json._ -class RequestsSpec extends FreeSpec with Matchers with OptionValues with ScalaCheckPropertyChecks with TransactionGen with NoShrink { +class RequestsSpec extends FreeSpec with OptionValues { private def transferRequestGen(version: Int): Gen[(KeyPair, JsObject)] = (for { sender <- accountGen diff --git a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedBurnV2Request.scala b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedBurnV2Request.scala index 0ea59605776..fd750a5c173 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedBurnV2Request.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedBurnV2Request.scala @@ -1,6 +1,6 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +import cats.syntax.traverse._ import com.wavesplatform.account.PublicKey import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.Proofs diff --git a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedCreateAliasV2Request.scala b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedCreateAliasV2Request.scala index 90d529cb5c3..c4286d80f1d 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedCreateAliasV2Request.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedCreateAliasV2Request.scala @@ -1,6 +1,7 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.account.PublicKey import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.{CreateAliasTransaction, Proofs, Transaction} diff --git a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedExchangeRequestV2.scala b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedExchangeRequestV2.scala index af3c1c15b74..7a3f3bc94bf 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedExchangeRequestV2.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedExchangeRequestV2.scala @@ -1,6 +1,7 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.assets.exchange.{ExchangeTransaction, Order} diff --git a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedIssueV2Request.scala b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedIssueV2Request.scala index 00a069eee58..96c4a09aefc 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedIssueV2Request.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedIssueV2Request.scala @@ -1,6 +1,7 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.account.PublicKey import com.wavesplatform.lang.ValidationError import com.wavesplatform.lang.script.Script diff --git a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedLeaseCancelV2Request.scala b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedLeaseCancelV2Request.scala index ccb44846e3f..4fe440dbfdd 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedLeaseCancelV2Request.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedLeaseCancelV2Request.scala @@ -1,6 +1,7 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.account.PublicKey import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.Proofs diff --git a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedLeaseV2Request.scala b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedLeaseV2Request.scala index e81572b08b3..37cb891b665 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedLeaseV2Request.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedLeaseV2Request.scala @@ -1,6 +1,7 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.account.{AddressOrAlias, PublicKey} import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.Proofs diff --git a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedReissueV2Request.scala b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedReissueV2Request.scala index de0d396a3c7..0a193aaaeb5 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedReissueV2Request.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedReissueV2Request.scala @@ -1,7 +1,8 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ -import com.wavesplatform.account.{AddressScheme, PublicKey} +import cats.instances.list._ +import cats.syntax.traverse._ +import com.wavesplatform.account.PublicKey import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.Proofs import com.wavesplatform.transaction.assets.ReissueTransaction @@ -20,7 +21,6 @@ case class SignedReissueV2Request( def toTx: Either[ValidationError, ReissueTransaction] = for { _sender <- PublicKey.fromBase58String(senderPublicKey) - chainId = AddressScheme.current.chainId _proofBytes <- proofs.traverse(s => parseBase58(s, "invalid proof", Proofs.MaxProofStringSize)) _proofs <- Proofs.create(_proofBytes) _assetId <- parseBase58ToIssuedAsset(assetId) diff --git a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedTransferV2Request.scala b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedTransferV2Request.scala index 1fd46dcb32d..141c7980613 100644 --- a/node/src/test/scala/com/wavesplatform/api/http/requests/SignedTransferV2Request.scala +++ b/node/src/test/scala/com/wavesplatform/api/http/requests/SignedTransferV2Request.scala @@ -1,6 +1,7 @@ package com.wavesplatform.api.http.requests -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ import com.wavesplatform.account.{AddressOrAlias, PublicKey} import com.wavesplatform.lang.ValidationError import com.wavesplatform.transaction.Proofs @@ -40,12 +41,12 @@ case class SignedTransferV2Request( def toTx: Either[ValidationError, TransferTransaction] = for { _sender <- PublicKey.fromBase58String(senderPublicKey) - _assetId <- parseBase58ToAsset(assetId.filter(_.length > 0), "invalid.assetId") - _feeAssetId <- parseBase58ToAsset(feeAssetId.filter(_.length > 0), "invalid.feeAssetId") + _assetId <- parseBase58ToAsset(assetId.filter(_.nonEmpty), "invalid.assetId") + _feeAssetId <- parseBase58ToAsset(feeAssetId.filter(_.nonEmpty), "invalid.feeAssetId") _proofBytes <- proofs.traverse(s => parseBase58(s, "invalid proof", Proofs.MaxProofStringSize)) _proofs <- Proofs.create(_proofBytes) _recipient <- AddressOrAlias.fromString(recipient) - _attachment <- parseBase58(attachment.filter(_.length > 0), "invalid.attachment", TransferTransaction.MaxAttachmentStringSize) + _attachment <- parseBase58(attachment.filter(_.nonEmpty), "invalid.attachment", TransferTransaction.MaxAttachmentStringSize) tx <- TransferTransaction.create(2.toByte, _sender, _recipient, _assetId, amount, _feeAssetId, fee, _attachment, timestamp, _proofs) } yield tx } diff --git a/node/src/test/scala/com/wavesplatform/block/TransactionsRootSpec.scala b/node/src/test/scala/com/wavesplatform/block/TransactionsRootSpec.scala index f50a314084d..66b784d7573 100644 --- a/node/src/test/scala/com/wavesplatform/block/TransactionsRootSpec.scala +++ b/node/src/test/scala/com/wavesplatform/block/TransactionsRootSpec.scala @@ -3,24 +3,17 @@ package com.wavesplatform.block import com.wavesplatform.account.KeyPair import com.wavesplatform.block.Block.TransactionProof import com.wavesplatform.common.merkle.Merkle._ +import com.wavesplatform.crypto.Blake2b256 import com.wavesplatform.protobuf.transaction.PBTransactions import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.Transaction import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.{BlockGen, NoShrink, TransactionGen} +import com.wavesplatform.BlockGen +import com.wavesplatform.test.FreeSpec import org.scalacheck.Gen -import org.scalatest.{FreeSpec, Matchers, OptionValues} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import scorex.crypto.hash.Blake2b256 - -class TransactionsRootSpec - extends FreeSpec - with OptionValues - with ScalaCheckPropertyChecks - with BlockGen - with TransactionGen - with NoShrink - with Matchers { +import org.scalatest.OptionValues + +class TransactionsRootSpec extends FreeSpec with OptionValues with BlockGen { val commonGen: Gen[(KeyPair, List[TransferTransaction])] = for { @@ -144,4 +137,3 @@ class TransactionsRootSpec block.verifyTransactionProof(proof) shouldBe false } } - diff --git a/node/src/test/scala/com/wavesplatform/code/DirectiveSetConstructingTest.scala b/node/src/test/scala/com/wavesplatform/code/DirectiveSetConstructingTest.scala index 405f936739e..aee7262d944 100644 --- a/node/src/test/scala/com/wavesplatform/code/DirectiveSetConstructingTest.scala +++ b/node/src/test/scala/com/wavesplatform/code/DirectiveSetConstructingTest.scala @@ -1,11 +1,10 @@ package com.wavesplatform.code -import com.wavesplatform.common.state.diffs.ProduceError.produce import com.wavesplatform.lang.directives.DirectiveSet import com.wavesplatform.lang.directives.values._ -import org.scalatest.{Matchers, PropSpec} +import com.wavesplatform.test._ -class DirectiveSetConstructingTest extends PropSpec with Matchers { +class DirectiveSetConstructingTest extends PropSpec { property("DirectiveSet should be successfully constructed with (V3, Account, Contract) params") { DirectiveSet(V3, Account, DApp) shouldBe DirectiveSet(V3, Account, DApp) } diff --git a/node/src/test/scala/com/wavesplatform/code/PartialUnificationTests.scala b/node/src/test/scala/com/wavesplatform/code/PartialUnificationTests.scala index 0306a973ffd..9dcf6a2eba1 100644 --- a/node/src/test/scala/com/wavesplatform/code/PartialUnificationTests.scala +++ b/node/src/test/scala/com/wavesplatform/code/PartialUnificationTests.scala @@ -1,8 +1,8 @@ package com.wavesplatform.code -import org.scalatest.{FlatSpec, Matchers} +import com.wavesplatform.test.FlatSpec // See http://eed3si9n.com/herding-cats/partial-unification.html -class PartialUnificationTests extends FlatSpec with Matchers { +class PartialUnificationTests extends FlatSpec { def foo[F[_], A](fa: F[A]): String = fa.toString "Partial unification" should "be enabled" in { diff --git a/node/src/test/scala/com/wavesplatform/consensus/FPPoSSelectorTest.scala b/node/src/test/scala/com/wavesplatform/consensus/FPPoSSelectorTest.scala index 3d05e901c73..3bfaf6058d3 100644 --- a/node/src/test/scala/com/wavesplatform/consensus/FPPoSSelectorTest.scala +++ b/node/src/test/scala/com/wavesplatform/consensus/FPPoSSelectorTest.scala @@ -6,7 +6,6 @@ import com.typesafe.config.ConfigFactory import com.wavesplatform.account.KeyPair import com.wavesplatform.block.Block import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.state.diffs.ProduceError import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.database.LevelDBFactory import com.wavesplatform.db.DBCacheSettings @@ -16,18 +15,17 @@ import com.wavesplatform.settings.{WavesSettings, _} import com.wavesplatform.state._ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.utils.TestLevelDB +import com.wavesplatform.test._ import com.wavesplatform.transaction.{BlockchainUpdater, GenesisTransaction} import com.wavesplatform.utils.Time -import com.wavesplatform.{EitherMatchers, TestHelpers, TransactionGen, WithDB, crypto} +import com.wavesplatform.{TestHelpers, WithDB, crypto} import org.iq80.leveldb.Options import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import scala.concurrent.duration._ import scala.util.Random -class FPPoSSelectorTest extends FreeSpec with Matchers with EitherMatchers with WithDB with TransactionGen with DBCacheSettings with ScalaCheckPropertyChecks { +class FPPoSSelectorTest extends FreeSpec with WithDB with DBCacheSettings { import FPPoSSelectorTest._ private val generationSignatureMethods = Table( diff --git a/node/src/test/scala/com/wavesplatform/consensus/FairPoSCalculatorTest.scala b/node/src/test/scala/com/wavesplatform/consensus/FairPoSCalculatorTest.scala index b055c15ec1b..e6f31a21c06 100644 --- a/node/src/test/scala/com/wavesplatform/consensus/FairPoSCalculatorTest.scala +++ b/node/src/test/scala/com/wavesplatform/consensus/FairPoSCalculatorTest.scala @@ -1,17 +1,16 @@ package com.wavesplatform.consensus import cats.data.NonEmptyList -import cats.implicits._ import com.wavesplatform.account.{KeyPair, PrivateKey, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, EitherExt2} import com.wavesplatform.crypto -import org.scalatest.{Matchers, PropSpec} +import com.wavesplatform.test.PropSpec import scala.io.Source import scala.util.Random -class FairPoSCalculatorTest extends PropSpec with Matchers { +class FairPoSCalculatorTest extends PropSpec { import FairPoSCalculatorTest._ import PoSCalculator._ diff --git a/node/src/test/scala/com/wavesplatform/consensus/nxt/TransactionsOrderingSpecification.scala b/node/src/test/scala/com/wavesplatform/consensus/nxt/TransactionsOrderingSpecification.scala index 7a00090124f..a044e4aa3a3 100644 --- a/node/src/test/scala/com/wavesplatform/consensus/nxt/TransactionsOrderingSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/consensus/nxt/TransactionsOrderingSpecification.scala @@ -4,14 +4,14 @@ import com.wavesplatform.account.{Address, KeyPair} 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.Waves import com.wavesplatform.transaction.transfer._ -import org.scalatest.{Assertions, Matchers, PropSpec} import scala.util.Random -class TransactionsOrderingSpecification extends PropSpec with Assertions with Matchers { +class TransactionsOrderingSpecification extends PropSpec { private val kp: KeyPair = KeyPair(ByteStr(new Array[Byte](32))) property("TransactionsOrdering.InBlock should sort correctly") { diff --git a/node/src/test/scala/com/wavesplatform/crypto/SigningFunctionsSpecification.scala b/node/src/test/scala/com/wavesplatform/crypto/SigningFunctionsSpecification.scala index 62bf9d5d42d..06ecb4dede1 100644 --- a/node/src/test/scala/com/wavesplatform/crypto/SigningFunctionsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/crypto/SigningFunctionsSpecification.scala @@ -3,10 +3,9 @@ package com.wavesplatform.crypto import com.wavesplatform.account.KeyPair import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class SigningFunctionsSpecification extends PropSpec with PropertyChecks with Matchers { +class SigningFunctionsSpecification extends PropSpec { property("signed message should be verifiable with appropriate public key") { forAll { (seed1: Array[Byte], seed2: Array[Byte], message1: Array[Byte], message2: Array[Byte]) => diff --git a/node/src/test/scala/com/wavesplatform/database/LevelDBWriterSpec.scala b/node/src/test/scala/com/wavesplatform/database/LevelDBWriterSpec.scala index 142faff3fa7..63ebe9f5933 100644 --- a/node/src/test/scala/com/wavesplatform/database/LevelDBWriterSpec.scala +++ b/node/src/test/scala/com/wavesplatform/database/LevelDBWriterSpec.scala @@ -18,28 +18,23 @@ import com.wavesplatform.settings.{GenesisSettings, TestFunctionalitySettings, T import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.utils._ import com.wavesplatform.state.{BlockchainUpdaterImpl, Height, TransactionId, TxNum} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} import com.wavesplatform.utils.{SystemTime, Time} -import com.wavesplatform.{EitherMatchers, RequestGen, TransactionGen, WithDB, database} +import com.wavesplatform.{RequestGen, WithDB, database} import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.concurrent.duration.Duration //noinspection NameBooleanParameters class LevelDBWriterSpec extends FreeSpec - with Matchers - with EitherMatchers - with TransactionGen with WithDB with DBCacheSettings - with RequestGen - with ScalaCheckDrivenPropertyChecks { + with RequestGen { "Slice" - { "drops tail" in { LevelDBWriter.slice(Seq(10, 7, 4), 7, 10) shouldEqual Seq(10, 7) diff --git a/node/src/test/scala/com/wavesplatform/db/ScriptCacheTest.scala b/node/src/test/scala/com/wavesplatform/db/ScriptCacheTest.scala index 249ce85cd7b..6a2a753e50c 100644 --- a/node/src/test/scala/com/wavesplatform/db/ScriptCacheTest.scala +++ b/node/src/test/scala/com/wavesplatform/db/ScriptCacheTest.scala @@ -14,11 +14,11 @@ import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.{BlockchainUpdater, GenesisTransaction} import com.wavesplatform.utils.Time -import com.wavesplatform.{EitherMatchers, TransactionGen, WithDB} +import com.wavesplatform.WithDB +import com.wavesplatform.test.FreeSpec import org.scalacheck.Gen -import org.scalatest.{FreeSpec, Matchers} -class ScriptCacheTest extends FreeSpec with Matchers with WithDB with TransactionGen with EitherMatchers { +class ScriptCacheTest extends FreeSpec with WithDB { val CACHE_SIZE = 1 val AMOUNT = 10000000000L @@ -99,10 +99,12 @@ class ScriptCacheTest extends FreeSpec with Matchers with WithDB with Transactio } "Return correct script after rollback" in { - val scripts @ List((script, complexity)) = mkScripts(1) + val scripts = mkScripts(1) + val (script, complexity) = scripts.head withBlockchain(blockGen(scripts, _)) { - case (List(account), bcu) => + case (accounts, bcu) => + val account = accounts.head bcu.accountScript(account.toAddress) shouldEqual Some(AccountScriptInfo(account.publicKey, script, complexity)) val lastBlockHeader = bcu.lastBlockHeader.get diff --git a/node/src/test/scala/com/wavesplatform/db/WithState.scala b/node/src/test/scala/com/wavesplatform/db/WithState.scala index 389b6bcf21d..f9cc1e684dd 100644 --- a/node/src/test/scala/com/wavesplatform/db/WithState.scala +++ b/node/src/test/scala/com/wavesplatform/db/WithState.scala @@ -3,31 +3,29 @@ package com.wavesplatform.db import java.nio.file.Files import cats.Monoid -import com.wavesplatform.{NTPTime, TestHelpers} import com.wavesplatform.account.Address import com.wavesplatform.block.Block import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.database.{loadActiveLeases, LevelDBFactory, LevelDBWriter, TestStorageFactory} +import com.wavesplatform.database.{LevelDBFactory, LevelDBWriter, TestStorageFactory, loadActiveLeases} import com.wavesplatform.events.BlockchainUpdateTriggers import com.wavesplatform.features.{BlockchainFeature, BlockchainFeatures} import com.wavesplatform.history.Domain import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.lang.ValidationError import com.wavesplatform.mining.MiningConstraint -import com.wavesplatform.settings.{ - loadConfig, BlockchainSettings, FunctionalitySettings, TestSettings, WavesSettings, - TestFunctionalitySettings => TFS -} -import com.wavesplatform.state.{Blockchain, BlockchainUpdaterImpl, Diff} -import com.wavesplatform.state.diffs.{produce, BlockDiffer} +import com.wavesplatform.settings.{BlockchainSettings, FunctionalitySettings, TestSettings, WavesSettings, loadConfig, TestFunctionalitySettings => TFS} +import com.wavesplatform.state.diffs.{BlockDiffer, produce} import com.wavesplatform.state.reader.CompositeBlockchain import com.wavesplatform.state.utils.TestLevelDB -import com.wavesplatform.transaction.{Asset, Transaction} +import com.wavesplatform.state.{Blockchain, BlockchainUpdaterImpl, Diff} import com.wavesplatform.transaction.smart.script.trace.TracedResult +import com.wavesplatform.transaction.{Asset, Transaction} +import com.wavesplatform.{NTPTime, TestHelpers} import monix.reactive.Observer import monix.reactive.subjects.{PublishSubject, Subject} import org.iq80.leveldb.{DB, Options} -import org.scalatest.{Matchers, Suite} +import org.scalatest.Suite +import org.scalatest.matchers.should.Matchers trait WithState extends DBCacheSettings with Matchers with NTPTime { _: Suite => protected val ignoreSpendableBalanceChanged: Subject[(Address, Asset), (Address, Asset)] = PublishSubject() diff --git a/node/src/test/scala/com/wavesplatform/features/FeatureProviderTest.scala b/node/src/test/scala/com/wavesplatform/features/FeatureProviderTest.scala index 03019426b39..8db6996911f 100644 --- a/node/src/test/scala/com/wavesplatform/features/FeatureProviderTest.scala +++ b/node/src/test/scala/com/wavesplatform/features/FeatureProviderTest.scala @@ -3,12 +3,11 @@ package com.wavesplatform.features import com.wavesplatform.block.Block import com.wavesplatform.settings.{BlockchainSettings, FunctionalitySettings, GenesisSettings, RewardsSettings} import com.wavesplatform.state.Blockchain +import com.wavesplatform.test.FlatSpec import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{FlatSpec, Matchers} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -class FeatureProviderTest extends FlatSpec with Matchers with ScalaCheckPropertyChecks with MockFactory { +class FeatureProviderTest extends FlatSpec with MockFactory { "blockVersionAt" should "return valid version" in { val fs = FunctionalitySettings.MAINNET val v3ActivationHeight = fs.blockVersion3AfterHeight diff --git a/node/src/test/scala/com/wavesplatform/features/RideV5LimitsChangeTest.scala b/node/src/test/scala/com/wavesplatform/features/RideV5LimitsChangeTest.scala index a822b3e7a97..464b3b63eff 100644 --- a/node/src/test/scala/com/wavesplatform/features/RideV5LimitsChangeTest.scala +++ b/node/src/test/scala/com/wavesplatform/features/RideV5LimitsChangeTest.scala @@ -2,21 +2,19 @@ package com.wavesplatform.features import com.wavesplatform.TestTime import com.wavesplatform.block.Block -import com.wavesplatform.common.state.diffs.ProduceError.produce import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithDomain -import com.wavesplatform.it.util._ import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.mining.MiningConstraints.MaxScriptsComplexityInBlock import com.wavesplatform.mining._ import com.wavesplatform.state.diffs.BlockDiffer +import com.wavesplatform.test._ import com.wavesplatform.transaction.TxHelpers import org.scalamock.scalatest.PathMockFactory -import org.scalatest.{FlatSpec, Matchers} -class RideV5LimitsChangeTest extends FlatSpec with Matchers with WithDomain with PathMockFactory { +class RideV5LimitsChangeTest extends FlatSpec with WithDomain with PathMockFactory { "Blockchain" should "reject block with >1kk complexity before SynchronousCalls activated" in withDomain(DomainPresets.RideV4) { d => val contractSigner = TxHelpers.secondSigner val contractAddress = contractSigner.toAddress @@ -50,7 +48,7 @@ class RideV5LimitsChangeTest extends FlatSpec with Matchers with WithDomain with val invokeComplexity = 3620 val invokes = for (_ <- 1 to invokesCount) yield TxHelpers.invoke(contractAddress, "test") - val time = new TestTime() + val time = new TestTime() val block = d.createBlock(Block.ProtoBlockVersion, invokes, strictTime = true) val differResult = BlockDiffer diff --git a/node/src/test/scala/com/wavesplatform/history/BlockRewardSpec.scala b/node/src/test/scala/com/wavesplatform/history/BlockRewardSpec.scala index 61e873a77f5..d8f57ee7d56 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockRewardSpec.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockRewardSpec.scala @@ -15,22 +15,13 @@ import com.wavesplatform.mining.MiningConstraint import com.wavesplatform.settings.{Constants, FunctionalitySettings, RewardsSettings} import com.wavesplatform.state.diffs.BlockDiffer import com.wavesplatform.state.{Blockchain, Height} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.{EitherMatchers, NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks - -class BlockRewardSpec - extends FreeSpec - with ScalaCheckPropertyChecks - with WithDomain - with Matchers - with EitherMatchers - with TransactionGen - with NoShrink { + +class BlockRewardSpec extends FreeSpec with WithDomain { private val BlockRewardActivationHeight = 5 private val NGActivationHeight = 0 diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBadReferencesTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBadReferencesTest.scala index a40e27f6054..25aea249ca7 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBadReferencesTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBadReferencesTest.scala @@ -1,23 +1,17 @@ package com.wavesplatform.history -import com.wavesplatform.{EitherMatchers, TransactionGen} import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.transfer._ import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} class BlockchainUpdaterBadReferencesTest extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen { + with DomainScenarioDrivenPropertyCheck { val preconditionsAndPayments: Gen[(GenesisTransaction, TransferTransaction, TransferTransaction, TransferTransaction)] = for { master <- accountGen diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBlockMicroblockSequencesSameTransactionsTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBlockMicroblockSequencesSameTransactionsTest.scala index 2647ebbb2e8..5d8219d67cd 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBlockMicroblockSequencesSameTransactionsTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBlockMicroblockSequencesSameTransactionsTest.scala @@ -6,21 +6,12 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction._ import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{EitherMatchers, NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} - -class BlockchainUpdaterBlockMicroblockSequencesSameTransactionsTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen - with NoShrink { + +class BlockchainUpdaterBlockMicroblockSequencesSameTransactionsTest extends PropSpec with DomainScenarioDrivenPropertyCheck { import BlockchainUpdaterBlockMicroblockSequencesSameTransactionsTest._ @@ -164,7 +155,7 @@ object BlockchainUpdaterBlockMicroblockSequencesSameTransactionsTest { t <- if (h < total) genSizes(total - h) else Gen.const(Seq.empty) } yield h +: t - def genSplitSizes(total: Int): Gen[(Int, Seq[Int])] = genSizes(total).map { case h :: tail => (h, tail) } + def genSplitSizes(total: Int): Gen[(Int, Seq[Int])] = genSizes(total).map(s => s.head -> s.tail) type BlockAndMicroblockSize = (Int, Seq[Int]) type BlockAndMicroblockSizes = Seq[BlockAndMicroblockSize] diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBlockOnlyTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBlockOnlyTest.scala index 5d62753d92c..1d07118555c 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBlockOnlyTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBlockOnlyTest.scala @@ -4,20 +4,12 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction._ import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{EitherMatchers, TransactionGen} import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockchainUpdaterBlockOnlyTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen { +class BlockchainUpdaterBlockOnlyTest extends PropSpec with DomainScenarioDrivenPropertyCheck { def preconditionsAndPayments(paymentsAmt: Int): Gen[(GenesisTransaction, Seq[TransferTransaction])] = for { diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBurnTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBurnTest.scala index 5b4c7fa68a5..94c061427ef 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBurnTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterBurnTest.scala @@ -1,20 +1,18 @@ package com.wavesplatform.history -import com.wavesplatform.TransactionGen import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.settings.{BlockchainSettings, WavesSettings} import com.wavesplatform.state.diffs.{ENOUGH_AMT, produce} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.assets.{BurnTransaction, IssueTransaction, ReissueTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{Asset, GenesisTransaction, TxVersion} import org.scalacheck.Gen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockchainUpdaterBurnTest extends PropSpec with PropertyChecks with DomainScenarioDrivenPropertyCheck with Matchers with TransactionGen { +class BlockchainUpdaterBurnTest extends PropSpec with DomainScenarioDrivenPropertyCheck { val Waves: Long = 100000000 type Setup = diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterGeneratorFeeNextBlockOrMicroBlockTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterGeneratorFeeNextBlockOrMicroBlockTest.scala index 61ceb6df5cf..caa1b540005 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterGeneratorFeeNextBlockOrMicroBlockTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterGeneratorFeeNextBlockOrMicroBlockTest.scala @@ -1,23 +1,15 @@ package com.wavesplatform.history -import com.wavesplatform.{EitherMatchers, TransactionGen} import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.transfer._ import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockchainUpdaterGeneratorFeeNextBlockOrMicroBlockTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen { +class BlockchainUpdaterGeneratorFeeNextBlockOrMicroBlockTest extends PropSpec with DomainScenarioDrivenPropertyCheck { type Setup = (GenesisTransaction, TransferTransaction, TransferTransaction, TransferTransaction) diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterGeneratorFeeSameBlockTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterGeneratorFeeSameBlockTest.scala index 15bfd81fc92..cac16c28c46 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterGeneratorFeeSameBlockTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterGeneratorFeeSameBlockTest.scala @@ -4,20 +4,12 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{EitherMatchers, TransactionGen} import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockchainUpdaterGeneratorFeeSameBlockTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen { +class BlockchainUpdaterGeneratorFeeSameBlockTest extends PropSpec with DomainScenarioDrivenPropertyCheck { type Setup = (GenesisTransaction, TransferTransaction, TransferTransaction) diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterInMemoryDiffTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterInMemoryDiffTest.scala index a7eb893b3e6..27fd1b99a92 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterInMemoryDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterInMemoryDiffTest.scala @@ -1,23 +1,15 @@ package com.wavesplatform.history -import com.wavesplatform.{EitherMatchers, TransactionGen} import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.features.BlockchainFeatures +import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction._ import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.history.Domain.BlockchainUpdaterExt import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockchainUpdaterInMemoryDiffTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen { +class BlockchainUpdaterInMemoryDiffTest extends PropSpec with DomainScenarioDrivenPropertyCheck { val preconditionsAndPayments: Gen[(GenesisTransaction, TransferTransaction, TransferTransaction)] = for { master <- accountGen recipient <- accountGen @@ -34,7 +26,8 @@ class BlockchainUpdaterInMemoryDiffTest val blocksWithoutCompaction = chainBlocks( Seq(genesis) +: Seq.fill(MaxTransactionsPerBlockDiff * 2 - 1)(Seq.empty[Transaction]) :+ - Seq(payment1)) + Seq(payment1) + ) val blockTriggersCompaction = buildBlockOfTxs(blocksWithoutCompaction.last.id(), Seq(payment2)) blocksWithoutCompaction.foreach(b => domain.blockchainUpdater.processBlock(b) should beRight) diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterKeyAndMicroBlockConflictTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterKeyAndMicroBlockConflictTest.scala index 37e786e3593..f7f7b022b8c 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterKeyAndMicroBlockConflictTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterKeyAndMicroBlockConflictTest.scala @@ -6,19 +6,15 @@ import com.wavesplatform.block.{Block, MicroBlock} import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.lagonaki.mocks.TestBlock +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import org.scalacheck.Gen import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} class BlockchainUpdaterKeyAndMicroBlockConflictTest extends PropSpec - with PropertyChecks with DomainScenarioDrivenPropertyCheck with OptionValues - with Matchers - with EitherMatchers - with TransactionGen with BlocksTransactionsHelpers { property("new key block should be validated to previous") { @@ -62,9 +58,9 @@ class BlockchainUpdaterKeyAndMicroBlockConflictTest property("data keys should not be duplicated") { forAll(Preconditions.duplicateDataKeys()) { - case (genesisBlock, Seq(block1, block2), microBlocks, address) => + case (genesisBlock, blocks, microBlocks, address) => withDomain(DataAndMicroblocksActivatedAt0WavesSettings) { d => - Seq(genesisBlock, block1, block2).foreach(d.blockchainUpdater.processBlock(_) should beRight) + Seq(genesisBlock, blocks(0), blocks(1)).foreach(d.blockchainUpdater.processBlock(_) should beRight) d.blockchainUpdater.accountData(address, "test") shouldBe defined microBlocks.foreach(d.blockchainUpdater.processMicroBlock(_) should beRight) d.blockchainUpdater.accountData(address, "test") shouldBe defined diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterLiquidBlockTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterLiquidBlockTest.scala index 1ff4d9e28ee..8f9f720973e 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterLiquidBlockTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterLiquidBlockTest.scala @@ -3,24 +3,15 @@ package com.wavesplatform.history import com.wavesplatform._ import com.wavesplatform.block.{Block, MicroBlock} import com.wavesplatform.common.utils.EitherExt2 +import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.state.diffs.ENOUGH_AMT +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.TxValidationError.GenericError -import com.wavesplatform.history.Domain.BlockchainUpdaterExt import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockchainUpdaterLiquidBlockTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen - with BlocksTransactionsHelpers - with NoShrink { +class BlockchainUpdaterLiquidBlockTest extends PropSpec with DomainScenarioDrivenPropertyCheck with BlocksTransactionsHelpers { import QuickTX._ import UnsafeBlocks._ diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterMicroblockBadSignaturesTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterMicroblockBadSignaturesTest.scala index 51eff94de01..6c4e9f0ea5c 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterMicroblockBadSignaturesTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterMicroblockBadSignaturesTest.scala @@ -1,26 +1,19 @@ package com.wavesplatform.history -import com.wavesplatform.{EitherMatchers, TransactionGen} import com.wavesplatform.account.KeyPair import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.crypto._ import com.wavesplatform.features.BlockchainFeatures +import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.history.Domain.BlockchainUpdaterExt import org.scalacheck.Gen -import org.scalatest._ import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockchainUpdaterMicroblockBadSignaturesTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen { +class BlockchainUpdaterMicroblockBadSignaturesTest extends PropSpec with PropertyChecks with DomainScenarioDrivenPropertyCheck { val preconditionsAndPayments: Gen[(GenesisTransaction, TransferTransaction, TransferTransaction)] = for { master <- accountGen diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterMicroblockSunnyDayTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterMicroblockSunnyDayTest.scala index 64f8633c002..081807db207 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterMicroblockSunnyDayTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterMicroblockSunnyDayTest.scala @@ -1,6 +1,5 @@ package com.wavesplatform.history -import com.wavesplatform.{EitherMatchers, TransactionGen} import com.wavesplatform.account.{Address, AddressOrAlias, KeyPair} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 @@ -8,19 +7,12 @@ import com.wavesplatform.crypto._ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction._ import com.wavesplatform.transaction.transfer._ import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockchainUpdaterMicroblockSunnyDayTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen { +class BlockchainUpdaterMicroblockSunnyDayTest extends PropSpec with DomainScenarioDrivenPropertyCheck { type Setup = (GenesisTransaction, TransferTransaction, TransferTransaction, TransferTransaction) val preconditionsAndPayments: Gen[Setup] = for { @@ -135,7 +127,8 @@ class BlockchainUpdaterMicroblockSunnyDayTest val block0 = buildBlockOfTxs(randomSig, Seq(genesis)) val (block1, microBlocks1) = chainBaseAndMicro(block0.id(), masterToAlice, Seq(Seq(aliceToBob))) val otherSigner = KeyPair(ByteStr(Array.fill(KeyLength)(1: Byte))) - val block2 = customBuildBlockOfTxs(block0.id(), Seq(masterToAlice, aliceToBob2), otherSigner, 1, masterToAlice.timestamp, DefaultBaseTarget / 2) + val block2 = + customBuildBlockOfTxs(block0.id(), Seq(masterToAlice, aliceToBob2), otherSigner, 1, masterToAlice.timestamp, DefaultBaseTarget / 2) domain.blockchainUpdater.processBlock(block0) should beRight domain.blockchainUpdater.processBlock(block1) should beRight domain.blockchainUpdater.processMicroBlock(microBlocks1(0)) should beRight diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterNFTTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterNFTTest.scala index 4ef84fd341c..a83b328ed02 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterNFTTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterNFTTest.scala @@ -13,6 +13,7 @@ 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.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.assets.IssueTransaction @@ -20,21 +21,12 @@ import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalacheck.Gen import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockchainUpdaterNFTTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen - with BlocksTransactionsHelpers - with NoShrink { +class BlockchainUpdaterNFTTest extends PropSpec with DomainScenarioDrivenPropertyCheck with BlocksTransactionsHelpers { property("nft list should be consistent with transfer") { - forAll(Preconditions.nftTransfer()) { - case (issue, Seq(firstAccount, secondAccount), Seq(genesisBlock, issueBlock, keyBlock, postBlock), Seq(microBlock)) => + forAll(Preconditions.nftTransfer) { + case (issue, (firstAccount, secondAccount), (genesisBlock, issueBlock, keyBlock, postBlock), mbs) => withDomain(settingsWithFeatures(BlockchainFeatures.NG, BlockchainFeatures.ReduceNFTFee)) { d => d.blockchainUpdater.processBlock(genesisBlock) should beRight d.blockchainUpdater.processBlock(issueBlock) should beRight @@ -43,7 +35,7 @@ class BlockchainUpdaterNFTTest d.nftList(firstAccount).map(_._1.id) shouldBe Seq(issue.id()) d.nftList(secondAccount) shouldBe Nil - d.blockchainUpdater.processMicroBlock(microBlock) should beRight + d.blockchainUpdater.processMicroBlock(mbs.head) should beRight d.nftList(firstAccount) shouldBe Nil d.nftList(secondAccount).map(_._1.id) shouldBe Seq(issue.id()) @@ -55,8 +47,8 @@ class BlockchainUpdaterNFTTest } property("nft list should be consistent with invokescript") { - forAll(Preconditions.nftInvokeScript()) { - case (issue, Seq(firstAccount, secondAccount), Seq(genesisBlock, issueBlock, keyBlock, postBlock), Seq(microBlock)) => + forAll(Preconditions.nftInvokeScript) { + case (issue, (firstAccount, secondAccount), (genesisBlock, issueBlock, keyBlock, postBlock), mbs) => withDomain( settingsWithFeatures( BlockchainFeatures.NG, @@ -72,7 +64,7 @@ class BlockchainUpdaterNFTTest d.nftList(firstAccount).map(_._1.id) shouldBe Seq(issue.id()) d.nftList(secondAccount) shouldBe Nil - d.blockchainUpdater.processMicroBlock(microBlock) should beRight + d.blockchainUpdater.processMicroBlock(mbs.head) should beRight d.nftList(firstAccount) shouldBe Nil d.nftList(secondAccount).map(_._1.id) shouldBe Seq(issue.id()) @@ -84,8 +76,8 @@ class BlockchainUpdaterNFTTest } property("nft list should be persisted only once independently to using bloom filters") { - forAll(Preconditions.nftList()) { - case (issue, Seq(firstAccount, secondAccount), Seq(genesisBlock, firstBlock, secondBlock, postBlock)) => + forAll(Preconditions.nftList) { + case (issue, (firstAccount, secondAccount), (genesisBlock, firstBlock, secondBlock, postBlock)) => def assert(d: Domain): Assertion = { import com.wavesplatform.database.DBExt @@ -117,7 +109,7 @@ class BlockchainUpdaterNFTTest private[this] object Preconditions { import UnsafeBlocks._ - def nftTransfer(): Gen[(IssueTransaction, Seq[Address], Seq[Block], Seq[MicroBlock])] = { + val nftTransfer: Gen[(IssueTransaction, (Address, Address), (Block, Block, Block, Block), Seq[MicroBlock])] = { for { richAccount <- accountGen secondAccount <- accountGen @@ -158,11 +150,11 @@ class BlockchainUpdaterNFTTest version = 3.toByte, blockTime ) - (issue, Seq(richAccount.toAddress, secondAccount.toAddress), Seq(genesisBlock, issueBlock, keyBlock, postBlock), microBlocks) + (issue, (richAccount.toAddress, secondAccount.toAddress), (genesisBlock, issueBlock, keyBlock, postBlock), microBlocks) } } - def nftInvokeScript(): Gen[(IssueTransaction, Seq[Address], Seq[Block], Seq[MicroBlock])] = { + val nftInvokeScript: Gen[(IssueTransaction, (Address, Address), (Block, Block, Block, Block), Seq[MicroBlock])] = for { richAccount <- accountGen secondAccount <- accountGen @@ -240,11 +232,10 @@ class BlockchainUpdaterNFTTest version = 3, blockTime ) - (issue, Seq(richAccount.toAddress, secondAccount.toAddress), Seq(genesisBlock, issueBlock, keyBlock, postBlock), microBlocks) + (issue, (richAccount.toAddress, secondAccount.toAddress), (genesisBlock, issueBlock, keyBlock, postBlock), microBlocks) } - } - def nftList(): Gen[(IssueTransaction, Seq[Address], Seq[Block])] = { + val nftList: Gen[(IssueTransaction, (Address, Address), (Block, Block, Block, Block))] = for { firstAccount <- accountGen secondAccount <- accountGen @@ -289,8 +280,7 @@ class BlockchainUpdaterNFTTest blockTime ) - (issue, Seq(firstAccount.toAddress, secondAccount.toAddress), Seq(genesisBlock, firstBlock, secondBlock, postBlock)) + (issue, (firstAccount.toAddress, secondAccount.toAddress), (genesisBlock, firstBlock, secondBlock, postBlock)) } - } } } diff --git a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterSponsoredFeeBlockTest.scala b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterSponsoredFeeBlockTest.scala index 9adfb013c2a..1b2d54910c8 100644 --- a/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterSponsoredFeeBlockTest.scala +++ b/node/src/test/scala/com/wavesplatform/history/BlockchainUpdaterSponsoredFeeBlockTest.scala @@ -9,22 +9,14 @@ import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.settings.{BlockchainSettings, WavesSettings} import com.wavesplatform.state._ import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec 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.{EitherMatchers, TransactionGen} import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} - -class BlockchainUpdaterSponsoredFeeBlockTest - extends PropSpec - with PropertyChecks - with DomainScenarioDrivenPropertyCheck - with Matchers - with EitherMatchers - with TransactionGen { + +class BlockchainUpdaterSponsoredFeeBlockTest extends PropSpec with DomainScenarioDrivenPropertyCheck { private val amtTx = 100000 diff --git a/node/src/test/scala/com/wavesplatform/history/LeasingExpirySpec.scala b/node/src/test/scala/com/wavesplatform/history/LeasingExpirySpec.scala index bbcd16e063c..c976e56a153 100644 --- a/node/src/test/scala/com/wavesplatform/history/LeasingExpirySpec.scala +++ b/node/src/test/scala/com/wavesplatform/history/LeasingExpirySpec.scala @@ -1,6 +1,5 @@ package com.wavesplatform.history -import com.wavesplatform.{EitherMatchers, NoShrink, TransactionGen} import com.wavesplatform.account.{AddressOrAlias, Alias, KeyPair} import com.wavesplatform.block.Block import com.wavesplatform.common.state.ByteStr @@ -10,23 +9,15 @@ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.settings.{Constants, FunctionalitySettings} -import com.wavesplatform.state.{Blockchain, LeaseBalance} import com.wavesplatform.state.diffs.produce +import com.wavesplatform.state.{Blockchain, LeaseBalance} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.lease.LeaseTransaction import org.scalacheck.Gen import org.scalactic.source.Position -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks - -class LeasingExpirySpec - extends FreeSpec - with ScalaCheckPropertyChecks - with WithDomain - with Matchers - with EitherMatchers - with TransactionGen - with NoShrink { + +class LeasingExpirySpec extends FreeSpec with WithDomain { private val LeasingExpiryActivationHeight = 4 private val LeasingValidity = 2 diff --git a/node/src/test/scala/com/wavesplatform/http/AddressRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/AddressRouteSpec.scala index 8a56fd658e2..db187bb5556 100644 --- a/node/src/test/scala/com/wavesplatform/http/AddressRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/AddressRouteSpec.scala @@ -2,6 +2,7 @@ package com.wavesplatform.http import akka.http.scaladsl.testkit.RouteTestTimeout import com.google.protobuf.ByteString +import com.wavesplatform.{crypto, TestTime, TestWallet} import com.wavesplatform.account.{Address, AddressOrAlias} import com.wavesplatform.api.common.CommonAccountsApi import com.wavesplatform.api.http.AddressApiRoute @@ -23,11 +24,9 @@ import com.wavesplatform.state.diffs.FeeValidation import com.wavesplatform.state.{AccountScriptInfo, Blockchain} import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.utils.Schedulers -import com.wavesplatform.{NoShrink, TestTime, TestWallet, crypto} import io.netty.util.HashedWheelTimer import org.scalacheck.Gen import org.scalamock.scalatest.PathMockFactory -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json._ import scala.concurrent.duration._ @@ -35,10 +34,8 @@ import scala.concurrent.duration._ class AddressRouteSpec extends RouteSpec("/addresses") with PathMockFactory - with PropertyChecks with RestAPISettingsHelper with TestWallet - with NoShrink with WithDomain { testWallet.generateNewAccounts(10) @@ -76,7 +73,7 @@ class AddressRouteSpec routePath("/balance/{address}/{confirmations}") in withDomain() { d => val route = - addressApiRoute.copy(blockchain = d.blockchainUpdater, commonAccountsApi = CommonAccountsApi(d.liquidDiff, d.db, d.blockchainUpdater)).route + addressApiRoute.copy(blockchain = d.blockchainUpdater, commonAccountsApi = CommonAccountsApi(() => d.liquidDiff, d.db, d.blockchainUpdater)).route val address = TxHelpers.signer(1).toAddress d.appendBlock(TxHelpers.genesis(TxHelpers.defaultSigner.toAddress)) diff --git a/node/src/test/scala/com/wavesplatform/http/AliasBroadcastRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/AliasBroadcastRouteSpec.scala index 21fae9196cf..c7541c6572b 100644 --- a/node/src/test/scala/com/wavesplatform/http/AliasBroadcastRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/AliasBroadcastRouteSpec.scala @@ -10,9 +10,8 @@ import com.wavesplatform.transaction.Transaction import com.wavesplatform.transaction.TxValidationError.GenericError import com.wavesplatform.utils.Time import com.wavesplatform.wallet.Wallet -import com.wavesplatform.{NoShrink, RequestGen} +import com.wavesplatform.RequestGen import org.scalamock.scalatest.PathMockFactory -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json._ import play.api.libs.json._ @@ -20,9 +19,7 @@ class AliasBroadcastRouteSpec extends RouteSpec("/alias/broadcast/") with RequestGen with PathMockFactory - with PropertyChecks - with RestAPISettingsHelper - with NoShrink { + with RestAPISettingsHelper { private[this] val utxPoolSynchronizer = DummyTransactionPublisher.rejecting(tx => TransactionValidationError(GenericError("foo"), tx)) val route = AliasApiRoute(restAPISettings, stub[CommonTransactionsApi], stub[Wallet], utxPoolSynchronizer, stub[Time], stub[Blockchain]).route diff --git a/node/src/test/scala/com/wavesplatform/http/ApiErrorMatchers.scala b/node/src/test/scala/com/wavesplatform/http/ApiErrorMatchers.scala index c99da6ac730..65a3fa367df 100644 --- a/node/src/test/scala/com/wavesplatform/http/ApiErrorMatchers.scala +++ b/node/src/test/scala/com/wavesplatform/http/ApiErrorMatchers.scala @@ -3,7 +3,7 @@ package com.wavesplatform.http import akka.http.scaladsl.testkit.RouteTest import com.wavesplatform.api.http.ApiError import com.wavesplatform.api.http.ApiMarshallers._ -import org.scalatest.Matchers +import org.scalatest.matchers.should.Matchers import org.scalatest.matchers.{MatchResult, Matcher} import play.api.libs.json._ diff --git a/node/src/test/scala/com/wavesplatform/http/AssetsBroadcastRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/AssetsBroadcastRouteSpec.scala index c4f9e3262b9..a768eb64f13 100644 --- a/node/src/test/scala/com/wavesplatform/http/AssetsBroadcastRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/AssetsBroadcastRouteSpec.scala @@ -1,6 +1,7 @@ package com.wavesplatform.http import akka.http.scaladsl.model.StatusCodes +import com.wavesplatform.RequestGen import com.wavesplatform.api.common.{CommonAccountsApi, CommonAssetsApi} import com.wavesplatform.api.http.ApiError._ import com.wavesplatform.api.http._ @@ -8,7 +9,7 @@ import com.wavesplatform.api.http.assets._ import com.wavesplatform.api.http.requests.{SignedTransferV1Request, SignedTransferV2Request} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, EitherExt2} -import com.wavesplatform.it.util.DoubleExt +import com.wavesplatform.test._ import com.wavesplatform.state.Blockchain import com.wavesplatform.state.diffs.TransactionDiffer.TransactionValidationError import com.wavesplatform.transaction.TxValidationError.GenericError @@ -17,19 +18,15 @@ import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{Asset, Proofs, Transaction} import com.wavesplatform.utils.{Time, _} import com.wavesplatform.wallet.Wallet -import com.wavesplatform.{NoShrink, RequestGen} import org.scalacheck.{Gen => G} import org.scalamock.scalatest.PathMockFactory -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json._ class AssetsBroadcastRouteSpec extends RouteSpec("/assets/broadcast/") with RequestGen with PathMockFactory - with PropertyChecks - with RestAPISettingsHelper - with NoShrink { + with RestAPISettingsHelper { private[this] val route = AssetsApiRoute( restAPISettings, diff --git a/node/src/test/scala/com/wavesplatform/http/AssetsRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/AssetsRouteSpec.scala index e25d10d2846..63b2f96c56b 100644 --- a/node/src/test/scala/com/wavesplatform/http/AssetsRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/AssetsRouteSpec.scala @@ -9,10 +9,10 @@ import com.wavesplatform.api.http.assets.AssetsApiRoute import com.wavesplatform.api.http.requests.{TransferV1Request, TransferV2Request} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.it.util.DoubleExt import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 import com.wavesplatform.state.{AssetDescription, AssetScriptInfo, Blockchain, Height} +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.transfer._ diff --git a/node/src/test/scala/com/wavesplatform/http/BlocksApiRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/BlocksApiRouteSpec.scala index 5aa69938d66..5c760e3bc4d 100644 --- a/node/src/test/scala/com/wavesplatform/http/BlocksApiRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/BlocksApiRouteSpec.scala @@ -1,14 +1,12 @@ package com.wavesplatform.http -import scala.util.Random - -import com.wavesplatform.{NoShrink, TestWallet} +import com.wavesplatform.TestWallet import com.wavesplatform.api.BlockMeta import com.wavesplatform.api.common.CommonBlocksApi import com.wavesplatform.api.http.ApiMarshallers._ import com.wavesplatform.api.http.BlocksApiRoute -import com.wavesplatform.block.{Block, BlockHeader} import com.wavesplatform.block.serialization.BlockHeaderSerializer +import com.wavesplatform.block.{Block, BlockHeader} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.db.WithDomain import com.wavesplatform.lagonaki.mocks.TestBlock @@ -17,16 +15,15 @@ import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.utils.SystemTime import monix.reactive.Observable import org.scalamock.scalatest.PathMockFactory -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json._ +import scala.util.Random + class BlocksApiRouteSpec extends RouteSpec("/blocks") with PathMockFactory - with PropertyChecks with RestAPISettingsHelper with TestWallet - with NoShrink with WithDomain { private val blocksApi = mock[CommonBlocksApi] private val blocksApiRoute: BlocksApiRoute = BlocksApiRoute(restAPISettings, blocksApi, SystemTime) diff --git a/node/src/test/scala/com/wavesplatform/http/DebugApiRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/DebugApiRouteSpec.scala index 31c490a5e1a..69d56f4afa1 100644 --- a/node/src/test/scala/com/wavesplatform/http/DebugApiRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/DebugApiRouteSpec.scala @@ -10,7 +10,6 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils._ import com.wavesplatform.db.WithDomain import com.wavesplatform.features.BlockchainFeatures -import com.wavesplatform.it.util._ import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.v1.compiler.Terms.TRUE @@ -23,13 +22,14 @@ import com.wavesplatform.state.StateHash.SectionId import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.reader.LeaseDetails import com.wavesplatform.state.{AccountScriptInfo, AssetDescription, AssetScriptInfo, Blockchain, Height, InvokeScriptResult, NG, StateHash} +import com.wavesplatform.test._ import com.wavesplatform.transaction.assets.exchange.OrderType import com.wavesplatform.transaction.smart.InvokeScriptTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{TxHelpers, TxVersion} -import com.wavesplatform.{BlockchainStubHelpers, NTPTime, TestValues, TestWallet, TransactionGen} +import com.wavesplatform.{BlockchainStubHelpers, NTPTime, TestValues, TestWallet} import monix.eval.Task import org.scalamock.scalatest.PathMockFactory import play.api.libs.json.{JsArray, JsObject, JsValue, Json} @@ -44,7 +44,6 @@ class DebugApiRouteSpec with NTPTime with PathMockFactory with BlockchainStubHelpers - with TransactionGen with WithDomain { val wavesSettings = WavesSettings.default() @@ -546,12 +545,12 @@ class DebugApiRouteSpec val amount1 = 100 val recipient1 = Recipient.Address(ByteStr.decodeBase58("3NAgxLPGnw3RGv9JT6NTDaG5D1iLUehg2xd").get) val nonce1 = 0 - val leaseId1 = Lease.calculateId(Lease(recipient1, amount1, nonce1), invoke.id.value()) + val leaseId1 = Lease.calculateId(Lease(recipient1, amount1, nonce1), invoke.id()) val amount2 = 20 val recipient2 = Recipient.Alias("some_alias") val nonce2 = 2 - val leaseId2 = Lease.calculateId(Lease(recipient2, amount2, nonce2), invoke.id.value()) + val leaseId2 = Lease.calculateId(Lease(recipient2, amount2, nonce2), invoke.id()) val blockchain = createBlockchainStub { blockchain => (blockchain.balance _).when(*, *).returns(Long.MaxValue) diff --git a/node/src/test/scala/com/wavesplatform/http/LeaseBroadcastRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/LeaseBroadcastRouteSpec.scala index 223cb2c95e1..fc1513fd202 100644 --- a/node/src/test/scala/com/wavesplatform/http/LeaseBroadcastRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/LeaseBroadcastRouteSpec.scala @@ -1,5 +1,6 @@ package com.wavesplatform.http +import com.wavesplatform.RequestGen import com.wavesplatform.api.common.CommonAccountsApi import com.wavesplatform.api.http.ApiError._ import com.wavesplatform.api.http._ @@ -11,11 +12,9 @@ import com.wavesplatform.transaction.TxValidationError.GenericError import com.wavesplatform.transaction.lease.LeaseCancelTransaction import com.wavesplatform.utils.Time import com.wavesplatform.wallet.Wallet -import com.wavesplatform.{NoShrink, RequestGen} import org.scalacheck.Gen.posNum import org.scalacheck.{Gen => G} import org.scalamock.scalatest.PathMockFactory -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json._ import play.api.libs.json._ @@ -23,9 +22,7 @@ class LeaseBroadcastRouteSpec extends RouteSpec("/leasing/broadcast/") with RequestGen with PathMockFactory - with PropertyChecks - with RestAPISettingsHelper - with NoShrink { + with RestAPISettingsHelper { private[this] val publisher = DummyTransactionPublisher.rejecting(t => TransactionValidationError(GenericError("foo"), t)) private[this] val route = LeaseApiRoute(restAPISettings, stub[Wallet], stub[Blockchain], publisher, stub[Time], stub[CommonAccountsApi]).route "returns StateCheckFailed" - { diff --git a/node/src/test/scala/com/wavesplatform/http/LeaseRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/LeaseRouteSpec.scala index 04c88f92266..6d321ecbc20 100644 --- a/node/src/test/scala/com/wavesplatform/http/LeaseRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/LeaseRouteSpec.scala @@ -1,10 +1,7 @@ package com.wavesplatform.http -import scala.concurrent.Future - import akka.http.scaladsl.model.{ContentTypes, FormData, HttpEntity} import akka.http.scaladsl.server.Route -import com.wavesplatform.{NoShrink, NTPTime, TestWallet, TransactionGen} import com.wavesplatform.account.{Address, AddressOrAlias, KeyPair} import com.wavesplatform.api.common.{CommonAccountsApi, LeaseInfo} import com.wavesplatform.api.http.ApiMarshallers._ @@ -14,31 +11,31 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithDomain import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain -import com.wavesplatform.it.util.DoubleExt import com.wavesplatform.lang.directives.values.V5 import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, CONST_LONG, FUNCTION_CALL} import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.network.TransactionPublisher -import com.wavesplatform.state.{BinaryDataEntry, Blockchain, Diff} import com.wavesplatform.state.reader.LeaseDetails -import com.wavesplatform.transaction.{Asset, TxHelpers, TxVersion} +import com.wavesplatform.state.{BinaryDataEntry, Blockchain, Diff} +import com.wavesplatform.test._ import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} -import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.smart.script.trace.TracedResult +import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} +import com.wavesplatform.transaction.{Asset, TxHelpers, TxVersion} import com.wavesplatform.utils.SystemTime import com.wavesplatform.wallet.Wallet +import com.wavesplatform.{NTPTime, TestWallet, TransactionGen} import org.scalacheck.Gen import org.scalamock.scalatest.PathMockFactory -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import play.api.libs.json.{JsArray, JsObject, Json} +import scala.concurrent.Future + class LeaseRouteSpec extends RouteSpec("/leasing") - with ScalaCheckPropertyChecks with TransactionGen with RestAPISettingsHelper - with NoShrink with NTPTime with WithDomain with TestWallet @@ -50,7 +47,7 @@ class LeaseRouteSpec domain.blockchain, (_, _) => Future.successful(TracedResult(Right(true))), ntpTime, - CommonAccountsApi(domain.blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), domain.db, domain.blockchain) + CommonAccountsApi(() => domain.blockchainUpdater.bestLiquidDiff.getOrElse(Diff.empty), domain.db, domain.blockchain) ) private def withRoute(f: (Domain, Route) => Unit): Unit = diff --git a/node/src/test/scala/com/wavesplatform/http/ProtoVersionTransactionsSpec.scala b/node/src/test/scala/com/wavesplatform/http/ProtoVersionTransactionsSpec.scala index 245442a5ae3..5be5bf15ac0 100644 --- a/node/src/test/scala/com/wavesplatform/http/ProtoVersionTransactionsSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/ProtoVersionTransactionsSpec.scala @@ -2,6 +2,7 @@ package com.wavesplatform.http import akka.http.scaladsl.model.{HttpResponse, StatusCodes} import akka.http.scaladsl.server.Route +import com.wavesplatform.TestWallet import com.wavesplatform.account.KeyPair import com.wavesplatform.api.common.CommonTransactionsApi import com.wavesplatform.api.http.TransactionsApiRoute @@ -22,20 +23,12 @@ import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTran import com.wavesplatform.transaction.transfer.{MassTransferTransaction, TransferTransaction} import com.wavesplatform.transaction.{Asset, CreateAliasTransaction, DataTransaction, Proofs, Transaction, TxVersion, VersionedTransaction} import com.wavesplatform.utx.UtxPool -import com.wavesplatform.{TestWallet, TransactionGen} import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{Matchers, OptionValues} +import org.scalatest.OptionValues import play.api.libs.json._ -class ProtoVersionTransactionsSpec - extends RouteSpec("/transactions") - with RestAPISettingsHelper - with MockFactory - with TransactionGen - with Matchers - with OptionValues - with TestWallet { +class ProtoVersionTransactionsSpec extends RouteSpec("/transactions") with RestAPISettingsHelper with MockFactory with OptionValues with TestWallet { import com.wavesplatform.api.http.ApiMarshallers._ private val MinFee: Long = (0.001 * Constants.UnitsInWave).toLong diff --git a/node/src/test/scala/com/wavesplatform/http/RouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/RouteSpec.scala index 3f757994c0c..8e928cd80c3 100644 --- a/node/src/test/scala/com/wavesplatform/http/RouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/RouteSpec.scala @@ -3,11 +3,11 @@ package com.wavesplatform.http import akka.http.scaladsl.server.{ExceptionHandler, Route} import akka.http.scaladsl.testkit._ import com.wavesplatform.api.http -import org.scalatest.{FreeSpec, Matchers} -import org.scalatest.matchers.{Matcher, MatchResult} -import play.api.libs.json.{Json, JsValue} +import com.wavesplatform.test.FreeSpec +import org.scalatest.matchers.{MatchResult, Matcher} +import play.api.libs.json.{JsValue, Json} -abstract class RouteSpec(basePath: String) extends FreeSpec with ScalatestRouteTest with Matchers with ApiErrorMatchers { +abstract class RouteSpec(basePath: String) extends FreeSpec with ScalatestRouteTest with ApiErrorMatchers { protected implicit val exceptionHandler: ExceptionHandler = http.uncaughtExceptionHandler protected def seal(route: Route): Route = Route.seal(route) diff --git a/node/src/test/scala/com/wavesplatform/http/TransactionsRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/TransactionsRouteSpec.scala index fcc0c0c2d90..b0794cba509 100644 --- a/node/src/test/scala/com/wavesplatform/http/TransactionsRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/TransactionsRouteSpec.scala @@ -31,13 +31,12 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.script.trace.{AccountVerifierTrace, TracedResult} import com.wavesplatform.transaction.transfer.{MassTransferTransaction, TransferTransaction} import com.wavesplatform.transaction.{Asset, Proofs, Transaction, TxHelpers, TxVersion} -import com.wavesplatform.{BlockGen, BlockchainStubHelpers, NoShrink, TestTime, TestValues, TestWallet, TransactionGen} +import com.wavesplatform.{BlockGen, BlockchainStubHelpers, TestTime, TestValues, TestWallet} import monix.reactive.Observable import org.scalacheck.Gen._ import org.scalacheck.{Arbitrary, Gen} import org.scalamock.scalatest.MockFactory -import org.scalatest.{Matchers, OptionValues} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.OptionValues import play.api.libs.json.Json.JsValueWrapper import play.api.libs.json._ @@ -48,13 +47,9 @@ class TransactionsRouteSpec extends RouteSpec("/transactions") with RestAPISettingsHelper with MockFactory - with Matchers - with TransactionGen with BlockGen - with PropertyChecks with OptionValues with TestWallet - with NoShrink with BlockchainStubHelpers { private val blockchain = mock[Blockchain] @@ -1021,12 +1016,12 @@ class TransactionsRouteSpec val amount1 = 100 val nonce1 = 0 val recipient1 = Recipient.Address(ByteStr.decodeBase58("3NAgxLPGnw3RGv9JT6NTDaG5D1iLUehg2xd").get) - val leaseId1 = Lease.calculateId(Lease(recipient1, amount1, nonce1), invoke.id.value()) + val leaseId1 = Lease.calculateId(Lease(recipient1, amount1, nonce1), invoke.id()) val amount2 = 20 val nonce2 = 2 val recipient2 = Recipient.Alias("some_alias") - val leaseId2 = Lease.calculateId(Lease(recipient2, amount2, nonce2), invoke.id.value()) + val leaseId2 = Lease.calculateId(Lease(recipient2, amount2, nonce2), invoke.id()) val blockchain = createBlockchainStub { blockchain => val (dAppScript, _) = ScriptCompiler diff --git a/node/src/test/scala/com/wavesplatform/http/UtilsRouteSpec.scala b/node/src/test/scala/com/wavesplatform/http/UtilsRouteSpec.scala index c304bb0bf8e..7ee89beb785 100644 --- a/node/src/test/scala/com/wavesplatform/http/UtilsRouteSpec.scala +++ b/node/src/test/scala/com/wavesplatform/http/UtilsRouteSpec.scala @@ -61,7 +61,7 @@ class UtilsRouteSpec extends RouteSpec("/utils") with RestAPISettingsHelper with ) (() => utilsApi.blockchain.activatedFeatures).when().returning(Map()).anyNumberOfTimes() - private val route = utilsApi.route + private val route = seal(utilsApi.route) val script = FUNCTION_CALL( function = PureContext.eq.header, diff --git a/node/src/test/scala/com/wavesplatform/it/util/package.scala b/node/src/test/scala/com/wavesplatform/it/util/package.scala index a151c70e33a..81c089daf98 100644 --- a/node/src/test/scala/com/wavesplatform/it/util/package.scala +++ b/node/src/test/scala/com/wavesplatform/it/util/package.scala @@ -3,13 +3,8 @@ package com.wavesplatform.it import com.wavesplatform.account.{Address, AddressOrAlias, Alias} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.v1.traits.domain.Recipient -import com.wavesplatform.settings.Constants package object util { - implicit class DoubleExt(val d: Double) extends AnyVal { - def waves: Long = (BigDecimal(d) * Constants.UnitsInWave).toLong - } - implicit class AddressOrAliasExt(val a: AddressOrAlias) extends AnyVal { def toRide: Recipient = a match { diff --git a/node/src/test/scala/com/wavesplatform/lagonaki/unit/BlockSpecification.scala b/node/src/test/scala/com/wavesplatform/lagonaki/unit/BlockSpecification.scala index f06e259c0e4..4ebba33505c 100644 --- a/node/src/test/scala/com/wavesplatform/lagonaki/unit/BlockSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/lagonaki/unit/BlockSpecification.scala @@ -9,13 +9,12 @@ import com.wavesplatform.state.diffs.produce import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction._ import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{NoShrink, TransactionGen, crypto} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import org.scalacheck.Arbitrary.arbitrary import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockSpecification extends PropSpec with PropertyChecks with TransactionGen with Matchers with NoShrink { +class BlockSpecification extends PropSpec { val time = System.currentTimeMillis() - 5000 @@ -167,7 +166,8 @@ class BlockSpecification extends PropSpec with PropertyChecks with TransactionGe Seq.empty, -1L, transactionData - ).copy(signature = ByteStr(Array.fill(64)(0: Byte))) + ) + .copy(signature = ByteStr(Array.fill(64)(0: Byte))) block.signatureValid() shouldBe false } } diff --git a/node/src/test/scala/com/wavesplatform/lagonaki/unit/MicroBlockSpecification.scala b/node/src/test/scala/com/wavesplatform/lagonaki/unit/MicroBlockSpecification.scala index 11e18d1f1bb..abede5c1a53 100644 --- a/node/src/test/scala/com/wavesplatform/lagonaki/unit/MicroBlockSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/lagonaki/unit/MicroBlockSpecification.scala @@ -6,29 +6,30 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.mining.Miner import com.wavesplatform.state.diffs.produce +import com.wavesplatform.test.FunSuite import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction._ import com.wavesplatform.transaction.transfer._ import org.scalamock.scalatest.MockFactory -import org.scalatest.words.ShouldVerb -import org.scalatest.{FunSuite, Matchers} import scala.util.Random -class MicroBlockSpecification extends FunSuite with Matchers with MockFactory with ShouldVerb { +class MicroBlockSpecification extends FunSuite with MockFactory { - val prevResBlockSig = ByteStr(Array.fill(Block.BlockIdLength)(Random.nextInt(100).toByte)) - val totalResBlockSig = ByteStr(Array.fill(Block.BlockIdLength)(Random.nextInt(100).toByte)) - val reference = Array.fill(Block.BlockIdLength)(Random.nextInt(100).toByte) - val sender = KeyPair(reference.dropRight(2)) - val gen = KeyPair(reference) + private val prevResBlockSig = ByteStr(Array.fill(Block.BlockIdLength)(Random.nextInt(100).toByte)) + private val totalResBlockSig = ByteStr(Array.fill(Block.BlockIdLength)(Random.nextInt(100).toByte)) + private val reference = Array.fill(Block.BlockIdLength)(Random.nextInt(100).toByte) + private val sender = KeyPair(reference.dropRight(2)) + private val gen = KeyPair(reference) test("MicroBlock with txs bytes/parse roundtrip") { - val ts = System.currentTimeMillis() - 5000 - val tr: TransferTransaction = TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, Waves, 5, Waves, 2, ByteStr.empty, ts + 1).explicitGet() - 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() + val ts = System.currentTimeMillis() - 5000 + val tr: TransferTransaction = + TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, Waves, 5, Waves, 2, ByteStr.empty, ts + 1).explicitGet() + 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() val transactions = Seq(tr, tr2) @@ -57,7 +58,7 @@ class MicroBlockSpecification extends FunSuite with Matchers with MockFactory wi 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() + TransferTransaction.selfSigned(1.toByte, sender, gen.toAddress, Waves, 5, Waves, 1000, ByteStr.empty, System.currentTimeMillis()).explicitGet() val transactions = Seq.fill(Miner.MaxTransactionsPerMicroblock + 1)(transaction) val eitherBlockOrError = MicroBlock.buildAndSign(3.toByte, sender, transactions, prevResBlockSig, totalResBlockSig) diff --git a/node/src/test/scala/com/wavesplatform/lagonaki/unit/WalletSpecification.scala b/node/src/test/scala/com/wavesplatform/lagonaki/unit/WalletSpecification.scala index 043a1f11f1b..b0d3c767bc4 100644 --- a/node/src/test/scala/com/wavesplatform/lagonaki/unit/WalletSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/lagonaki/unit/WalletSpecification.scala @@ -6,10 +6,10 @@ import java.nio.file.Files import cats.syntax.option._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.settings.WalletSettings +import com.wavesplatform.test.FunSuite import com.wavesplatform.wallet.Wallet -import org.scalatest.{FunSuite, Matchers} -class WalletSpecification extends FunSuite with Matchers { +class WalletSpecification extends FunSuite { private val walletSize = 10 val w = Wallet(WalletSettings(None, "cookies".some, ByteStr.decodeBase58("FQgbSAm6swGbtqA3NE8PttijPhT4N3Ufh4bHFAkyVnQz").toOption)) @@ -52,7 +52,7 @@ class WalletSpecification extends FunSuite with Matchers { val w1 = Wallet(WalletSettings(walletFile, "cookies".some, ByteStr.decodeBase58("FQgbSAm6swGbtqA3NE8PttijPhT4N3Ufh4bHFAkyVnQz").toOption)) w1.generateNewAccounts(10) val w1PrivateKeys = w1.privateKeyAccounts - val w1nonce = w1.nonce + val w1nonce = w1.nonce val w2 = Wallet(WalletSettings(walletFile, "cookies".some, None)) w2.privateKeyAccounts.nonEmpty shouldBe true diff --git a/node/src/test/scala/com/wavesplatform/mining/BlockV5Test.scala b/node/src/test/scala/com/wavesplatform/mining/BlockV5Test.scala index e0e3dfdac4e..872bb619d10 100644 --- a/node/src/test/scala/com/wavesplatform/mining/BlockV5Test.scala +++ b/node/src/test/scala/com/wavesplatform/mining/BlockV5Test.scala @@ -19,13 +19,14 @@ import com.wavesplatform.protobuf.block.PBBlocks import com.wavesplatform.settings.{Constants, FunctionalitySettings, TestFunctionalitySettings, WalletSettings, WavesSettings} import com.wavesplatform.state.appender.BlockAppender 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, TxVersion} import com.wavesplatform.utils.Time import com.wavesplatform.utx.UtxPoolImpl import com.wavesplatform.wallet.Wallet -import com.wavesplatform.{BlocksTransactionsHelpers, EitherMatchers, NoShrink, TestTime, TransactionGen, crypto, protobuf} +import com.wavesplatform.{BlocksTransactionsHelpers, TestTime, crypto, protobuf} import io.netty.channel.group.DefaultChannelGroup import io.netty.util.concurrent.GlobalEventExecutor import monix.eval.Task @@ -34,19 +35,13 @@ import monix.reactive.Observer import org.scalacheck.Gen import org.scalatest._ import org.scalatest.enablers.Length -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import scala.concurrent.Await import scala.concurrent.duration._ class BlockV5Test extends FlatSpec - with ScalaCheckPropertyChecks with WithDomain - with Matchers - with EitherMatchers - with TransactionGen - with NoShrink with OptionValues with EitherValues with BlocksTransactionsHelpers { diff --git a/node/src/test/scala/com/wavesplatform/mining/BlockWithMaxBaseTargetTest.scala b/node/src/test/scala/com/wavesplatform/mining/BlockWithMaxBaseTargetTest.scala index 08a2442d39e..9f5661c372d 100644 --- a/node/src/test/scala/com/wavesplatform/mining/BlockWithMaxBaseTargetTest.scala +++ b/node/src/test/scala/com/wavesplatform/mining/BlockWithMaxBaseTargetTest.scala @@ -21,19 +21,19 @@ import com.wavesplatform.transaction.{BlockchainUpdater, GenesisTransaction} import com.wavesplatform.utils.BaseTargetReachedMaximum import com.wavesplatform.utx.UtxPoolImpl import com.wavesplatform.wallet.Wallet -import com.wavesplatform.{TransactionGen, WithDB} +import com.wavesplatform.WithDB +import com.wavesplatform.test.FreeSpec import io.netty.channel.group.DefaultChannelGroup import io.netty.util.concurrent.GlobalEventExecutor import monix.eval.Task import monix.execution.Scheduler import monix.execution.schedulers.SchedulerService import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.{FreeSpec, Matchers} import scala.concurrent.Await import scala.concurrent.duration._ -class BlockWithMaxBaseTargetTest extends FreeSpec with Matchers with WithDB with TransactionGen with DBCacheSettings { +class BlockWithMaxBaseTargetTest extends FreeSpec with WithDB with DBCacheSettings { "base target limit" - { "node should stop if base target greater than maximum in block creation " in { diff --git a/node/src/test/scala/com/wavesplatform/mining/MicroBlockMinerSpec.scala b/node/src/test/scala/com/wavesplatform/mining/MicroBlockMinerSpec.scala index c3beba61f80..5643b59e385 100644 --- a/node/src/test/scala/com/wavesplatform/mining/MicroBlockMinerSpec.scala +++ b/node/src/test/scala/com/wavesplatform/mining/MicroBlockMinerSpec.scala @@ -1,9 +1,6 @@ package com.wavesplatform.mining -import scala.concurrent.duration._ -import scala.util.Random - -import com.wavesplatform.{TestValues, TransactionGen} +import com.wavesplatform.TestValues import com.wavesplatform.account.Alias import com.wavesplatform.block.Block import com.wavesplatform.common.utils._ @@ -12,14 +9,17 @@ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.mining.microblocks.MicroBlockMinerImpl import com.wavesplatform.settings.TestFunctionalitySettings +import com.wavesplatform.test.FlatSpec import com.wavesplatform.transaction.{CreateAliasTransaction, GenesisTransaction, TxVersion} import com.wavesplatform.utils.Schedulers import com.wavesplatform.utx.UtxPoolImpl import monix.execution.Scheduler import org.scalamock.scalatest.PathMockFactory -import org.scalatest.{FlatSpec, Matchers} -class MicroBlockMinerSpec extends FlatSpec with Matchers with PathMockFactory with WithDomain with TransactionGen { +import scala.concurrent.duration._ +import scala.util.Random + +class MicroBlockMinerSpec extends FlatSpec with PathMockFactory with WithDomain { "Micro block miner" should "generate microblocks in flat interval" in { val scheduler = Schedulers.singleThread("test") val acc = TestValues.keyPair diff --git a/node/src/test/scala/com/wavesplatform/mining/MiningFailuresSuite.scala b/node/src/test/scala/com/wavesplatform/mining/MiningFailuresSuite.scala index 5a9847de3fe..b02a396f283 100644 --- a/node/src/test/scala/com/wavesplatform/mining/MiningFailuresSuite.scala +++ b/node/src/test/scala/com/wavesplatform/mining/MiningFailuresSuite.scala @@ -1,6 +1,7 @@ package com.wavesplatform.mining import com.typesafe.config.ConfigFactory +import com.wavesplatform.WithDB import com.wavesplatform.account.KeyPair import com.wavesplatform.block.{Block, SignedBlockHeader} import com.wavesplatform.common.state.ByteStr @@ -9,20 +10,19 @@ import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.settings._ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.{BalanceSnapshot, BlockMinerInfo, Blockchain, NG} +import com.wavesplatform.test.FlatSpec import com.wavesplatform.transaction.BlockchainUpdater import com.wavesplatform.transaction.TxValidationError.BlockFromFuture import com.wavesplatform.utx.UtxPoolImpl import com.wavesplatform.wallet.Wallet -import com.wavesplatform.{TransactionGen, WithDB} import io.netty.channel.group.DefaultChannelGroup import io.netty.util.concurrent.GlobalEventExecutor import monix.eval.Task import monix.execution.Scheduler import monix.execution.Scheduler.Implicits.global import org.scalamock.scalatest.PathMockFactory -import org.scalatest.{FlatSpec, Matchers} -class MiningFailuresSuite extends FlatSpec with Matchers with PathMockFactory with WithDB with TransactionGen { +class MiningFailuresSuite extends FlatSpec with PathMockFactory with WithDB { trait BlockchainUpdaterNG extends Blockchain with BlockchainUpdater with NG behavior of "Miner" diff --git a/node/src/test/scala/com/wavesplatform/mining/MiningWithRewardSuite.scala b/node/src/test/scala/com/wavesplatform/mining/MiningWithRewardSuite.scala index 06a4900656c..07244f6b1ad 100644 --- a/node/src/test/scala/com/wavesplatform/mining/MiningWithRewardSuite.scala +++ b/node/src/test/scala/com/wavesplatform/mining/MiningWithRewardSuite.scala @@ -27,7 +27,8 @@ import monix.execution.Scheduler import org.iq80.leveldb.DB import org.scalacheck.{Arbitrary, Gen} import org.scalatest.compatible.Assertion -import org.scalatest.{AsyncFlatSpec, Matchers} +import org.scalatest.flatspec.AsyncFlatSpec +import org.scalatest.matchers.should.Matchers import scala.concurrent.Future import scala.concurrent.duration._ diff --git a/node/src/test/scala/com/wavesplatform/mining/MultiDimensionalMiningConstraintSuite.scala b/node/src/test/scala/com/wavesplatform/mining/MultiDimensionalMiningConstraintSuite.scala index 73ab91585ea..a2d93855fd2 100644 --- a/node/src/test/scala/com/wavesplatform/mining/MultiDimensionalMiningConstraintSuite.scala +++ b/node/src/test/scala/com/wavesplatform/mining/MultiDimensionalMiningConstraintSuite.scala @@ -1,20 +1,12 @@ package com.wavesplatform.mining import com.wavesplatform.state.{Blockchain, Diff} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Transaction -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.{Arbitrary, Gen} import org.scalamock.scalatest.PathMockFactory -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} - -class MultiDimensionalMiningConstraintSuite - extends FreeSpec - with Matchers - with PropertyChecks - with PathMockFactory - with TransactionGen - with NoShrink { + +class MultiDimensionalMiningConstraintSuite extends FreeSpec with PathMockFactory { "MultiDimensionalMiningConstraint" - { "isFull" - { val emptyConstraintGen: Gen[MultiDimensionalMiningConstraint] = for { diff --git a/node/src/test/scala/com/wavesplatform/mining/OneDimensionalMiningConstraintSuite.scala b/node/src/test/scala/com/wavesplatform/mining/OneDimensionalMiningConstraintSuite.scala index e458b3b42b6..425a3ea2b7e 100644 --- a/node/src/test/scala/com/wavesplatform/mining/OneDimensionalMiningConstraintSuite.scala +++ b/node/src/test/scala/com/wavesplatform/mining/OneDimensionalMiningConstraintSuite.scala @@ -1,14 +1,12 @@ package com.wavesplatform.mining import com.wavesplatform.state.{Blockchain, Diff} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Transaction -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen import org.scalamock.scalatest.PathMockFactory -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class OneDimensionalMiningConstraintSuite extends FreeSpec with Matchers with PropertyChecks with PathMockFactory with TransactionGen with NoShrink { +class OneDimensionalMiningConstraintSuite extends FreeSpec with PathMockFactory { "OneDimensionalMiningConstraint" - { "should be full if the limit is 0, but not overfilled" in { val tank = createConstConstraint(0, 1, "const") diff --git a/node/src/test/scala/com/wavesplatform/mining/ScriptComplexityMiningConstraintSuite.scala b/node/src/test/scala/com/wavesplatform/mining/ScriptComplexityMiningConstraintSuite.scala index 6ec435d2fac..054a7e4186e 100644 --- a/node/src/test/scala/com/wavesplatform/mining/ScriptComplexityMiningConstraintSuite.scala +++ b/node/src/test/scala/com/wavesplatform/mining/ScriptComplexityMiningConstraintSuite.scala @@ -8,21 +8,13 @@ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.settings.WavesSettings import com.wavesplatform.state.diffs.TransactionDiffer import com.wavesplatform.state.{AccountScriptInfo, Blockchain, LeaseBalance} +import com.wavesplatform.test.FlatSpec import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.{DataTransaction, Transaction, TxVersion} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen import org.scalamock.scalatest.PathMockFactory -import org.scalatest.{FlatSpec, Matchers} -import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks -class ScriptComplexityMiningConstraintSuite - extends FlatSpec - with Matchers - with ScalaCheckDrivenPropertyChecks - with PathMockFactory - with TransactionGen - with NoShrink { +class ScriptComplexityMiningConstraintSuite extends FlatSpec with PathMockFactory { private val settings = WavesSettings.fromRootConfig(ConfigFactory.load()) private val complexity = OneDimensionalMiningConstraint(1000, TxEstimators.scriptsComplexity, "MaxScriptsComplexityInBlock") diff --git a/node/src/test/scala/com/wavesplatform/network/BasicMessagesRepoSpec.scala b/node/src/test/scala/com/wavesplatform/network/BasicMessagesRepoSpec.scala index a3b80b76540..5d6764f9d89 100644 --- a/node/src/test/scala/com/wavesplatform/network/BasicMessagesRepoSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/BasicMessagesRepoSpec.scala @@ -3,18 +3,17 @@ package com.wavesplatform.network import java.io.ByteArrayOutputStream import com.google.protobuf.{ByteString, CodedOutputStream, WireFormat} -import com.wavesplatform.TransactionGen 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 org.scalatest._ -class BasicMessagesRepoSpec extends FreeSpec with Matchers with TransactionGen { +class BasicMessagesRepoSpec extends FreeSpec { "PBBlockSpec max length" in { val maxSizedHeader = PBBlock.Header( Byte.MaxValue, diff --git a/node/src/test/scala/com/wavesplatform/network/BlacklistParallelSpecification.scala b/node/src/test/scala/com/wavesplatform/network/BlacklistParallelSpecification.scala index 24f2674d57d..eb0a37d5dbd 100644 --- a/node/src/test/scala/com/wavesplatform/network/BlacklistParallelSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/network/BlacklistParallelSpecification.scala @@ -4,8 +4,9 @@ import java.net.{InetAddress, InetSocketAddress} import com.typesafe.config.ConfigFactory import com.wavesplatform.settings.{NetworkSettings, loadConfig} +import com.wavesplatform.test.FeatureSpec import net.ceedubs.ficus.Ficus._ -import org.scalatest.{FeatureSpec, GivenWhenThen, ParallelTestExecution} +import org.scalatest.{GivenWhenThen, ParallelTestExecution} class BlacklistParallelSpecification extends FeatureSpec with GivenWhenThen with ParallelTestExecution { @@ -21,7 +22,7 @@ class BlacklistParallelSpecification extends FeatureSpec with GivenWhenThen with info("I want to blacklist other peers for certain time") info("So I can give them another chance after") - feature("Blacklist") { + Feature("Blacklist") { val peerDatabase = new PeerDatabaseImpl(networkSettings) @@ -35,7 +36,7 @@ class BlacklistParallelSpecification extends FeatureSpec with GivenWhenThen with def isBlacklisted(address: InetSocketAddress): Boolean = peerDatabase.blacklistedHosts.contains(address.getAddress) - scenario("Peer blacklist another peer") { + Scenario("Peer blacklist another peer") { Given("Peer database is empty") assert(peerDatabase.knownPeers.isEmpty) @@ -65,7 +66,7 @@ class BlacklistParallelSpecification extends FeatureSpec with GivenWhenThen with assert(peerDatabase.knownPeers.contains(address1)) } - scenario("Peer blacklist few peers") { + Scenario("Peer blacklist few peers") { Given("Peer database is empty") assert(peerDatabase.knownPeers.isEmpty) diff --git a/node/src/test/scala/com/wavesplatform/network/BlacklistSpecification.scala b/node/src/test/scala/com/wavesplatform/network/BlacklistSpecification.scala index 4f773f78c96..9d66f41e21c 100644 --- a/node/src/test/scala/com/wavesplatform/network/BlacklistSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/network/BlacklistSpecification.scala @@ -4,8 +4,9 @@ import java.net.{InetAddress, InetSocketAddress} import com.typesafe.config.ConfigFactory import com.wavesplatform.settings.NetworkSettings +import com.wavesplatform.test.FeatureSpec import net.ceedubs.ficus.Ficus._ -import org.scalatest.{FeatureSpec, GivenWhenThen} +import org.scalatest.GivenWhenThen class BlacklistSpecification extends FeatureSpec with GivenWhenThen { private val config = ConfigFactory.parseString("""waves.network { @@ -20,8 +21,8 @@ class BlacklistSpecification extends FeatureSpec with GivenWhenThen { info("I want to blacklist other peers for certain time") info("So I can give them another chance after") - feature("Blacklist") { - scenario("Peer blacklist another peer") { + Feature("Blacklist") { + Scenario("Peer blacklist another peer") { Given("Peer database is empty") val peerDatabase = new PeerDatabaseImpl(networkSettings) diff --git a/node/src/test/scala/com/wavesplatform/network/BrokenConnectionDetectorSpec.scala b/node/src/test/scala/com/wavesplatform/network/BrokenConnectionDetectorSpec.scala index 0e1557610ac..2fe0fe944c0 100644 --- a/node/src/test/scala/com/wavesplatform/network/BrokenConnectionDetectorSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/BrokenConnectionDetectorSpec.scala @@ -1,14 +1,12 @@ package com.wavesplatform.network -import com.wavesplatform.TransactionGen +import com.wavesplatform.test.FreeSpec import io.netty.channel.embedded.EmbeddedChannel import org.scalamock.scalatest.MockFactory -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import scala.concurrent.duration.DurationInt -class BrokenConnectionDetectorSpec extends FreeSpec with Matchers with MockFactory with PropertyChecks with TransactionGen { +class BrokenConnectionDetectorSpec extends FreeSpec with MockFactory { "should not close an active connection until the timeout" in { val handler = new BrokenConnectionDetector(400.millis) diff --git a/node/src/test/scala/com/wavesplatform/network/ChannelGroupExtSpec.scala b/node/src/test/scala/com/wavesplatform/network/ChannelGroupExtSpec.scala index 643665190a9..72dd27611b6 100644 --- a/node/src/test/scala/com/wavesplatform/network/ChannelGroupExtSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/ChannelGroupExtSpec.scala @@ -2,17 +2,17 @@ package com.wavesplatform.network import java.util.concurrent.ConcurrentHashMap +import com.wavesplatform.test.FreeSpec import io.netty.channel._ import io.netty.channel.embedded.EmbeddedChannel import io.netty.channel.group.DefaultChannelGroup import io.netty.util.concurrent.GlobalEventExecutor import org.scalamock.scalatest.MockFactory -import org.scalatest.{FreeSpec, Matchers} import scala.jdk.CollectionConverters._ import scala.util.Random -class ChannelGroupExtSpec extends FreeSpec with Matchers with MockFactory { +class ChannelGroupExtSpec extends FreeSpec with MockFactory { "broadcast" - { "should not send a message to the excluded channels" in { val message = "test" diff --git a/node/src/test/scala/com/wavesplatform/network/ClientSpec.scala b/node/src/test/scala/com/wavesplatform/network/ClientSpec.scala index f46181247cc..da50222fc97 100644 --- a/node/src/test/scala/com/wavesplatform/network/ClientSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/ClientSpec.scala @@ -2,18 +2,18 @@ package com.wavesplatform.network import java.util.concurrent.ConcurrentHashMap -import com.wavesplatform.{TransactionGen, Version} +import com.wavesplatform.Version +import com.wavesplatform.test.FreeSpec import io.netty.buffer.{ByteBuf, Unpooled} import io.netty.channel.Channel import io.netty.channel.embedded.EmbeddedChannel import io.netty.channel.group.ChannelGroup import org.scalamock.scalatest.MockFactory -import org.scalatest.{FreeSpec, Matchers} import scala.concurrent.duration.DurationInt import scala.util.Random -class ClientSpec extends FreeSpec with Matchers with MockFactory with TransactionGen { +class ClientSpec extends FreeSpec with MockFactory { private val clientHandshake = new Handshake( applicationName = "wavesI", diff --git a/node/src/test/scala/com/wavesplatform/network/HandshakeDecoderSpec.scala b/node/src/test/scala/com/wavesplatform/network/HandshakeDecoderSpec.scala index b004611ec26..1050386adef 100644 --- a/node/src/test/scala/com/wavesplatform/network/HandshakeDecoderSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/HandshakeDecoderSpec.scala @@ -3,16 +3,14 @@ package com.wavesplatform.network import java.nio.charset.StandardCharsets import com.google.common.primitives.{Ints, Longs} -import com.wavesplatform.{NoShrink, TransactionGen} +import com.wavesplatform.test.FreeSpec import io.netty.buffer.Unpooled import io.netty.channel.embedded.EmbeddedChannel import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter} import org.scalacheck.{Arbitrary, Gen} import org.scalamock.scalatest.MockFactory -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class HandshakeDecoderSpec extends FreeSpec with Matchers with MockFactory with PropertyChecks with TransactionGen with NoShrink { +class HandshakeDecoderSpec extends FreeSpec with MockFactory { "should read a handshake and remove itself from the pipeline" in { var mayBeDecodedHandshake: Option[Handshake] = None @@ -64,16 +62,15 @@ class HandshakeDecoderSpec extends FreeSpec with Matchers with MockFactory with false } - invalidBytesGen.map { - case List(appNameLen, nodeNameLen, declaredAddressLen) => - Array(appNameLen) ++ - appNameBytes ++ - versionBytes ++ - Array(nodeNameLen) ++ - nodeNameBytes ++ - nonceBytes ++ - Array(declaredAddressLen) ++ - timestampBytes + invalidBytesGen.map { l => + Array(l(0)) ++ + appNameBytes ++ + versionBytes ++ + Array(l(1)) ++ + nodeNameBytes ++ + nonceBytes ++ + Array(l(2)) ++ + timestampBytes } } diff --git a/node/src/test/scala/com/wavesplatform/network/LegacyFrameCodecSpec.scala b/node/src/test/scala/com/wavesplatform/network/LegacyFrameCodecSpec.scala index 634bc273c78..9750dd7182b 100644 --- a/node/src/test/scala/com/wavesplatform/network/LegacyFrameCodecSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/LegacyFrameCodecSpec.scala @@ -4,20 +4,19 @@ import java.net.InetSocketAddress import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.network.message.{MessageSpec, Message => ScorexMessage} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.assets.UpdateAssetInfoTransaction -import com.wavesplatform.{TestValues, TransactionGen, crypto} +import com.wavesplatform.{TestValues, crypto} import io.netty.buffer.Unpooled.wrappedBuffer import io.netty.buffer.{ByteBuf, Unpooled} import io.netty.channel.embedded.EmbeddedChannel import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import scala.concurrent.duration.DurationInt -class LegacyFrameCodecSpec extends FreeSpec with Matchers with MockFactory with PropertyChecks with TransactionGen { +class LegacyFrameCodecSpec extends FreeSpec with MockFactory { "should handle one message" in forAll(issueGen) { origTx => val codec = new LegacyFrameCodec(PeerDatabase.NoOp, 3.minutes) diff --git a/node/src/test/scala/com/wavesplatform/network/MessageCodecSpec.scala b/node/src/test/scala/com/wavesplatform/network/MessageCodecSpec.scala index f48011fe33b..d0f6cb01280 100644 --- a/node/src/test/scala/com/wavesplatform/network/MessageCodecSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/MessageCodecSpec.scala @@ -2,16 +2,13 @@ package com.wavesplatform.network import java.nio.charset.StandardCharsets -import com.wavesplatform.TransactionGen +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.{ProvenTransaction, Transaction} import io.netty.channel.ChannelHandlerContext import io.netty.channel.embedded.EmbeddedChannel -import org.scalamock.scalatest.MockFactory -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class MessageCodecSpec extends FreeSpec with Matchers with MockFactory with PropertyChecks with TransactionGen { +class MessageCodecSpec extends FreeSpec { "should block a sender of invalid messages" in { val codec = new SpiedMessageCodec diff --git a/node/src/test/scala/com/wavesplatform/network/MicroBlockInvSpecSpec.scala b/node/src/test/scala/com/wavesplatform/network/MicroBlockInvSpecSpec.scala index 5b762a246f2..d2d449f0531 100644 --- a/node/src/test/scala/com/wavesplatform/network/MicroBlockInvSpecSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/MicroBlockInvSpecSpec.scala @@ -2,13 +2,10 @@ package com.wavesplatform.network import com.wavesplatform.common.state.ByteStr import com.wavesplatform.crypto._ -import com.wavesplatform.{EitherMatchers, TransactionGen} +import com.wavesplatform.test.FreeSpec import org.scalacheck.Gen -import org.scalatest.concurrent.Eventually -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class MicroBlockInvSpecSpec extends FreeSpec with Matchers with EitherMatchers with PropertyChecks with Eventually with TransactionGen { +class MicroBlockInvSpecSpec extends FreeSpec { private val microBlockInvGen: Gen[MicroBlockInv] = for { acc <- accountGen diff --git a/node/src/test/scala/com/wavesplatform/network/MicroBlockSynchronizerSpec.scala b/node/src/test/scala/com/wavesplatform/network/MicroBlockSynchronizerSpec.scala index 213de8039fc..360fb1e14a3 100644 --- a/node/src/test/scala/com/wavesplatform/network/MicroBlockSynchronizerSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/MicroBlockSynchronizerSpec.scala @@ -2,16 +2,16 @@ package com.wavesplatform.network import com.wavesplatform.common.state.ByteStr import com.wavesplatform.settings.SynchronizationSettings.MicroblockSynchronizerSettings -import com.wavesplatform.{BlockGen, RxScheduler, TransactionGen} +import com.wavesplatform.test.FreeSpec +import com.wavesplatform.{BlockGen, RxScheduler} import io.netty.channel.Channel import io.netty.channel.embedded.EmbeddedChannel import monix.reactive.Observable import monix.reactive.subjects.{PublishSubject => PS} -import org.scalatest._ import scala.concurrent.duration._ -class MicroBlockSynchronizerSpec extends FreeSpec with Matchers with TransactionGen with RxScheduler with BlockGen { +class MicroBlockSynchronizerSpec extends FreeSpec with RxScheduler with BlockGen { override def testSchedulerName: String = "test-microblock-synchronizer" val defaultSettings = MicroblockSynchronizerSettings(1.second, 1.minute, 1.minute) diff --git a/node/src/test/scala/com/wavesplatform/network/RxExtensionLoaderSpec.scala b/node/src/test/scala/com/wavesplatform/network/RxExtensionLoaderSpec.scala index f0fbc27d8d7..d384ec643bb 100644 --- a/node/src/test/scala/com/wavesplatform/network/RxExtensionLoaderSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/RxExtensionLoaderSpec.scala @@ -4,19 +4,19 @@ import com.wavesplatform.block.Block import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.ValidationError import com.wavesplatform.network.RxScoreObserver.ChannelClosedAndSyncWith +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.TxValidationError.GenericError -import com.wavesplatform.{BlockGen, RxScheduler, TransactionGen} +import com.wavesplatform.{BlockGen, RxScheduler} import io.netty.channel.Channel import io.netty.channel.embedded.EmbeddedChannel import io.netty.channel.local.LocalChannel import monix.eval.{Coeval, Task} import monix.reactive.Observable import monix.reactive.subjects.{PublishSubject => PS} -import org.scalatest.{FreeSpec, Matchers} import scala.concurrent.duration._ -class RxExtensionLoaderSpec extends FreeSpec with Matchers with TransactionGen with RxScheduler with BlockGen { +class RxExtensionLoaderSpec extends FreeSpec with RxScheduler with BlockGen { val MaxRollback = 10 type Applier = (Channel, ExtensionBlocks) => Task[Either[ValidationError, Option[BigInt]]] diff --git a/node/src/test/scala/com/wavesplatform/network/RxScoreObserverSpec.scala b/node/src/test/scala/com/wavesplatform/network/RxScoreObserverSpec.scala index 27be242d0f2..6f064195fb4 100644 --- a/node/src/test/scala/com/wavesplatform/network/RxScoreObserverSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/RxScoreObserverSpec.scala @@ -1,16 +1,16 @@ package com.wavesplatform.network import com.wavesplatform.network.RxScoreObserver.SyncWith -import com.wavesplatform.{RxScheduler, TransactionGen} +import com.wavesplatform.RxScheduler +import com.wavesplatform.test.FreeSpec import io.netty.channel.Channel import io.netty.channel.local.LocalChannel import monix.eval.Coeval import monix.reactive.subjects.PublishSubject -import org.scalatest.{FreeSpec, Matchers} import scala.concurrent.duration._ -class RxScoreObserverSpec extends FreeSpec with Matchers with TransactionGen with RxScheduler { +class RxScoreObserverSpec extends FreeSpec with RxScheduler { override def testSchedulerName = "test-rx-score-observer" private def withObserver(f: (Coeval[Seq[SyncWith]], PublishSubject[BigInt], PublishSubject[(Channel, BigInt)], PublishSubject[Channel]) => Any) = { diff --git a/node/src/test/scala/com/wavesplatform/network/TimedTransactionPublisherSpec.scala b/node/src/test/scala/com/wavesplatform/network/TimedTransactionPublisherSpec.scala index 7b568d15168..3792b086b22 100644 --- a/node/src/test/scala/com/wavesplatform/network/TimedTransactionPublisherSpec.scala +++ b/node/src/test/scala/com/wavesplatform/network/TimedTransactionPublisherSpec.scala @@ -4,17 +4,18 @@ import java.util.concurrent.CountDownLatch import com.wavesplatform.account.PublicKey import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.lang.ValidationError +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.smart.script.trace.TracedResult import com.wavesplatform.transaction.{GenesisTransaction, Transaction} import com.wavesplatform.utils.Schedulers import io.netty.channel.embedded.EmbeddedChannel import io.netty.util.HashedWheelTimer import monix.execution.atomic.AtomicInt -import org.scalatest.{BeforeAndAfterAll, FreeSpec, Matchers} +import org.scalatest.BeforeAndAfterAll import scala.concurrent.duration._ -class TimedTransactionPublisherSpec extends FreeSpec with Matchers with BeforeAndAfterAll { +class TimedTransactionPublisherSpec extends FreeSpec with BeforeAndAfterAll { private[this] val timer = new HashedWheelTimer private[this] val scheduler = Schedulers.timeBoundedFixedPool(timer, 1.second, 1, "test-utx-sync") diff --git a/node/src/test/scala/com/wavesplatform/network/peer/PeerDatabaseImplSpecification.scala b/node/src/test/scala/com/wavesplatform/network/peer/PeerDatabaseImplSpecification.scala index 242d69719f9..b2923c577e1 100644 --- a/node/src/test/scala/com/wavesplatform/network/peer/PeerDatabaseImplSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/network/peer/PeerDatabaseImplSpecification.scala @@ -5,12 +5,12 @@ import java.net.InetSocketAddress import java.nio.file.Files import com.typesafe.config.ConfigFactory -import com.wavesplatform.network.PeerDatabaseImpl +import com.wavesplatform.network.{PeerDatabase, PeerDatabaseImpl} import com.wavesplatform.settings.NetworkSettings +import com.wavesplatform.test.FreeSpec import net.ceedubs.ficus.Ficus._ -import org.scalatest.{Matchers, path} -class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { +class PeerDatabaseImplSpecification extends FreeSpec { val host1 = "1.1.1.1" val host2 = "2.2.2.2" @@ -27,31 +27,33 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { private val config2 = ConfigFactory.parseString("""waves.network { | file = null | known-peers = [] - | peers-data-residence-time: 10s + | peers-data-residence-time = 10s |}""".stripMargin).withFallback(ConfigFactory.load()).resolve() private val settings2 = config2.as[NetworkSettings]("waves.network") private val config3 = ConfigFactory.parseString(s"""waves.network { | file = null | known-peers = ["$host1:1"] - | peers-data-residence-time: 2s - | enable-peers-exchange: no + | peers-data-residence-time = 2s + | enable-peers-exchange = no |}""".stripMargin).withFallback(ConfigFactory.load()).resolve() private val settings3 = config3.as[NetworkSettings]("waves.network") - val database = new PeerDatabaseImpl(settings1) - val database2 = new PeerDatabaseImpl(settings2) - val database3 = new PeerDatabaseImpl(settings3) + private def withDatabase(settings: NetworkSettings)(f: PeerDatabase => Unit): Unit = { + val pdb = new PeerDatabaseImpl(settings) + f(pdb) + pdb.close() + } "Peer database" - { - "new peer should not appear in internal buffer but does not appear in database" in { + "new peer should not appear in internal buffer but does not appear in database" in withDatabase(settings1) { database => database.knownPeers shouldBe empty database.addCandidate(address1) database.randomPeer(Set()) should contain(address1) database.knownPeers shouldBe empty } - "new peer should move from internal buffer to database" in { + "new peer should move from internal buffer to database" in withDatabase(settings1) { database => database.knownPeers shouldBe empty database.addCandidate(address1) database.knownPeers shouldBe empty @@ -59,7 +61,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { database.knownPeers.keys should contain(address1) } - "peer should should became obsolete after time" in { + "peer should should became obsolete after time" in withDatabase(settings1) { database => database.touch(address1) database.knownPeers.keys should contain(address1) sleepLong() @@ -67,7 +69,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { database.randomPeer(Set()) shouldBe empty } - "known-peers should be always in database" in { + "known-peers should be always in database" in withDatabase(settings3) { database3 => database3.knownPeers.keys should contain(address1) sleepLong() database3.knownPeers.keys should contain(address1) @@ -75,7 +77,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { database3.knownPeers.keys should contain(address1) } - "touching peer prevent it from obsoleting" in { + "touching peer prevent it from obsoleting" in withDatabase(settings1) { database => database.addCandidate(address1) database.touch(address1) sleepLong() @@ -84,7 +86,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { database.knownPeers.keys should contain(address1) } - "blacklisted peer should disappear from internal buffer and database" in { + "blacklisted peer should disappear from internal buffer and database" in withDatabase(settings1) { database => database.touch(address1) database.addCandidate(address2) database.knownPeers.keys should contain(address1) @@ -100,7 +102,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { database.randomPeer(Set()) should be(empty) } - "random peer should return peers from both from database and buffer" in { + "random peer should return peers from both from database and buffer" in withDatabase(settings2) { database2 => database2.touch(address1) database2.addCandidate(address2) val keys = database2.knownPeers.keys @@ -113,7 +115,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { set should contain(address2) } - "filters out excluded candidates" in { + "filters out excluded candidates" in withDatabase(settings1) { database => database.addCandidate(address1) database.addCandidate(address1) database.addCandidate(address2) @@ -121,7 +123,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { database.randomPeer(Set(address1)) should contain(address2) } - "filters out wildcard addresses" in { + "filters out wildcard addresses" in withDatabase(settings1) { database => database.addCandidate(new InetSocketAddress("0.0.0.0", 6863)) database.randomPeer(Set(address1, address2)) shouldBe None } @@ -133,7 +135,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { val prevConfig = ConfigFactory.parseString(s"""waves.network { | file = "$path" | known-peers = [] - | peers-data-residence-time: 100s + | peers-data-residence-time = 100s |}""".stripMargin).withFallback(ConfigFactory.load()).resolve() val prevSettings = prevConfig.as[NetworkSettings]("waves.network") val prevDatabase = new PeerDatabaseImpl(prevSettings) @@ -143,7 +145,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { val config = ConfigFactory.parseString(s"""waves.network { | file = "$path" | known-peers = [] - | peers-data-residence-time: 100s + | peers-data-residence-time = 100s | enable-blacklisting = no |}""".stripMargin).withFallback(ConfigFactory.load()).resolve() val settings = config.as[NetworkSettings]("waves.network") @@ -156,7 +158,7 @@ class PeerDatabaseImplSpecification extends path.FreeSpecLike with Matchers { val config = ConfigFactory.parseString(s"""waves.network { | file = null | known-peers = [] - | peers-data-residence-time: 100s + | peers-data-residence-time = 100s | enable-blacklisting = no |}""".stripMargin).withFallback(ConfigFactory.load()).resolve() val settings = config.as[NetworkSettings]("waves.network") diff --git a/node/src/test/scala/com/wavesplatform/serialization/DeserTest.scala b/node/src/test/scala/com/wavesplatform/serialization/DeserTest.scala index 8438bf3e48c..211edd8485c 100644 --- a/node/src/test/scala/com/wavesplatform/serialization/DeserTest.scala +++ b/node/src/test/scala/com/wavesplatform/serialization/DeserTest.scala @@ -1,12 +1,12 @@ package com.wavesplatform.serialization -import org.scalatest.{Matchers, PropSpec} +import com.wavesplatform.test.PropSpec -class DeserTest extends PropSpec with Matchers { +class DeserTest extends PropSpec { property("correctly serialized arrays") { val arrays: Seq[Array[Byte]] = Seq(Array(1, 2, 3), Array(), Array(1, 2)) - val bytes = Deser.serializeArrays(arrays) - Deser.parseArrays(bytes).toArray should be (arrays.toArray) + val bytes = Deser.serializeArrays(arrays) + Deser.parseArrays(bytes).toArray should be(arrays.toArray) } property("too big arrays count") { diff --git a/node/src/test/scala/com/wavesplatform/settings/BlockchainSettingsSpecification.scala b/node/src/test/scala/com/wavesplatform/settings/BlockchainSettingsSpecification.scala index 21f8166be39..412d3f9a6be 100644 --- a/node/src/test/scala/com/wavesplatform/settings/BlockchainSettingsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/settings/BlockchainSettingsSpecification.scala @@ -2,11 +2,11 @@ package com.wavesplatform.settings import com.typesafe.config.ConfigFactory import com.wavesplatform.common.state.ByteStr -import org.scalatest.{FlatSpec, Matchers} +import com.wavesplatform.test.FlatSpec import scala.concurrent.duration._ -class BlockchainSettingsSpecification extends FlatSpec with Matchers { +class BlockchainSettingsSpecification extends FlatSpec { "BlockchainSettings" should "read custom values" in { val config = loadConfig(ConfigFactory.parseString("""waves { | directory = "/waves" diff --git a/node/src/test/scala/com/wavesplatform/settings/FeaturesSettingsSpecification.scala b/node/src/test/scala/com/wavesplatform/settings/FeaturesSettingsSpecification.scala index 7e79b82a1d0..c313d209ddb 100644 --- a/node/src/test/scala/com/wavesplatform/settings/FeaturesSettingsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/settings/FeaturesSettingsSpecification.scala @@ -1,11 +1,11 @@ package com.wavesplatform.settings import com.typesafe.config.ConfigFactory +import com.wavesplatform.test.FlatSpec import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ -import org.scalatest.{FlatSpec, Matchers} -class FeaturesSettingsSpecification extends FlatSpec with Matchers { +class FeaturesSettingsSpecification extends FlatSpec { "FeaturesSettings" should "read values" in { val config = ConfigFactory.parseString(""" |waves { diff --git a/node/src/test/scala/com/wavesplatform/settings/MinerSettingsSpecification.scala b/node/src/test/scala/com/wavesplatform/settings/MinerSettingsSpecification.scala index c1f39c8270f..aff3bdfcb25 100644 --- a/node/src/test/scala/com/wavesplatform/settings/MinerSettingsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/settings/MinerSettingsSpecification.scala @@ -1,13 +1,13 @@ package com.wavesplatform.settings import com.typesafe.config.ConfigFactory +import com.wavesplatform.test.FlatSpec import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ -import org.scalatest.{FlatSpec, Matchers} import scala.concurrent.duration._ -class MinerSettingsSpecification extends FlatSpec with Matchers { +class MinerSettingsSpecification extends FlatSpec { "MinerSettings" should "read values" in { val config = ConfigFactory.parseString(""" |waves { diff --git a/node/src/test/scala/com/wavesplatform/settings/NetworkSettingsSpecification.scala b/node/src/test/scala/com/wavesplatform/settings/NetworkSettingsSpecification.scala index 93a69a1d722..4c4c46f6fd9 100644 --- a/node/src/test/scala/com/wavesplatform/settings/NetworkSettingsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/settings/NetworkSettingsSpecification.scala @@ -3,12 +3,12 @@ package com.wavesplatform.settings import java.net.InetSocketAddress import com.typesafe.config.ConfigFactory +import com.wavesplatform.test.FlatSpec import net.ceedubs.ficus.Ficus._ -import org.scalatest.{FlatSpec, Matchers} import scala.concurrent.duration._ -class NetworkSettingsSpecification extends FlatSpec with Matchers { +class NetworkSettingsSpecification extends FlatSpec { "NetworkSpecification" should "read values from config" in { val config = loadConfig(ConfigFactory.parseString("""waves.network { @@ -87,8 +87,11 @@ class NetworkSettingsSpecification extends FlatSpec with Matchers { } it should "fail with IllegalArgumentException on too long node name" in { - val config = loadConfig(ConfigFactory.parseString( - "waves.network.node-name = очень-длинное-название-в-многобайтной-кодировке-отличной-от-однобайтной-кодировки-американского-института-стандартов")) + val config = loadConfig( + ConfigFactory.parseString( + "waves.network.node-name = очень-длинное-название-в-многобайтной-кодировке-отличной-от-однобайтной-кодировки-американского-института-стандартов" + ) + ) intercept[IllegalArgumentException] { config.as[NetworkSettings]("waves.network") } diff --git a/node/src/test/scala/com/wavesplatform/settings/RestAPISettingsSpecification.scala b/node/src/test/scala/com/wavesplatform/settings/RestAPISettingsSpecification.scala index 8c3e23c3b28..6b5e04dea96 100644 --- a/node/src/test/scala/com/wavesplatform/settings/RestAPISettingsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/settings/RestAPISettingsSpecification.scala @@ -1,11 +1,11 @@ package com.wavesplatform.settings import com.typesafe.config.ConfigFactory +import com.wavesplatform.test.FlatSpec import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ -import org.scalatest.{FlatSpec, Matchers} -class RestAPISettingsSpecification extends FlatSpec with Matchers { +class RestAPISettingsSpecification extends FlatSpec { "RestAPISettings" should "read values" in { val config = ConfigFactory.parseString("""waves { | rest-api { diff --git a/node/src/test/scala/com/wavesplatform/settings/SynchronizationSettingsSpecification.scala b/node/src/test/scala/com/wavesplatform/settings/SynchronizationSettingsSpecification.scala index f5a7d671c78..7468db1b2f5 100644 --- a/node/src/test/scala/com/wavesplatform/settings/SynchronizationSettingsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/settings/SynchronizationSettingsSpecification.scala @@ -3,13 +3,13 @@ package com.wavesplatform.settings import com.typesafe.config.ConfigFactory import com.wavesplatform.network.InvalidBlockStorageImpl.InvalidBlockStorageSettings import com.wavesplatform.settings.SynchronizationSettings.{HistoryReplierSettings, MicroblockSynchronizerSettings, UtxSynchronizerSettings} +import com.wavesplatform.test.FlatSpec import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ -import org.scalatest.{FlatSpec, Matchers} import scala.concurrent.duration._ -class SynchronizationSettingsSpecification extends FlatSpec with Matchers { +class SynchronizationSettingsSpecification extends FlatSpec { "SynchronizationSettings" should "read values" in { val config = ConfigFactory.parseString(""" |waves { diff --git a/node/src/test/scala/com/wavesplatform/settings/UtxSettingsSpecification.scala b/node/src/test/scala/com/wavesplatform/settings/UtxSettingsSpecification.scala index d27e09494a9..8a1c09b043e 100644 --- a/node/src/test/scala/com/wavesplatform/settings/UtxSettingsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/settings/UtxSettingsSpecification.scala @@ -1,11 +1,11 @@ package com.wavesplatform.settings import com.typesafe.config.ConfigFactory +import com.wavesplatform.test.FlatSpec import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ -import org.scalatest.{FlatSpec, Matchers} -class UtxSettingsSpecification extends FlatSpec with Matchers { +class UtxSettingsSpecification extends FlatSpec { "UTXSettings" should "read values" in { val config = ConfigFactory.parseString("""waves { | utx { diff --git a/node/src/test/scala/com/wavesplatform/settings/WalletSettingsSpecification.scala b/node/src/test/scala/com/wavesplatform/settings/WalletSettingsSpecification.scala index e256a673803..a0f17b130bd 100644 --- a/node/src/test/scala/com/wavesplatform/settings/WalletSettingsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/settings/WalletSettingsSpecification.scala @@ -2,11 +2,11 @@ package com.wavesplatform.settings import com.typesafe.config.ConfigFactory import com.wavesplatform.common.state.ByteStr +import com.wavesplatform.test.FlatSpec import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ -import org.scalatest.{FlatSpec, Matchers} -class WalletSettingsSpecification extends FlatSpec with Matchers { +class WalletSettingsSpecification extends FlatSpec { "WalletSettings" should "read values from config" in { val config = loadConfig(ConfigFactory.parseString("""waves.wallet { | password: "some string as password" diff --git a/node/src/test/scala/com/wavesplatform/settings/WavesSettingsSpecification.scala b/node/src/test/scala/com/wavesplatform/settings/WavesSettingsSpecification.scala index c6b4c4e1676..6c6e0457351 100644 --- a/node/src/test/scala/com/wavesplatform/settings/WavesSettingsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/settings/WavesSettingsSpecification.scala @@ -3,9 +3,9 @@ package com.wavesplatform.settings import java.io.File import com.typesafe.config.ConfigFactory -import org.scalatest.{FlatSpec, Matchers} +import com.wavesplatform.test.FlatSpec -class WavesSettingsSpecification extends FlatSpec with Matchers { +class WavesSettingsSpecification extends FlatSpec { private def config(configName: String) = { WavesSettings.fromRootConfig( @@ -19,7 +19,8 @@ class WavesSettingsSpecification extends FlatSpec with Matchers { "WavesSettings" should s"read values from default config with $configName overrides" in { val settings = config(configName) - val expected = ConfigFactory.parseString(s"waves.directory = ${com.wavesplatform.settings.defaultDirectory(settings.config)}") + val expected = ConfigFactory + .parseString(s"waves.directory = ${com.wavesplatform.settings.defaultDirectory(settings.config)}") .withFallback(ConfigFactory.load()) .resolve() .getString("waves.directory") diff --git a/node/src/test/scala/com/wavesplatform/state/BlockchainUpdaterImplSpec.scala b/node/src/test/scala/com/wavesplatform/state/BlockchainUpdaterImplSpec.scala index 0279a39b462..c06cb7077a7 100644 --- a/node/src/test/scala/com/wavesplatform/state/BlockchainUpdaterImplSpec.scala +++ b/node/src/test/scala/com/wavesplatform/state/BlockchainUpdaterImplSpec.scala @@ -16,6 +16,7 @@ import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.settings.{WavesSettings, loadConfig} import com.wavesplatform.state.diffs.ENOUGH_AMT +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} @@ -25,13 +26,11 @@ import com.wavesplatform.utils.Time import com.wavesplatform.{EitherMatchers, NTPTime, RequestGen} import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{FreeSpec, Matchers} import scala.util.Random class BlockchainUpdaterImplSpec extends FreeSpec - with Matchers with EitherMatchers with WithDomain with RequestGen diff --git a/node/src/test/scala/com/wavesplatform/state/CommonSpec.scala b/node/src/test/scala/com/wavesplatform/state/CommonSpec.scala index 2a13f8bc2ad..848841c59e1 100644 --- a/node/src/test/scala/com/wavesplatform/state/CommonSpec.scala +++ b/node/src/test/scala/com/wavesplatform/state/CommonSpec.scala @@ -8,11 +8,10 @@ import com.wavesplatform.db.WithDomain import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.GenesisTransaction -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.TestTime +import com.wavesplatform.test.FreeSpec -class CommonSpec extends FreeSpec with Matchers with WithDomain with TransactionGen with PropertyChecks with NoShrink { +class CommonSpec extends FreeSpec with WithDomain { private val time = new TestTime private def nextTs = time.getTimestamp() private val AssetIdLength = 32 diff --git a/node/src/test/scala/com/wavesplatform/state/CompositeBlockchainSpec.scala b/node/src/test/scala/com/wavesplatform/state/CompositeBlockchainSpec.scala new file mode 100644 index 00000000000..e69de29bb2d diff --git a/node/src/test/scala/com/wavesplatform/state/NgStateTest.scala b/node/src/test/scala/com/wavesplatform/state/NgStateTest.scala index 5fd48e4d4a5..d13004b9b91 100644 --- a/node/src/test/scala/com/wavesplatform/state/NgStateTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/NgStateTest.scala @@ -3,14 +3,12 @@ package com.wavesplatform.state import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.history._ import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class NgStateTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink { +class NgStateTest extends PropSpec { def preconditionsAndPayments(amt: Int): Gen[(GenesisTransaction, Seq[TransferTransaction])] = for { diff --git a/node/src/test/scala/com/wavesplatform/state/PortfolioTest.scala b/node/src/test/scala/com/wavesplatform/state/PortfolioTest.scala index 43636049765..e88c79c6159 100644 --- a/node/src/test/scala/com/wavesplatform/state/PortfolioTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/PortfolioTest.scala @@ -2,15 +2,17 @@ package com.wavesplatform.state import java.nio.charset.StandardCharsets -import cats._ +import cats.Monoid import com.wavesplatform.TestValues import com.wavesplatform.common.state.ByteStr +import com.wavesplatform.test.FunSuite import com.wavesplatform.transaction.Asset.IssuedAsset -import org.scalatest.{FunSuite, Matchers} -class PortfolioTest extends FunSuite with Matchers { +class PortfolioTest extends FunSuite { test("pessimistic - should return only withdraws") { - val Seq(fooKey, barKey, bazKey) = Seq("foo", "bar", "baz").map(x => IssuedAsset(ByteStr(x.getBytes(StandardCharsets.UTF_8)))) + val fooKey = IssuedAsset(ByteStr("foo".getBytes(StandardCharsets.UTF_8))) + val barKey = IssuedAsset(ByteStr("bar".getBytes(StandardCharsets.UTF_8))) + val bazKey = IssuedAsset(ByteStr("baz".getBytes(StandardCharsets.UTF_8))) val orig = Portfolio( balance = -10, diff --git a/node/src/test/scala/com/wavesplatform/state/RollbackSpec.scala b/node/src/test/scala/com/wavesplatform/state/RollbackSpec.scala index f8796069f9c..25be14d73e3 100644 --- a/node/src/test/scala/com/wavesplatform/state/RollbackSpec.scala +++ b/node/src/test/scala/com/wavesplatform/state/RollbackSpec.scala @@ -1,39 +1,39 @@ package com.wavesplatform.state -import com.wavesplatform.{history, NoShrink, TestTime, TransactionGen} import com.wavesplatform.account.{Address, KeyPair} import com.wavesplatform.block.Block import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.crypto.SignatureLength import com.wavesplatform.db.WithDomain -import com.wavesplatform.features._ import com.wavesplatform.features.BlockchainFeatures._ +import com.wavesplatform.features._ import com.wavesplatform.history.Domain import com.wavesplatform.it.util.AddressOrAliasExt import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.lang.directives.values.V5 import com.wavesplatform.lang.script.v1.ExprScript -import com.wavesplatform.lang.v1.compiler.{Terms, TestCompiler} +import com.wavesplatform.lang.v1.FunctionHeader 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.lang.v1.FunctionHeader import com.wavesplatform.settings.{TestFunctionalitySettings, WavesSettings} import com.wavesplatform.state.reader.LeaseDetails -import com.wavesplatform.transaction.{CreateAliasTransaction, DataTransaction, GenesisTransaction, Transaction, TxVersion} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError.AliasDoesNotExist import com.wavesplatform.transaction.assets.{IssueTransaction, ReissueTransaction} import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.transfer._ +import com.wavesplatform.transaction.{CreateAliasTransaction, DataTransaction, GenesisTransaction, Transaction, TxVersion} import com.wavesplatform.utils.StringBytes -import org.scalacheck.{Arbitrary, Gen} +import com.wavesplatform.{TestTime, history} import org.scalacheck.Gen.alphaLowerChar -import org.scalatest.{Assertion, Assertions, FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalacheck.{Arbitrary, Gen} +import org.scalatest.{Assertion, Assertions} -class RollbackSpec extends FreeSpec with Matchers with WithDomain with TransactionGen with PropertyChecks with NoShrink { +class RollbackSpec extends FreeSpec with WithDomain { private val time = new TestTime private def nextTs = time.getTimestamp() @@ -810,7 +810,7 @@ class RollbackSpec extends FreeSpec with Matchers with WithDomain with Transacti withDomain(createSettings(Ride4DApps -> 0, BlockV5 -> 0, SmartAccounts -> 0, SynchronousCalls -> 0)) { d => val leaseAmount = smallFeeGen.sample.get val leaseTx = LeaseTransaction.selfSigned(2.toByte, dApp, invoker.toAddress, leaseAmount, setScript.fee, nextTs).explicitGet() - val leaseId = leaseTx.id.value() + val leaseId = leaseTx.id() d.appendBlock(genesis) d.appendBlock(TestBlock.create(nextTs, d.lastBlockId, Seq(setScript, leaseTx))) diff --git a/node/src/test/scala/com/wavesplatform/state/StateHashSpec.scala b/node/src/test/scala/com/wavesplatform/state/StateHashSpec.scala index 982b048b0f3..ed0e72710e4 100644 --- a/node/src/test/scala/com/wavesplatform/state/StateHashSpec.scala +++ b/node/src/test/scala/com/wavesplatform/state/StateHashSpec.scala @@ -6,11 +6,11 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils._ import com.wavesplatform.lang.v1.estimator.ScriptEstimatorV1 import com.wavesplatform.state.StateHash.SectionId +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.smart.script.ScriptCompiler -import org.scalatest.{FreeSpec, Matchers} -class StateHashSpec extends FreeSpec with Matchers { +class StateHashSpec extends FreeSpec { "state hash" - { val stateHash = new StateHashBuilder val address = Address.fromString("3My3KZgFQ3CrVHgz6vGRt8687sH4oAA1qp8").explicitGet() diff --git a/node/src/test/scala/com/wavesplatform/state/TransactionsByAddressSpec.scala b/node/src/test/scala/com/wavesplatform/state/TransactionsByAddressSpec.scala index deb228f572c..20dfcd99039 100644 --- a/node/src/test/scala/com/wavesplatform/state/TransactionsByAddressSpec.scala +++ b/node/src/test/scala/com/wavesplatform/state/TransactionsByAddressSpec.scala @@ -10,15 +10,14 @@ import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.settings.{Constants, GenesisSettings, GenesisTransactionSettings} import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{GenesisTransaction, Transaction} -import com.wavesplatform.{BlockGen, NoShrink} +import com.wavesplatform.BlockGen +import com.wavesplatform.test.FreeSpec import org.scalacheck.Gen import org.scalactic.source.Position -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.concurrent.duration._ -class TransactionsByAddressSpec extends FreeSpec with ScalaCheckDrivenPropertyChecks with BlockGen with WithDomain with Matchers with NoShrink { +class TransactionsByAddressSpec extends FreeSpec with BlockGen with WithDomain { def transferGen(sender: KeyPair, rs: Gen[AddressOrAlias], maxAmount: Long): Gen[TransferTransaction] = for { recipient <- rs diff --git a/node/src/test/scala/com/wavesplatform/state/appender/ExtensionAppenderSpec.scala b/node/src/test/scala/com/wavesplatform/state/appender/ExtensionAppenderSpec.scala index f07124b5fdb..088a0398053 100644 --- a/node/src/test/scala/com/wavesplatform/state/appender/ExtensionAppenderSpec.scala +++ b/node/src/test/scala/com/wavesplatform/state/appender/ExtensionAppenderSpec.scala @@ -1,26 +1,25 @@ package com.wavesplatform.state.appender +import com.wavesplatform.TestTime import com.wavesplatform.block.Block import com.wavesplatform.common.utils._ import com.wavesplatform.db.WithDomain import com.wavesplatform.network.{ExtensionBlocks, InvalidBlockStorage, PeerDatabase} +import com.wavesplatform.test.FlatSpec import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.utils.SystemTime import com.wavesplatform.utx.UtxPoolImpl -import com.wavesplatform.TestTime import monix.execution.Scheduler.Implicits.global import monix.reactive.subjects.ConcurrentSubject -import org.scalamock.scalatest.PathMockFactory -import org.scalatest.{FlatSpec, Matchers} -class ExtensionAppenderSpec extends FlatSpec with Matchers with WithDomain with PathMockFactory { +class ExtensionAppenderSpec extends FlatSpec with WithDomain { "Extension appender" should "drop duplicate transactions from UTX" in withDomain() { d => - val utx = new UtxPoolImpl(SystemTime, d.blockchain, ConcurrentSubject.publish, SettingsFromDefaultConfig.utxSettings) - val time = new TestTime() - val extensionAppender = ExtensionAppender(d.blockchain, utx, d.posSelector, time, stub[InvalidBlockStorage], stub[PeerDatabase], global)(null, _) + val utx = new UtxPoolImpl(SystemTime, d.blockchain, ConcurrentSubject.publish, SettingsFromDefaultConfig.utxSettings) + val time = new TestTime() + val extensionAppender = ExtensionAppender(d.blockchain, utx, d.posSelector, time, InvalidBlockStorage.NoOp, PeerDatabase.NoOp, global)(null, _) d.appendBlock(TxHelpers.genesis(TxHelpers.defaultAddress)) - val tx = TxHelpers.transfer() + val tx = TxHelpers.transfer() val block1 = d.createBlock(Block.PlainBlockVersion, Seq(tx), strictTime = true) utx.putIfNew(tx).resultE.explicitGet() d.appendBlock(tx) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/AssetTransactionsDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/AssetTransactionsDiffTest.scala index 0216a289f57..d0c347661d3 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/AssetTransactionsDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/AssetTransactionsDiffTest.scala @@ -20,18 +20,13 @@ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets._ import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} -import com.wavesplatform.{BlocksTransactionsHelpers, NoShrink, TransactionGen} +import com.wavesplatform.BlocksTransactionsHelpers +import com.wavesplatform.test.PropSpec import fastparse.Parsed import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} class AssetTransactionsDiffTest extends PropSpec - with PropertyChecks - with Matchers - with TransactionGen - with NoShrink with BlocksTransactionsHelpers with WithDomain { @@ -404,13 +399,13 @@ class AssetTransactionsDiffTest property(s"Can update with CompositeBlockchain") { forAll(genesisIssueUpdateWithSecondAsset) { - case (gen, Seq(issue, issue1), signer, update1) => + case (gen, issues, signer, update1) => withDomain(domainSettingsWithFS(assetInfoUpdateEnabled.copy(minAssetInfoUpdateInterval = 0))) { d => val blockchain = d.blockchainUpdater - val genesisBlock = TestBlock.create(gen :+ issue :+ issue1) + val genesisBlock = TestBlock.create(gen ++ issues) d.appendBlock(genesisBlock) - val (keyBlock, Seq(microBlock)) = + val (keyBlock, mbs) = UnsafeBlocks.unsafeChainBaseAndMicro( genesisBlock.id(), Nil, @@ -420,7 +415,10 @@ class AssetTransactionsDiffTest genesisBlock.header.timestamp + 100 ) d.appendBlock(keyBlock) - val microBlockId = d.appendMicroBlock(microBlock) + val microBlockId = d.appendMicroBlock(mbs.head) + + val issue = issues(0) + val issue1 = issues(1) { // Check liquid block val desc = blockchain.assetDescription(issue.asset).get diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/BalanceDiffValidationTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/BalanceDiffValidationTest.scala index b53ba57a056..71cafd268cf 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/BalanceDiffValidationTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/BalanceDiffValidationTest.scala @@ -4,15 +4,13 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithState import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.settings.TestFunctionalitySettings +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.lease.LeaseTransaction import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BalanceDiffValidationTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class BalanceDiffValidationTest extends PropSpec with WithState { val ownLessThatLeaseOut: Gen[(GenesisTransaction, TransferTransaction, LeaseTransaction, LeaseTransaction, TransferTransaction)] = for { master <- accountGen diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/BlockDifferDetailedDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/BlockDifferDetailedDiffTest.scala index 8841bbc3e3c..b6e0b2b0a01 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/BlockDifferDetailedDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/BlockDifferDetailedDiffTest.scala @@ -1,6 +1,5 @@ package com.wavesplatform.state.diffs -import com.wavesplatform.BlockGen import com.wavesplatform.account.Address import com.wavesplatform.block.Block import com.wavesplatform.common.utils.EitherExt2 @@ -12,11 +11,11 @@ import com.wavesplatform.settings.{FunctionalitySettings, TestFunctionalitySetti import com.wavesplatform.state.diffs.BlockDiffer.DetailedDiff import com.wavesplatform.state.{Blockchain, Diff} import com.wavesplatform.transaction.GenesisTransaction +import com.wavesplatform.BlockGen +import com.wavesplatform.test.FreeSpec import org.scalacheck.Gen -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class BlockDifferDetailedDiffTest extends FreeSpec with Matchers with PropertyChecks with BlockGen with WithState { +class BlockDifferDetailedDiffTest extends FreeSpec with BlockGen with WithState { private def assertDetailedDiff(preconditions: Seq[Block], block: Block, fs: FunctionalitySettings = TFS.Enabled)( assertion: (Diff, DetailedDiff) => Unit diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/BlockDifferTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/BlockDifferTest.scala index 3d5e7485062..c9188662889 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/BlockDifferTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/BlockDifferTest.scala @@ -2,7 +2,6 @@ package com.wavesplatform.state.diffs import java.util.concurrent.ThreadLocalRandom -import com.wavesplatform.BlockGen import com.wavesplatform.account.KeyPair import com.wavesplatform.block.Block import com.wavesplatform.common.utils.EitherExt2 @@ -12,9 +11,10 @@ import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.settings.FunctionalitySettings import com.wavesplatform.state.{Blockchain, Diff} import com.wavesplatform.transaction.GenesisTransaction -import org.scalatest.{FreeSpecLike, Matchers} +import com.wavesplatform.BlockGen +import com.wavesplatform.test.FreeSpec -class BlockDifferTest extends FreeSpecLike with Matchers with BlockGen with WithState { +class BlockDifferTest extends FreeSpec with BlockGen with WithState { private val TransactionFee = 10 def randomKeyPair(): KeyPair = { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/CommonValidationTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/CommonValidationTest.scala index 9b811ad3bd6..59852c02652 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/CommonValidationTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/CommonValidationTest.scala @@ -12,6 +12,7 @@ import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.mining.MiningConstraint import com.wavesplatform.settings.{Constants, FunctionalitySettings, TestFunctionalitySettings} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets._ import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} @@ -20,12 +21,9 @@ import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTran import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{CreateAliasTransaction, DataTransaction, GenesisTransaction, PaymentTransaction, Proofs, Transaction, TxVersion} import com.wavesplatform.utils._ -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class CommonValidationTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with WithState with NoShrink { +class CommonValidationTest extends PropSpec with WithState { property("disallows double spending") { val preconditionsAndPayment: Gen[(GenesisTransaction, TransferTransaction)] = for { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/CommonValidationTimeTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/CommonValidationTimeTest.scala index 355bf2cfc74..586b37e203d 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/CommonValidationTimeTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/CommonValidationTimeTest.scala @@ -4,12 +4,10 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithState import com.wavesplatform.settings.TestFunctionalitySettings.Enabled import com.wavesplatform.state._ -import com.wavesplatform.{NoShrink, TransactionGen} +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class CommonValidationTimeTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink with WithState { +class CommonValidationTimeTest extends PropSpec with WithState { property("disallows too old transacions") { forAll(for { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/CreateAliasTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/CreateAliasTransactionDiffTest.scala index d9387757a7e..65cbdd6b761 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/CreateAliasTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/CreateAliasTransactionDiffTest.scala @@ -9,15 +9,13 @@ import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state._ import com.wavesplatform.state.utils.addressTransactions +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.{Asset, CreateAliasTransaction, GenesisTransaction, Transaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class CreateAliasTransactionDiffTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class CreateAliasTransactionDiffTest extends PropSpec with WithState { val fs = TestFunctionalitySettings.Enabled.copy( diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/DataTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/DataTransactionDiffTest.scala index efeab1a90f1..e4a800f8251 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/DataTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/DataTransactionDiffTest.scala @@ -8,13 +8,11 @@ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lagonaki.mocks.TestBlock.{create => block} import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, DataEntry, IntegerDataEntry} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class DataTransactionDiffTest extends PropSpec with PropertyChecks with TransactionGen with NoShrink with WithState { +class DataTransactionDiffTest extends PropSpec with WithState { val fs = TestFunctionalitySettings.Enabled.copy(preActivatedFeatures = Map(BlockchainFeatures.DataTransaction.id -> 0)) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiffTest.scala index 735f4c0b85a..f66e5f90e0a 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ExchangeTransactionDiffTest.scala @@ -19,6 +19,7 @@ import com.wavesplatform.settings.{Constants, FunctionalitySettings, TestFunctio import com.wavesplatform.state._ import com.wavesplatform.state.diffs.ExchangeTransactionDiff.getOrderFeePortfolio import com.wavesplatform.state.diffs.TransactionDiffer.TransactionValidationError +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError.AccountBalanceError import com.wavesplatform.transaction._ @@ -29,19 +30,15 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTransfer import com.wavesplatform.transaction.transfer.{MassTransferTransaction, TransferTransaction} import com.wavesplatform.utils._ -import com.wavesplatform.{NoShrink, TestValues, TransactionGen, crypto} +import com.wavesplatform.{TestValues, crypto} import org.scalacheck.Gen -import org.scalatest.{EitherValues, Inside, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.{EitherValues, Inside} import scala.util.Random class ExchangeTransactionDiffTest extends PropSpec - with PropertyChecks - with TransactionGen with Inside - with NoShrink with WithDomain with EitherValues { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/GenesisTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/GenesisTransactionDiffTest.scala index 7487298e898..d2f27beab3c 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/GenesisTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/GenesisTransactionDiffTest.scala @@ -4,12 +4,10 @@ import cats._ import com.wavesplatform.db.WithState import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.state._ -import com.wavesplatform.{NoShrink, TransactionGen} +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class GenesisTransactionDiffTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class GenesisTransactionDiffTest extends PropSpec with WithState { def nelMax[T](g: Gen[T], max: Int = 10): Gen[List[T]] = Gen.choose(1, max).flatMap(Gen.listOfN(_, g)) property("fails if height != 1") { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/LeaseTransactionsDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/LeaseTransactionsDiffTest.scala index 3132446c90f..7cec3a0f2a6 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/LeaseTransactionsDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/LeaseTransactionsDiffTest.scala @@ -7,19 +7,16 @@ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithDomain import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain._ -import com.wavesplatform.it.util.DoubleExt import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state._ +import com.wavesplatform.test._ import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class LeaseTransactionsDiffTest extends PropSpec with PropertyChecks with WithDomain with TransactionGen with NoShrink { +class LeaseTransactionsDiffTest extends PropSpec with WithDomain { private val allowMultipleLeaseCancelTransactionUntilTimestamp = Long.MaxValue / 2 private val settings = diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/MassTransferTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/MassTransferTransactionDiffTest.scala index 82afe8890a0..f3a34e50acf 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/MassTransferTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/MassTransferTransactionDiffTest.scala @@ -6,16 +6,14 @@ import com.wavesplatform.db.WithState import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lagonaki.mocks.TestBlock.{create => block} import com.wavesplatform.settings.TestFunctionalitySettings +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTransfer import com.wavesplatform.transaction.{Asset, GenesisTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class MassTransferTransactionDiffTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class MassTransferTransactionDiffTest extends PropSpec with WithState { val fs = TestFunctionalitySettings.Enabled.copy(preActivatedFeatures = Map(BlockchainFeatures.MassTransfer.id -> 0)) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/PaymentTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/PaymentTransactionDiffTest.scala index 27f3b559f59..3490c30a710 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/PaymentTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/PaymentTransactionDiffTest.scala @@ -6,13 +6,11 @@ import com.wavesplatform.db.WithState import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.{GenesisTransaction, PaymentTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class PaymentTransactionDiffTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class PaymentTransactionDiffTest extends PropSpec with WithState { val preconditionsAndPayments: Gen[(GenesisTransaction, PaymentTransaction, PaymentTransaction)] = for { master <- accountGen diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ReissueTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ReissueTransactionDiffTest.scala index b3a678c5d0e..2e3bf90bfb0 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ReissueTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ReissueTransactionDiffTest.scala @@ -9,22 +9,14 @@ import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.lang.ValidationError import com.wavesplatform.mining.MiningConstraint import com.wavesplatform.settings.{Constants, FunctionalitySettings, TestFunctionalitySettings} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.assets.{IssueTransaction, ReissueTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.EitherValues -class ReissueTransactionDiffTest - extends PropSpec - with PropertyChecks - with Matchers - with TransactionGen - with WithState - with EitherValues - with NoShrink { +class ReissueTransactionDiffTest extends PropSpec with WithState with EitherValues { import ReissueTransactionDiffTest._ private val beforeActivationScenario = diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ScriptsCountTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ScriptsCountTest.scala index 6979e39007f..f787c636241 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ScriptsCountTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ScriptsCountTest.scala @@ -13,6 +13,7 @@ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state._ import com.wavesplatform.state.reader.CompositeBlockchain +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction._ import com.wavesplatform.transaction.assets._ @@ -21,9 +22,7 @@ import com.wavesplatform.transaction.lease._ import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTransfer import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{NoShrink, TransactionGen} -import org.scalatest.{Inside, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.Inside object ScriptsCountTest { def calculateLegacy(blockchain: Blockchain, tx: Transaction): Int = { @@ -64,7 +63,7 @@ object ScriptsCountTest { } //noinspection NameBooleanParameters -class ScriptsCountTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink with Inside { +class ScriptsCountTest extends PropSpec with WithState with Inside { private val fs = TestFunctionalitySettings.Enabled.copy( preActivatedFeatures = Map( @@ -141,7 +140,8 @@ class ScriptsCountTest extends PropSpec with PropertyChecks with WithState with .create(1.toByte, master.publicKey, IssuedAsset(issueScr.id()), Some(allAllowed), fee, timestamp, Proofs.empty) .explicitGet() data = DataTransaction.selfSigned(1.toByte, master, List(BooleanDataEntry("q", true)), 15000000, timestamp).explicitGet() - tr1 = TransferTransaction.selfSigned(2.toByte, master, acc.toAddress, Waves, 10000000000L, Waves, fee, ByteStr.empty, timestamp) + tr1 = TransferTransaction + .selfSigned(2.toByte, master, acc.toAddress, Waves, 10000000000L, Waves, fee, ByteStr.empty, timestamp) .explicitGet() tr2 = TransferTransaction .selfSigned(2.toByte, master, acc.toAddress, IssuedAsset(issueScr.id()), 1000000000L, Waves, fee, ByteStr.empty, timestamp) @@ -170,17 +170,17 @@ class ScriptsCountTest extends PropSpec with PropertyChecks with WithState with setContractB = SetScriptTransaction.selfSigned(1.toByte, acc, Some(allAllowed), fee, ts).explicitGet() issueScrB = IssueTransaction( - TxVersion.V2, - acc.publicKey, - assetName, - description, - quantity + 1000000000L, - decimals, - true, - Some(allAllowed), - iFee, - timestamp - ).signWith(acc.privateKey) + TxVersion.V2, + acc.publicKey, + assetName, + description, + quantity + 1000000000L, + decimals, + true, + Some(allAllowed), + iFee, + timestamp + ).signWith(acc.privateKey) assetPairB = AssetPair(IssuedAsset(issueScrB.id()), IssuedAsset(issueScr.id())) o1b = Order.buy(2: Byte, master, master.publicKey, assetPairB, 100000001L, 100000001L, timestamp, 10000L, 1) o2b = Order.sell(2: Byte, acc, master.publicKey, assetPairB, 100000001L, 100000001L, timestamp, 10000L, 1) @@ -244,35 +244,34 @@ class ScriptsCountTest extends PropSpec with PropertyChecks with WithState with resetContract = SetScriptTransaction.selfSigned(1.toByte, master, Some(allAllowed), fee, ts + 1).explicitGet() (_, assetName, description, quantity, decimals, _, iFee, timestamp) <- issueParamGen issueSp = IssueTransaction( - TxVersion.V2, - master.publicKey, - assetName, - description, - quantity + 1000000000L, - decimals, - true, - None, - iFee, - timestamp - ) - .signWith(master.privateKey) + TxVersion.V2, + master.publicKey, + assetName, + description, + quantity + 1000000000L, + decimals, + true, + None, + iFee, + timestamp + ).signWith(master.privateKey) sponsorTx = SponsorFeeTransaction.selfSigned(1.toByte, master, IssuedAsset(issueSp.id()), Some(1), fee, timestamp).explicitGet() burnSp = BurnTransaction.selfSigned(2.toByte, master, IssuedAsset(issueSp.id()), 1, fee, timestamp).explicitGet() reissueSp = ReissueTransaction .selfSigned(2.toByte, master, IssuedAsset(issueSp.id()), 1, true, fee, timestamp) .explicitGet() issueScr = IssueTransaction( - TxVersion.V2, - master.publicKey, - assetName, - description, - quantity + 1000000000L, - decimals, - true, - Some(allAllowed), - iFee, - timestamp - ).signWith(master.privateKey) + TxVersion.V2, + master.publicKey, + assetName, + description, + quantity + 1000000000L, + decimals, + true, + Some(allAllowed), + iFee, + timestamp + ).signWith(master.privateKey) burnScr = BurnTransaction.selfSigned(2.toByte, master, IssuedAsset(issueScr.id()), 1, fee, timestamp).explicitGet() reissueScr = ReissueTransaction diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiffTest.scala index 08afb097f67..62be3af6b43 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/SetScriptTransactionDiffTest.scala @@ -14,14 +14,12 @@ import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.lang.v1.compiler.{Terms, TestCompiler} import com.wavesplatform.protobuf.dapp.DAppMeta import com.wavesplatform.settings.{FunctionalitySettings, TestFunctionalitySettings} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class SetScriptTransactionDiffTest extends PropSpec with PropertyChecks with TransactionGen with NoShrink with WithState { +class SetScriptTransactionDiffTest extends PropSpec with WithState { private val fs = TestFunctionalitySettings.Enabled.copy( preActivatedFeatures = Map(BlockchainFeatures.SmartAccounts.id -> 0, BlockchainFeatures.Ride4DApps.id -> 0) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/SponsorshipDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/SponsorshipDiffTest.scala index b69095ae98e..a171c74da62 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/SponsorshipDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/SponsorshipDiffTest.scala @@ -1,6 +1,5 @@ package com.wavesplatform.state.diffs -import com.wavesplatform.TransactionGen import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithState @@ -9,16 +8,15 @@ import com.wavesplatform.features.BlockchainFeatures.BlockV5 import com.wavesplatform.lagonaki.mocks.TestBlock.{create => block} import com.wavesplatform.settings.{Constants, FunctionalitySettings, TestFunctionalitySettings} import com.wavesplatform.state._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.{IssueTransaction, SponsorFeeTransaction} import com.wavesplatform.transaction.lease.LeaseTransaction import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} import com.wavesplatform.utils._ -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class SponsorshipDiffTest extends PropSpec with PropertyChecks with WithState with TransactionGen { +class SponsorshipDiffTest extends PropSpec with WithState { def settings(sponsorshipActivationHeight: Int): FunctionalitySettings = TestFunctionalitySettings.Enabled.copy( diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/TransactionValidationErrorPrintTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/TransactionValidationErrorPrintTest.scala index 0dee5a67c6f..067f952002d 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/TransactionValidationErrorPrintTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/TransactionValidationErrorPrintTest.scala @@ -11,15 +11,16 @@ import com.wavesplatform.lang.utils.compilerContext import com.wavesplatform.lang.v1.compiler.ExpressionCompiler import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.state.diffs.TransactionDiffer.TransactionValidationError +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError.ScriptExecutionError import com.wavesplatform.transaction.assets.{IssueTransaction, SetAssetScriptTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{GenesisTransaction, TxValidationError, TxVersion} import com.wavesplatform.utils._ -import org.scalatest.{EitherValues, Inside, PropSpec} +import org.scalatest.Inside -class TransactionValidationErrorPrintTest extends PropSpec with Inside with WithState with EitherValues { +class TransactionValidationErrorPrintTest extends PropSpec with Inside with WithState { property("output transaction error should be easy to read") { val assetScript = s""" diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/TransferTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/TransferTransactionDiffTest.scala index f7d11669c26..28ca6fc1492 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/TransferTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/TransferTransactionDiffTest.scala @@ -1,6 +1,6 @@ package com.wavesplatform.state.diffs -import cats.implicits._ +import cats.syntax.option._ import com.wavesplatform.account.Address import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 @@ -8,17 +8,15 @@ import com.wavesplatform.db.WithState import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.settings.TestFunctionalitySettings +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError.GenericError import com.wavesplatform.transaction.assets._ import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{Asset, GenesisTransaction, TxValidationError} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class TransferTransactionDiffTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class TransferTransactionDiffTest extends PropSpec with WithState { val preconditionsAndTransfer: Gen[(GenesisTransaction, IssueTransaction, IssueTransaction, TransferTransaction)] = for { master <- accountGen @@ -37,7 +35,7 @@ class TransferTransactionDiffTest extends PropSpec with PropertyChecks with With property("transfers assets to recipient preserving waves invariant") { forAll(preconditionsAndTransfer) { - case ((genesis, issue1, issue2, transfer)) => + case (genesis, issue1, issue2, transfer) => assertDiffAndState(Seq(TestBlock.create(Seq(genesis, issue1, issue2))), TestBlock.create(Seq(transfer))) { case (totalDiff, newState) => assertBalanceInvariant(totalDiff) @@ -62,11 +60,11 @@ class TransferTransactionDiffTest extends PropSpec with PropertyChecks with With recepient <- otherAccountGen(master) ts <- positiveIntGen genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet() - issue: IssueTransaction <- issueReissueBurnGeneratorP(ENOUGH_AMT, master).map(_._1) + issue: IssueTransaction <- issueReissueBurnGeneratorP(ENOUGH_AMT, master).map(_._1) feeIssue: IssueTransaction <- issueV2TransactionGen(master, scriptGen.map(_.some)) - transferV1 <- transferGeneratorP(master, recepient.toAddress, IssuedAsset(issue.id()), IssuedAsset(feeIssue.id())) - transferV2 <- transferGeneratorP(master, recepient.toAddress, IssuedAsset(issue.id()), IssuedAsset(feeIssue.id())) - transfer <- Gen.oneOf(transferV1, transferV2) + transferV1 <- transferGeneratorP(master, recepient.toAddress, IssuedAsset(issue.id()), IssuedAsset(feeIssue.id())) + transferV2 <- transferGeneratorP(master, recepient.toAddress, IssuedAsset(issue.id()), IssuedAsset(feeIssue.id())) + transfer <- Gen.oneOf(transferV1, transferV2) } yield (genesis, issue, feeIssue, transfer) } @@ -78,7 +76,8 @@ class TransferTransactionDiffTest extends PropSpec with PropertyChecks with With genesis: GenesisTransaction = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet() issue: IssueTransaction <- issueReissueBurnGeneratorP(Long.MaxValue, master).map(_._1) asset = IssuedAsset(issue.id()) - transfer = TransferTransaction.selfSigned(1.toByte, master, recepient.toAddress, asset, Long.MaxValue, Waves, 100000, ByteStr.empty, ts) + transfer = TransferTransaction + .selfSigned(1.toByte, master, recepient.toAddress, asset, Long.MaxValue, Waves, 100000, ByteStr.empty, ts) .explicitGet() } yield (genesis, issue, transfer) @@ -110,10 +109,9 @@ class TransferTransactionDiffTest extends PropSpec with PropertyChecks with With forAll(transferWithSmartAssetFee) { case (genesis, issue, fee, transfer) => assertDiffAndState(Seq(TestBlock.create(Seq(genesis))), TestBlock.create(Seq(issue, fee)), smartEnabledFS) { - case (_, state) => { + case (_, state) => val diffOrError = TransferTransactionDiff(state, System.currentTimeMillis())(transfer) diffOrError shouldBe Left(GenericError("Smart assets can't participate in TransferTransactions as a fee")) - } } } } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/BigIntInvokeTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/BigIntInvokeTest.scala index f6fc053d019..7bd1ffe0e42 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/BigIntInvokeTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/BigIntInvokeTest.scala @@ -23,18 +23,14 @@ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{GenesisTransaction, Transaction} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import org.scalatest.{EitherValues, Inside} class BigIntInvokeTest extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink with Inside with WithState with DBCacheSettings @@ -204,7 +200,7 @@ class BigIntInvokeTest fsWithV5 ) { case (diff, _) => - diff.errorMessage(invoke.id.value()) shouldBe None + diff.errorMessage(invoke.id()) shouldBe None diff.scriptsRun shouldBe 2 diff.accountData.head._2.data("key").value shouldBe 1 } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/CallableV4DiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/CallableV4DiffTest.scala index ebb241c6c0b..48f067a624d 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/CallableV4DiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/CallableV4DiffTest.scala @@ -14,17 +14,16 @@ import com.wavesplatform.state.diffs.FeeValidation.{FeeConstants, FeeUnit} import com.wavesplatform.state.diffs.TransactionDiffer.TransactionValidationError import com.wavesplatform.state.diffs.{ENOUGH_AMT, _} import com.wavesplatform.state.{EmptyDataEntry, SponsorshipValue} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.script.trace.{AssetVerifierTrace, InvokeScriptTrace} import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{GenesisTransaction, Transaction, TxVersion} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.EitherValues -class CallableV4DiffTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink with WithDomain with EitherValues { +class CallableV4DiffTest extends PropSpec with WithDomain with EitherValues { property("reissue and burn actions result state") { forAll(paymentPreconditions(feeMultiplier = 0)) { case (genesis, setScript, invoke, issue, master, reissueAmount, burnAmount) => diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/CallableV5LimitTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/CallableV5LimitTest.scala index 41641999051..893d1ef8e85 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/CallableV5LimitTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/CallableV5LimitTest.scala @@ -6,19 +6,18 @@ import com.wavesplatform.db.WithDomain import com.wavesplatform.lang.directives.values.{StdLibVersion, V4, 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.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} -import org.scalatest.{EitherValues, Matchers, PropSpec} +import com.wavesplatform.{TestTime, TransactionGen} +import org.scalatest.EitherValues import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class CallableV5LimitTest extends PropSpec with ScalaCheckPropertyChecks - with Matchers with TransactionGen - with NoShrink with WithDomain with EitherValues { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/DAppDataEntryTypeTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/DAppDataEntryTypeTest.scala index c2d6d8cac5c..3bcb1d840c3 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/DAppDataEntryTypeTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/DAppDataEntryTypeTest.scala @@ -17,18 +17,16 @@ import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{GenesisTransaction, Transaction} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} +import org.scalatest.{EitherValues, Inside} import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class DAppDataEntryTypeTest extends PropSpec with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink with Inside with WithState with DBCacheSettings diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeActionsAvailabilityTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeActionsAvailabilityTest.scala index 36fb708d70b..b290ef532b6 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeActionsAvailabilityTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeActionsAvailabilityTest.scala @@ -1,31 +1,28 @@ package com.wavesplatform.state.diffs.ci +import com.wavesplatform.TestTime import com.wavesplatform.account.Address import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.db.{DBCacheSettings, WithDomain, WithState} +import com.wavesplatform.db.{DBCacheSettings, WithDomain} import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.diffs.ENOUGH_AMT +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} +import org.scalatest.{EitherValues, Inside} import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class InvokeActionsAvailabilityTest extends PropSpec with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink with Inside - with WithState with DBCacheSettings with MockFactory with WithDomain diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeActionsFeeTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeActionsFeeTest.scala index 06724b6d915..ad99a0584d4 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeActionsFeeTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeActionsFeeTest.scala @@ -18,18 +18,14 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{GenesisTransaction, Transaction} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import org.scalatest.{EitherValues, Inside} class InvokeActionsFeeTest extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink with Inside with WithState with DBCacheSettings @@ -98,7 +94,7 @@ class InvokeActionsFeeTest genesis2 <- GenesisTransaction.create(scriptedInvoker.toAddress, ENOUGH_AMT, ts) genesis3 <- GenesisTransaction.create(nonScriptedInvoker.toAddress, ENOUGH_AMT, ts) issue <- IssueTransaction.selfSigned(2.toByte, dAppAcc, "Asset", "Description", ENOUGH_AMT, 8, true, Some(verifier), fee, ts) - asset = IssuedAsset(issue.id.value()) + asset = IssuedAsset(issue.id()) transfer1 <- TransferTransaction.selfSigned(2.toByte, dAppAcc, scriptedInvoker.toAddress, asset, Int.MaxValue, Waves, fee, ByteStr.empty, ts) transfer2 <- TransferTransaction.selfSigned( 2.toByte, @@ -129,12 +125,12 @@ class InvokeActionsFeeTest val invokeFromScripted1 = invokeFromScripted() val invokeFromNonScripted1 = invokeFromNonScripted() d.appendBlock(invokeFromScripted1, invokeFromNonScripted1) - d.blockchain.bestLiquidDiff.get.errorMessage(invokeFromScripted1.id.value()).get.text should include( + d.blockchain.bestLiquidDiff.get.errorMessage(invokeFromScripted1.id()).get.text should include( s"Fee in WAVES for InvokeScriptTransaction (${invokeFromScripted1.fee} in WAVES) " + s"with 6 total scripts invoked " + s"does not exceed minimal value of ${FeeConstants(InvokeScriptTransaction.typeId) * FeeUnit + 6 * ScriptExtraFee} WAVES" ) - d.blockchain.bestLiquidDiff.get.errorMessage(invokeFromNonScripted1.id.value()).get.text should include( + d.blockchain.bestLiquidDiff.get.errorMessage(invokeFromNonScripted1.id()).get.text should include( s"Fee in WAVES for InvokeScriptTransaction (${invokeFromNonScripted1.fee} in WAVES) " + s"with 5 total scripts invoked " + s"does not exceed minimal value of ${FeeConstants(InvokeScriptTransaction.typeId) * FeeUnit + 5 * ScriptExtraFee} WAVES" @@ -146,12 +142,12 @@ class InvokeActionsFeeTest val invokeFromScripted2 = invokeFromScripted() val invokeFromNonScripted2 = invokeFromNonScripted() d.appendBlock(invokeFromScripted2, invokeFromNonScripted2) - d.blockchain.bestLiquidDiff.get.errorMessage(invokeFromScripted2.id.value()).get.text should include( + d.blockchain.bestLiquidDiff.get.errorMessage(invokeFromScripted2.id()).get.text should include( s"Fee in WAVES for InvokeScriptTransaction (${invokeFromScripted2.fee} in WAVES) " + s"with 1 total scripts invoked " + s"does not exceed minimal value of ${FeeConstants(InvokeScriptTransaction.typeId) * FeeUnit + ScriptExtraFee} WAVES" ) - d.blockchain.bestLiquidDiff.get.errorMessage(invokeFromNonScripted2.id.value()) shouldBe None + d.blockchain.bestLiquidDiff.get.errorMessage(invokeFromNonScripted2.id()) shouldBe None } } } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeAssetChecksTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeAssetChecksTest.scala index e12eb6a2d34..02e6678766d 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeAssetChecksTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeAssetChecksTest.scala @@ -16,24 +16,13 @@ import com.wavesplatform.state.{Diff, InvokeScriptResult, NewTransactionInfo, Po import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import org.scalatest.{EitherValues, Inside} -class InvokeAssetChecksTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with Inside - with WithState - with DBCacheSettings - with MockFactory - with WithDomain - with EitherValues { +class InvokeAssetChecksTest extends PropSpec with Inside with WithState with DBCacheSettings with MockFactory with WithDomain with EitherValues { private val time = new TestTime private def ts = time.getTimestamp() @@ -85,7 +74,7 @@ class InvokeAssetChecksTest val miner = TestBlock.defaultSigner.toAddress val dAppAddress = invoke.dAppAddressOrAlias.asInstanceOf[Address] def invokeInfo(succeeded: Boolean) = - Map(invoke.id.value() -> NewTransactionInfo(invoke, Set(invoke.senderAddress, dAppAddress), succeeded)) + Map(invoke.id() -> NewTransactionInfo(invoke, Set(invoke.senderAddress, dAppAddress), succeeded)) val expectedResult = if (activated) { @@ -101,7 +90,7 @@ class InvokeAssetChecksTest miner -> Portfolio.waves(invoke.fee) ), scriptsComplexity = 8, - scriptResults = Map(invoke.id.value() -> InvokeScriptResult(error = Some(ErrorMessage(1, expectingMessage)))) + scriptResults = Map(invoke.id() -> InvokeScriptResult(error = Some(ErrorMessage(1, expectingMessage)))) ) } else { val asset = if (func == "invalidLength") invalidLengthAsset else unexistingAsset @@ -115,7 +104,7 @@ class InvokeAssetChecksTest scriptsRun = 1, scriptsComplexity = 18, scriptResults = Map( - invoke.id.value() -> InvokeScriptResult( + invoke.id() -> InvokeScriptResult( transfers = Seq( InvokeScriptResult.Payment(invoke.senderAddress, Waves, 0), InvokeScriptResult.Payment(invoke.senderAddress, asset, 0) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeFeeMultiplierTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeFeeMultiplierTest.scala index a7b67212d15..af86d8b1c18 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeFeeMultiplierTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeFeeMultiplierTest.scala @@ -13,26 +13,15 @@ import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction, Transaction} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import org.scalatest.EitherValues import scala.util.Try -class InvokeFeeMultiplierTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with Inside - with WithState - with DBCacheSettings - with MockFactory - with WithDomain - with EitherValues { +class InvokeFeeMultiplierTest extends PropSpec with WithState with DBCacheSettings with MockFactory with WithDomain with EitherValues { private val time = new TestTime private def ts = time.getTimestamp() @@ -89,7 +78,7 @@ class InvokeFeeMultiplierTest FunctionHeader.User("init"), List( CONST_STRING("").explicitGet(), - CONST_STRING(issue.id.value().toString).explicitGet(), + CONST_STRING(issue.id().toString).explicitGet(), CONST_STRING("").explicitGet(), CONST_LONG(1), CONST_LONG(1), @@ -102,7 +91,7 @@ class InvokeFeeMultiplierTest ) ) call = Some(FUNCTION_CALL(FunctionHeader.User("buyBack"), Nil)) - payment = Seq(Payment(1, IssuedAsset(issue.id.value()))) + payment = Seq(Payment(1, IssuedAsset(issue.id()))) initInvoke <- InvokeScriptTransaction.selfSigned(1.toByte, master, master.toAddress, initCall, Nil, initFee, Waves, ts) invoke1 <- InvokeScriptTransaction.selfSigned(1.toByte, invoker, master.toAddress, call, payment, fee, Waves, ts) invoke2 <- InvokeScriptTransaction.selfSigned(1.toByte, invoker, master.toAddress, call, payment, fee, Waves, ts) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokePaymentsAvailabilityTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokePaymentsAvailabilityTest.scala index e87d43e3d73..93c717a571b 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokePaymentsAvailabilityTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokePaymentsAvailabilityTest.scala @@ -1,34 +1,23 @@ package com.wavesplatform.state.diffs.ci +import com.wavesplatform.TestTime import com.wavesplatform.account.Address import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.db.{DBCacheSettings, WithDomain, WithState} +import com.wavesplatform.db.{DBCacheSettings, WithDomain} import com.wavesplatform.lang.directives.values.V5 import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.diffs.ENOUGH_AMT +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks - -class InvokePaymentsAvailabilityTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with Inside - with WithState - with DBCacheSettings - with MockFactory - with WithDomain - with EitherValues { +import org.scalatest.{EitherValues, Inside} + +class InvokePaymentsAvailabilityTest extends PropSpec with Inside with DBCacheSettings with MockFactory with WithDomain with EitherValues { import DomainPresets._ private val time = new TestTime diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokePaymentsLimitTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokePaymentsLimitTest.scala index a3154be66f0..3be8f615c1d 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokePaymentsLimitTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokePaymentsLimitTest.scala @@ -1,5 +1,6 @@ package com.wavesplatform.state.diffs.ci +import com.wavesplatform.TestTime import com.wavesplatform.account.Address import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.{DBCacheSettings, WithDomain, WithState} @@ -8,23 +9,17 @@ import com.wavesplatform.lang.directives.values.{StdLibVersion, V4, V5} import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.diffs.ENOUGH_AMT +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{GenesisTransaction, Transaction, TxVersion} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import org.scalatest.{EitherValues, Inside} -class InvokePaymentsLimitTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink +class InvokePaymentsLimitTest extends PropSpec with Inside with WithState with DBCacheSettings diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptTransactionCrosscontractInvokeDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptTransactionCrosscontractInvokeDiffTest.scala index 04c9bcf165b..372dea89a1f 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptTransactionCrosscontractInvokeDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptTransactionCrosscontractInvokeDiffTest.scala @@ -15,27 +15,19 @@ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.{IntegerDataEntry, StringDataEntry} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction, TxVersion} -import com.wavesplatform.{NoShrink, TransactionGen} -import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.EitherValues class InvokeScriptTransactionCrosscontractInvokeDiffTest extends PropSpec - with PropertyChecks - with Matchers - with TransactionGen - with NoShrink - with Inside with WithState with DBCacheSettings - with MockFactory with EitherValues { private val fsWithV5 = TestFunctionalitySettings.Enabled.copy( @@ -142,7 +134,7 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest case (genesisTxs, invokeTx, secondDApp) => assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, bc) => - diff.errorMessage(invokeTx.id.value()) shouldBe None + diff.errorMessage(invokeTx.id()) shouldBe None bc.accountData(secondDApp, invokeEntry1Key) shouldBe Some(IntegerDataEntry(invokeEntry1Key, invokeEntry1Val)) bc.accountData(secondDApp, invokeEntry2Key) shouldBe Some(IntegerDataEntry(invokeEntry2Key, invokeEntry2NewVal)) @@ -230,7 +222,7 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest case (genesisTxs, invokeTx, mainDApp) => assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, bc) => - diff.errorMessage(invokeTx.id.value()) shouldBe None + diff.errorMessage(invokeTx.id()) shouldBe None bc.accountData(mainDApp, invokeEntry1Key) shouldBe Some(IntegerDataEntry(invokeEntry1Key, invokeEntry1Val)) bc.accountData(mainDApp, invokeEntry2Key) shouldBe Some(IntegerDataEntry(invokeEntry2Key, invokeEntry2NewVal)) @@ -414,7 +406,7 @@ class InvokeScriptTransactionCrosscontractInvokeDiffTest case (genesisTxs, invokeTx, thirdAcc, transferAsset, paymentAsset) => assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, bc) => - diff.errorMessage(invokeTx.id.value()) shouldBe None + diff.errorMessage(invokeTx.id()) shouldBe None bc.balance(thirdAcc, IssuedAsset(transferAsset)) shouldBe transferAssetAmount bc.balance(thirdAcc, IssuedAsset(paymentAsset)) shouldBe paymentAssetAmount diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptTransactionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptTransactionDiffTest.scala index d1ccb5dc7ba..95bff3513af 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptTransactionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptTransactionDiffTest.scala @@ -33,6 +33,7 @@ import com.wavesplatform.state._ import com.wavesplatform.state.diffs.FeeValidation.FeeConstants import com.wavesplatform.state.diffs.invoke.InvokeScriptTransactionDiff import com.wavesplatform.state.diffs.{ENOUGH_AMT, FeeValidation, produce} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError._ import com.wavesplatform.transaction.assets._ @@ -43,26 +44,14 @@ import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTr import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{Asset, _} import com.wavesplatform.utils._ -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.{Arbitrary, Gen} import org.scalamock.scalatest.MockFactory import org.scalatest.exceptions.TestFailedException -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.{EitherValues, Inside} import scala.collection.immutable -class InvokeScriptTransactionDiffTest - extends PropSpec - with PropertyChecks - with Matchers - with TransactionGen - with NoShrink - with Inside - with WithState - with DBCacheSettings - with MockFactory - with EitherValues { +class InvokeScriptTransactionDiffTest extends PropSpec with WithState with DBCacheSettings with EitherValues with Inside with MockFactory { private val fs = TestFunctionalitySettings.Enabled.copy( preActivatedFeatures = Map( @@ -214,7 +203,7 @@ class InvokeScriptTransactionDiffTest FUNCTION_CALL( User(FieldNames.ScriptTransfer), List( - recipientAddress match { + (recipientAddress: @unchecked) match { case recipientAddress: Address => FUNCTION_CALL(User("Address"), List(CONST_BYTESTR(ByteStr(recipientAddress.bytes)).explicitGet())) case recipientAddress: Alias => FUNCTION_CALL(User("Alias"), List(CONST_STRING(recipientAddress.name).explicitGet())) }, @@ -2025,7 +2014,9 @@ class InvokeScriptTransactionDiffTest | if (i == "throw" && check) then | throw("Some error") | else if (i == "insufficient fee" && check) then - | [ ${(1 to ContractLimits.MaxCallableActionsAmount(V4)).map(i => s"""Issue("Asset $i", "", 100, 8, true, unit, $i)""").mkString(",")} ] + | [ ${(1 to ContractLimits.MaxCallableActionsAmount(V4)) + .map(i => s"""Issue("Asset $i", "", 100, 8, true, unit, $i)""") + .mkString(",")} ] | else if (i == "negative amount" && check) then | [ ScriptTransfer(inv.caller, -1, a) ] | else if (i == "overflow amount" && check) then @@ -2035,7 +2026,9 @@ class InvokeScriptTransactionDiffTest | else if (i == "max actions" && check) then | [ ${(0 to ContractLimits.MaxCallableActionsAmount(V4)).map(_ => "ScriptTransfer(inv.caller, 10, a)").mkString(",")} ] | else if (i == "invalid data entries" && check) then - | [ ${(0 to ContractLimits.MaxWriteSetSize(V4)).map(x => s"""IntegerEntry("val", $x)""").mkString(",")},ScriptTransfer(inv.caller, 10, a)] + | [ ${(0 to ContractLimits.MaxWriteSetSize(V4)) + .map(x => s"""IntegerEntry("val", $x)""") + .mkString(",")},ScriptTransfer(inv.caller, 10, a)] | else [] |} | @@ -2072,14 +2065,15 @@ class InvokeScriptTransactionDiffTest forAll(scenario) { case (genesisTxs, _, txs) => - txs.foreach { case (name, invokeTx) => - assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { - case (diff, _) => - if (name == "ok") - diff.errorMessage(invokeTx.id.value()) shouldBe empty - else - diff.errorMessage(invokeTx.id.value()) shouldBe defined - } + txs.foreach { + case (name, invokeTx) => + assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { + case (diff, _) => + if (name == "ok") + diff.errorMessage(invokeTx.id()) shouldBe empty + else + diff.errorMessage(invokeTx.id()) shouldBe defined + } } } } @@ -2166,7 +2160,7 @@ class InvokeScriptTransactionDiffTest case (genesisTxs, invokeTx, dApp, assetsComplexity) => assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, bc) => - diff.errorMessage(invokeTx.id.value()) shouldBe defined + diff.errorMessage(invokeTx.id()) shouldBe defined diff.scriptsComplexity should be > 0L } } @@ -2221,7 +2215,7 @@ class InvokeScriptTransactionDiffTest case (genesisTxs, invokeTx, dApp, script) => assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, bc) => - diff.errorMessage(invokeTx.id.value()) shouldBe None + diff.errorMessage(invokeTx.id()) shouldBe None val hash = ByteStr(com.wavesplatform.lang.Global.blake2b256(script.bytes().arr)) bc.accountData(dApp, "hash1").get.value shouldBe hash bc.accountData(dApp, "hash2").get.value shouldBe hash @@ -2287,7 +2281,7 @@ class InvokeScriptTransactionDiffTest case (genesisTxs, invokeTx, dApp) => assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, bc) => - diff.errorMessage(invokeTx.id.value()) shouldBe None + diff.errorMessage(invokeTx.id()) shouldBe None bc.accountData(dApp, "key") shouldBe Some(IntegerDataEntry("key", 1)) bc.accountData(dApp, "bar") shouldBe Some(IntegerDataEntry("bar", 1)) } @@ -2352,7 +2346,7 @@ class InvokeScriptTransactionDiffTest case (genesisTxs, invokeTx, _) => assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, _) => - diff.errorMessage(invokeTx.id.value()) shouldBe None + diff.errorMessage(invokeTx.id()) shouldBe None diff.scriptsComplexity shouldBe 108 diff.scriptsRun shouldBe 2 } @@ -2460,8 +2454,9 @@ class InvokeScriptTransactionDiffTest assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, bc) => diff.scriptResults(invokeTx.id()).error shouldBe None - val List(l: InvokeScriptResult.Lease, l1: InvokeScriptResult.Lease) = diff.scriptResults(invokeTx.id()).leases - val List(l2) = diff.scriptResults(invokeTx.id()).leaseCancels + val l = diff.scriptResults(invokeTx.id()).leases(0) + val l1 = diff.scriptResults(invokeTx.id()).leases(1) + val l2 = diff.scriptResults(invokeTx.id()).leaseCancels(0) l.amount shouldBe 13 l.recipient shouldBe service l1.amount shouldBe 23 @@ -2574,8 +2569,9 @@ class InvokeScriptTransactionDiffTest assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, bc) => diff.scriptResults(invokeTx.id()).error shouldBe None - val List(l:InvokeScriptResult.Lease, l1:InvokeScriptResult.Lease) = diff.scriptResults(invokeTx.id()).leases - val List(l2) = diff.scriptResults(invokeTx.id()).leaseCancels + val l = diff.scriptResults(invokeTx.id()).leases(0) + val l1 = diff.scriptResults(invokeTx.id()).leases(1) + val l2 = diff.scriptResults(invokeTx.id()).leaseCancels(0) l.amount shouldBe 13 l.recipient shouldBe service l1.amount shouldBe 23 @@ -2691,7 +2687,6 @@ class InvokeScriptTransactionDiffTest } } - property("non-NFT issue work") { def contract(): DApp = { val expr = { @@ -3745,7 +3740,7 @@ class InvokeScriptTransactionDiffTest case (genesisTxs, invokeTx, clientDApp, serviceDApp, transferAsset) => assertDiffAndState(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { case (diff, bc) => - diff.errorMessage(invokeTx.id.value()) shouldBe None + diff.errorMessage(invokeTx.id()) shouldBe None bc.accountData(clientDApp, "key") shouldBe Some(IntegerDataEntry("key", 1)) bc.accountData(serviceDApp, "bar") shouldBe Some(IntegerDataEntry("bar", 1)) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptV5LimitsTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptV5LimitsTest.scala index aff4ed6e067..0287777f717 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptV5LimitsTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/InvokeScriptV5LimitsTest.scala @@ -10,17 +10,17 @@ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.contract.DApp.{CallableAnnotation, CallableFunction} -import com.wavesplatform.lang.directives.values.{DApp => DAppType, _} import com.wavesplatform.lang.directives.DirectiveSet +import com.wavesplatform.lang.directives.values.{DApp => DAppType, _} import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.script.{ContractScript, Script} import com.wavesplatform.lang.v1.FunctionHeader.{Native, User} import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.compiler.Terms._ +import com.wavesplatform.lang.v1.evaluator.FunctionIds import com.wavesplatform.lang.v1.evaluator.FunctionIds.{CREATE_LIST, THROW} import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.{FieldNames, WavesContext} import com.wavesplatform.lang.v1.evaluator.ctx.impl.{CryptoContext, PureContext} -import com.wavesplatform.lang.v1.evaluator.FunctionIds import com.wavesplatform.lang.v1.parser.{Expressions, Parser} import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.{FunctionHeader, compiler} @@ -29,30 +29,19 @@ import com.wavesplatform.protobuf.dapp.DAppMeta import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state._ import com.wavesplatform.state.diffs.{ENOUGH_AMT, produce} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets._ import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{Asset, _} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.EitherValues import scala.collection.immutable -class InvokeScriptV5LimitsTest - extends PropSpec - with PropertyChecks - with Matchers - with TransactionGen - with NoShrink - with Inside - with WithState - with DBCacheSettings - with MockFactory - with EitherValues { +class InvokeScriptV5LimitsTest extends PropSpec with WithState with DBCacheSettings with MockFactory with EitherValues { private val fsWithV5 = TestFunctionalitySettings.Enabled.copy( preActivatedFeatures = Map( @@ -195,7 +184,7 @@ class InvokeScriptV5LimitsTest FUNCTION_CALL( User(FieldNames.ScriptTransfer), List( - recipientAddress match { + (recipientAddress: @unchecked) match { case recipientAddress: Address => FUNCTION_CALL(User("Address"), List(CONST_BYTESTR(ByteStr(recipientAddress.bytes)).explicitGet())) case recipientAddress: Alias => FUNCTION_CALL(User("Alias"), List(CONST_STRING(recipientAddress.name).explicitGet())) }, @@ -633,8 +622,8 @@ class InvokeScriptV5LimitsTest forAll(scenario) { case (genesisTxs, invokeTx, dApp, service) => - assertDiffEi(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { - ei => ei should produce("Actions count limit is exceeded") + assertDiffEi(Seq(TestBlock.create(genesisTxs)), TestBlock.create(Seq(invokeTx), Block.ProtoBlockVersion), fsWithV5) { ei => + ei should produce("Actions count limit is exceeded") } } } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/LeaseActionDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/LeaseActionDiffTest.scala index 17d0abb33e7..69755a621dd 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/LeaseActionDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/LeaseActionDiffTest.scala @@ -1,6 +1,8 @@ package com.wavesplatform.state.diffs.ci -import cats.implicits._ +import cats.instances.list._ +import cats.syntax.traverse._ +import com.wavesplatform.TestTime import com.wavesplatform.account.{Address, Alias} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 @@ -15,19 +17,17 @@ import com.wavesplatform.lang.v1.traits.domain.{Lease, Recipient} import com.wavesplatform.settings.{FunctionalitySettings, TestFunctionalitySettings} import com.wavesplatform.state.diffs.{ENOUGH_AMT, produce} import com.wavesplatform.state.{LeaseBalance, Portfolio} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{Authorized, GenesisTransaction, Transaction} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} import org.scalacheck.Gen import org.scalatest.exceptions.TestFailedException -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import scala.util.Random -class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink with WithDomain with EitherValues { +class LeaseActionDiffTest extends PropSpec with WithDomain { private val time = new TestTime private def ts = time.getTimestamp() @@ -206,13 +206,13 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit i => LeaseTransaction.selfSigned(2.toByte, dAppAcc, invoker.toAddress, leaseTxAmount1, fee, ts + i) ) leaseToDApp <- LeaseTransaction.selfSigned(2.toByte, invoker, dAppAcc.toAddress, leaseTxAmount2, fee, ts + 100) - calculatedId = Lease.calculateId(Lease(recipient, leaseAmount, 0), invoke.id.value()) + calculatedId = Lease.calculateId(Lease(recipient, leaseAmount, 0), invoke.id()) leaseCancelId = if (cancelLeaseActionByTx) calculatedId - else if (cancelLeaseFromInvoker) leaseToDApp.id.value() - else leasesFromDApp.head.id.value() + else if (cancelLeaseFromInvoker) leaseToDApp.id() + else leasesFromDApp.head.id() leaseCancelAcc = if (cancelLeaseFromInvoker) invoker else dAppAcc leaseCancel <- LeaseCancelTransaction.signed(2.toByte, leaseCancelAcc.publicKey, leaseCancelId, fee, ts + 100, leaseCancelAcc.privateKey) - multipleCancelDApp = multipleLeaseCancelsDApp(leasesFromDApp.map(_.id.value())) + multipleCancelDApp = multipleLeaseCancelsDApp(leasesFromDApp.map(_.id())) dApp = if (useLeaseCancelDApp) multipleCancelDApp else customDApp.getOrElse(singleLeaseDApp(recipient, leaseAmount)) setDApp <- SetScriptTransaction.selfSigned(1.toByte, dAppAcc, Some(dApp), setScriptFee, ts + 100) preparingTxs = List(genesis, genesis2) ::: aliasTxs ::: List(setDApp) @@ -485,7 +485,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()) shouldBe empty + diff.errorMessage(invoke.id()) shouldBe empty diff.portfolios(invoker) shouldBe Portfolio(-invoke.fee) diff.portfolios(dAppAcc) shouldBe Portfolio(-leaseCancelTx.fee) } @@ -501,7 +501,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "InvalidAddress(Wrong addressBytes length: expected: 26, actual: 0)" + diff.errorMessage(invoke.id()).get.text shouldBe "InvalidAddress(Wrong addressBytes length: expected: 26, actual: 0)" } } } @@ -515,7 +515,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "InvalidAddress(Wrong addressBytes length: expected: 26, actual: 10)" + diff.errorMessage(invoke.id()).get.text shouldBe "InvalidAddress(Wrong addressBytes length: expected: 26, actual: 10)" } } } @@ -532,7 +532,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "InvalidAddress(Bad address checksum)" + diff.errorMessage(invoke.id()).get.text shouldBe "InvalidAddress(Bad address checksum)" } } } @@ -546,7 +546,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "Alias 'alias:T:alias2' does not exists." + diff.errorMessage(invoke.id()).get.text shouldBe "Alias 'alias:T:alias2' does not exists." } } } @@ -560,7 +560,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe s"Alias should contain only following characters: ${Alias.AliasAlphabet}" + diff.errorMessage(invoke.id()).get.text shouldBe s"Alias should contain only following characters: ${Alias.AliasAlphabet}" } } } @@ -574,7 +574,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "NonPositiveAmount(0,waves)" + diff.errorMessage(invoke.id()).get.text shouldBe "NonPositiveAmount(0,waves)" } } } @@ -588,7 +588,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "NonPositiveAmount(-100,waves)" + diff.errorMessage(invoke.id()).get.text shouldBe "NonPositiveAmount(-100,waves)" } } } @@ -620,7 +620,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe s"Cannot lease more than own: Balance: $dAppBalance, already leased: 0" + diff.errorMessage(invoke.id()).get.text shouldBe s"Cannot lease more than own: Balance: $dAppBalance, already leased: 0" } } } @@ -629,14 +629,15 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit val setScriptFee = ciFee(1).sample.get val dAppBalance = ENOUGH_AMT - setScriptFee forAll(leasePreconditions(customSetScriptFee = Some(setScriptFee), customAmount = Some(dAppBalance))) { - case (preparingTxs, invoke, _, _, _, leaseTxs @ List(leaseFromDApp, _), _) => + case (preparingTxs, invoke, _, _, _, leaseTxs, _) => + val leaseFromDApp = leaseTxs.head assertDiffAndState( Seq(TestBlock.create(preparingTxs ::: leaseTxs)), TestBlock.create(Seq(invoke)), v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe + diff.errorMessage(invoke.id()).get.text shouldBe s"Cannot lease more than own: Balance: ${dAppBalance - leaseFromDApp.fee}, already leased: ${leaseFromDApp.amount}" } } @@ -653,8 +654,8 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - val id = Lease.calculateId(Lease(recipient, amount, nonce = 0), invoke.id.value()) - diff.errorMessage(invoke.id.value()).get.text shouldBe s"Lease with id=$id is already in the state" + val id = Lease.calculateId(Lease(recipient, amount, nonce = 0), invoke.id()) + diff.errorMessage(invoke.id()).get.text shouldBe s"Lease with id=$id is already in the state" } } } @@ -668,7 +669,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "Cannot lease to self" + diff.errorMessage(invoke.id()).get.text shouldBe "Cannot lease to self" } } } @@ -682,7 +683,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "Cannot lease to self" + diff.errorMessage(invoke.id()).get.text shouldBe "Cannot lease to self" } } } @@ -699,7 +700,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()) shouldBe empty + diff.errorMessage(invoke.id()) shouldBe empty diff.portfolios(invoker) shouldBe Portfolio(-invoke.fee) diff.portfolios(dAppAcc) shouldBe Portfolio(lease = LeaseBalance(in = 0, out = amount * 10)) diff.portfolios(recipient) shouldBe Portfolio(lease = LeaseBalance(in = amount * 10, out = 0)) @@ -719,7 +720,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "Actions count limit is exceeded" + diff.errorMessage(invoke.id()).get.text shouldBe "Actions count limit is exceeded" } } } @@ -766,7 +767,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text should include("is already in the state") + diff.errorMessage(invoke.id()).get.text should include("is already in the state") } } } @@ -782,7 +783,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()) shouldBe empty + diff.errorMessage(invoke.id()) shouldBe empty diff.portfolios(invoker) shouldBe Portfolio(-invoke.fee) diff.portfolios(dAppAcc) shouldBe Portfolio(lease = LeaseBalance(in = 0, out = amount)) diff.portfolios(recipient) shouldBe Portfolio(lease = LeaseBalance(in = amount, 0)) @@ -792,7 +793,8 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit property(s"LeaseCancel action for lease performed via LeaseTransaction") { forAll(leasePreconditions(useLeaseCancelDApp = true)) { - case (preparingTxs, invoke, _, dAppAcc, invoker, leaseTxs @ List(leaseFromDApp, _), _) => + case (preparingTxs, invoke, _, dAppAcc, invoker, leaseTxs, _) => + val leaseFromDApp = leaseTxs.head assertDiffAndState( Seq(TestBlock.create(preparingTxs ++ leaseTxs)), TestBlock.create(Seq(invoke)), @@ -815,7 +817,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe s"Lease with id=$leaseId not found" + diff.errorMessage(invoke.id()).get.text shouldBe s"Lease with id=$leaseId not found" } } } @@ -830,7 +832,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe s"Lease id=$leaseId has invalid length = 1 byte(s) while expecting 32" + diff.errorMessage(invoke.id()).get.text shouldBe s"Lease id=$leaseId has invalid length = 1 byte(s) while expecting 32" } } } @@ -846,8 +848,8 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - val leaseId = Lease.calculateId(Lease(recipient, amount, nonce = 0), invoke.id.value()) - diff.errorMessage(invoke.id.value()).get.text shouldBe s"Duplicate LeaseCancel id(s): $leaseId" + val leaseId = Lease.calculateId(Lease(recipient, amount, nonce = 0), invoke.id()) + diff.errorMessage(invoke.id()).get.text shouldBe s"Duplicate LeaseCancel id(s): $leaseId" } } } @@ -861,21 +863,22 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "Cannot cancel already cancelled lease" + diff.errorMessage(invoke.id()).get.text shouldBe "Cannot cancel already cancelled lease" } } } property(s"10 LeaseCancel actions") { forAll(leasePreconditions(useLeaseCancelDApp = true, leaseCancelCount = 10)) { - case (preparingTxs, invoke, _, dAppAcc, invoker, leaseTxs :+ _, _) => + case (preparingTxs, invoke, _, dAppAcc, invoker, ltx, _) => + val leaseTxs = ltx.init assertDiffAndState( Seq(TestBlock.create(preparingTxs ++ leaseTxs)), TestBlock.create(Seq(invoke)), v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()) shouldBe empty + diff.errorMessage(invoke.id()) shouldBe empty diff.portfolios(invoker) shouldBe Portfolio(-invoke.fee, LeaseBalance(in = -leaseTxs.map(_.amount).sum, out = 0)) diff.portfolios(dAppAcc) shouldBe Portfolio(0, LeaseBalance(in = 0, out = -leaseTxs.map(_.amount).sum)) } @@ -884,14 +887,14 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit property(s"31 LeaseCancel actions") { forAll(leasePreconditions(useLeaseCancelDApp = true, leaseCancelCount = 31)) { - case (preparingTxs, invoke, _, _, _, leaseTxs :+ _, _) => + case (preparingTxs, invoke, _, _, _, ltx, _) => assertDiffAndState( - Seq(TestBlock.create(preparingTxs ++ leaseTxs)), + Seq(TestBlock.create(preparingTxs ++ ltx.init)), TestBlock.create(Seq(invoke)), v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "Actions count limit is exceeded" + diff.errorMessage(invoke.id()).get.text shouldBe "Actions count limit is exceeded" } } } @@ -912,7 +915,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()) shouldBe empty + diff.errorMessage(invoke.id()) shouldBe empty diff.portfolios(invoker) shouldBe Portfolio(-invoke.fee) diff.portfolios(dAppAcc) shouldBe Portfolio(-transfersCount, lease = LeaseBalance(in = 0, out = leaseAmount)) diff.portfolios(recipient) shouldBe Portfolio(transfersCount, lease = LeaseBalance(in = leaseAmount, out = 0)) @@ -935,7 +938,7 @@ class LeaseActionDiffTest extends PropSpec with PropertyChecks with Matchers wit v5Features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()).get.text shouldBe "Actions count limit is exceeded" + diff.errorMessage(invoke.id()).get.text shouldBe "Actions count limit is exceeded" } } } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/ListParamInvokeTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/ListParamInvokeTest.scala index 568b83e7cfb..1ddec8b90a3 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/ListParamInvokeTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/ListParamInvokeTest.scala @@ -16,15 +16,14 @@ import com.wavesplatform.lang.v1.evaluator.FunctionIds import com.wavesplatform.protobuf.dapp.DAppMeta import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state.diffs.{ENOUGH_AMT, produce} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.Inside -class ListParamInvokeTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink with WithState with Inside { +class ListParamInvokeTest extends PropSpec with WithState with Inside { property("unactivated") { // precompiled to avoid compilation error val v3DApp = diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/MultiPaymentInvokeDiffTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/MultiPaymentInvokeDiffTest.scala index e1ad77f6623..8c406e95739 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/MultiPaymentInvokeDiffTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/MultiPaymentInvokeDiffTest.scala @@ -1,6 +1,6 @@ package com.wavesplatform.state.diffs.ci -import cats.implicits._ +import cats.syntax.option._ import com.wavesplatform.account.KeyPair import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 @@ -14,16 +14,14 @@ import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.settings.{Constants, TestFunctionalitySettings} import com.wavesplatform.state.Diff import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class MultiPaymentInvokeDiffTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink with WithState with Inside { +class MultiPaymentInvokeDiffTest extends PropSpec with WithState { private val oldVersions = Gen.oneOf(V1, V2, V3) property("multi payment with verifier and transfer set") { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/OverdraftTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/OverdraftTest.scala index e2ba84dad9a..097e20f18cb 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/OverdraftTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/OverdraftTest.scala @@ -13,17 +13,15 @@ import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.settings.{FunctionalitySettings, TestFunctionalitySettings} import com.wavesplatform.state.diffs.FeeValidation.FeeConstants import com.wavesplatform.state.diffs.{ENOUGH_AMT, FeeValidation, produce} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class OverdraftTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink with WithState with Inside { +class OverdraftTest extends PropSpec with WithState { private val InvokeFee = FeeConstants(InvokeScriptTransaction.typeId) * FeeValidation.FeeUnit private val SetScriptFee = FeeConstants(SetScriptTransaction.typeId) * FeeValidation.FeeUnit private val IssueFee = FeeConstants(IssueTransaction.typeId) * FeeValidation.FeeUnit diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/ScriptTransferByAliasTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/ScriptTransferByAliasTest.scala index 84e9e0c52ad..9aa2884dd9a 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/ScriptTransferByAliasTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/ScriptTransferByAliasTest.scala @@ -2,7 +2,7 @@ package com.wavesplatform.state.diffs.ci import com.wavesplatform.account.{Address, Alias} import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.db.{DBCacheSettings, WithDomain, WithState} +import com.wavesplatform.db.WithDomain import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.directives.values.V4 import com.wavesplatform.lang.script.Script @@ -13,24 +13,11 @@ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{CreateAliasTransaction, GenesisTransaction, Transaction} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen -import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -class ScriptTransferByAliasTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with Inside - with WithState - with DBCacheSettings - with MockFactory - with WithDomain - with EitherValues { +class ScriptTransferByAliasTest extends PropSpec with WithDomain { private val time = new TestTime private def ts = time.getTimestamp() @@ -100,7 +87,7 @@ class ScriptTransferByAliasTest genesis3 <- GenesisTransaction.create(receiver.toAddress, ENOUGH_AMT, ts) createAlias <- CreateAliasTransaction.selfSigned(2.toByte, receiver, Alias.create(alias).explicitGet(), fee, ts) issue <- IssueTransaction.selfSigned(2.toByte, dAppAcc, "Asset", "Description", ENOUGH_AMT, 8, true, Some(verifier), fee, ts) - asset = IssuedAsset(issue.id.value()) + asset = IssuedAsset(issue.id()) setDApp <- SetScriptTransaction.selfSigned(1.toByte, dAppAcc, Some(dApp(asset)), fee, ts) invoke = () => InvokeScriptTransaction.selfSigned(1.toByte, invoker, dAppAcc.toAddress, None, Nil, fee, Waves, ts).explicitGet() } yield (List(genesis, genesis2, genesis3, createAlias, issue, setDApp), invoke, asset, receiver.toAddress) @@ -113,7 +100,7 @@ class ScriptTransferByAliasTest val invoke1 = invoke() d.appendBlock(invoke1) - d.blockchain.bestLiquidDiff.get.errorMessage(invoke1.id.value()).get.text should include( + d.blockchain.bestLiquidDiff.get.errorMessage(invoke1.id()).get.text should include( s"Transaction is not allowed by script of the asset $asset: alias expected!" ) @@ -122,7 +109,7 @@ class ScriptTransferByAliasTest val invoke2 = invoke() d.appendBlock(invoke2) - d.blockchain.bestLiquidDiff.get.errorMessage(invoke2.id.value()) shouldBe None + d.blockchain.bestLiquidDiff.get.errorMessage(invoke2.id()) shouldBe None d.balance(receiver, asset) shouldBe transferAmount } } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppComplexityCountTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppComplexityCountTest.scala index b21ae23803c..aa00822b253 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppComplexityCountTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppComplexityCountTest.scala @@ -1,11 +1,14 @@ package com.wavesplatform.state.diffs.ci -import cats.implicits._ +import cats.instances.list._ +import cats.instances.map._ +import cats.syntax.semigroup._ +import cats.syntax.traverse._ import com.wavesplatform.account.Address import com.wavesplatform.block.Block import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.db.{DBCacheSettings, WithState} +import com.wavesplatform.db.WithState import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.lang.directives.values.V5 @@ -15,6 +18,7 @@ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state.Portfolio import com.wavesplatform.state.diffs.{ENOUGH_AMT, produce} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment @@ -22,23 +26,9 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{GenesisTransaction, Transaction, TxVersion} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -class SyncDAppComplexityCountTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with Inside - with WithState - with DBCacheSettings - with MockFactory - with EitherValues { +class SyncDAppComplexityCountTest extends PropSpec with WithState { private val fsWithV5 = TestFunctionalitySettings.Enabled.copy( preActivatedFeatures = Map( @@ -142,7 +132,7 @@ class SyncDAppComplexityCountTest ts + 1 ) .explicitGet() - asset = IssuedAsset(assetIssue.id.value()) + asset = IssuedAsset(assetIssue.id()) payment = List(Payment(1, asset)) dAppGenesisTxs = dAppAccs.flatMap( @@ -218,11 +208,11 @@ class SyncDAppComplexityCountTest val diff = diffE.explicitGet() diff.scriptsComplexity shouldBe complexity if (exceeding) - diff.errorMessage(invokeTx.id.value()).get.text should include("Invoke complexity limit = 26000 is exceeded") + diff.errorMessage(invokeTx.id()).get.text should include("Invoke complexity limit = 26000 is exceeded") else if (raiseError) - diff.errorMessage(invokeTx.id.value()).get.text should include("Error raised") + diff.errorMessage(invokeTx.id()).get.text should include("Error raised") else - diff.errorMessage(invokeTx.id.value()) shouldBe None + diff.errorMessage(invokeTx.id()) shouldBe None val dAppAddress = invokeTx.dAppAddressOrAlias.asInstanceOf[Address] val basePortfolios = Map( diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppForbidOldVersionsTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppForbidOldVersionsTest.scala index 44773098990..f47c140fd78 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppForbidOldVersionsTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppForbidOldVersionsTest.scala @@ -1,5 +1,6 @@ package com.wavesplatform.state.diffs.ci +import com.wavesplatform.TestTime import com.wavesplatform.account.Address import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.{DBCacheSettings, WithDomain, WithState} @@ -7,26 +8,23 @@ import com.wavesplatform.lang.directives.values.{StdLibVersion, V3, V4, V5} import com.wavesplatform.lang.script.Script 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.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} +import org.scalatest.{EitherValues, Inside} import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class SyncDAppForbidOldVersionsTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with Inside - with WithState - with DBCacheSettings - with MockFactory - with WithDomain - with EitherValues { + extends PropSpec + with ScalaCheckPropertyChecks + with Inside + with WithState + with DBCacheSettings + with MockFactory + with WithDomain + with EitherValues { import DomainPresets._ private val time = new TestTime diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppRecursionTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppRecursionTest.scala index 2407ac66155..7c34a18408f 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppRecursionTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/ci/SyncDAppRecursionTest.scala @@ -15,18 +15,10 @@ import com.wavesplatform.state.diffs.{ENOUGH_AMT, produce} import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.smart._ -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec -class SyncDAppRecursionTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with WithDomain - with EitherValues { +class SyncDAppRecursionTest extends PropSpec with WithDomain { private val time = new TestTime private def ts = time.getTimestamp() @@ -112,7 +104,7 @@ class SyncDAppRecursionTest features ) { case (diff, _) => - diff.errorMessage(invoke.id.value()) shouldBe None + diff.errorMessage(invoke.id()) shouldBe None diff.scriptsRun shouldBe 3 } } @@ -246,9 +238,9 @@ class SyncDAppRecursionTest invoke = InvokeScriptTransaction .selfSigned(1.toByte, dApp1, dApp2.toAddress, fc, Nil, fee, Waves, ts) .explicitGet() - } yield (List(genesis1, genesis2, genesis3, genesis4, setDApp1, setDApp2, setDApp3, setDApp4), invoke) + } yield (List(genesis1, genesis2, genesis3, genesis4, setDApp1, setDApp2, setDApp3, setDApp4), setDApp3, invoke) - val (preparingTxs @ _ :+ (setDApp3: SetScriptTransaction) :+ _, invoke) = preconditions.sample.get + val (preparingTxs, setDApp3, invoke) = preconditions.sample.get assertDiffEi( Seq(TestBlock.create(preparingTxs)), TestBlock.create(Seq(invoke)), @@ -387,18 +379,20 @@ class SyncDAppRecursionTest invoke = InvokeScriptTransaction .selfSigned(1.toByte, dApp1, dApp2.toAddress, fc, Nil, fee, Waves, ts) .explicitGet() - } yield (List(genesis1, genesis2, genesis3, genesis4, setDApp1, setDApp2, setDApp3, setDApp4), invoke) + } yield (List(genesis1, genesis2, genesis3, genesis4, setDApp1, setDApp2, setDApp3, setDApp4), invoke, dApp3.toAddress) - val (preparingTxs @ _ :+ (setDApp3: SetScriptTransaction) :+ _, invoke) = preconditions.sample.get - assertDiffEi( - Seq(TestBlock.create(preparingTxs)), - TestBlock.create(Seq(invoke)), - features - )( - _ should produce( - s"The invocation stack contains multiple invocations of the dApp at address ${setDApp3.sender.toAddress} with invocations of another dApp between them" - ) - ) + forAll(preconditions) { + case (preparingTxs, invoke,addr) => + assertDiffEi( + Seq(TestBlock.create(preparingTxs)), + TestBlock.create(Seq(invoke)), + features + )( + _ should produce( + s"The invocation stack contains multiple invocations of the dApp at address $addr with invocations of another dApp between them" + ) + ) + } } // A -> B -[r]-> C -> D -> B -[r]-> E -> B diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/package.scala b/node/src/test/scala/com/wavesplatform/state/diffs/package.scala index 84348c7fd8f..6e090d3a2a2 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/package.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/package.scala @@ -1,8 +1,6 @@ package com.wavesplatform.state -import org.scalatest.Matchers - -package object diffs extends Matchers { +package object diffs { val ENOUGH_AMT: Long = Long.MaxValue / 3 def produce(errorMessage: String, requireFailed: Boolean = false): DiffProduceError = new DiffProduceError(errorMessage, requireFailed) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/DiffComplexityCountTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/DiffComplexityCountTest.scala index 752805db8a6..47f106c2eac 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/DiffComplexityCountTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/DiffComplexityCountTest.scala @@ -18,17 +18,13 @@ import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec import org.scalamock.scalatest.MockFactory -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import org.scalatest.{EitherValues, Inside} class DiffComplexityCountTest extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink with Inside with WithState with DBCacheSettings @@ -110,7 +106,7 @@ class DiffComplexityCountTest genesis <- GenesisTransaction.create(account1.toAddress, ENOUGH_AMT, ts) genesis2 <- GenesisTransaction.create(account2.toAddress, ENOUGH_AMT, ts) issue <- IssueTransaction.selfSigned(2.toByte, account1, "Asset", "Description", ENOUGH_AMT, 8, true, Some(verifier), fee, ts) - asset = IssuedAsset(issue.id.value()) + asset = IssuedAsset(issue.id()) transfer1 <- TransferTransaction.selfSigned(2.toByte, account1, account2.toAddress, asset, Int.MaxValue, Waves, fee, ByteStr.empty, ts) setVerifier <- SetScriptTransaction.selfSigned(1.toByte, account2, Some(verifier), fee, ts) setDApp <- SetScriptTransaction.selfSigned(1.toByte, account1, Some(dApp(asset)), fee, ts) @@ -127,7 +123,7 @@ class DiffComplexityCountTest val invoke1 = invoke() d.appendBlock(invoke1) - d.blockchain.bestLiquidDiff.get.errorMessage(invoke1.id.value()) shouldBe empty + d.blockchain.bestLiquidDiff.get.errorMessage(invoke1.id()) shouldBe empty d.blockchain.bestLiquidDiff.get.scriptsComplexity shouldBe 13382 // dApp + 3 actions + 2 payments + verifier = 7 * 1900 = 13300 d.appendBlock() @@ -135,7 +131,7 @@ class DiffComplexityCountTest val invoke2 = invoke() d.appendBlock(invoke2) - d.blockchain.bestLiquidDiff.get.errorMessage(invoke2.id.value()) shouldBe empty + d.blockchain.bestLiquidDiff.get.errorMessage(invoke2.id()) shouldBe empty d.blockchain.bestLiquidDiff.get.scriptsComplexity shouldBe 17 } } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/SmartAccountFeeTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/SmartAccountFeeTest.scala index 0efd9172c74..51fecf93b68 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/SmartAccountFeeTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/SmartAccountFeeTest.scala @@ -15,18 +15,10 @@ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction, Transaction, TxWithFee} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec -class SmartAccountFeeTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with WithDomain - with EitherValues { +class SmartAccountFeeTest extends PropSpec with WithDomain { private val time = new TestTime private def ts = time.getTimestamp() @@ -236,7 +228,7 @@ class SmartAccountFeeTest } private def assertNoError(tx: Transaction, d: Domain) = - d.blockchain.bestLiquidDiff.get.errorMessage(tx.id.value()) shouldBe None + d.blockchain.bestLiquidDiff.get.errorMessage(tx.id()) shouldBe None property(s"small verifier is free after ${BlockchainFeatures.SynchronousCalls} activation") { forAll(preconditions) { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/SmartAssetEvalTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/SmartAssetEvalTest.scala index 67de9867483..c7ef616c301 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/SmartAssetEvalTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/SmartAssetEvalTest.scala @@ -9,17 +9,15 @@ import com.wavesplatform.lang.utils._ import com.wavesplatform.lang.v1.compiler.ExpressionCompiler import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.{IssueTransaction, SetAssetScriptTransaction} import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} import com.wavesplatform.utils._ -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class SmartAssetEvalTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class SmartAssetEvalTest extends PropSpec with WithState { val preconditions: Gen[(GenesisTransaction, IssueTransaction, SetAssetScriptTransaction, TransferTransaction)] = for { firstAcc <- accountGen @@ -42,17 +40,17 @@ class SmartAssetEvalTest extends PropSpec with PropertyChecks with WithState wit .explicitGet() issueTransaction = IssueTransaction( - TxVersion.V2, - firstAcc.publicKey, - "name".utf8Bytes, - "description".utf8Bytes, - 100, - 0, - false, - Some(emptyExprScript), - 1000000, - ts - ).signWith(firstAcc.privateKey) + TxVersion.V2, + firstAcc.publicKey, + "name".utf8Bytes, + "description".utf8Bytes, + 100, + 0, + false, + Some(emptyExprScript), + 1000000, + ts + ).signWith(firstAcc.privateKey) asset = IssuedAsset(issueTransaction.id()) @@ -79,7 +77,8 @@ class SmartAssetEvalTest extends PropSpec with PropertyChecks with WithState wit .signed(1.toByte, firstAcc.publicKey, asset, Some(typedScript), 1000, ts + 10, firstAcc.privateKey) .explicitGet() - assetTransferTransaction = TransferTransaction.selfSigned(1.toByte, firstAcc, secondAcc.toAddress, asset, 1, Waves, 1000, ByteStr.empty, ts + 20) + assetTransferTransaction = TransferTransaction + .selfSigned(1.toByte, firstAcc, secondAcc.toAddress, asset, 1, Waves, 1000, ByteStr.empty, ts + 20) .explicitGet() } yield (genesis, issueTransaction, setAssetScriptTransaction, assetTransferTransaction) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/performance/SigVerifyPerformanceTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/performance/SigVerifyPerformanceTest.scala index 879b4e1b212..0151e213485 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/performance/SigVerifyPerformanceTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/performance/SigVerifyPerformanceTest.scala @@ -14,15 +14,13 @@ import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.metrics.Instrumented import com.wavesplatform.state.diffs._ import com.wavesplatform.state.diffs.smart._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class SigVerifyPerformanceTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class SigVerifyPerformanceTest extends PropSpec with WithState { private val AmtOfTxs = 10000 @@ -30,13 +28,13 @@ class SigVerifyPerformanceTest extends PropSpec with PropertyChecks with WithSta for { amt <- smallFeeGen fee <- smallFeeGen - } yield TransferTransaction.selfSigned(1.toByte, from, to.toAddress, Waves, amt, Waves, fee, ByteStr.empty, ts).explicitGet() + } yield TransferTransaction.selfSigned(1.toByte, from, to.toAddress, Waves, amt, Waves, fee, ByteStr.empty, ts).explicitGet() private def scriptedSendGen(from: KeyPair, to: PublicKey, ts: Long): Gen[TransferTransaction] = for { amt <- smallFeeGen fee <- smallFeeGen - } yield TransferTransaction.selfSigned(2.toByte, from, to.toAddress, Waves, amt, Waves, fee, ByteStr.empty, ts).explicitGet() + } yield TransferTransaction.selfSigned(2.toByte, from, to.toAddress, Waves, amt, Waves, fee, ByteStr.empty, ts).explicitGet() private def differentTransfers(typed: EXPR) = for { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/AddressTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/AddressTest.scala index efd69f2db7b..6b49fe8840c 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/AddressTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/AddressTest.scala @@ -10,13 +10,11 @@ import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, CaseObj} import com.wavesplatform.lang.v1.evaluator.ctx.impl.unit import com.wavesplatform.state.diffs._ import com.wavesplatform.state.diffs.smart.predef +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.TxValidationError.InvalidAddress -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class AddressTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink { +class AddressTest extends PropSpec { property("should calculate address from public key") { forAll(accountGen) { acc => val script = diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/BrokenUnicodeTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/BrokenUnicodeTest.scala index 42470d392f3..8464f4b9d90 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/BrokenUnicodeTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/BrokenUnicodeTest.scala @@ -1,5 +1,6 @@ package com.wavesplatform.state.diffs.smart.predef +import com.wavesplatform.TestTime import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithDomain @@ -10,23 +11,15 @@ import com.wavesplatform.lang.v1.compiler.TestCompiler 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.transfer.TransferTransaction import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import org.scalatest.EitherValues -class BrokenUnicodeTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with WithDomain - with EitherValues { +class BrokenUnicodeTest extends PropSpec with WithDomain with EitherValues { private val time = new TestTime private def ts = time.getTimestamp() diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/CommonFunctionsTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/CommonFunctionsTest.scala index fe182bd1dfe..1a43f9dbcd8 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/CommonFunctionsTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/CommonFunctionsTest.scala @@ -7,15 +7,14 @@ import com.wavesplatform.lang.Testing._ import com.wavesplatform.lang.v1.compiler.Terms.CONST_BYTESTR import com.wavesplatform.lang.v1.evaluator.ctx.impl._ import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.{DataTransaction, Proofs} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{Assertions, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.Assertions import shapeless.Coproduct -class CommonFunctionsTest extends PropSpec with PropertyChecks with Matchers with TransactionGen with NoShrink { +class CommonFunctionsTest extends PropSpec { property("extract should transaction transfer assetId if exists") { forAll(transferV1Gen) { @@ -211,7 +210,7 @@ class CommonFunctionsTest extends PropSpec with PropertyChecks with Matchers wit property("data constructors") { forAll(transferV2Gen, longEntryGen(dataAsciiKeyGen)) { (t, entry) => - val compareClause = t.recipient match { + val compareClause = (t.recipient: @unchecked) match { case addr: Address => s"tx.recipient == Address(base58'${addr.stringRepr}')" case alias: Alias => s"""tx.recipient == Alias("${alias.name}")""" } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ContextFunctionsTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ContextFunctionsTest.scala index 2d76f55081a..140c2585595 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ContextFunctionsTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ContextFunctionsTest.scala @@ -1,6 +1,6 @@ package com.wavesplatform.state.diffs.smart.predef -import cats.implicits._ +import cats.syntax.semigroup._ import com.wavesplatform.account.KeyPair import com.wavesplatform.block.Block import com.wavesplatform.common.state.ByteStr @@ -27,6 +27,7 @@ import com.wavesplatform.state._ import com.wavesplatform.state.diffs.FeeValidation.{FeeConstants, FeeUnit} import com.wavesplatform.state.diffs.smart.smartEnabledFS import com.wavesplatform.state.diffs.{ENOUGH_AMT, FeeValidation} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.assets.{IssueTransaction, SponsorFeeTransaction} import com.wavesplatform.transaction.serialization.impl.PBTransactionSerializer @@ -34,13 +35,10 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction, TxVersion} import com.wavesplatform.utils._ -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import shapeless.Coproduct -class ContextFunctionsTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class ContextFunctionsTest extends PropSpec with WithState { def compactDataTransactionGen(sender: KeyPair): Gen[DataTransaction] = for { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/DAppVerifierRestrictionsTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/DAppVerifierRestrictionsTest.scala index 56f2d3ab214..757f6dedfa8 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/DAppVerifierRestrictionsTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/DAppVerifierRestrictionsTest.scala @@ -1,25 +1,18 @@ package com.wavesplatform.state.diffs.smart.predef +import com.wavesplatform.TestTime 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.state.diffs.ci.ciFee +import com.wavesplatform.test._ import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.smart.SetScriptTransaction -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import org.scalatest.EitherValues -class DAppVerifierRestrictionsTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with WithDomain - with EitherValues { +class DAppVerifierRestrictionsTest extends PropSpec with WithDomain with EitherValues { import DomainPresets._ @@ -56,7 +49,9 @@ class DAppVerifierRestrictionsTest withDomain(RideV5) { d => d.appendBlock(genesis: _*) (the[RuntimeException] thrownBy d.appendBlock(setInvoke)).getMessage should include(s"DApp-to-dApp invocations are not allowed from verifier") - (the[RuntimeException] thrownBy d.appendBlock(setReentrantInvoke)).getMessage should include(s"DApp-to-dApp invocations are not allowed from verifier") + (the[RuntimeException] thrownBy d.appendBlock(setReentrantInvoke)).getMessage should include( + s"DApp-to-dApp invocations are not allowed from verifier" + ) } } } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/IsDataStorageUntouchedTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/IsDataStorageUntouchedTest.scala index 9d14e819201..a3db4eda017 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/IsDataStorageUntouchedTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/IsDataStorageUntouchedTest.scala @@ -1,4 +1,5 @@ package com.wavesplatform.state.diffs.smart.predef +import com.wavesplatform.TestTime import com.wavesplatform.account.Address import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithDomain @@ -8,21 +9,12 @@ import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.diffs.ci.ciFee import com.wavesplatform.state.{BooleanDataEntry, EmptyDataEntry} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction, TxVersion} -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -class IsDataStorageUntouchedTest - extends PropSpec - with ScalaCheckPropertyChecks - with Matchers - with TransactionGen - with NoShrink - with WithDomain - with EitherValues { +class IsDataStorageUntouchedTest extends PropSpec with WithDomain { import DomainPresets._ diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ObsoleteTransactionBindingsTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ObsoleteTransactionBindingsTest.scala index cc4a2dff2a3..85d5c2f3a1b 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ObsoleteTransactionBindingsTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ObsoleteTransactionBindingsTest.scala @@ -11,13 +11,11 @@ import com.wavesplatform.lang.v1.compiler.ExpressionCompiler import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.settings.TestFunctionalitySettings import com.wavesplatform.state.diffs.ENOUGH_AMT +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.{GenesisTransaction, PaymentTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class ObsoleteTransactionBindingsTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class ObsoleteTransactionBindingsTest extends PropSpec with WithState { def script(g: GenesisTransaction, p: PaymentTransaction): String = s"""let genTx = extract(transactionById(base58'${g.id().toString}')) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ScriptVersionsTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ScriptVersionsTest.scala index ab2f65fe22b..0654369b248 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ScriptVersionsTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/ScriptVersionsTest.scala @@ -1,6 +1,5 @@ package com.wavesplatform.state.diffs.smart.predef -import com.wavesplatform.TransactionGen import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.features.BlockchainFeatures @@ -16,15 +15,14 @@ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.state.diffs._ import com.wavesplatform.state.{BinaryDataEntry, Blockchain, BooleanDataEntry, EmptyDataEntry, IntegerDataEntry, StringDataEntry} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Transaction import com.wavesplatform.transaction.smart.script.{ScriptCompiler, ScriptRunner} import com.wavesplatform.utils.EmptyBlockchain import org.scalacheck.Gen -import org.scalatest.{FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import shapeless.Coproduct -class ScriptVersionsTest extends FreeSpec with PropertyChecks with Matchers with TransactionGen { +class ScriptVersionsTest extends FreeSpec { private def eval[T <: EVALUATED]( script: String, version: StdLibVersion, diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/SerContextFunctionsTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/SerContextFunctionsTest.scala index 258e80b995c..ce50afcf469 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/SerContextFunctionsTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/SerContextFunctionsTest.scala @@ -9,14 +9,12 @@ import com.wavesplatform.lang.v1.Serde import com.wavesplatform.lang.v1.compiler.ExpressionCompiler import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, IntegerDataEntry, StringDataEntry} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{DataTransaction, Proofs} -import com.wavesplatform.{NoShrink, TransactionGen} -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class SerContextFunctionsTest extends PropSpec with PropertyChecks with Matchers with NoShrink with TransactionGen { +class SerContextFunctionsTest extends PropSpec { property("check serialization of script with all functions") { val entry1 = IntegerDataEntry("int", 24) val entry2 = BooleanDataEntry("bool", true) diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/TransactionBindingsTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/TransactionBindingsTest.scala index 180277f4f2f..ba361f80450 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/TransactionBindingsTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/predef/TransactionBindingsTest.scala @@ -2,7 +2,6 @@ package com.wavesplatform.state.diffs.smart.predef import com.wavesplatform.account.{Address, Alias} import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.state.diffs.ProduceError._ import com.wavesplatform.common.utils.{Base58, EitherExt2} import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lang.Global @@ -24,21 +23,17 @@ import com.wavesplatform.transaction.smart.BlockchainContext.In import com.wavesplatform.transaction.smart.{WavesEnvironment, buildThisValue} import com.wavesplatform.transaction.{DataTransaction, Proofs, ProvenTransaction, TxVersion, VersionedTransaction} import com.wavesplatform.utils.EmptyBlockchain -import com.wavesplatform.{NoShrink, TransactionGen, crypto} +import com.wavesplatform.crypto +import com.wavesplatform.test._ import monix.eval.Coeval import org.scalacheck.Gen import org.scalamock.scalatest.PathMockFactory -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.EitherValues import play.api.libs.json.Json import shapeless.Coproduct class TransactionBindingsTest extends PropSpec - with PropertyChecks - with Matchers - with TransactionGen - with NoShrink with PathMockFactory with EitherValues { private val T = 'T'.toByte diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/AddressFromRecipientScenarioTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/AddressFromRecipientScenarioTest.scala index a6702698050..1ecbfae5ccd 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/AddressFromRecipientScenarioTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/AddressFromRecipientScenarioTest.scala @@ -7,15 +7,13 @@ import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, CaseObj} import com.wavesplatform.state.diffs._ import com.wavesplatform.state.diffs.smart.predef._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{CreateAliasTransaction, GenesisTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class AddressFromRecipientScenarioTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class AddressFromRecipientScenarioTest extends PropSpec with WithState { val preconditionsAndAliasCreations: Gen[(Seq[GenesisTransaction], CreateAliasTransaction, TransferTransaction, TransferTransaction)] = for { master <- accountGen diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/BalancesV4Test.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/BalancesV4Test.scala index 116129e6a4d..ad9c0678df9 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/BalancesV4Test.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/BalancesV4Test.scala @@ -1,6 +1,6 @@ package com.wavesplatform.state.diffs.smart.scenarios -import cats.implicits._ +import cats.syntax.semigroup._ import com.wavesplatform.account.Alias import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 @@ -29,11 +29,10 @@ import com.wavesplatform.transaction.lease._ import com.wavesplatform.transaction.smart._ import com.wavesplatform.transaction.transfer._ import com.wavesplatform.utils._ -import com.wavesplatform.{NoShrink, TestTime, TransactionGen} -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.TestTime +import com.wavesplatform.test.PropSpec -class BalancesV4Test extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class BalancesV4Test extends PropSpec with WithState { val MinFee: Long = Constants.UnitsInWave / 1000L val DataTxFee: Long = 15000000L @@ -115,7 +114,7 @@ class BalancesV4Test extends PropSpec with PropertyChecks with WithState with Tr rideV4Activated ) { case (d, s) => - val apiBalance = com.wavesplatform.api.common.CommonAccountsApi(d, db, s).balanceDetails(acc1.toAddress) + val apiBalance = com.wavesplatform.api.common.CommonAccountsApi(() => d, db, s).balanceDetails(acc1.toAddress) val data = d.accountData(dapp.toAddress) data.data("available") shouldBe IntegerDataEntry("available", apiBalance.available) apiBalance.available shouldBe 16 * Constants.UnitsInWave diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/MultiSig2of3Test.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/MultiSig2of3Test.scala index 1a7d914ee25..c3c65ef8d40 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/MultiSig2of3Test.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/MultiSig2of3Test.scala @@ -17,12 +17,11 @@ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction._ import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{NoShrink, TransactionGen, crypto} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class MultiSig2of3Test extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class MultiSig2of3Test extends PropSpec with WithState { def multisigTypedExpr(pk0: PublicKey, pk1: PublicKey, pk2: PublicKey): EXPR = { val script = @@ -65,7 +64,8 @@ class MultiSig2of3Test extends PropSpec with PropertyChecks with WithState with Waves, amount, Waves, - fee, ByteStr.empty, + fee, + ByteStr.empty, timestamp, proofs = Proofs.empty, recipient.toAddress.chainId diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/NotaryControlledTransferScenarioTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/NotaryControlledTransferScenarioTest.scala index 19b1ed5c089..38668122be8 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/NotaryControlledTransferScenarioTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/NotaryControlledTransferScenarioTest.scala @@ -18,34 +18,30 @@ import com.wavesplatform.state._ import com.wavesplatform.state.diffs._ import com.wavesplatform.state.diffs.smart._ import com.wavesplatform.state.diffs.smart.predef.chainId +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.WavesEnvironment import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction, TxVersion} import com.wavesplatform.utils.{EmptyBlockchain, _} -import com.wavesplatform.{NoShrink, TransactionGen} import monix.eval.Coeval -import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} - -class NotaryControlledTransferScenarioTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { - val preconditions: Gen[(Seq[GenesisTransaction], IssueTransaction, DataTransaction, TransferTransaction, DataTransaction, DataTransaction, TransferTransaction)] = - for { - company <- accountGen - king <- accountGen - notary <- accountGen - accountA <- accountGen - accountB <- accountGen - ts <- timestampGen - genesis1 = GenesisTransaction.create(company.toAddress, ENOUGH_AMT, ts).explicitGet() - genesis2 = GenesisTransaction.create(king.toAddress, ENOUGH_AMT, ts).explicitGet() - genesis3 = GenesisTransaction.create(notary.toAddress, ENOUGH_AMT, ts).explicitGet() - genesis4 = GenesisTransaction.create(accountA.toAddress, ENOUGH_AMT, ts).explicitGet() - genesis5 = GenesisTransaction.create(accountB.toAddress, ENOUGH_AMT, ts).explicitGet() - - assetScript = s""" + +class NotaryControlledTransferScenarioTest extends PropSpec with WithState { + private val preconditions = for { + company <- accountGen + king <- accountGen + notary <- accountGen + accountA <- accountGen + accountB <- accountGen + ts <- timestampGen + genesis1 = GenesisTransaction.create(company.toAddress, ENOUGH_AMT, ts).explicitGet() + genesis2 = GenesisTransaction.create(king.toAddress, ENOUGH_AMT, ts).explicitGet() + genesis3 = GenesisTransaction.create(notary.toAddress, ENOUGH_AMT, ts).explicitGet() + genesis4 = GenesisTransaction.create(accountA.toAddress, ENOUGH_AMT, ts).explicitGet() + genesis5 = GenesisTransaction.create(accountB.toAddress, ENOUGH_AMT, ts).explicitGet() + + assetScript = s""" | | match tx { | case ttx: TransferTransaction => @@ -66,54 +62,54 @@ class NotaryControlledTransferScenarioTest extends PropSpec with PropertyChecks | } """.stripMargin - untypedScript = Parser.parseExpr(assetScript).get.value - - typedScript = ExprScript(ExpressionCompiler(compilerContext(V1, Expression, isAssetScript = false), untypedScript).explicitGet()._1) - .explicitGet() - - issueTransaction = IssueTransaction( - TxVersion.V2, - company.publicKey, - "name".utf8Bytes, - "description".utf8Bytes, - 100, - 0, - false, - Some(typedScript), - 1000000, - ts - ).signWith(company.privateKey) - - - assetId = IssuedAsset(issueTransaction.id()) - - kingDataTransaction = DataTransaction - .selfSigned(1.toByte, king, List(BinaryDataEntry("notary1PK", notary.publicKey)), 1000, ts + 1) - .explicitGet() - - transferFromCompanyToA = TransferTransaction.selfSigned(1.toByte, company, accountA.toAddress, assetId, 1, Waves, 1000, ByteStr.empty, ts + 20) - .explicitGet() - - transferFromAToB = TransferTransaction - .selfSigned(1.toByte, accountA, accountB.toAddress, assetId, 1, Waves, 1000, ByteStr.empty, ts + 30) - .explicitGet() - - notaryDataTransaction = DataTransaction - .selfSigned(1.toByte, notary, List(BooleanDataEntry(transferFromAToB.id().toString, true)), 1000, ts + 4) - .explicitGet() - - accountBDataTransaction = DataTransaction - .selfSigned(1.toByte, accountB, List(BooleanDataEntry(transferFromAToB.id().toString, true)), 1000, ts + 5) - .explicitGet() - } yield ( - Seq(genesis1, genesis2, genesis3, genesis4, genesis5), - issueTransaction, - kingDataTransaction, - transferFromCompanyToA, - notaryDataTransaction, - accountBDataTransaction, - transferFromAToB - ) + untypedScript = Parser.parseExpr(assetScript).get.value + + typedScript = ExprScript(ExpressionCompiler(compilerContext(V1, Expression, isAssetScript = false), untypedScript).explicitGet()._1) + .explicitGet() + + issueTransaction = IssueTransaction( + TxVersion.V2, + company.publicKey, + "name".utf8Bytes, + "description".utf8Bytes, + 100, + 0, + false, + Some(typedScript), + 1000000, + ts + ).signWith(company.privateKey) + + assetId = IssuedAsset(issueTransaction.id()) + + kingDataTransaction = DataTransaction + .selfSigned(1.toByte, king, List(BinaryDataEntry("notary1PK", notary.publicKey)), 1000, ts + 1) + .explicitGet() + + transferFromCompanyToA = TransferTransaction + .selfSigned(1.toByte, company, accountA.toAddress, assetId, 1, Waves, 1000, ByteStr.empty, ts + 20) + .explicitGet() + + transferFromAToB = TransferTransaction + .selfSigned(1.toByte, accountA, accountB.toAddress, assetId, 1, Waves, 1000, ByteStr.empty, ts + 30) + .explicitGet() + + notaryDataTransaction = DataTransaction + .selfSigned(1.toByte, notary, List(BooleanDataEntry(transferFromAToB.id().toString, true)), 1000, ts + 4) + .explicitGet() + + accountBDataTransaction = DataTransaction + .selfSigned(1.toByte, accountB, List(BooleanDataEntry(transferFromAToB.id().toString, true)), 1000, ts + 5) + .explicitGet() + } yield ( + Seq(genesis1, genesis2, genesis3, genesis4, genesis5), + issueTransaction, + kingDataTransaction, + transferFromCompanyToA, + notaryDataTransaction, + accountBDataTransaction, + transferFromAToB + ) def dummyEvalContext(version: StdLibVersion): EvaluationContext[Environment, Id] = { val ds = DirectiveSet(V1, Asset, Expression).explicitGet() diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OneProofForNonScriptedAccountTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OneProofForNonScriptedAccountTest.scala index 8cc49cd95b8..91a87087b68 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OneProofForNonScriptedAccountTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OneProofForNonScriptedAccountTest.scala @@ -8,14 +8,12 @@ import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.state.diffs.smart.smartEnabledFS import com.wavesplatform.state.diffs.{ENOUGH_AMT, produce} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{GenesisTransaction, Proofs} -import com.wavesplatform.{NoShrink, TransactionGen} -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class OneProofForNonScriptedAccountTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class OneProofForNonScriptedAccountTest extends PropSpec with WithState { property("exactly 1 proof required for non-scripted accounts") { val s = for { @@ -26,7 +24,7 @@ class OneProofForNonScriptedAccountTest extends PropSpec with PropertyChecks wit ts <- positiveIntGen genesis = GenesisTransaction.create(master.toAddress, ENOUGH_AMT, ts).explicitGet() setScript <- selfSignedSetScriptTransactionGenP(master, ExprScript(TRUE).explicitGet()) - transfer = TransferTransaction.selfSigned(2.toByte, master, recepient.toAddress, Waves, amt, Waves, fee, ByteStr.empty, ts).explicitGet() + transfer = TransferTransaction.selfSigned(2.toByte, master, recepient.toAddress, Waves, amt, Waves, fee, ByteStr.empty, ts).explicitGet() } yield (genesis, setScript, transfer) forAll(s) { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OnlyTransferIsAllowedTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OnlyTransferIsAllowedTest.scala index 5a7ceaf5836..916877b1d92 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OnlyTransferIsAllowedTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OnlyTransferIsAllowedTest.scala @@ -9,11 +9,9 @@ import com.wavesplatform.lang.v1.compiler.ExpressionCompiler import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.state.diffs._ import com.wavesplatform.state.diffs.smart._ -import com.wavesplatform.{NoShrink, TransactionGen} -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class OnlyTransferIsAllowedTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class OnlyTransferIsAllowedTest extends PropSpec with WithState { property("transfer is allowed but lease is not due to predicate") { @@ -33,8 +31,9 @@ class OnlyTransferIsAllowedTest extends PropSpec with PropertyChecks with WithSt forAll(preconditionsTransferAndLease(transferAllowed)) { case (genesis, script, lease, transfer) => assertDiffAndState(Seq(TestBlock.create(Seq(genesis, script))), TestBlock.create(Seq(transfer)), smartEnabledFS) { case _ => () } - assertDiffEi(Seq(TestBlock.create(Seq(genesis, script))), TestBlock.create(Seq(lease)), smartEnabledFS)(totalDiffEi => - totalDiffEi should produce("TransactionNotAllowedByScript")) + assertDiffEi(Seq(TestBlock.create(Seq(genesis, script))), TestBlock.create(Seq(lease)), smartEnabledFS)( + totalDiffEi => totalDiffEi should produce("TransactionNotAllowedByScript") + ) } } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OracleDataTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OracleDataTest.scala index 902b06da970..d8663dfc021 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OracleDataTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/OracleDataTest.scala @@ -13,16 +13,14 @@ import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.state.diffs.TransactionDiffer.TransactionValidationError import com.wavesplatform.state.diffs._ import com.wavesplatform.state.diffs.smart.smartEnabledFS +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.TxValidationError.ScriptExecutionError import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.transfer._ import com.wavesplatform.transaction.{CreateAliasTransaction, DataTransaction, GenesisTransaction, Proofs} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class OracleDataTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink with Matchers { +class OracleDataTest extends PropSpec with WithState { val preconditions : Gen[(GenesisTransaction, GenesisTransaction, CreateAliasTransaction, SetScriptTransaction, DataTransaction, TransferTransaction)] = for { diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/ScriptedSponsorTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/ScriptedSponsorTest.scala index 681227648b1..66274b716d6 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/ScriptedSponsorTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/ScriptedSponsorTest.scala @@ -7,6 +7,7 @@ import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.lagonaki.mocks.TestBlock import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.settings.TestFunctionalitySettings +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.{IssueTransaction, SponsorFeeTransaction} import com.wavesplatform.transaction.smart.SetScriptTransaction @@ -14,11 +15,8 @@ import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{GenesisTransaction, TxVersion} import com.wavesplatform.utils._ -import com.wavesplatform.{NoShrink, TransactionGen} -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class ScriptedSponsorTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class ScriptedSponsorTest extends PropSpec with WithState { import com.wavesplatform.state.diffs._ diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/TransactionFieldAccessTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/TransactionFieldAccessTest.scala index a617117afac..57a292da456 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/TransactionFieldAccessTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/TransactionFieldAccessTest.scala @@ -9,19 +9,16 @@ import com.wavesplatform.lang.v1.compiler.ExpressionCompiler import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.state.diffs.produce import com.wavesplatform.state.diffs.smart._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.lease.LeaseTransaction import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class TransactionFieldAccessTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class TransactionFieldAccessTest extends PropSpec with WithState { - private def preconditionsTransferAndLease( - code: String): Gen[(GenesisTransaction, SetScriptTransaction, LeaseTransaction, TransferTransaction)] = { + private def preconditionsTransferAndLease(code: String): Gen[(GenesisTransaction, SetScriptTransaction, LeaseTransaction, TransferTransaction)] = { val untyped = Parser.parseExpr(code).get.value val typed = ExpressionCompiler(compilerContext(V1, Expression, isAssetScript = false), untyped).explicitGet()._1 preconditionsTransferAndLease(typed) @@ -42,8 +39,9 @@ class TransactionFieldAccessTest extends PropSpec with PropertyChecks with WithS forAll(preconditionsTransferAndLease(script)) { case ((genesis, script, lease, transfer)) => assertDiffAndState(Seq(TestBlock.create(Seq(genesis, script))), TestBlock.create(Seq(transfer)), smartEnabledFS) { case _ => () } - assertDiffEi(Seq(TestBlock.create(Seq(genesis, script))), TestBlock.create(Seq(lease)), smartEnabledFS)(totalDiffEi => - totalDiffEi should produce("TransactionNotAllowedByScript")) + assertDiffEi(Seq(TestBlock.create(Seq(genesis, script))), TestBlock.create(Seq(lease)), smartEnabledFS)( + totalDiffEi => totalDiffEi should produce("TransactionNotAllowedByScript") + ) } } } diff --git a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/TransferByIdTest.scala b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/TransferByIdTest.scala index 2be42749b48..6208f881701 100644 --- a/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/TransferByIdTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/diffs/smart/scenarios/TransferByIdTest.scala @@ -11,15 +11,13 @@ import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.state.BinaryDataEntry import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.diffs.smart.smartEnabledFS +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.smart.SetScriptTransaction import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{DataTransaction, GenesisTransaction} -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -class TransferByIdTest extends PropSpec with ScalaCheckPropertyChecks with WithState with TransactionGen with NoShrink { +class TransferByIdTest extends PropSpec with WithState { val scriptSrc = s""" diff --git a/node/src/test/scala/com/wavesplatform/state/reader/StateReaderEffectiveBalancePropertyTest.scala b/node/src/test/scala/com/wavesplatform/state/reader/StateReaderEffectiveBalancePropertyTest.scala index 54703598c0a..72d1d02d66f 100644 --- a/node/src/test/scala/com/wavesplatform/state/reader/StateReaderEffectiveBalancePropertyTest.scala +++ b/node/src/test/scala/com/wavesplatform/state/reader/StateReaderEffectiveBalancePropertyTest.scala @@ -7,14 +7,12 @@ import com.wavesplatform.lagonaki.mocks.TestBlock.{create => block} import com.wavesplatform.settings.TestFunctionalitySettings.Enabled import com.wavesplatform.state.LeaseBalance import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.GenesisTransaction import com.wavesplatform.transaction.lease.LeaseTransaction -import com.wavesplatform.{NoShrink, TransactionGen} import org.scalacheck.Gen -import org.scalatest.PropSpec -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class StateReaderEffectiveBalancePropertyTest extends PropSpec with PropertyChecks with WithState with TransactionGen with NoShrink { +class StateReaderEffectiveBalancePropertyTest extends PropSpec with WithState { property("No-interactions genesis account's effectiveBalance doesn't depend on depths") { val setup: Gen[(GenesisTransaction, Int, Int, Int)] = for { master <- accountGen diff --git a/node/src/test/scala/com/wavesplatform/test/specs.scala b/node/src/test/scala/com/wavesplatform/test/specs.scala new file mode 100644 index 00000000000..89f29ca489c --- /dev/null +++ b/node/src/test/scala/com/wavesplatform/test/specs.scala @@ -0,0 +1,20 @@ +package com.wavesplatform.test + +import com.wavesplatform.{EitherMatchers, TransactionGen} +import org.scalacheck.ShrinkLowPriority +import org.scalatest._ +import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks + +trait BaseSuite extends matchers.should.Matchers with ScalaCheckPropertyChecks with ShrinkLowPriority with TransactionGen with EitherMatchers { this: Suite => + +} + +abstract class FunSuite extends funsuite.AnyFunSuite with BaseSuite + +abstract class FlatSpec extends flatspec.AnyFlatSpec with BaseSuite + +abstract class FeatureSpec extends featurespec.AnyFeatureSpec with BaseSuite + +abstract class FreeSpec extends freespec.AnyFreeSpec with BaseSuite + +abstract class PropSpec extends propspec.AnyPropSpec with BaseSuite diff --git a/node/src/test/scala/com/wavesplatform/transaction/BlockchainUpdaterTest.scala b/node/src/test/scala/com/wavesplatform/transaction/BlockchainUpdaterTest.scala index 027138bde9b..15c173791e1 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/BlockchainUpdaterTest.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/BlockchainUpdaterTest.scala @@ -9,13 +9,12 @@ import com.wavesplatform.db.WithDomain import com.wavesplatform.features.BlockchainFeatureStatus import com.wavesplatform.history.Domain.BlockchainUpdaterExt import com.wavesplatform.state._ -import com.wavesplatform.{EitherMatchers, history} -import org.scalatest.words.ShouldVerb -import org.scalatest.{FreeSpec, Matchers} +import com.wavesplatform.history +import com.wavesplatform.test.FreeSpec import scala.util.Try -class BlockchainUpdaterTest extends FreeSpec with Matchers with EitherMatchers with HistoryTest with ShouldVerb with WithDomain { +class BlockchainUpdaterTest extends FreeSpec with HistoryTest with WithDomain { private val ApprovalPeriod = 100 diff --git a/node/src/test/scala/com/wavesplatform/transaction/BurnTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/BurnTransactionSpecification.scala index 10f94e55202..dbce8b00e2b 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/BurnTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/BurnTransactionSpecification.scala @@ -5,12 +5,11 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base64, EitherExt2} import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.assets.BurnTransaction -import com.wavesplatform.{TransactionGen, crypto} -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import play.api.libs.json.Json -class BurnTransactionSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class BurnTransactionSpecification extends PropSpec { property("Burn serialization roundtrip") { forAll(burnGen) { tx: BurnTransaction => val recovered = tx.builder.parseBytes(tx.bytes()).get diff --git a/node/src/test/scala/com/wavesplatform/transaction/ChainIdSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/ChainIdSpecification.scala index 186a5109f91..63db22f0f40 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/ChainIdSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/ChainIdSpecification.scala @@ -14,12 +14,11 @@ import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransac import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction, Verifier} import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTransfer import com.wavesplatform.transaction.transfer.{MassTransferTransaction, TransferTransaction} -import com.wavesplatform.{TransactionGen, crypto} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class ChainIdSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class ChainIdSpecification extends PropSpec { private val otherChainId = 'W'.toByte private val aliasFromOther = Alias.createWithChainId("sasha", otherChainId).explicitGet() diff --git a/node/src/test/scala/com/wavesplatform/transaction/CreateAliasTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/CreateAliasTransactionSpecification.scala index 541bb6db79c..811acd7d2b2 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/CreateAliasTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/CreateAliasTransactionSpecification.scala @@ -1,14 +1,12 @@ package com.wavesplatform.transaction -import com.wavesplatform.TransactionGen import com.wavesplatform.account.{Alias, KeyPair, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec import play.api.libs.json.Json -class CreateAliasTransactionSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class CreateAliasTransactionSpecification extends PropSpec { property("CreateAliasTransaction serialization roundtrip") { forAll(createAliasGen) { tx: CreateAliasTransaction => @@ -50,7 +48,14 @@ class CreateAliasTransactionSpecification extends PropSpec with PropertyChecks w """) val tx = CreateAliasTransaction - .create(Transaction.V1, PublicKey.fromBase58String("FM5ojNqW7e9cZ9zhPYGkpSP1Pcd8Z3e3MNKYVS5pGJ8Z").explicitGet(), "myalias", 100000, 1526910778245L, Proofs(ByteStr.decodeBase58("CC1jQ4qkuVfMvB2Kpg2Go6QKXJxUFC8UUswUxBsxwisrR8N5s3Yc8zA6dhjTwfWKfdouSTAnRXCxTXb3T6pJq3T").get)) + .create( + Transaction.V1, + PublicKey.fromBase58String("FM5ojNqW7e9cZ9zhPYGkpSP1Pcd8Z3e3MNKYVS5pGJ8Z").explicitGet(), + "myalias", + 100000, + 1526910778245L, + Proofs(ByteStr.decodeBase58("CC1jQ4qkuVfMvB2Kpg2Go6QKXJxUFC8UUswUxBsxwisrR8N5s3Yc8zA6dhjTwfWKfdouSTAnRXCxTXb3T6pJq3T").get) + ) .explicitGet() js shouldEqual tx.json() @@ -74,7 +79,14 @@ class CreateAliasTransactionSpecification extends PropSpec with PropertyChecks w """) val tx = CreateAliasTransaction - .create(Transaction.V2, PublicKey.fromBase58String("FM5ojNqW7e9cZ9zhPYGkpSP1Pcd8Z3e3MNKYVS5pGJ8Z").explicitGet(), "myalias", 100000, 1526910778245L, Proofs(Seq(ByteStr.decodeBase58("26U7rQTwpdma5GYSZb5bNygVCtSuWL6DKet1Nauf5J57v19mmfnq434YrkKYJqvYt2ydQBUT3P7Xgj5ZVDVAcc5k").get))) + .create( + Transaction.V2, + PublicKey.fromBase58String("FM5ojNqW7e9cZ9zhPYGkpSP1Pcd8Z3e3MNKYVS5pGJ8Z").explicitGet(), + "myalias", + 100000, + 1526910778245L, + Proofs(Seq(ByteStr.decodeBase58("26U7rQTwpdma5GYSZb5bNygVCtSuWL6DKet1Nauf5J57v19mmfnq434YrkKYJqvYt2ydQBUT3P7Xgj5ZVDVAcc5k").get)) + ) .explicitGet() js shouldEqual tx.json() diff --git a/node/src/test/scala/com/wavesplatform/transaction/DataTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/DataTransactionSpecification.scala index 1cce7f7c7fd..6e1bab21c04 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/DataTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/DataTransactionSpecification.scala @@ -8,13 +8,13 @@ import com.wavesplatform.common.utils.{Base58, Base64, EitherExt2} import com.wavesplatform.state.DataEntry._ import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, DataEntry, EmptyDataEntry, IntegerDataEntry, StringDataEntry} import com.wavesplatform.transaction.TxValidationError.GenericError -import com.wavesplatform.{TransactionGen, crypto} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import org.scalacheck.{Arbitrary, Gen} import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json -class DataTransactionSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class DataTransactionSpecification extends PropSpec { private def checkSerialization(tx: DataTransaction): Assertion = { val parsed = DataTransaction.parseBytes(tx.bytes()).get diff --git a/node/src/test/scala/com/wavesplatform/transaction/ExchangeTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/ExchangeTransactionSpecification.scala index 4494cd32ec0..8b382770b91 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/ExchangeTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/ExchangeTransactionSpecification.scala @@ -4,19 +4,18 @@ import com.wavesplatform.account.{KeyPair, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base64, EitherExt2} import com.wavesplatform.lang.ValidationError +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError.{GenericError, OrderValidationError} import com.wavesplatform.transaction.assets.exchange.AssetPair.extractAssetId import com.wavesplatform.transaction.assets.exchange.{Order, _} -import com.wavesplatform.{NTPTime, NoShrink, TransactionGen, crypto} +import com.wavesplatform.{NTPTime, crypto} import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json import scala.math.pow -class ExchangeTransactionSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen with NTPTime with NoShrink { +class ExchangeTransactionSpecification extends PropSpec with NTPTime { val versionsGen: Gen[(Byte, Byte, Byte)] = Gen.oneOf( (1.toByte, 1.toByte, 1.toByte), (1.toByte, 2.toByte, 2.toByte), diff --git a/node/src/test/scala/com/wavesplatform/transaction/GenericTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/GenericTransactionSpecification.scala index 3ee92313f22..07eb2642c30 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/GenericTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/GenericTransactionSpecification.scala @@ -1,21 +1,16 @@ package com.wavesplatform.transaction -import com.wavesplatform.{TransactionGen, crypto} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json._ -abstract class GenericTransactionSpecification[T <: com.wavesplatform.transaction.Transaction] - extends PropSpec - with PropertyChecks - with Matchers - with TransactionGen { +abstract class GenericTransactionSpecification[T <: Transaction] extends PropSpec { def transactionParser: com.wavesplatform.transaction.TransactionParser def updateProofs(tx: T, p: Proofs): T def generator: Gen[(Seq[com.wavesplatform.transaction.Transaction], T)] - def assertTxs(first: Transaction, second: T): Unit + def assertTxs(first: T, second: T): Unit def jsonRepr: Seq[(JsValue, T)] def transactionName: String def preserBytesJson: Option[(Array[Byte], JsValue)] = None @@ -23,7 +18,7 @@ abstract class GenericTransactionSpecification[T <: com.wavesplatform.transactio property(s"$transactionName serialization roundtrip") { forAll(generator) { case (_, tx) => - assertTxs(transactionParser.parseBytes(tx.bytes()).get, tx) + assertTxs(transactionParser.parseBytes(tx.bytes()).get.asInstanceOf[T], tx) } } diff --git a/node/src/test/scala/com/wavesplatform/transaction/GenesisTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/GenesisTransactionSpecification.scala index 3c315388a77..de06e514b2b 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/GenesisTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/GenesisTransactionSpecification.scala @@ -3,11 +3,10 @@ package com.wavesplatform.transaction import com.wavesplatform.account.{KeyPair, PublicKey} import com.wavesplatform.common.utils.{Base58, EitherExt2} import com.wavesplatform.protobuf.transaction.PBTransactions +import com.wavesplatform.test.PropSpec import org.scalacheck.{Arbitrary, Gen} -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class GenesisTransactionSpecification extends PropSpec with PropertyChecks with Matchers { +class GenesisTransactionSpecification extends PropSpec { private val defaultRecipient = PublicKey(Array.fill(32)(0: Byte)) diff --git a/node/src/test/scala/com/wavesplatform/transaction/InvokeScriptComplexitySpec.scala b/node/src/test/scala/com/wavesplatform/transaction/InvokeScriptComplexitySpec.scala index fd7ec1189b0..6b98f40e2fa 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/InvokeScriptComplexitySpec.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/InvokeScriptComplexitySpec.scala @@ -1,26 +1,24 @@ package com.wavesplatform.transaction +import com.wavesplatform.NTPTime import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithDomain import com.wavesplatform.features.BlockchainFeatures -import com.wavesplatform.it.util.DoubleExt import com.wavesplatform.lang.directives.values.V5 import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms.{CONST_BYTESTR, CONST_STRING, FUNCTION_CALL} import com.wavesplatform.lang.v1.compiler.TestCompiler import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.utx.UtxPoolImpl -import com.wavesplatform.{NTPTime, NoShrink, TransactionGen} import monix.reactive.Observer -import org.scalatest.FreeSpec -import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -class InvokeScriptComplexitySpec extends FreeSpec with WithDomain with ScalaCheckPropertyChecks with TransactionGen with NTPTime with NoShrink { +class InvokeScriptComplexitySpec extends FreeSpec with WithDomain with NTPTime { private[this] val dApp1 = TestCompiler(V5).compileContract(""" |{-# STDLIB_VERSION 5 #-} |{-# CONTENT_TYPE DAPP #-} diff --git a/node/src/test/scala/com/wavesplatform/transaction/InvokeScriptTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/InvokeScriptTransactionSpecification.scala index c7d5ee3d637..26dd5d5715b 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/InvokeScriptTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/InvokeScriptTransactionSpecification.scala @@ -4,7 +4,6 @@ import com.google.protobuf.ByteString import com.wavesplatform.account._ import com.wavesplatform.api.http.requests.{InvokeScriptRequest, SignedInvokeScriptRequest} import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.state.diffs.ProduceError.produce import com.wavesplatform.common.utils.{Base64, _} import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.compiler.Terms.{ARR, CONST_BIGINT, CONST_LONG, CaseObj} @@ -17,12 +16,11 @@ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.TxValidationError.NonPositiveAmount import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, Verifier} -import com.wavesplatform.{EitherMatchers, TransactionGen, crypto} -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.crypto +import com.wavesplatform.test._ import play.api.libs.json.{JsObject, Json} -class InvokeScriptTransactionSpecification extends PropSpec with PropertyChecks with Matchers with EitherMatchers with TransactionGen { +class InvokeScriptTransactionSpecification extends PropSpec { val publicKey = "73pu8pHFNpj9tmWuYjqnZ962tXzJvLGX86dxjZxGYhoK" @@ -227,7 +225,6 @@ class InvokeScriptTransactionSpecification extends PropSpec with PropertyChecks } property(s"can't have more than ${ContractLimits.MaxInvokeScriptArgs} args") { - import com.wavesplatform.common.state.diffs.ProduceError._ val pk = PublicKey.fromBase58String(publicKey).explicitGet() InvokeScriptTransaction.create( 1.toByte, diff --git a/node/src/test/scala/com/wavesplatform/transaction/IssueTransactionV1Specification.scala b/node/src/test/scala/com/wavesplatform/transaction/IssueTransactionV1Specification.scala index 23a451bf87e..557ce9b50dd 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/IssueTransactionV1Specification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/IssueTransactionV1Specification.scala @@ -4,12 +4,11 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base64, EitherExt2} import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.utils._ -import com.wavesplatform.{TransactionGen, crypto} -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import play.api.libs.json.Json -class IssueTransactionV1Specification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class IssueTransactionV1Specification extends PropSpec { property("Issue serialization roundtrip") { forAll(issueGen) { issue: IssueTransaction => val recovered = issue.builder.parseBytes(issue.bytes()).get @@ -75,18 +74,18 @@ class IssueTransactionV1Specification extends PropSpec with PropertyChecks with """) val tx = IssueTransaction( - TxVersion.V1, - PublicKey.fromBase58String("FM5ojNqW7e9cZ9zhPYGkpSP1Pcd8Z3e3MNKYVS5pGJ8Z").explicitGet(), - "Gigacoin".utf8Bytes, - "Gigacoin".utf8Bytes, - 10000000000L, - 8.toByte, - true, - script = None, - 100000000, - 1526287561757L, - Proofs(ByteStr.decodeBase58("28kE1uN1pX2bwhzr9UHw5UuB9meTFEDFgeunNgy6nZWpHX4pzkGYotu8DhQ88AdqUG6Yy5wcXgHseKPBUygSgRMJ").get) - ) + TxVersion.V1, + PublicKey.fromBase58String("FM5ojNqW7e9cZ9zhPYGkpSP1Pcd8Z3e3MNKYVS5pGJ8Z").explicitGet(), + "Gigacoin".utf8Bytes, + "Gigacoin".utf8Bytes, + 10000000000L, + 8.toByte, + true, + script = None, + 100000000, + 1526287561757L, + Proofs(ByteStr.decodeBase58("28kE1uN1pX2bwhzr9UHw5UuB9meTFEDFgeunNgy6nZWpHX4pzkGYotu8DhQ88AdqUG6Yy5wcXgHseKPBUygSgRMJ").get) + ) tx.json() shouldEqual js } diff --git a/node/src/test/scala/com/wavesplatform/transaction/IssueTransactionV2Specification.scala b/node/src/test/scala/com/wavesplatform/transaction/IssueTransactionV2Specification.scala index 00f9d410303..6de882fde21 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/IssueTransactionV2Specification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/IssueTransactionV2Specification.scala @@ -14,21 +14,17 @@ import com.wavesplatform.lang.v1.parser.Parser import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.{Global, utils} import com.wavesplatform.state.HistoryTest +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.assets.IssueTransaction import com.wavesplatform.utils._ -import com.wavesplatform.{NoShrink, TransactionGen, WithDB, crypto} -import org.scalatest.{EitherValues, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.{WithDB, crypto} +import org.scalatest.EitherValues import play.api.libs.json.Json class IssueTransactionV2Specification extends PropSpec - with PropertyChecks - with Matchers - with TransactionGen with WithDB with HistoryTest - with NoShrink with EitherValues { property("IssueV2 serialization roundtrip") { diff --git a/node/src/test/scala/com/wavesplatform/transaction/LeaseCancelTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/LeaseCancelTransactionSpecification.scala index 5e2cf627344..8047e6bdb0c 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/LeaseCancelTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/LeaseCancelTransactionSpecification.scala @@ -1,16 +1,14 @@ package com.wavesplatform.transaction -import com.wavesplatform.TransactionGen import com.wavesplatform.account.PublicKey import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, EitherExt2} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.lease.LeaseCancelTransaction import com.wavesplatform.transaction.serialization.impl.LeaseCancelTxSerializer -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json -class LeaseCancelTransactionSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class LeaseCancelTransactionSpecification extends PropSpec { property("Lease cancel serialization roundtrip") { forAll(leaseCancelGen) { tx: LeaseCancelTransaction => diff --git a/node/src/test/scala/com/wavesplatform/transaction/LeaseTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/LeaseTransactionSpecification.scala index 434c03c50ca..cd07d2f1f42 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/LeaseTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/LeaseTransactionSpecification.scala @@ -1,15 +1,13 @@ package com.wavesplatform.transaction -import com.wavesplatform.TransactionGen import com.wavesplatform.account.{Address, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, EitherExt2} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.lease.LeaseTransaction -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json -class LeaseTransactionSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class LeaseTransactionSpecification extends PropSpec { property("Lease transaction serialization roundtrip") { forAll(leaseGen) { tx: LeaseTransaction => diff --git a/node/src/test/scala/com/wavesplatform/transaction/MassTransferTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/MassTransferTransactionSpecification.scala index cdb098e0570..73e2b390bf5 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/MassTransferTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/MassTransferTransactionSpecification.scala @@ -2,20 +2,18 @@ package com.wavesplatform.transaction import com.wavesplatform.account.PublicKey import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.state.diffs.ProduceError._ import com.wavesplatform.common.utils.{Base64, EitherExt2} +import com.wavesplatform.crypto +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.TxValidationError.GenericError import com.wavesplatform.transaction.transfer.MassTransferTransaction.{MaxTransferCount, ParsedTransfer, Transfer} import com.wavesplatform.transaction.transfer._ -import com.wavesplatform.{TransactionGen, crypto} -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json import scala.util.Success -class MassTransferTransactionSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class MassTransferTransactionSpecification extends PropSpec { property("serialization roundtrip") { forAll(massTransferGen) { tx: MassTransferTransaction => diff --git a/node/src/test/scala/com/wavesplatform/transaction/OrderSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/OrderSpecification.scala index 8e021ad8093..ef7a3a7050f 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/OrderSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/OrderSpecification.scala @@ -5,13 +5,13 @@ import com.wavesplatform.state.diffs._ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.exchange.{AssetPair, Order, OrderType} import com.wavesplatform.transaction.smart.Verifier -import com.wavesplatform.{NTPTime, TransactionGen} +import com.wavesplatform.NTPTime +import com.wavesplatform.test.PropSpec import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import scala.util.Random -class OrderSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen with ValidationMatcher with NTPTime { +class OrderSpecification extends PropSpec with ValidationMatcher with NTPTime { property("Order serialization roundtrip") { forAll(orderV1Gen) { order => val recovered = Order.parseBytes(Order.V1, order.bytes()).get diff --git a/node/src/test/scala/com/wavesplatform/transaction/ProtoVersionTransactionsSpec.scala b/node/src/test/scala/com/wavesplatform/transaction/ProtoVersionTransactionsSpec.scala index 00e8a55ede3..8a4ad775eb1 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/ProtoVersionTransactionsSpec.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/ProtoVersionTransactionsSpec.scala @@ -1,6 +1,5 @@ package com.wavesplatform.transaction -import com.wavesplatform.TransactionGen import com.wavesplatform.account.{AddressScheme, KeyPair} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base64, EitherExt2} @@ -9,6 +8,7 @@ import com.wavesplatform.lang.v1.compiler.Terms.{CONST_LONG, FUNCTION_CALL} import com.wavesplatform.protobuf.transaction.{PBSignedTransaction, PBTransactions} import com.wavesplatform.protobuf.utils.PBUtils import com.wavesplatform.settings.Constants +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.assets._ import com.wavesplatform.transaction.assets.exchange.{ExchangeTransaction, Order} @@ -19,9 +19,8 @@ import com.wavesplatform.transaction.transfer.MassTransferTransaction.ParsedTran import com.wavesplatform.transaction.transfer.{MassTransferTransaction, TransferTransaction} import com.wavesplatform.utils.StringBytes import org.scalacheck.Gen -import org.scalatest.{FreeSpec, Matchers} -class ProtoVersionTransactionsSpec extends FreeSpec with TransactionGen with Matchers { +class ProtoVersionTransactionsSpec extends FreeSpec { val MinFee: Long = (0.001 * Constants.UnitsInWave).toLong val DataTxFee: Long = 15000000 diff --git a/node/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV1Specification.scala b/node/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV1Specification.scala index a6f35c2c1ce..74c3023d6aa 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV1Specification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV1Specification.scala @@ -5,12 +5,11 @@ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base64, EitherExt2} import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.assets.ReissueTransaction -import com.wavesplatform.{TransactionGen, crypto} -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import play.api.libs.json.Json -class ReissueTransactionV1Specification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class ReissueTransactionV1Specification extends PropSpec { property("Reissue serialization roundtrip") { forAll(reissueGen) { tx: ReissueTransaction => diff --git a/node/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV2Specification.scala b/node/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV2Specification.scala index 13169fb2df1..b620fa1eba1 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV2Specification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/ReissueTransactionV2Specification.scala @@ -15,17 +15,16 @@ class ReissueTransactionV2Specification extends GenericTransactionSpecification[ tx.copy(proofs = p) } - def assertTxs(f: Transaction, second: ReissueTransaction): Unit = f match { - case first: ReissueTransaction => - first.sender shouldEqual second.sender - first.timestamp shouldEqual second.timestamp - first.fee shouldEqual second.fee - first.version shouldEqual second.version - first.quantity shouldEqual second.quantity - first.reissuable shouldEqual second.reissuable - first.asset shouldEqual second.asset - first.proofs shouldEqual second.proofs - first.bytes() shouldEqual second.bytes() + def assertTxs(first: ReissueTransaction, second: ReissueTransaction): Unit = { + first.sender shouldEqual second.sender + first.timestamp shouldEqual second.timestamp + first.fee shouldEqual second.fee + first.version shouldEqual second.version + first.quantity shouldEqual second.quantity + first.reissuable shouldEqual second.reissuable + first.asset shouldEqual second.asset + first.proofs shouldEqual second.proofs + first.bytes() shouldEqual second.bytes() } def generator: Gen[(Seq[com.wavesplatform.transaction.Transaction], ReissueTransaction)] = @@ -34,8 +33,18 @@ class ReissueTransactionV2Specification extends GenericTransactionSpecification[ fee <- smallFeeGen reissuable <- Gen.oneOf(true, false) } yield { - val issue = IssueTransaction(TxVersion.V1, sender.publicKey, assetName, description, quantity, decimals, reissuable = true, script = None, iFee, timestamp) - .signWith(sender.privateKey) + val issue = IssueTransaction( + TxVersion.V1, + sender.publicKey, + assetName, + description, + quantity, + decimals, + reissuable = true, + script = None, + iFee, + timestamp + ).signWith(sender.privateKey) val reissue1 = ReissueTransaction .selfSigned(2.toByte, sender, issue.asset, quantity, reissuable = reissuable, fee, timestamp) .explicitGet() diff --git a/node/src/test/scala/com/wavesplatform/transaction/SetAssetScriptTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/SetAssetScriptTransactionSpecification.scala index e408c331b29..4e2f4794646 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/SetAssetScriptTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/SetAssetScriptTransactionSpecification.scala @@ -2,7 +2,6 @@ package com.wavesplatform.transaction import com.wavesplatform.account.{AddressScheme, PublicKey} import com.wavesplatform.common.state.ByteStr -import com.wavesplatform.common.state.diffs.ProduceError._ import com.wavesplatform.common.utils.{Base64, EitherExt2} import com.wavesplatform.lang.contract.DApp import com.wavesplatform.lang.directives.values._ @@ -12,6 +11,7 @@ import com.wavesplatform.transaction.Asset.IssuedAsset import com.wavesplatform.transaction.assets.SetAssetScriptTransaction import org.scalacheck.Gen import play.api.libs.json._ +import com.wavesplatform.test._ class SetAssetScriptTransactionSpecification extends GenericTransactionSpecification[SetAssetScriptTransaction] { property("issuer can`t make SetAssetScript tx when Script is Contract") { @@ -46,8 +46,7 @@ class SetAssetScriptTransactionSpecification extends GenericTransactionSpecifica override def updateProofs(tx: SetAssetScriptTransaction, p: Proofs): SetAssetScriptTransaction = tx.copy(1.toByte, proofs = p) override def generator: Gen[(Seq[Transaction], SetAssetScriptTransaction)] = setAssetScriptTransactionGen - override def assertTxs(f: Transaction, second: SetAssetScriptTransaction): Unit = f match { - case first: SetAssetScriptTransaction => + override def assertTxs(first: SetAssetScriptTransaction, second: SetAssetScriptTransaction): Unit = { first.sender shouldEqual second.sender first.timestamp shouldEqual second.timestamp first.fee shouldEqual second.fee diff --git a/node/src/test/scala/com/wavesplatform/transaction/SetScriptTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/SetScriptTransactionSpecification.scala index 4144f25169c..7e38156868b 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/SetScriptTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/SetScriptTransactionSpecification.scala @@ -15,15 +15,14 @@ class SetScriptTransactionSpecification extends GenericTransactionSpecification[ tx.copy(1.toByte, proofs = p) } - def assertTxs(f: Transaction, second: SetScriptTransaction): Unit = f match { - case first: SetScriptTransaction => - first.sender shouldEqual second.sender - first.timestamp shouldEqual second.timestamp - first.fee shouldEqual second.fee - first.version shouldEqual second.version - first.proofs shouldEqual second.proofs - first.bytes() shouldEqual second.bytes() - first.script shouldEqual second.script + def assertTxs(first: SetScriptTransaction, second: SetScriptTransaction): Unit = { + first.sender shouldEqual second.sender + first.timestamp shouldEqual second.timestamp + first.fee shouldEqual second.fee + first.version shouldEqual second.version + first.proofs shouldEqual second.proofs + first.bytes() shouldEqual second.bytes() + first.script shouldEqual second.script } def generator: Gen[((Seq[com.wavesplatform.transaction.Transaction], SetScriptTransaction))] = setScriptTransactionGen.map(t => (Seq(), t)) diff --git a/node/src/test/scala/com/wavesplatform/transaction/SponsorFeeTransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/SponsorFeeTransactionSpecification.scala index c7385a4e774..50667a5c426 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/SponsorFeeTransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/SponsorFeeTransactionSpecification.scala @@ -13,13 +13,12 @@ import com.wavesplatform.state.diffs._ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.{IssueTransaction, SponsorFeeTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction -import com.wavesplatform.{TransactionGen, crypto} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import org.scalacheck.Gen -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json -class SponsorFeeTransactionSpecification extends PropSpec with PropertyChecks with WithState with TransactionGen { +class SponsorFeeTransactionSpecification extends PropSpec with WithState { val One = 100000000L val NgAndSponsorshipSettings: FunctionalitySettings = TestFunctionalitySettings.Enabled.copy( preActivatedFeatures = Map(NG.id -> 0, FeeSponsorship.id -> 0, SmartAccounts.id -> 0), @@ -156,8 +155,18 @@ class SponsorFeeTransactionSpecification extends PropSpec with PropertyChecks wi for { sender <- accountGen (_, assetName, description, quantity, decimals, reissuable, iFee, timestamp) <- issueParamGen - issue = IssueTransaction(TxVersion.V1, sender.publicKey, assetName, description, quantity, decimals, reissuable = reissuable, script = None, iFee, timestamp) - .signWith(sender.privateKey) + issue = IssueTransaction( + TxVersion.V1, + sender.publicKey, + assetName, + description, + quantity, + decimals, + reissuable = reissuable, + script = None, + iFee, + timestamp + ).signWith(sender.privateKey) minFee <- smallFeeGen assetId = issue.assetId } yield SponsorFeeTransaction.selfSigned(1.toByte, sender, IssuedAsset(assetId), Some(minFee), fee, timestamp) should produce( @@ -171,8 +180,18 @@ class SponsorFeeTransactionSpecification extends PropSpec with PropertyChecks wi for { sender <- accountGen (_, assetName, description, quantity, decimals, reissuable, iFee, timestamp) <- issueParamGen - issue = IssueTransaction(TxVersion.V1, sender.publicKey, assetName, description, quantity, decimals, reissuable = reissuable, script = None, iFee, timestamp) - .signWith(sender.privateKey) + issue = IssueTransaction( + TxVersion.V1, + sender.publicKey, + assetName, + description, + quantity, + decimals, + reissuable = reissuable, + script = None, + iFee, + timestamp + ).signWith(sender.privateKey) minFee = None assetId = issue.assetId } yield SponsorFeeTransaction.selfSigned(1.toByte, sender, IssuedAsset(assetId), minFee, fee, timestamp) should produce("insufficient fee") @@ -183,10 +202,13 @@ class SponsorFeeTransactionSpecification extends PropSpec with PropertyChecks wi val setup = for { (acc, name, desc, quantity, decimals, reissuable, fee, ts) <- issueParamGen genesis = GenesisTransaction.create(acc.toAddress, ENOUGH_AMT, ts).explicitGet() - issue = IssueTransaction(TxVersion.V1, acc.publicKey, name, desc, quantity, decimals, reissuable, script = None, fee, ts).signWith(acc.privateKey) + issue = IssueTransaction(TxVersion.V1, acc.publicKey, name, desc, quantity, decimals, reissuable, script = None, fee, ts) + .signWith(acc.privateKey) minFee <- Gen.choose(1L, issue.quantity) - sponsor = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee), One, ts).explicitGet() - transfer = TransferTransaction.selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee, ByteStr.empty, ts).explicitGet() + sponsor = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee), One, ts).explicitGet() + transfer = TransferTransaction + .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee, ByteStr.empty, ts) + .explicitGet() } yield (acc, genesis, issue, sponsor, transfer) forAll(setup) { @@ -206,12 +228,15 @@ class SponsorFeeTransactionSpecification extends PropSpec with PropertyChecks wi val setup = for { (acc, name, desc, quantity, decimals, reissuable, fee, ts) <- issueParamGen genesis = GenesisTransaction.create(acc.toAddress, ENOUGH_AMT, ts).explicitGet() - issue = IssueTransaction(TxVersion.V1, acc.publicKey, name, desc, quantity, decimals, reissuable, script = None, fee, ts).signWith(acc.privateKey) + issue = IssueTransaction(TxVersion.V1, acc.publicKey, name, desc, quantity, decimals, reissuable, script = None, fee, ts) + .signWith(acc.privateKey) minFee <- Gen.choose(1000000L, issue.quantity) sponsor = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee), One, ts).explicitGet() - transfer1 = TransferTransaction.selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee + 7, ByteStr.empty, ts) + transfer1 = TransferTransaction + .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee + 7, ByteStr.empty, ts) .explicitGet() - transfer2 = TransferTransaction.selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee + 9, ByteStr.empty, ts) + transfer2 = TransferTransaction + .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, feeAsset = IssuedAsset(issue.id()), minFee + 9, ByteStr.empty, ts) .explicitGet() } yield (acc, genesis, issue, sponsor, transfer1, transfer2) @@ -232,13 +257,18 @@ class SponsorFeeTransactionSpecification extends PropSpec with PropertyChecks wi val setup = for { (acc, name, desc, quantity, decimals, reissuable, fee, ts) <- issueParamGen genesis = GenesisTransaction.create(acc.toAddress, ENOUGH_AMT, ts).explicitGet() - issue = IssueTransaction(TxVersion.V1, acc.publicKey, name, desc, quantity, decimals, reissuable, script = None, fee, ts).signWith(acc.privateKey) + issue = IssueTransaction(TxVersion.V1, acc.publicKey, name, desc, quantity, decimals, reissuable, script = None, fee, ts) + .signWith(acc.privateKey) minFee <- Gen.choose(1, issue.quantity / 11) - sponsor1 = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee), One, ts).explicitGet() - transfer1 = TransferTransaction.selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, IssuedAsset(issue.id()), fee = minFee, ByteStr.empty, ts).explicitGet() - sponsor2 = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee * 10), One, ts).explicitGet() - transfer2 = TransferTransaction.selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, IssuedAsset(issue.id()), fee = minFee * 10, ByteStr.empty, ts).explicitGet() + sponsor1 = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee), One, ts).explicitGet() + transfer1 = TransferTransaction + .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, IssuedAsset(issue.id()), fee = minFee, ByteStr.empty, ts) + .explicitGet() + sponsor2 = SponsorFeeTransaction.selfSigned(1.toByte, acc, IssuedAsset(issue.id()), Some(minFee * 10), One, ts).explicitGet() + transfer2 = TransferTransaction + .selfSigned(1.toByte, acc, acc.toAddress, Waves, 1L, IssuedAsset(issue.id()), fee = minFee * 10, ByteStr.empty, ts) + .explicitGet() } yield (acc, genesis, issue, sponsor1, transfer1, sponsor2, transfer2) forAll(setup) { diff --git a/node/src/test/scala/com/wavesplatform/transaction/TransactionSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/TransactionSpecification.scala index e23174e4f69..022fe87bf8a 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/TransactionSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/TransactionSpecification.scala @@ -1,13 +1,11 @@ package com.wavesplatform.transaction -import com.wavesplatform.TransactionGen import com.wavesplatform.account.KeyPair import com.wavesplatform.common.utils.EitherExt2 +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.transfer._ -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class TransactionSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class TransactionSpecification extends PropSpec { property("transaction fields should be constructed in a right way") { forAll(bytes32gen, bytes32gen, timestampGen, positiveLongGen, positiveLongGen) { diff --git a/node/src/test/scala/com/wavesplatform/transaction/TransferTransactionV1Specification.scala b/node/src/test/scala/com/wavesplatform/transaction/TransferTransactionV1Specification.scala index 73435390538..a6464c96baa 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/TransferTransactionV1Specification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/TransferTransactionV1Specification.scala @@ -1,17 +1,15 @@ package com.wavesplatform.transaction -import com.wavesplatform.TransactionGen import com.wavesplatform.account.{Address, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, EitherExt2} import com.wavesplatform.state.diffs._ +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer._ -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json -class TransferTransactionV1Specification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class TransferTransactionV1Specification extends PropSpec { property("Transfer serialization roundtrip") { forAll(transferV1Gen) { transfer: TransferTransaction => diff --git a/node/src/test/scala/com/wavesplatform/transaction/TransferTransactionV2Specification.scala b/node/src/test/scala/com/wavesplatform/transaction/TransferTransactionV2Specification.scala index f953904c425..98f139c74d6 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/TransferTransactionV2Specification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/TransferTransactionV2Specification.scala @@ -1,16 +1,14 @@ package com.wavesplatform.transaction -import com.wavesplatform.TransactionGen import com.wavesplatform.account.{Address, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, EitherExt2} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer._ -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json.Json -class TransferTransactionV2Specification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class TransferTransactionV2Specification extends PropSpec { property("VersionedTransferTransactionSpecification serialization roundtrip") { forAll(transferV2Gen) { tx: TransferTransaction => diff --git a/node/src/test/scala/com/wavesplatform/transaction/TxHelpers.scala b/node/src/test/scala/com/wavesplatform/transaction/TxHelpers.scala index adb8b942bc4..05bafd90107 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/TxHelpers.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/TxHelpers.scala @@ -5,19 +5,19 @@ import com.wavesplatform.TestValues import com.wavesplatform.account.{Address, AddressOrAlias, KeyPair} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils._ -import com.wavesplatform.it.util.DoubleExt import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.FunctionHeader import com.wavesplatform.lang.v1.compiler.Terms.{EXPR, FUNCTION_CALL} import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.state.StringDataEntry +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} -import com.wavesplatform.transaction.assets.{IssueTransaction, ReissueTransaction} import com.wavesplatform.transaction.assets.exchange.{AssetPair, ExchangeTransaction, Order, OrderType} +import com.wavesplatform.transaction.assets.{IssueTransaction, ReissueTransaction} import com.wavesplatform.transaction.lease.{LeaseCancelTransaction, LeaseTransaction} -import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler +import com.wavesplatform.transaction.smart.{InvokeScriptTransaction, SetScriptTransaction} import com.wavesplatform.transaction.transfer.TransferTransaction object TxHelpers { diff --git a/node/src/test/scala/com/wavesplatform/transaction/api/http/alias/AliasRequestTests.scala b/node/src/test/scala/com/wavesplatform/transaction/api/http/alias/AliasRequestTests.scala index 5c46d201959..6ba980bd64d 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/api/http/alias/AliasRequestTests.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/api/http/alias/AliasRequestTests.scala @@ -1,10 +1,10 @@ package com.wavesplatform.transaction.api.http.alias import com.wavesplatform.api.http.requests.{CreateAliasV1Request, SignedCreateAliasV1Request} -import org.scalatest.{FunSuite, Matchers} +import com.wavesplatform.test.FunSuite import play.api.libs.json.Json -class AliasRequestTests extends FunSuite with Matchers { +class AliasRequestTests extends FunSuite { test("CreateAliasRequest") { val json = """ diff --git a/node/src/test/scala/com/wavesplatform/transaction/api/http/assets/SignedRequestsTest.scala b/node/src/test/scala/com/wavesplatform/transaction/api/http/assets/SignedRequestsTest.scala index f4356e25454..4e291f0d658 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/api/http/assets/SignedRequestsTest.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/api/http/assets/SignedRequestsTest.scala @@ -4,11 +4,11 @@ import com.wavesplatform.api.http.requests._ import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.lang.script.Script +import com.wavesplatform.test.FunSuite import com.wavesplatform.transaction.Proofs -import org.scalatest.{FunSuite, Matchers} import play.api.libs.json.Json -class SignedRequestsTest extends FunSuite with Matchers { +class SignedRequestsTest extends FunSuite { test("AssetIssueRequest json parsing works") { val json = @@ -255,7 +255,9 @@ class SignedRequestsTest extends FunSuite with Matchers { """.stripMargin val req = Json.parse(json).validate[SignedSetAssetScriptRequest].get req.assetId.id.toString shouldBe "Ha35nwsnmYxHRF8UmKG3S523BycBLZFU4FZnjXryKd4L" - req.proofs shouldBe Proofs(Seq(ByteStr.decodeBase58("3QrF81WkwGhbNvKcwpAVyBPL1MLuAG5qmR6fmtK9PTYQoFKGsFg1Rtd2kbMBuX2ZfiFX58nR1XwC19LUXZUmkXE7").get)) + req.proofs shouldBe Proofs( + Seq(ByteStr.decodeBase58("3QrF81WkwGhbNvKcwpAVyBPL1MLuAG5qmR6fmtK9PTYQoFKGsFg1Rtd2kbMBuX2ZfiFX58nR1XwC19LUXZUmkXE7").get) + ) req.fee shouldBe 100000L req.timestamp shouldBe 1520945679531L diff --git a/node/src/test/scala/com/wavesplatform/transaction/api/http/leasing/LeaseV1RequestsTests.scala b/node/src/test/scala/com/wavesplatform/transaction/api/http/leasing/LeaseV1RequestsTests.scala index c43d92ee9b2..122c976f1ed 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/api/http/leasing/LeaseV1RequestsTests.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/api/http/leasing/LeaseV1RequestsTests.scala @@ -1,10 +1,10 @@ package com.wavesplatform.transaction.api.http.leasing import com.wavesplatform.api.http.requests.{LeaseCancelV1Request, LeaseV1Request, SignedLeaseCancelV1Request, SignedLeaseV1Request} -import org.scalatest.{FunSuite, Matchers} +import com.wavesplatform.test.FunSuite import play.api.libs.json.Json -class LeaseV1RequestsTests extends FunSuite with Matchers { +class LeaseV1RequestsTests extends FunSuite { test("LeaseRequest") { val json = diff --git a/node/src/test/scala/com/wavesplatform/transaction/assets/exchange/OrderJsonSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/assets/exchange/OrderJsonSpecification.scala index b2a97c8547d..0a39ad21dcf 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/assets/exchange/OrderJsonSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/assets/exchange/OrderJsonSpecification.scala @@ -1,17 +1,15 @@ package com.wavesplatform.transaction.assets.exchange -import com.wavesplatform.TransactionGen import com.wavesplatform.account.{KeyPair, PublicKey} import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, EitherExt2} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.exchange.OrderJson._ import com.wavesplatform.transaction.smart.Verifier -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import play.api.libs.json._ -class OrderJsonSpecification extends PropSpec with PropertyChecks with Matchers with TransactionGen { +class OrderJsonSpecification extends PropSpec { property("Read Order from json") { val keyPair = KeyPair("123".getBytes("UTF-8")) diff --git a/node/src/test/scala/com/wavesplatform/transaction/smart/OrderProofTest.scala b/node/src/test/scala/com/wavesplatform/transaction/smart/OrderProofTest.scala index 181a305b950..7967dcc7e50 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/smart/OrderProofTest.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/smart/OrderProofTest.scala @@ -4,9 +4,9 @@ import com.wavesplatform.lang.directives.values.{V1, V2, V3} import com.wavesplatform.lang.v1.compiler.Terms.{ARR, CaseObj} import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.Bindings import com.wavesplatform.lang.v1.traits.domain.{APair, Ord, OrdType, Recipient} -import org.scalatest.{FreeSpec, Matchers} +import com.wavesplatform.test.FreeSpec -class OrderProofTest extends FreeSpec with Matchers { +class OrderProofTest extends FreeSpec { private def getBindingObjProofStr(obj: CaseObj): Option[String] = obj.fields.get("proofs").map(arr => arr.asInstanceOf[ARR].xs.toList.head.toString) diff --git a/node/src/test/scala/com/wavesplatform/transaction/smart/SubInvokeStateChangesSpec.scala b/node/src/test/scala/com/wavesplatform/transaction/smart/SubInvokeStateChangesSpec.scala index 3cab527670e..01c10b674ac 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/smart/SubInvokeStateChangesSpec.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/smart/SubInvokeStateChangesSpec.scala @@ -2,15 +2,14 @@ package com.wavesplatform.transaction.smart import com.wavesplatform.account.Address import com.wavesplatform.db.WithDomain -import com.wavesplatform.it.util.DoubleExt import com.wavesplatform.lang.directives.values.StdLibVersion import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.v1.compiler.TestCompiler +import com.wavesplatform.test._ import com.wavesplatform.transaction.TxHelpers -import org.scalatest.{FlatSpec, Matchers} import play.api.libs.json.Json -class SubInvokeStateChangesSpec extends FlatSpec with Matchers with WithDomain { +class SubInvokeStateChangesSpec extends FlatSpec with WithDomain { val ContractFunction = "default" val compileV5: String => Script = TestCompiler(StdLibVersion.V5).compileContract(_) diff --git a/node/src/test/scala/com/wavesplatform/transaction/smart/VerifierSpecification.scala b/node/src/test/scala/com/wavesplatform/transaction/smart/VerifierSpecification.scala index 9f12dca8f86..f10e2dd3224 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/smart/VerifierSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/smart/VerifierSpecification.scala @@ -1,35 +1,27 @@ package com.wavesplatform.transaction.smart +import com.wavesplatform.NTPTime import com.wavesplatform.account.{KeyPair, PublicKey} import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.db.WithDomain import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.history.Domain._ -import com.wavesplatform.it.util._ import com.wavesplatform.lang.script.Script import com.wavesplatform.lang.script.v1.ExprScript import com.wavesplatform.lang.v1.compiler.Terms import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.state.diffs.produce +import com.wavesplatform.test._ import com.wavesplatform.transaction.Asset import com.wavesplatform.transaction.Asset.{IssuedAsset, Waves} import com.wavesplatform.transaction.assets.exchange._ import com.wavesplatform.transaction.assets.{IssueTransaction, SetAssetScriptTransaction} import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.{NTPTime, NoShrink, TransactionGen} -import org.scalamock.scalatest.MockFactory -import org.scalatest._ -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} class VerifierSpecification extends PropSpec - with PropertyChecks - with Matchers - with MockFactory - with TransactionGen with NTPTime - with WithDomain - with NoShrink { + with WithDomain { private def mkIssue(issuer: KeyPair, name: String, script: Option[Script] = None) = IssueTransaction .selfSigned( diff --git a/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptCompilerV1Test.scala b/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptCompilerV1Test.scala index 14bcae3ea13..df4ab086994 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptCompilerV1Test.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptCompilerV1Test.scala @@ -1,6 +1,6 @@ package com.wavesplatform.transaction.smart.script -import cats.implicits._ +import cats.syntax.option._ import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.lang.directives.values._ import com.wavesplatform.lang.script.v1.ExprScript @@ -10,10 +10,10 @@ import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.lang.v1.evaluator.FunctionIds._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext import com.wavesplatform.state.diffs._ -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec +import org.scalatest.{EitherValues, Inside} -class ScriptCompilerV1Test extends PropSpec with PropertyChecks with Matchers with Inside with EitherValues { +class ScriptCompilerV1Test extends PropSpec with EitherValues with Inside { private val estimator = ScriptEstimatorV2 property("compile script with specified version") { @@ -87,7 +87,8 @@ class ScriptCompilerV1Test extends PropSpec with PropertyChecks with Matchers wi | case _ => false |}""".stripMargin, estimator - ).explicitGet() + ) + .explicitGet() } property("account script with 'this' address link") { @@ -104,7 +105,8 @@ class ScriptCompilerV1Test extends PropSpec with PropertyChecks with Matchers wi | case _ => false |}""".stripMargin, estimator - ).explicitGet() + ) + .explicitGet() } property("asset script with 'this' address link") { @@ -122,7 +124,8 @@ class ScriptCompilerV1Test extends PropSpec with PropertyChecks with Matchers wi | case _ => false |}""".stripMargin, estimator - ).explicitGet() + ) + .explicitGet() } property("binary operations priority && ||") { @@ -351,7 +354,7 @@ class ScriptCompilerV1Test extends PropSpec with PropertyChecks with Matchers wi ScriptCompiler.compile(script, estimator) should produce( "Compilation failed: Match case variables should not be named as RIDE types, " + - "but `InvokeScriptTransaction`, `DataTransaction` found in 91-239" + "but `InvokeScriptTransaction`, `DataTransaction` found in 91-239" ) } diff --git a/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptReaderTest.scala b/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptReaderTest.scala index 2f91242ae52..30dc9d3a2d5 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptReaderTest.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptReaderTest.scala @@ -8,12 +8,12 @@ import com.wavesplatform.lang.v1.Serde import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.lang.v1.testing.TypedScriptGen import com.wavesplatform.state.diffs.produce -import com.wavesplatform.{NoShrink, crypto} +import com.wavesplatform.crypto +import com.wavesplatform.test.PropSpec import org.scalacheck.{Arbitrary, Gen} -import org.scalatest.{EitherValues, Inside, Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import org.scalatest.{EitherValues, Inside} -class ScriptReaderTest extends PropSpec with PropertyChecks with Matchers with TypedScriptGen with Inside with NoShrink with EitherValues { +class ScriptReaderTest extends PropSpec with TypedScriptGen with Inside with EitherValues { val checksumLength = 4 property("should parse all bytes for V1") { diff --git a/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptV1Test.scala b/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptV1Test.scala index c8e921678c2..146a2e2f94f 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptV1Test.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/smart/script/ScriptV1Test.scala @@ -11,10 +11,9 @@ import com.wavesplatform.lang.v1.evaluator.FunctionIds._ import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext import com.wavesplatform.lang.v1.testing.TypedScriptGen import com.wavesplatform.state.diffs._ -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class ScriptV1Test extends PropSpec with PropertyChecks with Matchers with TypedScriptGen { +class ScriptV1Test extends PropSpec with TypedScriptGen { property("ScriptV1.apply should permit BOOLEAN scripts") { forAll(BOOLEANgen(10)) { expr => diff --git a/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/ContractScriptComplexityTest.scala b/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/ContractScriptComplexityTest.scala index 411b16c197f..274bb919561 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/ContractScriptComplexityTest.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/ContractScriptComplexityTest.scala @@ -11,10 +11,9 @@ import com.wavesplatform.lang.v1.estimator.ScriptEstimator import com.wavesplatform.lang.v1.evaluator.ctx.impl.PureContext._ import com.wavesplatform.lang.v1.testing.TypedScriptGen import com.wavesplatform.protobuf.dapp.DAppMeta -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} +import com.wavesplatform.test.PropSpec -class ContractScriptComplexityTest(estimator: ScriptEstimator) extends PropSpec with PropertyChecks with Matchers with TypedScriptGen { +class ContractScriptComplexityTest(estimator: ScriptEstimator) extends PropSpec with TypedScriptGen { property("estimate contract script correctly") { val contract = DApp( diff --git a/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/FunctionComplexityTest.scala b/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/FunctionComplexityTest.scala index 18373f32e66..76ab8f4f386 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/FunctionComplexityTest.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/FunctionComplexityTest.scala @@ -18,16 +18,15 @@ import com.wavesplatform.lang.v1.{CTX, FunctionHeader} import com.wavesplatform.lang.{Global, utils} import com.wavesplatform.state.diffs.smart.predef.{chainId, scriptWithAllV1Functions} import com.wavesplatform.state.{BinaryDataEntry, BooleanDataEntry, IntegerDataEntry, StringDataEntry} +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.smart.WavesEnvironment import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{DataTransaction, Proofs} import com.wavesplatform.utils.EmptyBlockchain import monix.eval.Coeval -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class FunctionComplexityTest(estimator: ScriptEstimator) extends PropSpec with PropertyChecks with Matchers with TypedScriptGen { +class FunctionComplexityTest(estimator: ScriptEstimator) extends PropSpec with TypedScriptGen { private val environment = new WavesEnvironment(chainId, Coeval(???), null, EmptyBlockchain, null, DirectiveSet.contractDirectiveSet, ByteStr.empty) private def estimate( diff --git a/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/UserFunctionComplexityTest.scala b/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/UserFunctionComplexityTest.scala index bbe468c6648..9d6a708b64f 100644 --- a/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/UserFunctionComplexityTest.scala +++ b/node/src/test/scala/com/wavesplatform/transaction/smart/script/estimator/UserFunctionComplexityTest.scala @@ -15,13 +15,12 @@ import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.lang.v1.{CTX, FunctionHeader} import com.wavesplatform.lang.{Global, utils} import com.wavesplatform.state.diffs.smart.predef.chainId +import com.wavesplatform.test.PropSpec import com.wavesplatform.transaction.smart.WavesEnvironment import com.wavesplatform.utils.EmptyBlockchain import monix.eval.Coeval -import org.scalatest.{Matchers, PropSpec} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} -class UserFunctionComplexityTest(estimator: ScriptEstimator) extends PropSpec with PropertyChecks with Matchers with TypedScriptGen { +class UserFunctionComplexityTest(estimator: ScriptEstimator) extends PropSpec with TypedScriptGen { private val environment = new WavesEnvironment(chainId, Coeval(???), null, EmptyBlockchain, null, DirectiveSet.contractDirectiveSet, ByteStr.empty) private def estimate(expr: EXPR, ctx: CTX[Environment], funcCosts: Map[FunctionHeader, Coeval[Long]]): Either[String, Long] = { diff --git a/node/src/test/scala/com/wavesplatform/utils/ObservedLoadingCacheSpecification.scala b/node/src/test/scala/com/wavesplatform/utils/ObservedLoadingCacheSpecification.scala index 693a2fb62f4..f928d9f0664 100644 --- a/node/src/test/scala/com/wavesplatform/utils/ObservedLoadingCacheSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/utils/ObservedLoadingCacheSpecification.scala @@ -5,17 +5,17 @@ import java.util.concurrent.atomic.AtomicLong import com.google.common.base.Ticker import com.google.common.cache.{CacheBuilder, CacheLoader, LoadingCache} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.utils.ObservedLoadingCacheSpecification.FakeTicker import monix.execution.Ack import monix.reactive.Observer import org.scalamock.scalatest.MockFactory -import org.scalatest.{FreeSpec, Matchers} -import scala.jdk.CollectionConverters._ import scala.concurrent.Future import scala.concurrent.duration.DurationInt +import scala.jdk.CollectionConverters._ -class ObservedLoadingCacheSpecification extends FreeSpec with Matchers with MockFactory { +class ObservedLoadingCacheSpecification extends FreeSpec with MockFactory { private val ExpiringTime = 10.minutes "notifies" - { diff --git a/node/src/test/scala/com/wavesplatform/utils/UtilsSpecification.scala b/node/src/test/scala/com/wavesplatform/utils/UtilsSpecification.scala index f27445b9515..24fd11dd64d 100644 --- a/node/src/test/scala/com/wavesplatform/utils/UtilsSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/utils/UtilsSpecification.scala @@ -1,6 +1,7 @@ package com.wavesplatform.utils import cats.Id +import com.wavesplatform.common.state.ByteStr import com.wavesplatform.lang.directives.DirectiveSet import com.wavesplatform.lang.directives.values.V3 import com.wavesplatform.lang.utils._ @@ -9,12 +10,11 @@ import com.wavesplatform.lang.v1.compiler.Types.BOOLEAN import com.wavesplatform.lang.v1.evaluator.ctx.{EvaluationContext, UserFunction} import com.wavesplatform.lang.v1.traits.Environment import com.wavesplatform.state.diffs.smart.predef.chainId -import com.wavesplatform.common.state.ByteStr +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.smart.WavesEnvironment import monix.eval.Coeval -import org.scalatest.{FreeSpec, Matchers} -class UtilsSpecification extends FreeSpec with Matchers { +class UtilsSpecification extends FreeSpec { private val environment = new WavesEnvironment(chainId, Coeval(???), null, EmptyBlockchain, null, DirectiveSet.contractDirectiveSet, ByteStr.empty) "estimate()" - { diff --git a/node/src/test/scala/com/wavesplatform/utx/UtxFailedTxsSpec.scala b/node/src/test/scala/com/wavesplatform/utx/UtxFailedTxsSpec.scala index 8170cdd24f0..37d40ef99b2 100644 --- a/node/src/test/scala/com/wavesplatform/utx/UtxFailedTxsSpec.scala +++ b/node/src/test/scala/com/wavesplatform/utx/UtxFailedTxsSpec.scala @@ -1,7 +1,6 @@ package com.wavesplatform.utx -import scala.concurrent.duration._ - +import com.wavesplatform.TestValues import com.wavesplatform.common.utils._ import com.wavesplatform.db.WithDomain import com.wavesplatform.features.BlockchainFeatures @@ -12,17 +11,18 @@ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.mining.MultiDimensionalMiningConstraint import com.wavesplatform.settings.{FunctionalitySettings, TestFunctionalitySettings} import com.wavesplatform.state.diffs.produce +import com.wavesplatform.test.FlatSpec import com.wavesplatform.transaction.TxHelpers import com.wavesplatform.transaction.assets.exchange.OrderType import com.wavesplatform.transaction.smart.InvokeScriptTransaction.Payment import com.wavesplatform.transaction.smart.script.ScriptCompiler -import com.wavesplatform.TestValues import monix.reactive.subjects.PublishSubject -import org.scalatest.{FlatSpec, Matchers} import org.scalatest.concurrent.Eventually +import scala.concurrent.duration._ + //noinspection RedundantDefaultArgument -class UtxFailedTxsSpec extends FlatSpec with Matchers with WithDomain with Eventually { +class UtxFailedTxsSpec extends FlatSpec with WithDomain with Eventually { val dApp = TxHelpers.secondSigner "UTX pool" should s"drop failed Invoke with complexity <= ${ContractLimits.FailFreeInvokeComplexity}" in utxTest { (d, utx) => diff --git a/node/src/test/scala/com/wavesplatform/utx/UtxPoolSpecification.scala b/node/src/test/scala/com/wavesplatform/utx/UtxPoolSpecification.scala index 25d31a8c290..d837fc97156 100644 --- a/node/src/test/scala/com/wavesplatform/utx/UtxPoolSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/utx/UtxPoolSpecification.scala @@ -41,10 +41,11 @@ import org.scalacheck.Gen._ import org.scalacheck.{Arbitrary, Gen} import org.scalamock.scalatest.MockFactory import org.scalatest.concurrent.Eventually -import org.scalatest.{EitherValues, FreeSpec, Matchers} -import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} - +import org.scalatest.EitherValues import java.nio.file.{Files, Path} + +import com.wavesplatform.test.FreeSpec + import scala.collection.mutable.ListBuffer import scala.concurrent.duration._ import scala.util.Random @@ -66,12 +67,7 @@ private object UtxPoolSpecification { class UtxPoolSpecification extends FreeSpec - with Matchers - with EitherMatchers with MockFactory - with PropertyChecks - with TransactionGen - with NoShrink with BlocksTransactionsHelpers with WithDomain with EitherValues @@ -180,7 +176,7 @@ class UtxPoolSpecification (sender3, senderBalance3) <- accountsGen } yield { val bcu = mkBlockchain(Map(sender1.toAddress -> senderBalance1, sender2.toAddress -> senderBalance2, sender3.toAddress -> senderBalance3)) - (Seq((sender1, senderBalance1), (sender2, senderBalance2), (sender3, senderBalance3)), bcu) + (((sender1, senderBalance1), (sender2, senderBalance2), (sender3, senderBalance3)), bcu) } private val twoOutOfManyValidPayments = (for { @@ -499,7 +495,7 @@ class UtxPoolSpecification "adds new transactions when transaction is whitelisted" in { forAll(stateWithThreeAccounts) { - case (Seq((sender1, senderBalance1), (sender2, senderBalance2), (sender3, _)), bcu) => + case (((sender1, senderBalance1), (sender2, senderBalance2), (sender3, _)), bcu) => val time = new TestTime() val precondition = TestBlock.create( @@ -571,7 +567,7 @@ class UtxPoolSpecification } "packUnconfirmed takes whitelisted first of all" in forAll(stateWithThreeAccounts) { - case (Seq((sender1, senderBalance1), (sender2, senderBalance2), (sender3, _)), bcu) => + case (((sender1, senderBalance1), (sender2, senderBalance2), (sender3, _)), bcu) => val time = new TestTime() val precondition = TestBlock.create( @@ -1002,7 +998,7 @@ class UtxPoolSpecification val utxPool = new UtxPoolImpl(time, d.blockchainUpdater, ignoreSpendableBalanceChanged, WavesSettings.default().utxSettings, events += _) - def assertEvents(f: Seq[UtxEvent] => Unit): Unit = { + def assertEvents(f: PartialFunction[Seq[UtxEvent], Unit]): Unit = { val currentEvents = events.toVector f(currentEvents) events.clear() diff --git a/node/src/test/scala/com/wavesplatform/utx/UtxPriorityPoolSpecification.scala b/node/src/test/scala/com/wavesplatform/utx/UtxPriorityPoolSpecification.scala index 307dc62a598..fe57a53904e 100644 --- a/node/src/test/scala/com/wavesplatform/utx/UtxPriorityPoolSpecification.scala +++ b/node/src/test/scala/com/wavesplatform/utx/UtxPriorityPoolSpecification.scala @@ -14,30 +14,27 @@ import com.wavesplatform.mining.{MultiDimensionalMiningConstraint, OneDimensiona import com.wavesplatform.settings.WavesSettings import com.wavesplatform.state.diffs.ENOUGH_AMT import com.wavesplatform.state.{AccountScriptInfo, Blockchain, Diff, LeaseBalance, Portfolio} +import com.wavesplatform.test.FreeSpec import com.wavesplatform.transaction.Asset.Waves import com.wavesplatform.transaction.transfer.TransferTransaction import com.wavesplatform.transaction.{Transaction, TxHelpers, TxVersion} import com.wavesplatform.utils.Time import com.wavesplatform.utx.UtxPool.PackStrategy -import com.wavesplatform.{BlocksTransactionsHelpers, EitherMatchers, NoShrink, TestValues, TransactionGen} +import com.wavesplatform.{BlocksTransactionsHelpers, TestValues} import org.scalacheck.Gen import org.scalacheck.Gen.chooseNum import org.scalamock.scalatest.MockFactory +import org.scalatest.EitherValues import org.scalatest.concurrent.Eventually import org.scalatest.concurrent.PatienceConfiguration.{Interval, Timeout} -import org.scalatest.{EitherValues, FreeSpec, Matchers} import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.concurrent.duration._ class UtxPriorityPoolSpecification extends FreeSpec - with Matchers - with EitherMatchers with MockFactory with ScalaCheckDrivenPropertyChecks - with TransactionGen - with NoShrink with BlocksTransactionsHelpers with WithDomain with EitherValues diff --git a/project/CommonSettings.scala b/project/CommonSettings.scala index 9b19423bdc0..0f4d6e43b86 100644 --- a/project/CommonSettings.scala +++ b/project/CommonSettings.scala @@ -8,9 +8,7 @@ object CommonSettings extends AutoPlugin { override def trigger: PluginTrigger = allRequirements // These options doesn't work for ScalaJS - override def projectSettings: Seq[Def.Setting[_]] = Seq( - packageSource := sourceDirectory.value / "package" - ) + override def projectSettings: Seq[Def.Setting[_]] = Seq() } trait CommonKeys { diff --git a/project/Dependencies.scala b/project/Dependencies.scala index 895cbbadc8e..f7537dda467 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -1,45 +1,46 @@ import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._ -import sbt._ import sbt.Keys._ +import sbt._ //noinspection TypeAnnotation object Dependencies { // Node protobuf schemas private[this] val protoSchemasLib = - "com.wavesplatform" % "protobuf-schemas" % "1.3.1" classifier "proto" intransitive () + "com.wavesplatform" % "protobuf-schemas" % "1.3.2-SNAPSHOT" classifier "protobuf-src" intransitive () - def akkaModule(module: String): ModuleID = "com.typesafe.akka" %% s"akka-$module" % "2.6.4" + def akkaModule(module: String): ModuleID = "com.typesafe.akka" %% s"akka-$module" % "2.6.14" - private def akkaHttpModule(module: String) = "com.typesafe.akka" %% module % "10.1.12" - private def kamonModule(module: String) = "io.kamon" %% s"kamon-$module" % "2.1.0" - private def jacksonModule(group: String, module: String) = s"com.fasterxml.jackson.$group" % s"jackson-$module" % "2.11.0" - private def bouncyCastle(module: String) = "org.bouncycastle" % s"$module-jdk15on" % "1.59" + private def akkaHttpModule(module: String) = "com.typesafe.akka" %% module % "10.2.4" + private def nettyModule(module: String) = "io.netty" % s"netty-$module" % "4.1.65.Final" + private def kamonModule(module: String) = "io.kamon" %% s"kamon-$module" % "2.2.0" + private def jacksonModule(group: String, module: String) = s"com.fasterxml.jackson.$group" % s"jackson-$module" % "2.12.3" + private def bouncyCastle(module: String) = "org.bouncycastle" % s"$module-jdk15on" % "1.68" private def iq80leveldb(module: String) = "org.iq80.leveldb" % module % "0.12" - private def catsModule(module: String, version: String = "2.1.0") = Def.setting("org.typelevel" %%% s"cats-$module" % version) - def monixModule(module: String) = Def.setting("io.monix" %%% s"monix-$module" % "3.3.0") + private def catsModule(module: String, version: String = "2.6.1") = Def.setting("org.typelevel" %%% s"cats-$module" % version) + def monixModule(module: String) = Def.setting("io.monix" %%% s"monix-$module" % "3.4.0") - private val kindProjector = compilerPlugin("org.typelevel" % "kind-projector" % "0.11.0" cross CrossVersion.full) + val kindProjector = compilerPlugin("org.typelevel" % "kind-projector" % "0.13.0" cross CrossVersion.full) - val akkaHttp = akkaHttpModule("akka-http") - val jacksonModuleScala = jacksonModule("module", "module-scala").withCrossVersion(CrossVersion.Binary()) - val googleGuava = "com.google.guava" % "guava" % "27.0.1-jre" - val kamonCore = kamonModule("core") - val machinist = "org.typelevel" %% "machinist" % "0.6.8" - val logback = "ch.qos.logback" % "logback-classic" % "1.2.3" - val janino = "org.codehaus.janino" % "janino" % "3.0.12" - val asyncHttpClient = "org.asynchttpclient" % "async-http-client" % "2.7.0" - val curve25519 = "com.wavesplatform" % "curve25519-java" % "0.6.4" - val nettyHandler: ModuleID = "io.netty" % "netty-handler" % "4.1.59.Final" + val akkaHttp = akkaHttpModule("akka-http") + val jacksonModuleScala = jacksonModule("module", "module-scala").withCrossVersion(CrossVersion.Binary()) + val googleGuava = "com.google.guava" % "guava" % "30.1.1-jre" + val kamonCore = kamonModule("core") + val machinist = "org.typelevel" %% "machinist" % "0.6.8" + val logback = "ch.qos.logback" % "logback-classic" % "1.2.3" + val janino = "org.codehaus.janino" % "janino" % "3.1.4" + val asyncHttpClient = "org.asynchttpclient" % "async-http-client" % "2.12.3" + val curve25519 = "com.wavesplatform" % "curve25519-java" % "0.6.4" + val nettyHandler = nettyModule("handler") val catsEffect = catsModule("effect", "2.1.3") val catsCore = catsModule("core") - val shapeless = Def.setting("com.chuusai" %%% "shapeless" % "2.3.3") + val shapeless = Def.setting("com.chuusai" %%% "shapeless" % "2.3.7") - val scalaTest = "org.scalatest" %% "scalatest" % "3.0.8" % Test + val scalaTest = "org.scalatest" %% "scalatest" % "3.2.9" % Test - val kafka = "org.apache.kafka" %% "kafka" % "2.5.0" + val sttp3 = "com.softwaremill.sttp.client3" % "core_2.13" % "3.2.3" val enforcedVersions = Def.setting( Seq( @@ -54,6 +55,7 @@ object Dependencies { jacksonModule("core", "annotations"), jacksonModule("core", "databind"), jacksonModule("dataformat", "dataformat-yaml"), + jacksonModule("dataformat", "dataformat-properties"), jacksonModule("jaxrs", "jaxrs-base"), jacksonModule("jaxrs", "jaxrs-json-provider"), kamonCore, @@ -63,7 +65,6 @@ object Dependencies { "com.squareup.okio" % "okio" % "1.14.0", "com.lihaoyi" %% "sourcecode" % "0.2.1", nettyHandler, - bouncyCastle("bcpkix"), bouncyCastle("bcprov"), "org.apache.httpcomponents" % "httpcore" % "4.4.5", "org.javassist" % "javassist" % "3.21.0-GA", @@ -73,19 +74,17 @@ object Dependencies { catsEffect.value, catsCore.value, catsModule("kernel").value, - catsModule("macros").value, - shapeless.value, - kafka + catsModule("macros", "2.1.1").value, + shapeless.value ) ) - val console = Seq("com.github.scopt" %% "scopt" % "4.0.0-RC2") + val console = Seq("com.github.scopt" %% "scopt" % "4.0.1") - val common = Def.setting( - Seq( - scalaTest - ) - ) + val langCompilerPlugins = Def.setting(Seq( + compilerPlugin("com.olegpy" %% "better-monadic-for" % "0.3.1"), + kindProjector + )) val lang = Def.setting( Seq( @@ -93,39 +92,32 @@ object Dependencies { // explicit dependency can likely be removed when monix 3 is released monixModule("eval").value, catsCore.value.exclude("org.scala-js", "scalajs-library_2.13"), - ("org.rudogma" %%% "supertagged" % "1.5").exclude("org.scala-js", "scalajs-library_2.13"), - ("com.lihaoyi" %%% "fastparse" % "2.2.4").exclude("org.scala-js", "scalajs-library_2.13"), - ("org.parboiled" %%% "parboiled" % "2.1.8").exclude("org.scala-js", "scalajs-library_2.13"), + ("com.lihaoyi" %%% "fastparse" % "2.3.2").exclude("org.scala-js", "scalajs-library_2.13"), + ("org.parboiled" %%% "parboiled" % "2.3.0").exclude("org.scala-js", "scalajs-library_2.13"), shapeless.value.exclude("org.scala-js", "scalajs-library_2.13"), - machinist.exclude("org.scala-js", "scalajs-library_2.13"), - catsEffect.value, ("org.typelevel" %% "cats-mtl-core" % "0.7.1").exclude("org.scalacheck", "scalacheck_2.13"), - "ch.obermuhlner" % "big-math" % "2.1.0", - ("org.scorexfoundation" %% "scrypto" % "2.1.8").exclude("org.whispersystems", "curve25519-java"), + "ch.obermuhlner" % "big-math" % "2.3.0", curve25519, - bouncyCastle("bcpkix"), bouncyCastle("bcprov"), - kindProjector, - compilerPlugin("com.olegpy" %% "better-monadic-for" % "0.3.1"), - "com.softwaremill.sttp" %%% "core" % "1.6.4", - "com.wavesplatform" % "zwaves" % "0.1.0-SNAPSHOT", - "com.wavesplatform" % "zwaves-bn256" % "0.1.5-SNAPSHOT", - "org.web3j" % "crypto" % "4.5.18" - ) ++ scalapbRuntime.value ++ circe.value ++ protobuf.value + "com.wavesplatform" % "zwaves" % "0.1.0-SNAPSHOT", + "com.wavesplatform" % "zwaves-bn256" % "0.1.5-SNAPSHOT", + "org.web3j" % "crypto" % "5.0.0" + ) ++ langCompilerPlugins.value ++ scalapbRuntime.value ++ protobuf.value ) lazy val it = scalaTest +: Seq( logback, - "com.spotify" % "docker-client" % "8.15.1", + "com.spotify" % "docker-client" % "8.16.0", jacksonModule("dataformat", "dataformat-properties"), asyncHttpClient ).map(_ % Test) lazy val test = scalaTest +: Seq( logback, - "org.scalacheck" %% "scalacheck" % "1.14.3", + "org.scalatestplus" %% "scalacheck-1-15" % "3.2.9.0", + "org.scalacheck" %% "scalacheck" % "1.15.4", "org.mockito" % "mockito-all" % "1.10.19", - "org.scalamock" %% "scalamock" % "4.4.0" + "org.scalamock" %% "scalamock" % "5.1.0" ).map(_ % Test) lazy val logDeps = Seq( @@ -134,27 +126,32 @@ object Dependencies { akkaModule("slf4j") % Runtime ) + private def leveldbJava(module: String = "") = "org.iq80.leveldb" % s"leveldb${if (module.nonEmpty) "-" else ""}$module" % "0.12" + private[this] val levelDBJNA = { val levelDbVersion = "1.22.3" Seq( + "net.java.dev.jna" % "jna" % "5.8.0", "com.wavesplatform.leveldb-jna" % "leveldb-jna-core" % levelDbVersion, - "com.wavesplatform.leveldb-jna" % "leveldb-jna-native" % levelDbVersion + "com.wavesplatform.leveldb-jna" % "leveldb-jna-native" % levelDbVersion, + leveldbJava("api") ) } lazy val node = Def.setting( Seq( - "commons-net" % "commons-net" % "3.6", - "org.apache.commons" % "commons-lang3" % "3.9", - "com.iheart" %% "ficus" % "1.4.7", - "net.logstash.logback" % "logstash-logback-encoder" % "4.11" % Runtime, + ("org.rudogma" %%% "supertagged" % "2.0-RC2").exclude("org.scala-js", "scalajs-library_2.13"), + "commons-net" % "commons-net" % "3.8.0", + "org.apache.commons" % "commons-lang3" % "3.12.0", + "com.iheart" %% "ficus" % "1.5.0", + "net.logstash.logback" % "logstash-logback-encoder" % "6.6" % Runtime, kamonCore, kamonModule("system-metrics"), kamonModule("influxdb"), - "org.influxdb" % "influxdb-java" % "2.14", + "org.influxdb" % "influxdb-java" % "2.21", googleGuava, "com.google.code.findbugs" % "jsr305" % "3.0.2" % Compile, // javax.annotation stubs - "com.typesafe.play" %% "play-json" % "2.9.0", + "com.typesafe.play" %% "play-json" % "2.9.2", akkaModule("actor"), akkaModule("stream"), akkaHttp, @@ -162,10 +159,10 @@ object Dependencies { kindProjector, monixModule("reactive").value, nettyHandler, - iq80leveldb("leveldb-api"), - akkaModule("testkit") % Test, - akkaHttpModule("akka-http-testkit") % Test, - iq80leveldb("leveldb").exclude("com.google.guava", "guava") % Test + "com.typesafe.scala-logging" %% "scala-logging" % "3.9.3", + akkaModule("testkit") % Test, + akkaHttpModule("akka-http-testkit") % Test, + leveldbJava().exclude("com.google.guava", "guava") % Test ) ++ test ++ console ++ logDeps ++ levelDBJNA ++ protobuf.value ) @@ -173,8 +170,7 @@ object Dependencies { val version = scalapb.compiler.Version.scalapbVersion Seq( "com.thesamet.scalapb" %%% "scalapb-runtime" % version, - "com.thesamet.scalapb" %%% "scalapb-runtime" % version % "protobuf", - "com.thesamet.scalapb" %% "scalapb-json4s" % "0.9.3" + "com.thesamet.scalapb" %%% "scalapb-runtime" % version % "protobuf" ) } @@ -189,15 +185,11 @@ object Dependencies { ) lazy val circe = Def.setting { - val circeVersion = "0.13.0" + val circeVersion = "0.14.1" Seq( "io.circe" %%% "circe-core", "io.circe" %%% "circe-generic", "io.circe" %%% "circe-parser" ).map(_ % circeVersion) } - - lazy val circeJsInterop = Def.setting { - "io.circe" %%% "not-java-time" % "0.2.0" - } } diff --git a/project/ExtensionPackaging.scala b/project/ExtensionPackaging.scala index 91227d06ade..5fe9cf9ab06 100644 --- a/project/ExtensionPackaging.scala +++ b/project/ExtensionPackaging.scala @@ -28,7 +28,6 @@ object ExtensionPackaging extends AutoPlugin { Seq( packageDoc / publishArtifact := false, packageSrc / publishArtifact := false, - Universal / javaOptions := Nil, // Here we record the classpath as it's added to the mappings separately, so // we can use its order to generate the bash/bat scripts. classpathOrdering := Nil, @@ -70,8 +69,7 @@ object ExtensionPackaging extends AutoPlugin { Debian / normalizedName := s"${name.value}${network.value.packageSuffix}", Debian / packageName := s"${name.value}${network.value.packageSuffix}", libraryDependencies ++= Dependencies.logDeps, - javaOptions in run ++= extensionClasses.value.zipWithIndex.map { case (extension, index) => s"-Dwaves.extensions.$index=$extension" }, - maintainer := "wavesplatform.com" + run / javaOptions ++= extensionClasses.value.zipWithIndex.map { case (extension, index) => s"-Dwaves.extensions.$index=$extension" } ) ++ maintainerFix private def maintainerFix = @@ -145,7 +143,7 @@ object ExtensionPackaging extends AutoPlugin { val providedClasspath = refs.map { ref => stateTask.flatMap { state => val extracted = Project.extract(state) - extracted.get(Runtime / dependencyClasspath in ref) + extracted.get(ref / Runtime / dependencyClasspath) } } diff --git a/project/RunApplicationSettings.scala b/project/RunApplicationSettings.scala index 278f4cb53b1..1b86813a0c2 100644 --- a/project/RunApplicationSettings.scala +++ b/project/RunApplicationSettings.scala @@ -6,7 +6,7 @@ object RunApplicationSettings extends AutoPlugin { inConfig(Compile)( Seq( mainClass := Some("com.wavesplatform.Application"), - discoveredMainClasses := (mainClass in Compile).value.toSeq, + discoveredMainClasses := (Compile / mainClass).value.toSeq, run / fork := true )) } diff --git a/project/Tasks.scala b/project/Tasks.scala index 3e15696f5fc..61042ff1215 100644 --- a/project/Tasks.scala +++ b/project/Tasks.scala @@ -145,7 +145,7 @@ object Tasks { | } """.stripMargin - val rawDocFile = sourceManaged.value / "com" / "wavesplatform" / "DocSource.scala" + val rawDocFile = (Compile / sourceManaged).value / "com" / "wavesplatform" / "DocSource.scala" IO.write(rawDocFile, sourceStr) Seq(rawDocFile) diff --git a/project/build.properties b/project/build.properties index a919a9b5f46..67d27a1dfe0 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version=1.3.8 +sbt.version=1.5.3 diff --git a/project/plugins.sbt b/project/plugins.sbt index b9f5504cd40..1aa67c6f6bd 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -4,30 +4,28 @@ resolvers ++= Seq( ) // Should go before Scala.js -addSbtPlugin("com.thesamet" % "sbt-protoc" % "0.99.28") +addSbtPlugin("com.thesamet" % "sbt-protoc" % "1.0.3") -libraryDependencies += "com.thesamet.scalapb" %% "compilerplugin" % "0.9.0" +libraryDependencies += "com.thesamet.scalapb" %% "compilerplugin" % "0.11.3" Seq( "com.eed3si9n" % "sbt-assembly" % "0.14.10", "com.typesafe.sbt" % "sbt-native-packager" % "1.3.25", "org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0", - "org.scoverage" % "sbt-scoverage" % "1.6.1", - "se.marcuslonnberg" % "sbt-docker" % "1.8.1", + "se.marcuslonnberg" % "sbt-docker" % "1.8.2", "com.typesafe.sbt" % "sbt-git" % "1.0.0", - "org.scala-js" % "sbt-scalajs" % "0.6.33", - "org.portable-scala" % "sbt-scalajs-crossproject" % "0.6.0", + "org.scala-js" % "sbt-scalajs" % "1.5.1", + "org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0", "org.scalameta" % "sbt-scalafmt" % "2.2.1", - "pl.project13.scala" % "sbt-jmh" % "0.3.3", - "com.jsuereth" % "sbt-pgp" % "1.1.1", - "com.github.cb372" % "sbt-explicit-dependencies" % "0.2.10" + "pl.project13.scala" % "sbt-jmh" % "0.3.7", + "com.jsuereth" % "sbt-pgp" % "1.1.1" ).map(addSbtPlugin) libraryDependencies ++= Seq( "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.12.1", - "org.hjson" % "hjson" % "3.0.0", - "org.vafer" % "jdeb" % "1.5" artifacts Artifact("jdeb", "jar", "jar"), - "org.slf4j" % "jcl-over-slf4j" % "1.7.30", + "org.hjson" % "hjson" % "3.0.0", + "org.vafer" % "jdeb" % "1.5" artifacts Artifact("jdeb", "jar", "jar"), + "org.slf4j" % "jcl-over-slf4j" % "1.7.30", ("com.spotify" % "docker-client" % "8.15.1") .exclude("commons-logging", "commons-logging") ) diff --git a/repl/js/src/main/scala/com/wavesplatform/lang/v1/repl/Global.scala b/repl/js/src/main/scala/com/wavesplatform/lang/v1/repl/Global.scala new file mode 100644 index 00000000000..a0a14f843a2 --- /dev/null +++ b/repl/js/src/main/scala/com/wavesplatform/lang/v1/repl/Global.scala @@ -0,0 +1,14 @@ +package com.wavesplatform.lang.v1.repl + +import com.wavesplatform.lang.v1.repl.node.http.response.model.NodeResponse + +import scala.concurrent.{ExecutionContext, Future} +import scala.scalajs.js + +object Global { + def requestNode(url: String): Future[NodeResponse] = + impl.Global + .httpGet(js.Dynamic.literal(url = url)) + .toFuture + .map(r => NodeResponse(r.status.asInstanceOf[Int], r.body.asInstanceOf[String]))(ExecutionContext.global) +} diff --git a/repl/js/src/main/scala/com/wavesplatform/lang/v1/repl/impl/Global.scala b/repl/js/src/main/scala/com/wavesplatform/lang/v1/repl/impl/Global.scala new file mode 100644 index 00000000000..bb031039d5d --- /dev/null +++ b/repl/js/src/main/scala/com/wavesplatform/lang/v1/repl/impl/Global.scala @@ -0,0 +1,11 @@ +package com.wavesplatform.lang.v1.repl.impl + +import scala.scalajs.js +import scala.scalajs.js.annotation.JSGlobalScope +import scala.scalajs.js.{Object, Promise, native} + +@native +@JSGlobalScope +object Global extends Object { + def httpGet(params: js.Dynamic): Promise[js.Dynamic] = native +} \ No newline at end of file diff --git a/repl/jvm/src/main/scala/com/wavesplatform/lang/SttpClient.scala b/repl/jvm/src/main/scala/com/wavesplatform/lang/SttpClient.scala new file mode 100644 index 00000000000..57c0806fc95 --- /dev/null +++ b/repl/jvm/src/main/scala/com/wavesplatform/lang/SttpClient.scala @@ -0,0 +1,25 @@ +package com.wavesplatform.lang + +import com.wavesplatform.lang.v1.repl.node.http.response.model.NodeResponse +import sttp.client3._ + +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent.Future + +class SttpClient { + private val backend: SttpBackend[Identity, Any] = HttpURLConnectionBackend() + private val schemaRegex = "^\\w+://.+".r + + def requestNode(url: String): Future[NodeResponse] = { + val urlPrefix = + if (schemaRegex.findFirstMatchIn(url).nonEmpty) "" + else "http://" + + Future( + basicRequest + .get(uri"${urlPrefix + url}") + .header("user-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36") + .send(backend) + ).map(r => NodeResponse(r.code.code, r.body.fold(identity, identity))) + } +} diff --git a/repl/jvm/src/main/scala/com/wavesplatform/lang/v1/repl/Global.scala b/repl/jvm/src/main/scala/com/wavesplatform/lang/v1/repl/Global.scala new file mode 100644 index 00000000000..270cc5d4a65 --- /dev/null +++ b/repl/jvm/src/main/scala/com/wavesplatform/lang/v1/repl/Global.scala @@ -0,0 +1,12 @@ +package com.wavesplatform.lang.v1.repl + +import com.wavesplatform.lang.SttpClient +import com.wavesplatform.lang.v1.repl.node.http.response.model.NodeResponse + +import scala.concurrent.Future + +object Global { + private val client = new SttpClient() + + def requestNode(url: String): Future[NodeResponse] = client.requestNode(url) +} diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/DeclPrinter.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/DeclPrinter.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/DeclPrinter.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/DeclPrinter.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Implicits.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Implicits.scala similarity index 76% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Implicits.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Implicits.scala index b169b04f02b..11e899bcaf8 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Implicits.scala +++ b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Implicits.scala @@ -8,8 +8,8 @@ import scala.concurrent.ExecutionContext.Implicits.{global => g} import scala.concurrent.Future object Implicits { - implicit def stackUnsafeMonad[F[_] : Monad]: Monad[EvalF[F, ?]] = - new StackSafeMonad[EvalF[F, ?]] { + implicit def stackUnsafeMonad[F[_] : Monad]: Monad[EvalF[F, *]] = + new StackSafeMonad[EvalF[F, *]] { override def flatMap[A, B](fa: Eval[F[A]])(f: A => Eval[F[B]]): Eval[F[B]] = fa.map(_.flatMap(f(_).value)) @@ -18,5 +18,5 @@ object Implicits { } implicit val futureMonad: Monad[Future] = Monad[Future] - implicit val futureEvalFMonad: Monad[EvalF[Future, ?]] = stackUnsafeMonad[Future] + implicit val futureEvalFMonad: Monad[EvalF[Future, *]] = stackUnsafeMonad[Future] } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Repl.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Repl.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Repl.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/Repl.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/ReplEngine.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/ReplEngine.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/ReplEngine.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/ReplEngine.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/StateView.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/StateView.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/StateView.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/StateView.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/ErrorMessageEnvironment.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/ErrorMessageEnvironment.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/ErrorMessageEnvironment.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/ErrorMessageEnvironment.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeClient.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeClient.scala similarity index 94% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeClient.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeClient.scala index a7a5faa270d..9baa689009d 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeClient.scala +++ b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeClient.scala @@ -3,18 +3,18 @@ package com.wavesplatform.lang.v1.repl.node.http import cats.Functor import cats.implicits._ import com.wavesplatform.common.utils.EitherExt2 -import com.wavesplatform.lang.v1.repl.global import com.wavesplatform.lang.v1.repl.node.http.NodeClient.ResponseWrapper import com.wavesplatform.lang.v1.repl.node.http.response.model.NodeResponse import io.circe.Decoder import io.circe.parser.decode +import com.wavesplatform.lang.v1.repl.Global import scala.concurrent.ExecutionContext.Implicits.{global => g} import scala.concurrent.Future private[node] case class NodeClient(baseUrl: String) { def get[F[_] : Functor : ResponseWrapper, R: Decoder](path: String): Future[F[R]] = - global.requestNode(baseUrl + path) + Global.requestNode(baseUrl + path) .map(r => r: F[String]) .map(_.map(decode[R]).map(_.explicitGet())) } diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeConnectionSettings.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeConnectionSettings.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeConnectionSettings.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/NodeConnectionSettings.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/WebEnvironment.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/WebEnvironment.scala similarity index 86% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/WebEnvironment.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/WebEnvironment.scala index 2452d71cf85..4cee90bf652 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/WebEnvironment.scala +++ b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/WebEnvironment.scala @@ -8,7 +8,7 @@ import com.wavesplatform.lang.v1.repl.node.http.NodeClient._ import com.wavesplatform.lang.v1.repl.node.http.response.ImplicitMappings import com.wavesplatform.lang.v1.repl.node.http.response.model.Transaction._ import com.wavesplatform.lang.v1.repl.node.http.response.model._ -import com.wavesplatform.lang.v1.traits.Environment.InputEntity +import com.wavesplatform.lang.v1.traits.Environment.{BalanceDetails, InputEntity} import com.wavesplatform.lang.v1.traits.domain.Recipient.{Address, Alias} import com.wavesplatform.lang.v1.traits.domain.{BlockInfo, Recipient, ScriptAssetInfo, Tx} import com.wavesplatform.lang.v1.traits.{DataType, Environment} @@ -23,6 +23,8 @@ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future private[repl] case class WebEnvironment(settings: NodeConnectionSettings) extends Environment[Future] { + import WebEnvironment._ + private val client = NodeClient(settings.normalizedUrl) private val mappings = ImplicitMappings(settings.chainId) import mappings._ @@ -79,7 +81,7 @@ private[repl] case class WebEnvironment(settings: NodeConnectionSettings) extend generator <- c.downField("generator").as[ByteString] generatorPublicKey <- c.downField("generatorPublicKey").as[ByteString] vrf <- c.downField("VRF").as[Option[ByteString]] - } yield BlockInfoResponse(timestamp, height, nxt, generator, generatorPublicKey, vrf) + } yield BlockInfoResponse(timestamp, height, nxt, generator, generatorPublicKey, vrf) } override def blockInfoByHeight(height: Int): Future[Option[BlockInfo]] = @@ -102,7 +104,7 @@ private[repl] case class WebEnvironment(settings: NodeConnectionSettings) extend } override def resolveAlias(name: String): Future[Either[String, Address]] = - getEntity[Either[String, ?], AddressResponse, Address](s"/alias/by-alias/$name") + getEntity[Either[String, *], AddressResponse, Address](s"/alias/by-alias/$name") implicit val balanceResponseDecoder: Decoder[BalanceResponse] = new Decoder[BalanceResponse] { final def apply(c: HCursor): Decoder.Result[BalanceResponse] = @@ -112,23 +114,23 @@ private[repl] case class WebEnvironment(settings: NodeConnectionSettings) extend } override def accountBalanceOf( - recipient: Recipient, - assetId: Option[Array[Byte]] - ): Future[Either[String, Long]] = + recipient: Recipient, + assetId: Option[Array[Byte]] + ): Future[Either[String, Long]] = for { address <- extractAddress(recipient) - entity <- getEntity[Either[String, ?], BalanceResponse, Long]((assetId match { + entity <- getEntity[Either[String, *], BalanceResponse, Long]((assetId match { case Some(assetId) => s"/assets/balance/${address}/${Base58.encode(assetId)}" case None => s"/address/balance/${address}" })) } yield entity override def accountWavesBalanceOf( - recipient: Recipient - ): Future[Either[String, Environment.BalanceDetails]] = + recipient: Recipient + ): Future[Either[String, Environment.BalanceDetails]] = for { address <- extractAddress(recipient) - entity <- client.get[Either[String, ?], Environment.BalanceDetails](s"/addresses/balance/details/$address") + entity <- client.get[Either[String, *], Environment.BalanceDetails](s"/addresses/balance/details/$address") } yield entity private def extractAddress(addressOrAlias: Recipient): Future[String] = @@ -153,3 +155,14 @@ private[repl] case class WebEnvironment(settings: NodeConnectionSettings) extend override def accountScript(addressOrAlias: Recipient): Future[Option[Script]] = ??? override def callScript(dApp: Address, func: String, args: List[EVALUATED], payments: Seq[(Option[Array[Byte]], Long)], availableComplexity: Int, reentrant: Boolean): Coeval[Future[(Either[ValidationError, EVALUATED], Int)]] = ??? } + +object WebEnvironment { + implicit val BalanceDetailsDecoder: Decoder[BalanceDetails] = (c: HCursor) => + for { + available <- c.downField("available").as[Long] + regular <- c.downField("regular").as[Long] + generating <- c.downField("generating").as[Long] + effective <- c.downField("effective").as[Long] + } yield BalanceDetails(available, regular, generating, effective) + +} diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ChainDependentMapper.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ChainDependentMapper.scala similarity index 98% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ChainDependentMapper.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ChainDependentMapper.scala index 71bc0a3e52b..be573fd3a19 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ChainDependentMapper.scala +++ b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ChainDependentMapper.scala @@ -112,7 +112,8 @@ private[node] class ChainDependentMapper(chainId: Byte) { } private def addressFromBytes(addressBytes: Array[Byte]): Either[String, Address] = { - val Array(version, network, _*) = addressBytes + val version = addressBytes(0) + val network = addressBytes(1) for { _ <- Either.cond( addressBytes.length == AddressLength, diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ImplicitMappings.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ImplicitMappings.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ImplicitMappings.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/ImplicitMappings.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/TransferTxSerializer.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/TransferTxSerializer.scala similarity index 93% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/TransferTxSerializer.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/TransferTxSerializer.scala index d2527e91633..c02bce51a80 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/TransferTxSerializer.scala +++ b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/TransferTxSerializer.scala @@ -12,6 +12,8 @@ import com.wavesplatform.protobuf.transaction._ import com.wavesplatform.protobuf.transaction.Transaction.Data object TransferTxSerializer { + import ByteString.{copyFrom => bs} + private val typeId: Byte = 4 def bodyBytes( @@ -41,7 +43,7 @@ object TransferTxSerializer { case 1 => Array(typeId) ++ baseBytes case 2 => Array(typeId, version) ++ baseBytes case _ => - protobufBytes(sender, chainId, amount, assetId.map(b => b), fee, feeAssetId.map(b => b), timestamp, version, proofs.map(p => p), attachment, recipient) + protobufBytes(bs(sender), chainId, amount, assetId.map(bs), fee, feeAssetId.map(bs), timestamp, version, proofs.map(bs), bs(attachment), recipient) } } @@ -86,9 +88,6 @@ object TransferTxSerializer { transaction.getTransaction.toByteArray } - private implicit def byteString(array: Array[Byte]): ByteString = - ByteString.copyFrom(array) - private def serializeArrayWithLength(b: Array[Byte]): Array[Byte] = { val length = b.length if (length.isValidShort) diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/AddressResponse.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/AddressResponse.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/AddressResponse.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/AddressResponse.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/AssetInfoResponse.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/AssetInfoResponse.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/AssetInfoResponse.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/AssetInfoResponse.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/BalanceResponse.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/BalanceResponse.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/BalanceResponse.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/BalanceResponse.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/BlockInfoResponse.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/BlockInfoResponse.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/BlockInfoResponse.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/BlockInfoResponse.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/ByteString.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/ByteString.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/ByteString.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/ByteString.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/DataEntry.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/DataEntry.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/DataEntry.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/DataEntry.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/HeightResponse.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/HeightResponse.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/HeightResponse.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/HeightResponse.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/NodeResponse.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/NodeResponse.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/NodeResponse.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/NodeResponse.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/Transaction.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/Transaction.scala similarity index 100% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/Transaction.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/node/http/response/model/Transaction.scala diff --git a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/package.scala b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/package.scala similarity index 94% rename from lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/package.scala rename to repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/package.scala index 6bc229ab602..0435657b671 100644 --- a/lang/shared/src/main/scala/com/wavesplatform/lang/v1/repl/package.scala +++ b/repl/shared/src/main/scala/com/wavesplatform/lang/v1/repl/package.scala @@ -26,5 +26,5 @@ package object repl { WavesContext.build(global, directives) def buildEnvironment(settings: Option[NodeConnectionSettings]): Environment[Future] = - settings.fold(ErrorMessageEnvironment[Future]("Blockchain state is unavailable from REPL"): Environment[Future])(WebEnvironment) + settings.fold(ErrorMessageEnvironment[Future]("Blockchain state is unavailable from REPL"): Environment[Future])(s => WebEnvironment(s)) } diff --git a/lang/tests/src/test/scala/com/wavesplatform/lang/v1/ReplTest.scala b/repl/shared/src/test/scala/com/wavesplatform/lang/v1/ReplTest.scala similarity index 100% rename from lang/tests/src/test/scala/com/wavesplatform/lang/v1/ReplTest.scala rename to repl/shared/src/test/scala/com/wavesplatform/lang/v1/ReplTest.scala