diff --git a/build.sbt b/build.sbt index 607f69f7fe..7abbedd07c 100644 --- a/build.sbt +++ b/build.sbt @@ -230,9 +230,27 @@ lazy val coreJS = core.js ) ) +lazy val data = crossProject(JVMPlatform, JSPlatform) + .in(file("data")) + .dependsOn(core % allConfigDependency) + .settings( + commonSettings ++ testSettings2, + commonDependenies2, + testingDependencies2, + scorexUtilDependency, fastparseDependency, circeDependency, scryptoDependency, + publish / skip := true + ) + .jvmSettings( crossScalaSettings ) + .jsSettings( + crossScalaSettingsJS, + useYarn := true + ) +lazy val dataJS = data.js + .enablePlugins(ScalaJSBundlerPlugin) + lazy val interpreter = crossProject(JVMPlatform, JSPlatform) .in(file("interpreter")) - .dependsOn(core % allConfigDependency) + .dependsOn(core % allConfigDependency, data % allConfigDependency) .settings( commonSettings ++ testSettings2, commonDependenies2, @@ -275,7 +293,7 @@ lazy val parsersJS = parsers.js lazy val sdk = crossProject(JVMPlatform, JSPlatform) .in(file("sdk")) - .dependsOn(core % allConfigDependency, interpreter % allConfigDependency, parsers % allConfigDependency) + .dependsOn(core % allConfigDependency, data % allConfigDependency, interpreter % allConfigDependency, parsers % allConfigDependency) .settings(commonSettings ++ testSettings2, commonDependenies2, testingDependencies2, @@ -343,13 +361,13 @@ lazy val scJS = sc.js lazy val sigma = (project in file(".")) - .aggregate(core.jvm, interpreter.jvm, parsers.jvm, sdk.jvm, sc.jvm) + .aggregate(core.jvm, data.jvm, interpreter.jvm, parsers.jvm, sdk.jvm, sc.jvm) .settings(libraryDefSettings, rootSettings) .settings(publish / aggregate := false) .settings(publishLocal / aggregate := false) lazy val aggregateCompile = ScopeFilter( - inProjects(core.jvm, interpreter.jvm, parsers.jvm, sdk.jvm, sc.jvm), + inProjects(core.jvm, data.jvm, interpreter.jvm, parsers.jvm, sdk.jvm, sc.jvm), inConfigurations(Compile)) lazy val rootSettings = Seq( diff --git a/core/js/src/main/scala/sigma/js/Value.scala b/core/js/src/main/scala/sigma/js/Value.scala index 234ef64203..b962198dec 100644 --- a/core/js/src/main/scala/sigma/js/Value.scala +++ b/core/js/src/main/scala/sigma/js/Value.scala @@ -40,13 +40,13 @@ import scala.scalajs.js.annotation.JSExportTopLevel class Value(val data: Any, val tpe: Type) extends js.Object { /** Get Sigma runtime value which can be passed to interpreter, saved in register and - * [[sigmastate.Values.Constant]] nodes. + * [[sigma.ast.Constant]] nodes. */ final def runtimeData: Any = toRuntimeData(data, tpe.rtype) /** * Encode this value as Base16 hex string. - * 1) it transforms this value into {@link sigmastate.Values.ConstantNode} of sigma. + * 1) it transforms this value into {@link sigma.ast.ConstantNode} of sigma. * 2) it serializes the constant into byte array using {@link sigmastate.serialization.ConstantSerializer} * 3) the bytes are encoded using Base16 encoder into string * @@ -71,7 +71,7 @@ object Value extends js.Object { val MinLong = -js.BigInt("0x8000000000000000") /** Helper method to get Sigma runtime value which can be passed to interpreter, saved - * in register and [[sigmastate.Values.Constant]] nodes. + * in register and [[sigma.ast.Constant]] nodes. */ final private[js] def toRuntimeData(data: Any, rtype: RType[_]): Any = rtype match { case sigma.BooleanType => data diff --git a/core/jvm/src/main/scala/sigma/crypto/Platform.scala b/core/jvm/src/main/scala/sigma/crypto/Platform.scala index c5123e6c18..b71694e81b 100644 --- a/core/jvm/src/main/scala/sigma/crypto/Platform.scala +++ b/core/jvm/src/main/scala/sigma/crypto/Platform.scala @@ -7,7 +7,6 @@ import org.bouncycastle.crypto.params.KeyParameter import org.bouncycastle.math.ec.{ECCurve, ECFieldElement, ECPoint} import java.math.BigInteger -import sigmastate._ import sigma.Coll import sigma._ import sigma.ast._ diff --git a/core/shared/src/main/scala/sigma/data/CSigmaProp.scala b/core/shared/src/main/scala/sigma/data/CSigmaProp.scala index 8a37705f8c..d8a472424c 100644 --- a/core/shared/src/main/scala/sigma/data/CSigmaProp.scala +++ b/core/shared/src/main/scala/sigma/data/CSigmaProp.scala @@ -3,7 +3,7 @@ package sigma.data import sigma.ast.SSigmaProp import sigma.serialization.CoreSerializer import sigma.util.Extensions.SigmaBooleanOps -import sigma.{Coll, Colls, SigmaProp} +import sigma.{Coll, Colls, GroupElement, SigmaProp} /** A default implementation of [[SigmaProp]] interface. * @@ -42,4 +42,20 @@ case class CSigmaProp(sigmaTree: SigmaBoolean) extends SigmaProp with WrapperOf[ override def toString: String = s"SigmaProp(${wrappedValue.showToString})" } - +object CSigmaProp { + /** Create trivial sigma proposition with given boolean value. */ + def apply(b: Boolean): CSigmaProp = + CSigmaProp(TrivialProp(b)) + + /** Create SigmaProp value with underlying ProveDlog proposition. */ + def withProveDlog(ge: GroupElement) = + CSigmaProp(ProveDlog(ge.asInstanceOf[CGroupElement].wrappedValue)) + + /** Create SigmaProp value with underlying ProveDHTuple proposition. */ + def withProveDHTuple(g: GroupElement, h: GroupElement, u: GroupElement, v: GroupElement) = + CSigmaProp(ProveDHTuple( + g.asInstanceOf[CGroupElement].wrappedValue, + h.asInstanceOf[CGroupElement].wrappedValue, + u.asInstanceOf[CGroupElement].wrappedValue, + v.asInstanceOf[CGroupElement].wrappedValue)) +} diff --git a/core/shared/src/main/scala/sigma/serialization/CoreByteReader.scala b/core/shared/src/main/scala/sigma/serialization/CoreByteReader.scala index 62c39749e1..e5c2e574ca 100644 --- a/core/shared/src/main/scala/sigma/serialization/CoreByteReader.scala +++ b/core/shared/src/main/scala/sigma/serialization/CoreByteReader.scala @@ -2,11 +2,8 @@ package sigma.serialization import scorex.util.Extensions._ import scorex.util.serialization.Reader -import sigma.util.safeNewArray -import debox.cfor import sigma.ast.SType import sigma.validation.ValidationRules.CheckPositionLimit -import sigmastate.serialization.TypeSerializer /** Reader used in the concrete implementations of [[SigmaSerializer]]. * It decorates the given reader, delegates most of the methods to it, but also adds new @@ -14,7 +11,7 @@ import sigmastate.serialization.TypeSerializer * * @param r the underlying reader this reader reads from * @param constantStore the store of constants which is used to resolve - * [[sigmastate.Values.ConstantPlaceholder]] + * [[sigma.ast.ConstantPlaceholder]] * @param resolvePlaceholdersToConstants if true then resolved constants will be * substituted in the tree instead of the placeholder. * @param maxTreeDepth limit on the tree depth (recursive invocations) diff --git a/core/shared/src/main/scala/sigma/serialization/CoreByteWriter.scala b/core/shared/src/main/scala/sigma/serialization/CoreByteWriter.scala index d9ab716e19..d6cc9a8d8e 100644 --- a/core/shared/src/main/scala/sigma/serialization/CoreByteWriter.scala +++ b/core/shared/src/main/scala/sigma/serialization/CoreByteWriter.scala @@ -1,10 +1,9 @@ package sigma.serialization -import scorex.util.serialization.{VLQByteBufferWriter, Writer} import scorex.util.serialization.Writer.Aux +import scorex.util.serialization.{VLQByteBufferWriter, Writer} import sigma.ast.SType import sigma.serialization.CoreByteWriter.{Bits, DataInfo, U, Vlq, ZigZag} -import sigmastate.serialization.TypeSerializer class CoreByteWriter(val w: Writer) extends Writer { type CH = w.CH diff --git a/core/shared/src/main/scala/sigma/serialization/TypeSerializer.scala b/core/shared/src/main/scala/sigma/serialization/TypeSerializer.scala index 27b125fa02..9c84de0944 100644 --- a/core/shared/src/main/scala/sigma/serialization/TypeSerializer.scala +++ b/core/shared/src/main/scala/sigma/serialization/TypeSerializer.scala @@ -1,4 +1,4 @@ -package sigmastate.serialization +package sigma.serialization import debox.cfor import sigma.ast.SCollectionType.{CollectionTypeCode, NestedCollectionTypeCode} diff --git a/core/shared/src/main/scala/sigma/util/CollectionUtil.scala b/core/shared/src/main/scala/sigma/util/CollectionUtil.scala index d6bcd69767..357fd3b9ef 100644 --- a/core/shared/src/main/scala/sigma/util/CollectionUtil.scala +++ b/core/shared/src/main/scala/sigma/util/CollectionUtil.scala @@ -41,6 +41,13 @@ object CollectionUtil { result } + /** Casts the array of `A`s into array of `B`s, where B is a superclass of A. */ + def castArray[A, B >: A : ClassTag](array: Array[A]): Array[B] = { + val result: Array[B] = new Array[B](array.length) + System.arraycopy(array, 0, result, 0, array.length) + result + } + /** Computes the deep hash code for the given array. * * This method calculates the hash code based on the array's elements and type, taking nested arrays diff --git a/core/shared/src/main/scala/sigma/validation/ValidationRules.scala b/core/shared/src/main/scala/sigma/validation/ValidationRules.scala index 6e5d84f0a3..249e2fce0a 100644 --- a/core/shared/src/main/scala/sigma/validation/ValidationRules.scala +++ b/core/shared/src/main/scala/sigma/validation/ValidationRules.scala @@ -4,7 +4,7 @@ import sigma.SigmaException import sigma.ast.{SGlobal, SOption, TypeCodes} import sigma.serialization.{ReaderPositionLimitExceeded, SerializerException} import sigma.util.Extensions.toUByte -import sigmastate.serialization.TypeSerializer.embeddableIdToType +import sigma.serialization.TypeSerializer.embeddableIdToType /** Base class for different validation rules registered in ValidationRules.currentSettings. * Each rule is identified by `id` and have a description. diff --git a/interpreter/js/src/main/scala/sigmastate/Platform.scala b/data/js/src/main/scala/sigma/Platform.scala similarity index 80% rename from interpreter/js/src/main/scala/sigmastate/Platform.scala rename to data/js/src/main/scala/sigma/Platform.scala index eff021c35f..29c761c3f1 100644 --- a/interpreter/js/src/main/scala/sigmastate/Platform.scala +++ b/data/js/src/main/scala/sigma/Platform.scala @@ -1,14 +1,8 @@ -package sigmastate +package sigma import org.ergoplatform.ErgoBox -import sigma.data.{AvlTreeData, Nullable, SigmaBoolean} -import sigma.{Evaluation, VersionContext} -import sigmastate.Values.{Constant, FalseLeaf, TrueLeaf} -import sigmastate.eval.SigmaDsl -import sigmastate.lang.SigmaBuilder -import sigma.Coll import sigma.ast._ -import sigma.{AnyValue, AvlTree, GroupElement, SigmaProp} +import sigma.data._ import java.math.BigInteger @@ -17,7 +11,7 @@ object Platform { * Uses scalan.Nullable instead of scala.Option to avoid allocation on consensus hot path. * This method is part of consensus and is used in [[SubstConstants]] operation. */ - private [sigmastate] def liftToConstant(obj: Any, builder: SigmaBuilder): Nullable[Constant[SType]] = { + private[sigma] def liftToConstant(obj: Any, builder: SigmaBuilder): Nullable[Constant[SType]] = { import builder._ obj match { case arr: Array[Boolean] => Nullable(mkCollectionConstant[SBoolean.type](arr, SBoolean)) @@ -25,14 +19,14 @@ object Platform { case arr: Array[Short] => Nullable(mkCollectionConstant[SShort.type](arr, SShort)) case arr: Array[Int] => Nullable(mkCollectionConstant[SInt.type](arr, SInt)) case arr: Array[Long] => Nullable(mkCollectionConstant[SLong.type](arr, SLong)) - case arr: Array[BigInteger] => Nullable(mkCollectionConstant[SBigInt.type](arr.map(SigmaDsl.BigInt(_)), SBigInt)) + case arr: Array[BigInteger] => Nullable(mkCollectionConstant[SBigInt.type](arr.map[BigInt](n => CBigInt(n)), SBigInt)) case arr: Array[String] => Nullable(mkCollectionConstant[SString.type](arr, SString)) case v: AnyValue => val tpe = Evaluation.rtypeToSType(v.tVal) Nullable(mkConstant[tpe.type](v.value.asInstanceOf[tpe.WrappedType], tpe)) case v: Int => Nullable(mkConstant[SInt.type](v, SInt)) case v: Long => Nullable(mkConstant[SLong.type](v, SLong)) - case v: BigInteger => Nullable(mkConstant[SBigInt.type](SigmaDsl.BigInt(v), SBigInt)) + case v: BigInteger => Nullable(mkConstant[SBigInt.type](CBigInt(v), SBigInt)) case n: sigma.BigInt => Nullable(mkConstant[SBigInt.type](n, SBigInt)) case ge: GroupElement => Nullable(mkConstant[SGroupElement.type](ge, SGroupElement)) case b: Boolean => Nullable(if (b) TrueLeaf else FalseLeaf) @@ -44,7 +38,7 @@ object Platform { // ErgoBox cannot be passed as argument as it is never valid value during evaluation. // Thus we can use activation-based versioning and fix this code when v5.0 is activated. case b: ErgoBox => - Nullable(mkConstant[SBox.type](SigmaDsl.Box(b), SBox)) // fixed in v5.0 + Nullable(mkConstant[SBox.type](CBox(b), SBox)) // fixed in v5.0 // this case is added in v5.0 and it can be useful when the box value comes from a // register or a context variable is passed to SubstConstants. @@ -53,9 +47,9 @@ object Platform { Nullable(mkConstant[SBox.type](b, SBox)) else Nullable.None // return the same result as in v4.x when there was no this case - case avl: AvlTreeData => Nullable(mkConstant[SAvlTree.type](SigmaDsl.avlTree(avl), SAvlTree)) + case avl: AvlTreeData => Nullable(mkConstant[SAvlTree.type](CAvlTree(avl), SAvlTree)) case avl: AvlTree => Nullable(mkConstant[SAvlTree.type](avl, SAvlTree)) - case sb: SigmaBoolean => Nullable(mkConstant[SSigmaProp.type](SigmaDsl.SigmaProp(sb), SSigmaProp)) + case sb: SigmaBoolean => Nullable(mkConstant[SSigmaProp.type](CSigmaProp(sb), SSigmaProp)) case p: SigmaProp => Nullable(mkConstant[SSigmaProp.type](p, SSigmaProp)) case coll: Coll[a] => val tpeItem = Evaluation.rtypeToSType(coll.tItem) diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ErgoTree.scala b/data/js/src/main/scala/sigma/ast/js/ErgoTree.scala similarity index 82% rename from sdk/js/src/main/scala/org/ergoplatform/sdk/js/ErgoTree.scala rename to data/js/src/main/scala/sigma/ast/js/ErgoTree.scala index 39f33ef403..1e5ec37d11 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ErgoTree.scala +++ b/data/js/src/main/scala/sigma/ast/js/ErgoTree.scala @@ -1,15 +1,15 @@ -package org.ergoplatform.sdk.js +package sigma.ast.js +import sigma.ast import sigma.js.Value -import sigmastate.Values import scala.scalajs.js import scala.scalajs.js.JSConverters.JSRichIterableOnce import scala.scalajs.js.annotation.JSExportTopLevel -/** An exported JavaScript class wrapping the Scala `Values.ErgoTree` type. */ +/** An exported JavaScript class wrapping the Scala `ErgoTree` type. */ @JSExportTopLevel("ErgoTree") -class ErgoTree(tree: sigmastate.ErgoTree) extends js.Object { +class ErgoTree(tree: ast.ErgoTree) extends js.Object { /** The first byte of serialized byte array which determines interpretation of the rest of the array. */ def header(): Byte = tree.header @@ -36,7 +36,7 @@ class ErgoTree(tree: sigmastate.ErgoTree) extends js.Object { /** Returns segregated constants of this tree as [[js.Array]]. */ def constants(): js.Array[Value] = { val constants = tree.constants - val values = constants.map(Isos.isoValueToConstant.from) + val values = constants.map(isoValueToConstant.from) values.toJSArray } } @@ -50,13 +50,13 @@ object ErgoTree extends js.Object { * @param hex a hexadecimal string representing the serialized ErgoTree */ def fromHex(hex: String): ErgoTree = - new ErgoTree(sigmastate.ErgoTree.fromHex(hex)) + new ErgoTree(ast.ErgoTree.fromHex(hex)) /** Deserializes an ErgoTree instance from an array of bytes. * * @param bytes an array of bytes representing the serialized ErgoTree */ def fromBytes(bytes: Array[Byte]): ErgoTree = { - new ErgoTree(sigmastate.ErgoTree.fromBytes(bytes)) + new ErgoTree(ast.ErgoTree.fromBytes(bytes)) } } diff --git a/data/js/src/main/scala/sigma/ast/js/package.scala b/data/js/src/main/scala/sigma/ast/js/package.scala new file mode 100644 index 0000000000..7af2a48ab0 --- /dev/null +++ b/data/js/src/main/scala/sigma/ast/js/package.scala @@ -0,0 +1,19 @@ +package sigma.ast + +import sigma.Evaluation +import sigma.data.Iso +import sigma.js.{Type, Value} + +package object js { + /** Conversion between `Value` and `Constant[SType]`. */ + implicit val isoValueToConstant: Iso[Value, Constant[SType]] = new Iso[Value, Constant[SType]] { + override def to(x: Value): Constant[SType] = + Constant(x.runtimeData.asInstanceOf[SType#WrappedType], Evaluation.rtypeToSType(x.tpe.rtype)) + + override def from(x: Constant[SType]): Value = { + val rtype = Evaluation.stypeToRType(x.tpe) + val jsvalue = Value.fromRuntimeData(x.value, rtype) + new Value(jsvalue, new Type(rtype)) + } + } +} diff --git a/interpreter/jvm/src/main/scala/sigmastate/Platform.scala b/data/jvm/src/main/scala/sigma/Platform.scala similarity index 90% rename from interpreter/jvm/src/main/scala/sigmastate/Platform.scala rename to data/jvm/src/main/scala/sigma/Platform.scala index 6db096b2da..bd39d75ab9 100644 --- a/interpreter/jvm/src/main/scala/sigmastate/Platform.scala +++ b/data/jvm/src/main/scala/sigma/Platform.scala @@ -1,14 +1,9 @@ -package sigmastate +package sigma import org.ergoplatform.ErgoBox -import sigma.data.{AvlTreeData, Nullable, SigmaBoolean} -import sigma.{Evaluation, VersionContext} -import sigmastate.Values.{Constant, FalseLeaf, TrueLeaf} -import sigmastate.eval.SigmaDsl -import sigmastate.lang.SigmaBuilder -import sigma.Coll import sigma.ast._ -import sigma.{AvlTree, GroupElement, SigmaProp} +import sigma.data.{AvlTreeData, Nullable, SigmaBoolean} +import sigma.eval.SigmaDsl import java.math.BigInteger @@ -18,7 +13,7 @@ object Platform { * Uses scalan.Nullable instead of scala.Option to avoid allocation on consensus hot path. * This method is part of consensus and is used in [[SubstConstants]] operation. */ - private [sigmastate] def liftToConstant(obj: Any, builder: SigmaBuilder): Nullable[Constant[SType]] = { + private[sigma] def liftToConstant(obj: Any, builder: SigmaBuilder): Nullable[Constant[SType]] = { import builder._ obj match { case arr: Array[Boolean] => Nullable(mkCollectionConstant[SBoolean.type](arr, SBoolean)) diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala b/data/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala similarity index 97% rename from interpreter/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala rename to data/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala index 458dee4d66..134a30bc83 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala +++ b/data/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala @@ -4,16 +4,14 @@ import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.encode.Base58 import scorex.utils.Ints -import sigma.ast.{SInt, SSigmaProp} -import sigma.data.ProveDlog +import sigma.ast.{DeserializeContext, SInt, SSigmaProp, Slice} +import sigma.data.{CSigmaProp, ProveDlog} import sigma.serialization.GroupElementSerializer import sigma.{Coll, SigmaException, VersionContext} -import sigmastate.ErgoTree.{ZeroHeader, setVersionBits} -import sigmastate.Values._ -import sigmastate._ -import sigmastate.crypto.DLogProtocol.ProveDlogProp -import sigmastate.serialization._ -import sigmastate.utxo.{DeserializeContext, Slice} +import sigma.ast.ErgoTree.{ZeroHeader, setVersionBits} +import sigma.ast._ +import sigma.ast.syntax._ +import sigma.serialization._ import scala.util.Try @@ -345,7 +343,7 @@ case class ErgoAddressEncoder(networkPrefix: NetworkPrefix) { */ def fromProposition(proposition: ErgoTree): Try[ErgoAddress] = Try { proposition.root match { - case Right(SigmaPropConstant(ProveDlogProp(d))) => P2PKAddress(d) + case Right(SigmaPropConstant(CSigmaProp(d: ProveDlog))) => P2PKAddress(d) case Right(IsPay2SHAddress(scriptHash)) => new Pay2SHAddress(scriptHash.toArray) case Right(b: Value[SSigmaProp.type]@unchecked) if b.tpe == SSigmaProp => Pay2SAddress(proposition) case Left(unparsedErgoTree) => diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBox.scala b/data/shared/src/main/scala/org/ergoplatform/ErgoBox.scala similarity index 91% rename from interpreter/shared/src/main/scala/org/ergoplatform/ErgoBox.scala rename to data/shared/src/main/scala/org/ergoplatform/ErgoBox.scala index bda49eb6ed..c6c91450ec 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBox.scala +++ b/data/shared/src/main/scala/org/ergoplatform/ErgoBox.scala @@ -1,22 +1,19 @@ package org.ergoplatform import org.ergoplatform.ErgoBox.{AdditionalRegisters, Token} -import org.ergoplatform.settings.ErgoAlgos import scorex.crypto.authds.ADKey import scorex.crypto.hash.Blake2b256 import scorex.util._ +import scorex.util.encode.Base16 import scorex.utils.{Ints, Shorts} import sigma.Extensions.ArrayOps import sigma.ast.SCollection.SByteArray -import sigma.ast.{SCollection, SLong, STuple, SType} import sigma.ast.SType.AnyOps import sigma.data.{Digest32Coll, SigmaConstants} -import sigmastate.Values._ -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{Helpers, SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.ExtractCreationInfo -import sigma.{Colls, _} -import sigmastate.ErgoTree +import sigma.ast._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} +import sigma._ +import sigma.util.CollectionUtil /** * Box (aka coin, or an unspent output) is a basic concept of a UTXO-based cryptocurrency. In Bitcoin, such an object @@ -78,7 +75,7 @@ class ErgoBox private ( override def get(identifier: RegisterId): Option[Value[SType]] = { identifier match { case ReferenceRegId => - val tupleVal = (creationHeight, Helpers.concatArrays(transactionId.toBytes, Shorts.toByteArray(index)).toColl) + val tupleVal = (creationHeight, CollectionUtil.concatArrays_v5(transactionId.toBytes, Shorts.toByteArray(index)).toColl) Some(Constant(tupleVal.asWrappedType, SReferenceRegType)) case _ => super.get(identifier) } @@ -107,8 +104,8 @@ class ErgoBox private ( def toCandidate: ErgoBoxCandidate = new ErgoBoxCandidate(value, ergoTree, creationHeight, additionalTokens, additionalRegisters) - override def toString: String = s"ErgoBox(${ErgoAlgos.encode(id)},$value,$ergoTree," + - s"tokens: (${additionalTokens.map(t => ErgoAlgos.encode(t._1) + ":" + t._2)}), $transactionId, " + + override def toString: String = s"ErgoBox(${Base16.encode(id)},$value,$ergoTree," + + s"tokens: (${additionalTokens.map(t => Base16.encode(t._1.toArray) + ":" + t._2)}), $transactionId, " + s"$index, $additionalRegisters, $creationHeight)" } @@ -185,9 +182,9 @@ object ErgoBox { .ensuring(_ == mandatoryRegisters.last.number + 1) val allRegisters: Seq[RegisterId] = - Helpers.concatArrays[RegisterId]( - Helpers.castArray(_mandatoryRegisters): Array[RegisterId], - Helpers.castArray(_nonMandatoryRegisters): Array[RegisterId]).ensuring(_.length == maxRegisters) + CollectionUtil.concatArrays_v5[RegisterId]( + CollectionUtil.castArray(_mandatoryRegisters): Array[RegisterId], + CollectionUtil.castArray(_nonMandatoryRegisters): Array[RegisterId]).ensuring(_.length == maxRegisters) val mandatoryRegistersCount: Byte = mandatoryRegisters.size.toByte val nonMandatoryRegistersCount: Byte = nonMandatoryRegisters.size.toByte diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBoxAssets.scala b/data/shared/src/main/scala/org/ergoplatform/ErgoBoxAssets.scala similarity index 100% rename from interpreter/shared/src/main/scala/org/ergoplatform/ErgoBoxAssets.scala rename to data/shared/src/main/scala/org/ergoplatform/ErgoBoxAssets.scala diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala b/data/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala similarity index 95% rename from interpreter/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala rename to data/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala index 2c73b119b3..ba306159d4 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala +++ b/data/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala @@ -2,19 +2,18 @@ package org.ergoplatform import debox.cfor import org.ergoplatform.ErgoBox._ -import org.ergoplatform.settings.ErgoAlgos +import scorex.util.encode.Base16 import scorex.util.{ModifierId, bytesToId} import sigma.Extensions.{ArrayOps, CollOps} -import sigma.ast.SType +import sigma.ast.{ErgoTree, SType} import sigma.ast.SType.AnyOps import sigma.data.Digest32Coll import sigma.util.safeNewArray import sigma.{Coll, Colls} -import sigmastate.ErgoTree -import sigmastate.Values._ -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast._ +import sigma.ast.syntax._ +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} import scala.collection.{immutable, mutable} import scala.runtime.ScalaRunTime @@ -97,7 +96,7 @@ class ErgoBoxCandidate(val value: Long, } override def toString: String = s"ErgoBoxCandidate($value, $ergoTree," + - s"tokens: (${additionalTokens.map(t => ErgoAlgos.encode(t._1) + ":" + t._2).toArray.mkString(", ")}), " + + s"tokens: (${additionalTokens.map(t => Base16.encode(t._1.toArray) + ":" + t._2).toArray.mkString(", ")}), " + s"$additionalRegisters, creationHeight: $creationHeight)" /** Additional tokens stored in the box, merged into a Map. @@ -216,7 +215,7 @@ object ErgoBoxCandidate { } else { val tokenIdSize = TokenId.size // optimization: access the value once cfor(0)(_ < nTokens, _ + 1) { i => - tokenIds(i) = Digest32Coll @@@ Colls.fromArray(r.getBytes(tokenIdSize)) // READ + tokenIds(i) = Digest32Coll @@ Colls.fromArray(r.getBytes(tokenIdSize)) // READ tokenAmounts(i) = r.getULong() // READ } } diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala b/data/shared/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala similarity index 97% rename from interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala rename to data/shared/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala index 469a5fb1df..eb36d60317 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala +++ b/data/shared/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala @@ -6,14 +6,12 @@ import scorex.crypto.authds.ADKey import scorex.crypto.hash.Blake2b256 import scorex.util._ import sigma.Colls +import sigma.ast.syntax.ErgoBoxCandidateRType import sigma.data.Digest32Coll +import sigma.eval.Extensions.EvalIterableOps +import sigma.interpreter.ProverResult import sigma.util.safeNewArray -import sigmastate._ -import sigmastate.eval.Extensions._ -import sigmastate.eval._ -import sigmastate.interpreter.ProverResult -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} import scala.util.Try diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/Input.scala b/data/shared/src/main/scala/org/ergoplatform/Input.scala similarity index 80% rename from interpreter/shared/src/main/scala/org/ergoplatform/Input.scala rename to data/shared/src/main/scala/org/ergoplatform/Input.scala index e0b4830797..4d15532ad2 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/Input.scala +++ b/data/shared/src/main/scala/org/ergoplatform/Input.scala @@ -1,13 +1,11 @@ package org.ergoplatform -import java.util - import org.ergoplatform.ErgoBox.BoxId -import org.ergoplatform.settings.ErgoAlgos import scorex.crypto.authds.ADKey -import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{Helpers, SigmaByteReader, SigmaByteWriter} +import scorex.util.encode.Base16 +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} +import sigma.util.CollectionUtil /** * Inputs, that are used to enrich script context, but won't be spent by the transaction @@ -15,14 +13,14 @@ import sigmastate.utils.{Helpers, SigmaByteReader, SigmaByteWriter} * @param boxId - id of a box to add into context (should be in UTXO) */ case class DataInput(boxId: BoxId) { - override def toString: String = s"DataInput(${ErgoAlgos.encode(boxId)})" + override def toString: String = s"DataInput(${Base16.encode(boxId)})" override def equals(obj: Any): Boolean = obj match { case x: DataInput => java.util.Arrays.equals(boxId, x.boxId) case _ => false } - override def hashCode(): Int = Helpers.deepHashCode(boxId) + override def hashCode(): Int = CollectionUtil.deepHashCode(boxId) } /** @@ -43,7 +41,7 @@ class UnsignedInput(val boxId: BoxId, val extension: ContextExtension) { case _ => false } - override def hashCode(): Int = Helpers.deepHashCode(boxId) + override def hashCode(): Int = CollectionUtil.deepHashCode(boxId) /** * Input, that should be signed by prover and verified by verifier. @@ -60,7 +58,7 @@ class UnsignedInput(val boxId: BoxId, val extension: ContextExtension) { */ case class Input(override val boxId: BoxId, spendingProof: ProverResult) extends UnsignedInput(boxId, spendingProof.extension) { - override def toString: String = s"Input(${ErgoAlgos.encode(boxId)},$spendingProof)" + override def toString: String = s"Input(${Base16.encode(boxId)},$spendingProof)" } object Input { diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala b/data/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala similarity index 96% rename from interpreter/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala rename to data/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala index e1d1993a21..9d4de47a99 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala +++ b/data/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala @@ -1,18 +1,17 @@ package org.ergoplatform.validation import sigma.SigmaException +import sigma.ast.{DeserializeContext, ErgoTree, MethodsContainer, SMethod} import sigma.ast.TypeCodes.LastConstantCode import sigma.serialization.{InvalidOpCode, SerializerException} import sigma.util.Extensions.toUByte import sigma.validation.ValidationRules._ import sigma.validation._ -import sigmastate.ErgoTree.HeaderType -import sigmastate.Values.SValue -import sigmastate.exceptions._ -import sigmastate.serialization.ValueCodes.OpCode -import sigmastate.serialization.ValueSerializer -import sigmastate.utxo.DeserializeContext -import sigmastate.{ErgoTree, _} +import sigma.ast.ErgoTree.HeaderType +import sigma.ast.syntax._ +import sigma.exceptions.InterpreterException +import sigma.serialization.ValueCodes.OpCode +import sigma.serialization.ValueSerializer /** All validation rules which are used to check soft-forkable conditions. Each validation * rule throws a [[org.ergoplatform.validation.ValidationException]]. Each diff --git a/data/shared/src/main/scala/sigma/SigmaDataReflection.scala b/data/shared/src/main/scala/sigma/SigmaDataReflection.scala new file mode 100644 index 0000000000..31703b0856 --- /dev/null +++ b/data/shared/src/main/scala/sigma/SigmaDataReflection.scala @@ -0,0 +1,635 @@ +package sigma + +import org.ergoplatform.ErgoBox.RegisterId +import sigma.ast.SCollection.{SBooleanArray, SByteArray, SIntArray} +import sigma.ast._ +import sigma.ast.syntax._ +import sigma.data.KeyValueColl +import sigma.eval.ErgoTreeEvaluator +import sigma.reflection.ReflectionData.registerClassEntry +import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} +import sigma.serialization.ValueCodes.OpCode + +/** Reflection metadata for `interpreter` module. + * For each class of this module that needs reflection metadata, + * we register a class entry with the necessary information. + * Only information that is needed at runtime is registered. + */ +object SigmaDataReflection { + val reflection = ReflectionData + + registerClassEntry(classOf[AND], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new AND(args(0).asInstanceOf[Value[SBooleanArray]]) + } + ) + ) + + registerClassEntry(classOf[ArithOp[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Byte])) { args => + new ArithOp(args(0).asInstanceOf[SValue], args(1).asInstanceOf[SValue], args(2).asInstanceOf[OpCode]) + } + ) + ) + + registerClassEntry(classOf[AtLeast], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new AtLeast(args(0).asInstanceOf[IntValue], args(1).asInstanceOf[CollectionValue[SSigmaProp.type]]) + } + ) + ) + + registerClassEntry(classOf[BinAnd], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new BinAnd(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[BinOr], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new BinOr(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[BinXor], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new BinXor(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[BoolToSigmaProp], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new BoolToSigmaProp(args(0).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[ByteArrayToBigInt], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ByteArrayToBigInt(args(0).asInstanceOf[Value[SByteArray]]) + } + ) + ) + + registerClassEntry(classOf[CalcBlake2b256], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new CalcBlake2b256(args(0).asInstanceOf[Value[SByteArray]]) + } + ) + ) + + registerClassEntry(classOf[CalcSha256], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new CalcSha256(args(0).asInstanceOf[Value[SByteArray]]) + } + ) + ) + + registerClassEntry(classOf[CreateProveDHTuple], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new CreateProveDHTuple(args(0).asInstanceOf[GroupElementValue], + args(1).asInstanceOf[GroupElementValue], + args(2).asInstanceOf[GroupElementValue], + args(3).asInstanceOf[GroupElementValue]) + } + ) + ) + + registerClassEntry(classOf[Downcast[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[SNumericType])) { args => + new Downcast(args(0).asInstanceOf[Value[SNumericType]], args(1).asInstanceOf[SNumericType]) + } + ) + ) + + registerClassEntry(classOf[EQ[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new EQ(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[Exponentiate], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new Exponentiate(args(0).asInstanceOf[GroupElementValue], args(1).asInstanceOf[BigIntValue]) + } + ) + ) + + registerClassEntry(classOf[GE[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new GE(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[GT[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new GT(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[If[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new If(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[SAnyValue], args(2).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[LE[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new LE(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[LT[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new LT(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[LogicalNot], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new LogicalNot(args(0).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[MultiplyGroup], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new MultiplyGroup(args(0).asInstanceOf[GroupElementValue], args(1).asInstanceOf[GroupElementValue]) + } + ) + ) + + registerClassEntry(classOf[NEQ[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new NEQ(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[Negation[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new Negation(args(0).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[OR], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new OR(args(0).asInstanceOf[Value[SBooleanArray]]) + } + ) + ) + + { val clazz = SAvlTreeMethods.getClass + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "update_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SAvlTreeMethods.type].update_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[AvlTree], + args(2).asInstanceOf[KeyValueColl], + args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "contains_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SAvlTreeMethods.type].contains_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[AvlTree], + args(2).asInstanceOf[Coll[Byte]], + args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "get_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SAvlTreeMethods.type].get_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[AvlTree], + args(2).asInstanceOf[Coll[Byte]], + args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "getMany_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SAvlTreeMethods.type].getMany_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[AvlTree], + args(2).asInstanceOf[Coll[Coll[Byte]]], + args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "remove_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SAvlTreeMethods.type].remove_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[AvlTree], + args(2).asInstanceOf[Coll[Coll[Byte]]], + args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "insert_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SAvlTreeMethods.type].insert_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[AvlTree], + args(2).asInstanceOf[KeyValueColl], + args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + } + ) + ) + } + + { val clazz = SCollectionMethods.getClass + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "zip_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SCollectionMethods.type].zip_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[Coll[Any]], + args(2).asInstanceOf[Coll[Any]])(args(3).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "getOrElse_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Int], classOf[java.lang.Object], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SCollectionMethods.type].getOrElse_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[Coll[Any]], + args(2).asInstanceOf[Int], + args(3).asInstanceOf[Any])(args(4).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "patch_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Int], classOf[Coll[_]], classOf[Int], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SCollectionMethods.type].patch_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[Coll[Any]], + args(2).asInstanceOf[Int], + args(3).asInstanceOf[Coll[Any]], + args(4).asInstanceOf[Int])(args(5).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "map_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Function1[_,_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SCollectionMethods.type].map_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[Coll[Any]], + args(2).asInstanceOf[Any => Any])(args(3).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "updated_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Int], classOf[java.lang.Object], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SCollectionMethods.type].updated_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[Coll[Any]], + args(2).asInstanceOf[Int], + args(3))(args(4).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "indexOf_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[java.lang.Object], classOf[Int], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SCollectionMethods.type].indexOf_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[Coll[Any]], args(2), args(3).asInstanceOf[Int])(args(4).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "updateMany_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SCollectionMethods.type].updateMany_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[Coll[Any]], + args(2).asInstanceOf[Coll[Int]], + args(3).asInstanceOf[Coll[Any]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "indices_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SCollectionMethods.type].indices_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[Coll[Any]])(args(2).asInstanceOf[ErgoTreeEvaluator]) + }, + mkMethod(clazz, "flatMap_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Function1[_,_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SCollectionMethods.type].flatMap_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[Coll[Any]], args(2).asInstanceOf[Any => Coll[Any]])(args(3).asInstanceOf[ErgoTreeEvaluator]) + } + ) + ) + } + + { val clazz = SGlobalMethods.getClass + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "xor_eval", Array[Class[_]](classOf[MethodCall], classOf[SigmaDslBuilder], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => + obj.asInstanceOf[SGlobalMethods.type].xor_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[SigmaDslBuilder], + args(2).asInstanceOf[Coll[Byte]], + args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + } + ) + ) + } + + registerClassEntry(classOf[SigmaAnd], + constructors = Array( + mkConstructor(Array(classOf[Seq[_]])) { args => + new SigmaAnd(args(0).asInstanceOf[Seq[SigmaPropValue]]) + } + ) + ) + + registerClassEntry(classOf[SigmaOr], + constructors = Array( + mkConstructor(Array(classOf[Seq[_]])) { args => + new SigmaOr(args(0).asInstanceOf[Seq[SigmaPropValue]]) + } + ) + ) + + registerClassEntry(classOf[SubstConstants[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new SubstConstants(args(0).asInstanceOf[Value[SByteArray]], + args(1).asInstanceOf[Value[SIntArray]], + args(2).asInstanceOf[CollectionValue[SType]]) + } + ) + ) + + registerClassEntry(classOf[Upcast[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[SNumericType])) { args => + new Upcast(args(0).asInstanceOf[Value[SNumericType]], args(1).asInstanceOf[SNumericType]) + } + ) + ) + + registerClassEntry(classOf[BlockValue], + constructors = Array( + mkConstructor(Array(classOf[IndexedSeq[_]], classOf[Value[_]])) { args => + new BlockValue(args(0).asInstanceOf[IndexedSeq[BlockItem]], args(1).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[ConcreteCollection[_]], + constructors = Array( + mkConstructor(Array(classOf[Seq[_]], classOf[SType])) { args => + new ConcreteCollection(args(0).asInstanceOf[Seq[SValue]], args(1).asInstanceOf[SType]) + } + ) + ) + + registerClassEntry(classOf[FuncValue], + constructors = Array( + mkConstructor(Array(classOf[IndexedSeq[_]], classOf[Value[_]])) { args => + new FuncValue(args(0).asInstanceOf[IndexedSeq[(Int, SType)]], args(1).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[Tuple], + constructors = Array( + mkConstructor(Array(classOf[IndexedSeq[_]])) { args => + new Tuple(args(0).asInstanceOf[IndexedSeq[SValue]]) + } + ) + ) + + registerClassEntry(classOf[ValDef], + constructors = Array( + mkConstructor(Array(classOf[Int], classOf[Seq[_]], classOf[Value[_]])) { args => + new ValDef(args(0).asInstanceOf[Int], args(1).asInstanceOf[Seq[STypeVar]], args(2).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[Apply], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[IndexedSeq[_]])) { args => + new Apply(args(0).asInstanceOf[SValue], args(1).asInstanceOf[IndexedSeq[SValue]]) + } + ) + ) + + registerClassEntry(classOf[ApplyTypes], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Seq[_]])) { args => + new ApplyTypes(args(0).asInstanceOf[SValue], args(1).asInstanceOf[Seq[SType]]) + } + ) + ) + + registerClassEntry(classOf[Block], + constructors = Array( + mkConstructor(Array(classOf[Seq[_]], classOf[Value[_]])) { args => + new Block(args(0).asInstanceOf[Seq[Val]], args(1).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[Lambda], + constructors = Array( + mkConstructor(Array(classOf[Seq[_]], classOf[IndexedSeq[_]], classOf[SType], classOf[Option[_]])) { args => + new Lambda(args(0).asInstanceOf[Seq[STypeParam]], + args(1).asInstanceOf[IndexedSeq[(String, SType)]], + args(2).asInstanceOf[SType], + args(3).asInstanceOf[Option[SValue]]) + } + ) + ) + + registerClassEntry(classOf[MethodCall], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[SMethod], classOf[IndexedSeq[_]], classOf[scala.collection.immutable.Map[_,_]])) { args => + new MethodCall(args(0).asInstanceOf[SValue], + args(1).asInstanceOf[SMethod], + args(2).asInstanceOf[IndexedSeq[SValue]], + args(3).asInstanceOf[Map[STypeVar,SType]]) + } + ) + ) + + registerClassEntry(classOf[MethodCallLike], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[java.lang.String], classOf[IndexedSeq[_]], classOf[SType])) { args => + new MethodCallLike(args(0).asInstanceOf[SValue], + args(1).asInstanceOf[String], + args(2).asInstanceOf[IndexedSeq[SValue]], + args(3).asInstanceOf[SType]) + } + ) + ) + + registerClassEntry(classOf[Select], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[java.lang.String], classOf[Option[_]])) { args => + new Select(args(0).asInstanceOf[SValue], args(1).asInstanceOf[String], args(2).asInstanceOf[Option[SType]]) + } + ) + ) + + registerClassEntry(classOf[ValNode], + constructors = Array( + mkConstructor(Array(classOf[java.lang.String], classOf[SType], classOf[Value[_]])) { args => + new ValNode(args(0).asInstanceOf[String], args(1).asInstanceOf[SType], args(2).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[Append[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new Append(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[CollectionValue[SType]]) + } + ) + ) + + registerClassEntry(classOf[ByIndex[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Option[_]])) { args => + new ByIndex(args(0).asInstanceOf[CollectionValue[SType]], + args(1).asInstanceOf[IntValue], args(2).asInstanceOf[Option[SValue]]) + } + ) + ) + + registerClassEntry(classOf[Exists[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new Exists(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[ExtractAmount], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractAmount(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[ExtractBytesWithNoRef], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractBytesWithNoRef(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[ExtractCreationInfo], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractCreationInfo(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[ExtractId], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractId(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[ExtractRegisterAs[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[org.ergoplatform.ErgoBox.RegisterId], classOf[SOption[_]])) { args => + new ExtractRegisterAs(args(0).asInstanceOf[BoxValue], args(1).asInstanceOf[RegisterId], args(2).asInstanceOf[SOption[SAny.type]]) + } + ) + ) + + registerClassEntry(classOf[ExtractScriptBytes], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractScriptBytes(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[Filter[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new Filter(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[Fold[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new Fold(args(0).asInstanceOf[CollectionValue[SType]], + args(1).asInstanceOf[SValue], args(2).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[ForAll[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new ForAll(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[MapCollection[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new MapCollection(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[OptionGet[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new OptionGet(args(0).asInstanceOf[Value[SOption[SType]]]) + } + ) + ) + + registerClassEntry(classOf[OptionGetOrElse[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new OptionGetOrElse(args(0).asInstanceOf[Value[SOption[SType]]], args(1).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[OptionIsDefined[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new OptionIsDefined(args(0).asInstanceOf[Value[SOption[SType]]]) + } + ) + ) + + registerClassEntry(classOf[SelectField], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Byte])) { args => + new SelectField(args(0).asInstanceOf[Value[STuple]], args(1).asInstanceOf[Byte]) + } + ) + ) + + registerClassEntry(classOf[SigmaPropBytes], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new SigmaPropBytes(args(0).asInstanceOf[SigmaPropValue]) + } + ) + ) + + registerClassEntry(classOf[SizeOf[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new SizeOf(args(0).asInstanceOf[CollectionValue[SType]]) + } + ) + ) + + registerClassEntry(classOf[Slice[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new Slice(args(0).asInstanceOf[CollectionValue[SType]], + args(1).asInstanceOf[IntValue], args(2).asInstanceOf[IntValue]) + } + ) + ) +} diff --git a/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTable.scala b/data/shared/src/main/scala/sigma/ast/ComplexityTable.scala similarity index 98% rename from interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTable.scala rename to data/shared/src/main/scala/sigma/ast/ComplexityTable.scala index dbda6eef4d..87b45b50b7 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTable.scala +++ b/data/shared/src/main/scala/sigma/ast/ComplexityTable.scala @@ -1,10 +1,6 @@ -package sigmastate.utxo +package sigma.ast -import org.ergoplatform._ -import sigmastate._ -import sigmastate.Values._ -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueCodes.OpCode +import sigma.serialization.ValueCodes.OpCode object ComplexityTable { diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/CostItem.scala b/data/shared/src/main/scala/sigma/ast/CostItem.scala similarity index 70% rename from interpreter/shared/src/main/scala/sigmastate/interpreter/CostItem.scala rename to data/shared/src/main/scala/sigma/ast/CostItem.scala index b0515602b2..8fa973b575 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/CostItem.scala +++ b/data/shared/src/main/scala/sigma/ast/CostItem.scala @@ -1,17 +1,15 @@ -package sigmastate.interpreter +package sigma.ast -import sigma.ast.SType -import sigmastate.{FixedCost, JitCost, PerItemCost, SMethod, TypeBasedCost} -import sigmastate.Values.{FixedCostValueCompanion, PerItemCostValueCompanion, ValueCompanion} -import sigmastate.lang.Terms.MethodCall +import sigma.ast +import sigma.eval.CostDetails -/** An item in the cost accumulation trace of a [[sigmastate.Values.ErgoTree]] evaluation. */ +/** An item in the cost accumulation trace of a [[sigma.ast.ErgoTree]] evaluation. */ abstract class CostItem { def opName: String def cost: JitCost } -/** An item in the cost accumulation trace of a [[sigmastate.Values.ErgoTree]] evaluation. +/** An item in the cost accumulation trace of a [[sigma.ast.ErgoTree]] evaluation. * Represents cost of simple operation. * Used for debugging, testing and profiling of costing. * @param opDesc descriptor of the ErgoTree operation @@ -30,13 +28,13 @@ object FixedCostItem { } } -/** An item in the cost accumulation trace of a [[sigmastate.Values.ErgoTree]] evaluation. +/** An item in the cost accumulation trace of a [[sigma.ast.ErgoTree]] evaluation. * Represents cost of an operation which depends on type (e.g. type of arguments). * Used for debugging, testing and profiling of costing. * @param opDesc descriptor of the ErgoTree operation * @param costKind type based cost descriptor added to accumulator * @param tpe concrete type on this the operation is executed - * @see [[sigmastate.LE]], [[sigmastate.GT]] + * @see [[LE]], [[GT]] */ case class TypeBasedCostItem( opDesc: OperationDesc, @@ -61,7 +59,7 @@ object TypeBasedCostItem { } } -/** An item in the cost accumulation trace of a [[sigmastate.Values.ErgoTree]] evaluation. +/** An item in the cost accumulation trace of a [[sigma.ast.ErgoTree]] evaluation. * Represents cost of a sequence of operation. * Used for debugging, testing and profiling of costing. * @@ -81,15 +79,4 @@ object SeqCostItem { SeqCostItem(companion.opDesc, companion.costKind, nItems) } -/** An item in the cost accumulation trace of a [[sigmastate.Values.ErgoTree]] evaluation. - * Represents cost of MethodCall operation. - * Used for debugging, testing and profiling of costing. - * - * @param items cost details obtained as part of MethodCall evaluation - */ -case class MethodCallCostItem(items: CostDetails) extends CostItem { - override def opName: String = MethodCall.typeName - override def cost: JitCost = items.cost -} - diff --git a/interpreter/shared/src/main/scala/sigmastate/CostKind.scala b/data/shared/src/main/scala/sigma/ast/CostKind.scala similarity index 95% rename from interpreter/shared/src/main/scala/sigmastate/CostKind.scala rename to data/shared/src/main/scala/sigma/ast/CostKind.scala index 18bb70901c..1fda6018ec 100644 --- a/interpreter/shared/src/main/scala/sigmastate/CostKind.scala +++ b/data/shared/src/main/scala/sigma/ast/CostKind.scala @@ -1,11 +1,9 @@ -package sigmastate - -import sigma.ast.SType +package sigma.ast import scala.runtime.Statics /** Cost descriptor of a single operation, usually associated with - * [[sigmastate.interpreter.OperationDesc]]. + * [[OperationDesc]]. */ sealed abstract class CostKind diff --git a/interpreter/shared/src/main/scala/sigmastate/ErgoTree.scala b/data/shared/src/main/scala/sigma/ast/ErgoTree.scala similarity index 95% rename from interpreter/shared/src/main/scala/sigmastate/ErgoTree.scala rename to data/shared/src/main/scala/sigma/ast/ErgoTree.scala index 9305b5f79c..1340ca4128 100644 --- a/interpreter/shared/src/main/scala/sigmastate/ErgoTree.scala +++ b/data/shared/src/main/scala/sigma/ast/ErgoTree.scala @@ -1,18 +1,17 @@ -package sigmastate +package sigma.ast -import org.ergoplatform.settings.ErgoAlgos import scorex.util.encode.Base16 import sigma.VersionContext -import sigma.ast.SType +import sigma.ast.ErgoTree.{HeaderType, substConstants} +import sigma.ast.SigmaPropConstant +import sigma.ast.syntax._ import sigma.data.SigmaBoolean import sigma.kiama.rewriting.Rewriter.{everywherebu, strategy} import sigma.validation.ValidationException -import sigmastate.ErgoTree.{HeaderType, substConstants} -import sigmastate.Values.{Constant, ConstantPlaceholder, SValue, SigmaPropConstant, SigmaPropValue, Value} -import sigmastate.eval.Extensions.SigmaBooleanOps -import sigmastate.lang.Terms.ValueOps -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.serialization.{ConstantStore, ErgoTreeSerializer, SigmaSerializer, ValueSerializer} +import sigma.ast.syntax.ValueOps +import sigma.eval.Extensions.SigmaBooleanOps +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer +import sigma.serialization.{ConstantStore, ErgoTreeSerializer, SigmaSerializer, ValueSerializer} import supertagged.TaggedType import java.util.Objects @@ -85,7 +84,7 @@ case class UnparsedErgoTree(bytes: mutable.WrappedArray[Byte], error: Validation * ErgoTreeSerializer parsing method computes the value of * this flag and provides it to the constructor. */ -case class ErgoTree private[sigmastate]( +case class ErgoTree private[sigma]( header: HeaderType, constants: IndexedSeq[Constant[SType]], root: Either[UnparsedErgoTree, SigmaPropValue], @@ -123,7 +122,7 @@ case class ErgoTree private[sigmastate]( @inline final def hasSize: Boolean = ErgoTree.hasSize(header) - private[sigmastate] var _bytes: Array[Byte] = propositionBytes + private[sigma] var _bytes: Array[Byte] = propositionBytes /** Serialized bytes of this tree. */ final def bytes: Array[Byte] = { @@ -134,7 +133,7 @@ case class ErgoTree private[sigmastate]( } /** Hexadecimal encoded string of ErgoTree.bytes. */ - final def bytesHex: String = ErgoAlgos.encode(bytes) + final def bytesHex: String = Base16.encode(bytes) private var _complexity: Int = givenComplexity @@ -149,7 +148,7 @@ case class ErgoTree private[sigmastate]( _complexity } - private[sigmastate] var _hasDeserialize: Option[Boolean] = givenDeserialize + private[sigma] var _hasDeserialize: Option[Boolean] = givenDeserialize /** Returns true if the tree contains at least one deserialization operation, * false otherwise. diff --git a/interpreter/shared/src/main/scala/sigmastate/JitCost.scala b/data/shared/src/main/scala/sigma/ast/JitCost.scala similarity index 87% rename from interpreter/shared/src/main/scala/sigmastate/JitCost.scala rename to data/shared/src/main/scala/sigma/ast/JitCost.scala index dd6d57fe9f..0b84dc21e2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/JitCost.scala +++ b/data/shared/src/main/scala/sigma/ast/JitCost.scala @@ -1,11 +1,12 @@ -package sigmastate +package sigma.ast /** Represents cost estimation computed by JITC interpreter. * The JITC costs use 10x more accurate scale comparing to block cost values. * * @see toBlockCost */ -case class JitCost private[sigmastate](private[sigmastate] val value: Int) extends AnyVal { +// TODO make 'value` private[sigma] after code moved from sigmastate package +case class JitCost private[sigma](val value: Int) extends AnyVal { /** Adds two cost values. */ def +(y: JitCost): JitCost = new JitCost(java7.compat.Math.addExact(value, y.value)) diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/OperationDesc.scala b/data/shared/src/main/scala/sigma/ast/OperationDesc.scala similarity index 93% rename from interpreter/shared/src/main/scala/sigmastate/interpreter/OperationDesc.scala rename to data/shared/src/main/scala/sigma/ast/OperationDesc.scala index ca7fc9b217..06ba3391a8 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/OperationDesc.scala +++ b/data/shared/src/main/scala/sigma/ast/OperationDesc.scala @@ -1,7 +1,4 @@ -package sigmastate.interpreter - -import sigmastate.{CostKind, SMethod} -import sigmastate.Values.ValueCompanion +package sigma.ast /** Each costable operation is described in one of the following ways: * 1) using [[ValueCompanion]] - operation with separate node class diff --git a/interpreter/shared/src/main/scala/sigmastate/Operations.scala b/data/shared/src/main/scala/sigma/ast/Operations.scala similarity index 99% rename from interpreter/shared/src/main/scala/sigmastate/Operations.scala rename to data/shared/src/main/scala/sigma/ast/Operations.scala index 0459062c8e..44804de84e 100644 --- a/interpreter/shared/src/main/scala/sigmastate/Operations.scala +++ b/data/shared/src/main/scala/sigma/ast/Operations.scala @@ -1,8 +1,7 @@ -package sigmastate +package sigma.ast import sigma.serialization.CoreByteWriter.ArgInfo -import sigmastate.lang.SigmaPredef.PredefinedFuncRegistry -import sigmastate.lang.StdSigmaBuilder +import SigmaPredef.PredefinedFuncRegistry /** WARNING: This file is generated by GenInfoObjects tool. * Don't edit it directly, use the tool instead to regenerate. diff --git a/interpreter/shared/src/main/scala/sigmastate/SMethod.scala b/data/shared/src/main/scala/sigma/ast/SMethod.scala similarity index 95% rename from interpreter/shared/src/main/scala/sigmastate/SMethod.scala rename to data/shared/src/main/scala/sigma/ast/SMethod.scala index 8b7e600cfb..2d306d8948 100644 --- a/interpreter/shared/src/main/scala/sigmastate/SMethod.scala +++ b/data/shared/src/main/scala/sigma/ast/SMethod.scala @@ -1,18 +1,14 @@ -package sigmastate +package sigma.ast import debox.cfor -import org.ergoplatform.validation.ValidationRules -import sigma.{Coll, Evaluation} -import sigma.ast._ +import sigma.ast.SMethod.{InvokeDescBuilder, MethodCostFunc} +import sigma.ast.syntax._ import sigma.data.RType +import sigma.eval.{CostDetails, ErgoTreeEvaluator, GivenCost, TracedCost} import sigma.reflection.{RClass, RMethod} import sigma.serialization.CoreByteWriter.ArgInfo import sigma.validation.ValidationRules.CheckTypeWithMethods -import sigmastate.SMethod.{InvokeDescBuilder, MethodCostFunc} -import sigmastate.Values.{SValue, ValueCompanion} -import sigmastate.interpreter.{CostDetails, ErgoTreeEvaluator, FixedCostItem, GivenCost, MethodDesc, SeqCostItem, TracedCost} -import sigmastate.lang.{SigmaBuilder, Terms} -import sigmastate.lang.Terms.{MethodCall, OperationId} +import sigma.{Coll, Evaluation} import scala.collection.compat.immutable.ArraySeq import scala.reflect.ClassTag @@ -164,11 +160,6 @@ case class SMethod( /** Name of a language operation represented by this method. */ def opName = objType.getClass.getSimpleName + "." + name - /** Returns [[OperationId]] for AOT costing. */ - def opId: OperationId = { - OperationId(opName, stype) - } - /** Specializes this instance by creating a new [[SMethod]] instance where signature * is specialized with respect to the given object and args types. It is used in * [[sigmastate.serialization.MethodCallSerializer]] `parse` method, so it is part of @@ -254,7 +245,7 @@ object SMethod { else GivenCost(costKind.cost(coll.length)) case _ => - ErgoTreeEvaluator.error( + sys.error( s"Invalid object $obj of method call $mc: Coll type is expected") } } diff --git a/interpreter/shared/src/main/scala/sigmastate/lang/SigmaBuilder.scala b/data/shared/src/main/scala/sigma/ast/SigmaBuilder.scala similarity index 98% rename from interpreter/shared/src/main/scala/sigmastate/lang/SigmaBuilder.scala rename to data/shared/src/main/scala/sigma/ast/SigmaBuilder.scala index 16cbe0396f..cafba5f6b6 100644 --- a/interpreter/shared/src/main/scala/sigmastate/lang/SigmaBuilder.scala +++ b/data/shared/src/main/scala/sigma/ast/SigmaBuilder.scala @@ -1,20 +1,16 @@ -package sigmastate.lang +package sigma.ast import debox.cfor import org.ergoplatform.ErgoBox.RegisterId +import sigma.ast.Constraints._ import sigma.ast.SCollection.{SByteArray, SIntArray} import sigma.ast.SOption.SIntOption -import sigma.ast.{STypeSubst, _} +import sigma.ast.syntax._ import sigma.data.Nullable -import sigma.{AnyValue, Coll, Colls, Environment, Evaluation} -import sigmastate.Values._ -import sigmastate._ -import sigmastate.exceptions.ConstraintFailed -import sigmastate.lang.Constraints._ -import sigmastate.lang.Terms._ -import sigmastate.serialization.OpCodes -import sigmastate.serialization.ValueCodes.OpCode -import sigmastate.utxo._ +import sigma.exceptions.ConstraintFailed +import sigma.serialization.OpCodes +import sigma.serialization.ValueCodes.OpCode +import sigma.{AnyValue, Coll, Colls, Environment, Evaluation, Platform} import scala.util.DynamicVariable diff --git a/interpreter/shared/src/main/scala/sigmastate/lang/SigmaPredef.scala b/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala similarity index 98% rename from interpreter/shared/src/main/scala/sigmastate/lang/SigmaPredef.scala rename to data/shared/src/main/scala/sigma/ast/SigmaPredef.scala index 88a8ac685f..5cdbdedaa8 100644 --- a/interpreter/shared/src/main/scala/sigmastate/lang/SigmaPredef.scala +++ b/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala @@ -1,19 +1,16 @@ -package sigmastate.lang +package sigma.ast import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import org.ergoplatform.{ErgoAddressEncoder, P2PKAddress} -import sigma.data.Nullable import scorex.util.encode.{Base16, Base58, Base64} import sigma.ast.SCollection.{SByteArray, SIntArray} import sigma.ast.SOption.SIntOption -import sigma.ast._ +import sigma.ast.SigmaPropConstant +import sigma.ast.syntax._ +import sigma.data.Nullable +import sigma.exceptions.InvalidArguments import sigma.serialization.CoreByteWriter.ArgInfo -import sigmastate.Values.{BoolValue, ByteArrayConstant, Constant, ConstantPlaceholder, EvaluatedValue, IntValue, SValue, SigmaPropConstant, SigmaPropValue, StringConstant, Value, ValueCompanion} -import sigmastate._ -import sigmastate.lang.Terms._ -import sigmastate.exceptions.InvalidArguments -import sigmastate.serialization.ValueSerializer -import sigmastate.utxo.{DeserializeContext, DeserializeRegister, GetVar, SelectField} +import sigma.serialization.ValueSerializer object SigmaPredef { @@ -46,7 +43,7 @@ object SigmaPredef { import builder._ /** Type variable used in the signatures of global functions below. */ - import SType.{tT, tO, tR, tL, paramR, paramT, tK} + import SType.{paramR, paramT, tK, tL, tO, tR, tT} private val undefined: IrBuilderFunc = PartialFunction.empty[(SValue, Seq[SValue]), SValue] diff --git a/interpreter/shared/src/main/scala/sigmastate/lang/SourceContext.scala b/data/shared/src/main/scala/sigma/ast/SourceContext.scala similarity index 97% rename from interpreter/shared/src/main/scala/sigmastate/lang/SourceContext.scala rename to data/shared/src/main/scala/sigma/ast/SourceContext.scala index 2c814bdbdb..f9441e1a52 100644 --- a/interpreter/shared/src/main/scala/sigmastate/lang/SourceContext.scala +++ b/data/shared/src/main/scala/sigma/ast/SourceContext.scala @@ -1,4 +1,4 @@ -package sigmastate.lang +package sigma.ast import fastparse.Parsed.Failure diff --git a/interpreter/shared/src/main/scala/sigmastate/types.scala b/data/shared/src/main/scala/sigma/ast/methods.scala similarity index 92% rename from interpreter/shared/src/main/scala/sigmastate/types.scala rename to data/shared/src/main/scala/sigma/ast/methods.scala index f1a6f4f247..2173438fd5 100644 --- a/interpreter/shared/src/main/scala/sigmastate/types.scala +++ b/data/shared/src/main/scala/sigma/ast/methods.scala @@ -1,29 +1,21 @@ -package sigmastate +package sigma.ast -import debox.cfor import org.ergoplatform._ import org.ergoplatform.validation._ -import scorex.crypto.authds.avltree.batch.{Insert, Lookup, Remove, Update} -import scorex.crypto.authds.{ADKey, ADValue} +import sigma._ import sigma.ast.SCollection.{SBooleanArray, SBoxArray, SByteArray, SByteArray2, SHeaderArray} +import sigma.ast.SMethod.{MethodCallIrBuilder, MethodCostFunc, javaMethodOf} import sigma.ast.SType.TypeCode -import sigma.ast._ -import sigma.data.{Nullable, RType, SigmaConstants} +import sigma.ast.syntax.{SValue, ValueOps} +import sigma.data.OverloadHack.Overloaded1 +import sigma.data.{DataValueComparer, KeyValueColl, Nullable, RType, SigmaConstants} +import sigma.eval.{CostDetails, ErgoTreeEvaluator, TracedCost} import sigma.reflection.RClass import sigma.serialization.CoreByteWriter.ArgInfo -import sigma.{Coll, _} -import sigmastate.SMethod.{MethodCallIrBuilder, MethodCostFunc, javaMethodOf} -import sigmastate.Values._ -import sigmastate.eval._ -import sigmastate.interpreter._ -import sigmastate.lang.Terms -import sigmastate.lang.Terms._ -import sigmastate.utils.Overloading.Overload1 -import sigmastate.utils.SparseArrayContainer -import sigmastate.utxo._ +import sigma.utils.SparseArrayContainer +import scala.annotation.unused import scala.language.implicitConversions -import scala.util.{Failure, Success} /** Base type for all companions of AST nodes of sigma lang. */ trait SigmaNodeCompanion @@ -521,7 +513,8 @@ object SOptionMethods extends MethodsContainer { FilterMethod ) - def apply[T <: SType](implicit elemType: T, ov: Overload1): SOption[T] = SOption(elemType) + /** Creates a descriptor of `Option[T]` type for the given element type `T`. */ + def apply[T <: SType](implicit elemType: T, @unused ov: Overloaded1): SOption[T] = SOption(elemType) } object SCollectionMethods extends MethodsContainer with MethodByNameUnapply { @@ -796,7 +789,7 @@ object SCollectionMethods extends MethodsContainer with MethodByNameUnapply { } def throwInvalidFlatmap(mc: MethodCall) = { - ErgoTreeEvaluator.error( + sys.error( s"Unsupported lambda in flatMap: allowed usage `xs.flatMap(x => x.property)`: $mc") } @@ -1088,8 +1081,6 @@ case object SAvlTreeMethods extends MonoTypeMethods { lazy val TCollOptionCollByte = SCollection(SByteArrayOption) lazy val CollKeyValue = SCollection(STuple(SByteArray, SByteArray)) - type KeyValueColl = Coll[(Coll[Byte], Coll[Byte])] - lazy val digestMethod = SMethod(this, "digest", SFunc(SAvlTree, SByteArray), 1, FixedCost(JitCost(15))) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, @@ -1217,35 +1208,13 @@ case object SAvlTreeMethods extends MonoTypeMethods { PerItemCost(baseCost = JitCost(100), perChunkCost = JitCost(15), chunkSize = 1), NamedDesc("RemoveAvlTree")) - /** Creates [[AvlTreeVerifier]] for the given tree and proof. */ - def createVerifier(tree: AvlTree, proof: Coll[Byte])(implicit E: ErgoTreeEvaluator) = { - // the cost of tree reconstruction from proof is O(proof.length) - E.addSeqCost(CreateAvlVerifier_Info, proof.length) { () => - AvlTreeVerifier(tree, proof) - } - } - /** Implements evaluation of AvlTree.contains method call ErgoTree node. * Called via reflection based on naming convention. * @see SMethod.evalMethod */ def contains_eval(mc: MethodCall, tree: AvlTree, key: Coll[Byte], proof: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Boolean = { - val bv = createVerifier(tree, proof) - val nItems = bv.treeHeight - - var res = false - // the cost of tree lookup is O(bv.treeHeight) - E.addSeqCost(LookupAvlTree_Info, nItems) { () => - res = bv.performOneOperation(Lookup(ADKey @@ key.toArray)) match { - case Success(r) => r match { - case Some(_) => true - case _ => false - } - case Failure(_) => false - } - } - res + E.contains_eval(mc, tree, key, proof) } lazy val getMethod = SMethod(this, "get", @@ -1271,19 +1240,7 @@ case object SAvlTreeMethods extends MonoTypeMethods { */ def get_eval(mc: MethodCall, tree: AvlTree, key: Coll[Byte], proof: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Option[Coll[Byte]] = { - val bv = createVerifier(tree, proof) - val nItems = bv.treeHeight - - // the cost of tree lookup is O(bv.treeHeight) - E.addSeqCost(LookupAvlTree_Info, nItems) { () => - bv.performOneOperation(Lookup(ADKey @@ key.toArray)) match { - case Success(r) => r match { - case Some(v) => Some(Colls.fromArray(v)) - case _ => None - } - case Failure(_) => Interpreter.error(s"Tree proof is incorrect $tree") - } - } + E.get_eval(mc, tree, key, proof) } lazy val getManyMethod = SMethod(this, "getMany", @@ -1307,20 +1264,7 @@ case object SAvlTreeMethods extends MonoTypeMethods { */ def getMany_eval(mc: MethodCall, tree: AvlTree, keys: Coll[Coll[Byte]], proof: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Coll[Option[Coll[Byte]]] = { - val bv = createVerifier(tree, proof) - val nItems = bv.treeHeight - keys.map { key => - // the cost of tree lookup is O(bv.treeHeight) - E.addSeqCost(LookupAvlTree_Info, nItems) { () => - bv.performOneOperation(Lookup(ADKey @@ key.toArray)) match { - case Success(r) => r match { - case Some(v) => Some(Colls.fromArray(v)) - case _ => None - } - case Failure(_) => Interpreter.error(s"Tree proof is incorrect $tree") - } - } - } + E.getMany_eval(mc, tree, keys, proof) } lazy val insertMethod = SMethod(this, "insert", @@ -1346,36 +1290,7 @@ case object SAvlTreeMethods extends MonoTypeMethods { */ def insert_eval(mc: MethodCall, tree: AvlTree, entries: KeyValueColl, proof: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Option[AvlTree] = { - E.addCost(isInsertAllowed_Info) - if (!tree.isInsertAllowed) { - None - } else { - val bv = createVerifier(tree, proof) - // when the tree is empty we still need to add the insert cost - val nItems = Math.max(bv.treeHeight, 1) - - entries.forall { case (key, value) => - var res = true - // the cost of tree lookup is O(bv.treeHeight) - E.addSeqCost(InsertIntoAvlTree_Info, nItems) { () => - val insert = Insert(ADKey @@ key.toArray, ADValue @@ value.toArray) - val insertRes = bv.performOneOperation(insert) - // TODO v6.0: throwing exception is not consistent with update semantics - // however it preserves v4.0 semantics (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/908) - if (insertRes.isFailure) { - Interpreter.error(s"Incorrect insert for $tree (key: $key, value: $value, digest: ${tree.digest}): ${insertRes.failed.get}}") - } - res = insertRes.isSuccess - } - res - } - bv.digest match { - case Some(d) => - E.addCost(updateDigest_Info) - Some(tree.updateDigest(Colls.fromArray(d))) - case _ => None - } - } + E.insert_eval(mc, tree, entries, proof) } lazy val updateMethod = SMethod(this, "update", @@ -1402,32 +1317,7 @@ case object SAvlTreeMethods extends MonoTypeMethods { def update_eval(mc: MethodCall, tree: AvlTree, operations: KeyValueColl, proof: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Option[AvlTree] = { - E.addCost(isUpdateAllowed_Info) - if (!tree.isUpdateAllowed) { - None - } else { - val bv = createVerifier(tree, proof) - // when the tree is empty we still need to add the insert cost - val nItems = Math.max(bv.treeHeight, 1) - - // here we use forall as looping with fast break on first failed tree oparation - operations.forall { case (key, value) => - var res = true - // the cost of tree update is O(bv.treeHeight) - E.addSeqCost(UpdateAvlTree_Info, nItems) { () => - val op = Update(ADKey @@ key.toArray, ADValue @@ value.toArray) - val updateRes = bv.performOneOperation(op) - res = updateRes.isSuccess - } - res - } - bv.digest match { - case Some(d) => - E.addCost(updateDigest_Info) - Some(tree.updateDigest(Colls.fromArray(d))) - case _ => None - } - } + E.update_eval(mc, tree, operations, proof) } lazy val removeMethod = SMethod(this, "remove", @@ -1454,29 +1344,7 @@ case object SAvlTreeMethods extends MonoTypeMethods { def remove_eval(mc: MethodCall, tree: AvlTree, operations: Coll[Coll[Byte]], proof: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Option[AvlTree] = { - E.addCost(isRemoveAllowed_Info) - if (!tree.isRemoveAllowed) { - None - } else { - val bv = createVerifier(tree, proof) - // when the tree is empty we still need to add the insert cost - val nItems = Math.max(bv.treeHeight, 1) - - cfor(0)(_ < operations.length, _ + 1) { i => - E.addSeqCost(RemoveAvlTree_Info, nItems) { () => - val key = operations(i).toArray - bv.performOneOperation(Remove(ADKey @@ key)) - } - } - - E.addCost(digest_Info) - bv.digest match { - case Some(d) => - E.addCost(updateDigest_Info) - Some(tree.updateDigest(Colls.fromArray(d))) - case _ => None - } - } + E.remove_eval(mc, tree, operations, proof) } lazy val updateDigestMethod = SMethod(this, "updateDigest", diff --git a/data/shared/src/main/scala/sigma/ast/syntax.scala b/data/shared/src/main/scala/sigma/ast/syntax.scala new file mode 100644 index 0000000000..d75c71a779 --- /dev/null +++ b/data/shared/src/main/scala/sigma/ast/syntax.scala @@ -0,0 +1,213 @@ +package sigma.ast + +import sigma.ast.SCollection.{SByteArray, SIntArray} +import sigma.data.{AvlTreeData, CSigmaProp, GeneralType, Nullable, RType, SigmaBoolean, TrivialProp} +import org.ergoplatform.{ErgoBox, ErgoBoxCandidate} +import sigma.kiama.rewriting.Rewriter.{everywherebu, rewrite, rule} +import StdSigmaBuilder.mkUpcast +import sigma.SigmaDataReflection +import sigma.exceptions.InterpreterException + +import scala.annotation.nowarn +import scala.reflect.classTag + +/** Contains global definitions which define syntactic extensions for working with classes + * of sigma.ast package. + */ +object syntax { + /** Force initialization of reflection. */ + val reflection = SigmaDataReflection + + /** The following type synonyms are used throughout the codebase to simplify type annotations. */ + type SValue = Value[SType] + type BoolValue = Value[SBoolean.type] + type ByteValue = Value[SByte.type] + type ShortValue = Value[SShort.type] + type IntValue = Value[SInt.type] + type LongValue = Value[SLong.type] + type BigIntValue = Value[SBigInt.type] + type BoxValue = Value[SBox.type] + type GroupElementValue = Value[SGroupElement.type] + type SigmaPropValue = Value[SSigmaProp.type] + type AvlTreeValue = Value[SAvlTree.type] + type SAnyValue = Value[SAny.type] + type CollectionValue[T <: SType] = Value[SCollection[T]] + + type BooleanConstant = Constant[SBoolean.type] + type ByteConstant = Constant[SByte.type] + type ShortConstant = Constant[SShort.type] + type IntConstant = Constant[SInt.type] + type LongConstant = Constant[SLong.type] + type StringConstant = Constant[SString.type] + type BigIntConstant = Constant[SBigInt.type] + type BoxConstant = Constant[SBox.type] + type GroupElementConstant = Constant[SGroupElement.type] + type SigmaPropConstant = Constant[SSigmaProp.type] + type AvlTreeConstant = Constant[SAvlTree.type] + type CollectionConstant[T <: SType] = Constant[SCollection[T]] + + /** Sigma proposition with trivial false proposition. */ + val FalseSigmaProp = SigmaPropConstant(CSigmaProp(TrivialProp.FalseProp)) + + /** Sigma proposition with trivial true proposition. */ + val TrueSigmaProp = SigmaPropConstant(CSigmaProp(TrivialProp.TrueProp)) + + /** Methods to work with tree nodes of [[SCollection]] type. */ + implicit class CollectionOps[T <: SType](val coll: Value[SCollection[T]]) extends AnyVal { + /** Returns number of items in the collection expression. */ + def length: Int = matchCase(_.items.length, _.value.length, _.items.length) + + /** Returns a sequence of items in the collection expression. */ + def items: Seq[Value[SType]] = matchCase(_.items, _ => sys.error(s"Cannot get 'items' property of node $coll"), _.items) + + /** Abstracts from details of pattern matching collection expressions. + * Folds over given `coll` structure. + */ + def matchCase[R]( + whenConcrete: ConcreteCollection[T] => R, + whenConstant: CollectionConstant[T] => R, + whenTuple: Tuple => R + ): R = coll match { + case cc: ConcreteCollection[T]@unchecked => whenConcrete(cc) + case const: CollectionConstant[T]@unchecked => whenConstant(const) + case tuple: Tuple => whenTuple(tuple) + case _ => sys.error(s"Unexpected node $coll") + } + } + + /** Methods to work with tree nodes of [[SSigmaProp]] type. */ + implicit class SigmaPropValueOps(val p: Value[SSigmaProp.type]) extends AnyVal { + def propBytes: Value[SByteArray] = SigmaPropBytes(p) + } + + /** Methods to work with tree nodes of [[SSigmaProp]] type. */ + implicit class OptionValueOps[T <: SType](val p: Value[SOption[T]]) extends AnyVal { + def get: Value[T] = OptionGet(p) + + def getOrElse(default: Value[T]): Value[T] = OptionGetOrElse(p, default) + + def isDefined: Value[SBoolean.type] = OptionIsDefined(p) + } + + + def GetVarBoolean(varId: Byte): GetVar[SBoolean.type] = GetVar(varId, SBoolean) + + def GetVarByte(varId: Byte): GetVar[SByte.type] = GetVar(varId, SByte) + + def GetVarShort(varId: Byte): GetVar[SShort.type] = GetVar(varId, SShort) + + def GetVarInt(varId: Byte): GetVar[SInt.type] = GetVar(varId, SInt) + + def GetVarLong(varId: Byte): GetVar[SLong.type] = GetVar(varId, SLong) + + def GetVarBigInt(varId: Byte): GetVar[SBigInt.type] = GetVar(varId, SBigInt) + + def GetVarBox(varId: Byte): GetVar[SBox.type] = GetVar(varId, SBox) + + def GetVarSigmaProp(varId: Byte): GetVar[SSigmaProp.type] = GetVar(varId, SSigmaProp) + + def GetVarByteArray(varId: Byte): GetVar[SCollection[SByte.type]] = GetVar(varId, SByteArray) + + def GetVarIntArray(varId: Byte): GetVar[SCollection[SInt.type]] = GetVar(varId, SIntArray) + + implicit def boolToSigmaProp(b: BoolValue): SigmaPropValue = BoolToSigmaProp(b) + + /** Shadow the implicit from sigma package so it doesn't interfere with the resolution + * of ClassTags below. + */ + @nowarn private def rtypeToClassTag = ??? + + /** RType descriptors for predefined types used in AOTC-based interpreter. */ + implicit val SigmaBooleanRType: RType[SigmaBoolean] = RType.fromClassTag(classTag[SigmaBoolean]) + + implicit val ErgoBoxRType: RType[ErgoBox] = RType.fromClassTag(classTag[ErgoBox]) + + implicit val ErgoBoxCandidateRType: RType[ErgoBoxCandidate] = RType.fromClassTag(classTag[ErgoBoxCandidate]) + + implicit val AvlTreeDataRType: RType[AvlTreeData] = GeneralType(classTag[AvlTreeData]) + + /** Type casting methods for [[Value]] nodes. + * Each `asX` method casts the value to the corresponding `X` type of node. + * No runtime checks are performed, so the caller should ensure that the value has the + * expected type. + * */ + implicit class ValueOps(val v: Value[SType]) extends AnyVal { + def asValue[T <: SType]: Value[T] = v.asInstanceOf[Value[T]] + + def asNumValue: Value[SNumericType] = v.asInstanceOf[Value[SNumericType]] + + def asBoolValue: Value[SBoolean.type] = v.asInstanceOf[Value[SBoolean.type]] + + def asByteValue: Value[SByte.type] = v.asInstanceOf[Value[SByte.type]] + + def asIntValue: Value[SInt.type] = v.asInstanceOf[Value[SInt.type]] + + def asBigInt: Value[SBigInt.type] = v.asInstanceOf[Value[SBigInt.type]] + + def asBox: Value[SBox.type] = v.asInstanceOf[Value[SBox.type]] + + def asGroupElement: Value[SGroupElement.type] = v.asInstanceOf[Value[SGroupElement.type]] + + def asSigmaProp: Value[SSigmaProp.type] = v.asInstanceOf[Value[SSigmaProp.type]] + + def asByteArray: Value[SByteArray] = v.asInstanceOf[Value[SByteArray]] + + def asIntArray: Value[SIntArray] = v.asInstanceOf[Value[SIntArray]] + + def asCollection[T <: SType]: Value[SCollection[T]] = v.asInstanceOf[Value[SCollection[T]]] + + def asOption[T <: SType]: Value[SOption[T]] = v.asInstanceOf[Value[SOption[T]]] + + def asTuple: Value[STuple] = v.asInstanceOf[Value[STuple]] + + def asFunc: Value[SFunc] = v.asInstanceOf[Value[SFunc]] + + /** Upcast the value `v` to the given type checking that `v` if of a numeric type. + * @param targetType type to upcast to + * @return upcasted value + */ + def upcastTo[T <: SNumericType](targetType: T): Value[T] = { + assert(v.tpe.isInstanceOf[SNumericType], + s"Cannot upcast value of type ${v.tpe} to $targetType: only numeric types can be upcasted.") + val tV = v.asValue[SNumericType] + assert(targetType.max(tV.tpe) == targetType, + s"Invalid upcast from $tV to $targetType: target type should be larger than source type.") + if (targetType == tV.tpe) v.asValue[T] + else + mkUpcast(tV, targetType).withSrcCtx(v.sourceContext) + } + + /** Assigns optional [[SourceContext]] to the value `v`. + * The is effectful operation changing state of `v`. + * @return the same instance of `v` with the given source context assigned + */ + def withSrcCtx[T <: SType](sourceContext: Nullable[SourceContext]): Value[T] = { + v.sourceContext = sourceContext + v.asValue[T] + } + + /** + * Sets the source context of the `v` instance only if it's empty (i.e. not set yet). + */ + def withEnsuredSrcCtx[T <: SType](sourceContext: Nullable[SourceContext]): Value[T] = { + if (v.sourceContext.isEmpty) v.sourceContext = sourceContext + v.asValue[T] + } + + /** + * Set source context to all nodes missing source context in the given tree. + * + * @param srcCtx source context to set + * @return AST where all nodes with missing source context are set to the given srcCtx + */ + def withPropagatedSrcCtx[T <: SType](srcCtx: Nullable[SourceContext]): Value[T] = { + rewrite(everywherebu(rule[Any] { + case node: SValue if node != null && node.sourceContext.isEmpty => + node.withSrcCtx(srcCtx) + }))(v).asValue[T] + } + } + + /** Helper method to throw errors from Interpreter. */ + def error(msg: String) = throw new InterpreterException(msg) +} diff --git a/interpreter/shared/src/main/scala/sigmastate/utxo/transformers.scala b/data/shared/src/main/scala/sigma/ast/transformers.scala similarity index 96% rename from interpreter/shared/src/main/scala/sigmastate/utxo/transformers.scala rename to data/shared/src/main/scala/sigma/ast/transformers.scala index c747abde09..939da79d98 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utxo/transformers.scala +++ b/data/shared/src/main/scala/sigma/ast/transformers.scala @@ -1,22 +1,16 @@ -package sigmastate.utxo +package sigma.ast -import sigmastate.Values._ -import sigmastate.lang.Terms._ -import sigmastate._ -import sigmastate.serialization.OpCodes import org.ergoplatform.ErgoBox.RegisterId +import sigma.ast.Operations._ import sigma.ast.SCollection.SByteArray -import sigma.ast._ -import sigma.data.RType +import sigma.ast.syntax.SValue +import sigma.data.{CSigmaProp, RType} +import sigma.eval.ErgoTreeEvaluator +import sigma.eval.ErgoTreeEvaluator.DataEnv import sigma.serialization.CoreByteWriter.ArgInfo -import sigmastate.Operations._ -import sigmastate.eval.SigmaDsl -import sigmastate.exceptions.InterpreterException -import sigmastate.interpreter.ErgoTreeEvaluator -import sigmastate.interpreter.ErgoTreeEvaluator.{DataEnv, error} -import sigma.{Coll, Evaluation} -import sigma.{Box, SigmaProp} -import sigmastate.serialization.ValueCodes.OpCode +import sigma.serialization.OpCodes +import sigma.serialization.ValueCodes.OpCode +import sigma.{Box, Coll, Evaluation} // TODO refactor: remove this trait as it doesn't have semantic meaning @@ -241,14 +235,6 @@ object Fold extends ValueCompanion { override def opCode: OpCode = OpCodes.FoldCode override val costKind = PerItemCost( baseCost = JitCost(3), perChunkCost = JitCost(1), chunkSize = 10) - def sum[T <: SNumericType](input: Value[SCollection[T]], varId: Int)(implicit tT: T) = - Fold(input, - Constant(tT.upcast(0.toByte), tT), - FuncValue(Array((varId, STuple(tT, tT))), - Plus( - SelectField(ValUse(varId, STuple(tT, tT)), 1).asNumValue, - SelectField(ValUse(varId, STuple(tT, tT)), 2).asNumValue)) - ) } /** The element of the collection or default value. @@ -303,7 +289,7 @@ case class SelectField(input: Value[STuple], fieldIndex: Byte) case p: Tuple2[_,_] => if (fieldIndex == 1) p._1 else if (fieldIndex == 2) p._2 - else error(s"Unknown fieldIndex $fieldIndex to select from $p: evaluating tree $this") + else sys.error(s"Unknown fieldIndex $fieldIndex to select from $p: evaluating tree $this") case _ => Value.typeError(input, inputV) } @@ -337,8 +323,8 @@ case class SigmaPropBytes(input: Value[SSigmaProp.type]) override def tpe = SByteArray override val opType = SFunc(input.tpe, tpe) protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - val inputV = input.evalTo[SigmaProp](env) - val numNodes = SigmaDsl.toSigmaBoolean(inputV).size + val inputV = input.evalTo[CSigmaProp](env) + val numNodes = inputV.wrappedValue.size addSeqCost(SigmaPropBytes.costKind, numNodes) { () => inputV.propBytes } diff --git a/interpreter/shared/src/main/scala/sigmastate/trees.scala b/data/shared/src/main/scala/sigma/ast/trees.scala similarity index 98% rename from interpreter/shared/src/main/scala/sigmastate/trees.scala rename to data/shared/src/main/scala/sigma/ast/trees.scala index fb5f178389..38d4565f30 100644 --- a/interpreter/shared/src/main/scala/sigmastate/trees.scala +++ b/data/shared/src/main/scala/sigma/ast/trees.scala @@ -1,30 +1,26 @@ -package sigmastate +package sigma.ast import debox.{cfor, Map => DMap} -import sigma.data.ExactIntegral._ -import sigma.data.ExactOrdering._ -import sigma.data.OverloadHack.Overloaded1 -import sigma.data.{CAND, COR, CTHRESHOLD, ExactIntegral, ExactOrdering, SigmaBoolean, SigmaConstants} import scorex.crypto.hash.{Blake2b256, CryptographicHash32, Sha256} -import sigma.ast.SCollection +import sigma.ast.ArithOp.OperationImpl +import sigma.ast.Operations._ import sigma.ast.SCollection.{SByteArray, SIntArray} import sigma.ast.SOption.SIntOption -import sigma.{Coll, Colls, GroupElement, SigmaProp, VersionContext} -import sigmastate.ArithOp.OperationImpl -import sigmastate.Operations._ -import sigma.ast._ +import sigma.ast.syntax._ +import sigma.data.ExactIntegral._ +import sigma.data.ExactOrdering._ +import sigma.data.OverloadHack.Overloaded1 +import sigma.data._ import sigma.serialization.CoreByteWriter.ArgInfo import sigma.validation.SigmaValidationSettings -import sigmastate.Values._ -import sigmastate.eval.Extensions.EvalCollOps -import sigmastate.eval.NumericOps.{BigIntIsExactIntegral, BigIntIsExactOrdering} -import sigmastate.eval.SigmaDsl -import sigmastate.interpreter.ErgoTreeEvaluator -import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv -import sigmastate.serialization.OpCodes._ -import sigmastate.serialization.ValueCodes.OpCode -import sigmastate.serialization._ -import sigmastate.utxo.{SimpleTransformerCompanion, Transformer} +import sigma.{Coll, Colls, GroupElement, SigmaProp, VersionContext} +import NumericOps.{BigIntIsExactIntegral, BigIntIsExactOrdering} +import sigma.eval.ErgoTreeEvaluator.DataEnv +import sigma.eval.Extensions.EvalCollOps +import sigma.eval.{ErgoTreeEvaluator, SigmaDsl} +import sigma.serialization.OpCodes._ +import sigma.serialization.ValueCodes.OpCode +import sigma.serialization._ import scala.collection.mutable @@ -40,7 +36,7 @@ case class BoolToSigmaProp(value: BoolValue) extends SigmaPropValue { val v = value.evalTo[Any](env) addCost(BoolToSigmaProp.costKind) if (VersionContext.current.isJitActivated) { - SigmaDsl.sigmaProp(v.asInstanceOf[Boolean]) + CSigmaProp(v.asInstanceOf[Boolean]) } else { // before v5.0 is activated we follow the old v4.x semantics to handle cases // when the value is not a boolean. There are historical transactions with such @@ -48,7 +44,7 @@ case class BoolToSigmaProp(value: BoolValue) extends SigmaPropValue { v match { case sp: SigmaProp => sp case _ => - SigmaDsl.sigmaProp(v.asInstanceOf[Boolean]) + CSigmaProp(v.asInstanceOf[Boolean]) } } } @@ -68,7 +64,7 @@ case class CreateProveDlog(value: Value[SGroupElement.type]) extends SigmaPropVa protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { val v = value.evalTo[GroupElement](env) addCost(CreateProveDlog.costKind) - SigmaDsl.proveDlog(v) + CSigmaProp.withProveDlog(v) } } object CreateProveDlog extends FixedCostValueCompanion { @@ -109,7 +105,7 @@ case class CreateProveDHTuple(gv: Value[SGroupElement.type], val u = uv.evalTo[GroupElement](env) val v = vv.evalTo[GroupElement](env) addCost(CreateProveDHTuple.costKind) - SigmaDsl.proveDHTuple(g, h, u, v) + CSigmaProp.withProveDHTuple(g, h, u, v) } } object CreateProveDHTuple extends FixedCostValueCompanion { @@ -676,7 +672,7 @@ object SubstConstants extends ValueCompanion { /** Transforms serialized bytes of ErgoTree with segregated constants by * replacing constants at given positions with new values. This operation * allow to use serialized scripts as pre-defined templates. - * See [[sigmastate.SubstConstants]] for details. + * See [[SubstConstants]] for details. * * @param scriptBytes serialized ErgoTree with ConstantSegregationFlag set to 1. * @param positions zero based indexes in ErgoTree.constants array which @@ -865,7 +861,7 @@ object ArithOp { } } - private[sigmastate] val operations: DMap[Byte, ArithOpCompanion] = + private[sigma] val operations: DMap[Byte, ArithOpCompanion] = DMap.fromIterable(Seq(Plus, Minus, Multiply, Division, Modulo, Min, Max).map(o => (o.opCode, o))) /** Represents implementation of numeric Arith operations for the given type argTpe. */ @@ -874,7 +870,7 @@ object ArithOp { val o = _o.asInstanceOf[ExactOrdering[Any]] } - private[sigmastate] val impls: DMap[SType.TypeCode, OperationImpl] = + private[sigma] val impls: DMap[SType.TypeCode, OperationImpl] = DMap.fromIterable(Seq( SByte -> new OperationImpl(ByteIsExactIntegral, ByteIsExactOrdering, SByte), SShort -> new OperationImpl(ShortIsExactIntegral, ShortIsExactOrdering, SShort), diff --git a/data/shared/src/main/scala/sigma/ast/values.scala b/data/shared/src/main/scala/sigma/ast/values.scala new file mode 100644 index 0000000000..1ded9d6b5c --- /dev/null +++ b/data/shared/src/main/scala/sigma/ast/values.scala @@ -0,0 +1,1511 @@ +package sigma.ast + +import debox.cfor +import sigma.Extensions.ArrayOps +import sigma._ +import sigma.ast.SCollection.SByteArray +import sigma.ast.TypeCodes.ConstantCode +import sigma.ast.syntax._ +import sigma.crypto.{CryptoConstants, EcPointType} +import sigma.data.OverloadHack.Overloaded1 +import sigma.data.{CSigmaDslBuilder, CSigmaProp, Nullable, RType, SigmaBoolean} +import sigma.eval.ErgoTreeEvaluator.DataEnv +import sigma.eval.{ErgoTreeEvaluator, SigmaDsl} +import sigma.exceptions.InterpreterException +import sigma.kiama.rewriting.Rewriter.count +import sigma.serialization.OpCodes._ +import sigma.serialization.ValueCodes.OpCode +import sigma.serialization._ +import sigma.util.CollectionUtil._ +import sigma.util.Extensions._ + +import java.math.BigInteger +import java.util.{Arrays, Objects} +import scala.annotation.unused +import scala.collection.compat.immutable.ArraySeq +import scala.collection.mutable +import scala.language.implicitConversions + +/** Base class for all ErgoTree expression nodes. + * + * @see [[ErgoTree]] + */ +abstract class Value[+S <: SType] extends SigmaNode { + /** The companion node descriptor with opCode, cost and other metadata. */ + def companion: ValueCompanion + + /** Unique id of the node class used in serialization of ErgoTree. */ + def opCode: OpCode = companion.opCode + + /** The type of the value represented by this node. If the value is an operation it is + * the type of operation result. */ + def tpe: S + + /** Every value represents an operation and that operation can be associated with a function type, + * describing functional meaning of the operation, kind of operation signature. + * Thus, we can obtain global operation identifiers by combining Value.opName with Value.opType, + * so that if (v1.opName == v2.opName) && (v1.opType == v2.opType) then v1 and v2 are functionally + * point-wise equivalent. + * This in particular means that if two _different_ ops have the same opType they _should_ have + * different opNames. + * Thus defined op ids are used in a v4.x Cost Model - a table of all existing primitives coupled with + * performance parameters. + * */ + def opType: SFunc + + /** Name of the operation. */ + def opName: String = this.getClass.getSimpleName + + /** Transforms this expression to SigmaProp expression or throws an exception. */ + def toSigmaProp: SigmaPropValue = this match { + case b if b.tpe == SBoolean => BoolToSigmaProp(this.asBoolValue) + case p if p.tpe == SSigmaProp => p.asSigmaProp + case _ => sys.error(s"Expected SBoolean or SSigmaProp typed value, but was: $this") + } + + /** Parser has some source information like line,column in the text. We need to keep it up until RuntimeCosting. + * The way to do this is to add Nullable property to every Value. Since Parser is always using SigmaBuilder + * to create nodes, + * Adding additional (implicit source: SourceContext) parameter to every builder method would pollute its API + * and also doesn't make sence during deserialization, where Builder is also used. + * We can assume some indirect mechanism to pass current source context into every mkXXX method of Builder. + * We can pass it using `scala.util.DynamicVariable` by wrapping each mkXXX call into `withValue { }` calls. + * The same will happen in Typer. + * We can take sourceContext from untyped nodes and use it while creating typed nodes. + * And we can make sourceContext of every Value writeOnce value, i.e. it will be Nullable.Null by default, + * but can be set afterwards, but only once. + * This property will not participate in equality and other operations, so will be invisible for existing code. + * But Builder can use it to set sourceContext if it is present. + */ + private[ast] var _sourceContext: Nullable[SourceContext] = Nullable.None + + def sourceContext: Nullable[SourceContext] = _sourceContext + + def sourceContext_=(srcCtx: Nullable[SourceContext]): Unit = + if (_sourceContext.isEmpty) { + _sourceContext = srcCtx + } else { + sys.error("_sourceContext can be set only once") + } + + /** Defines an evaluation semantics of this tree node (aka Value or expression) in the given data environment. + * Should be implemented by all the ErgoTree nodes (aka operations). + * Thus, the ErgoTree interpreter implementation consists of combined implementations of this method. + * NOTE, this method shouldn't be called directly, instead use `evalTo` method. + * + * @param E Evaluator which defines evaluation context, cost accumulator, settings etc. + * @param env immutable map, which binds variables (given by ids) to the values + * @return the data value which is the result of evaluation + */ + protected def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = + sys.error(s"Should be overriden in ${this.getClass}: $this") + + /** Evaluates this node to the value of the given expected type. + * This method should called from all `eval` implementations. + * + * @tparam T expected type of the resulting value + * @param E Evaluator which defines evaluation context, cost accumulator, settings etc. + * @param env immutable map, which binds variables (given by ids) to the values + * @return the data value which is the result of evaluation + */ + @inline + final def evalTo[T](env: DataEnv)(implicit E: ErgoTreeEvaluator): T = { + if (E.settings.isMeasureOperationTime) E.profiler.onBeforeNode(this) + val v = eval(env) + if (E.settings.isMeasureOperationTime) E.profiler.onAfterNode(this) + v.asInstanceOf[T] + } + + /** Add the cost given by the kind to the accumulator and associate it with this operation + * node. + */ + @inline + final def addCost(costKind: FixedCost)(implicit E: ErgoTreeEvaluator): Unit = { + E.addCost(costKind, this.companion.opDesc) + } + + /** Add the cost given by the descriptor to the accumulator and associate it with this operation + * node. + */ + @inline + final def addCost[R](costKind: TypeBasedCost, tpe: SType) + (block: () => R) + (implicit E: ErgoTreeEvaluator): R = { + E.addTypeBasedCost(costKind, tpe, this.companion.opDesc)(block) + } + + /** Add the cost of a repeated operation to the accumulator and associate it with this + * operation. The number of items (loop iterations) is known in advance (like in + * Coll.map operation) + * + * @param costKind cost descriptor of the operation + * @param nItems number of operations known in advance (before loop execution) + */ + @inline + final def addSeqCostNoOp(costKind: PerItemCost, nItems: Int) + (implicit E: ErgoTreeEvaluator): Unit = { + E.addSeqCostNoOp(costKind, nItems, this.companion.opDesc) + } + + /** Add the cost of a repeated operation to the accumulator and associate it with this + * operation. The number of items (loop iterations) is known in advance (like in + * Coll.map operation) + * + * @param costKind cost descriptor of the operation + * @param nItems number of operations known in advance (before loop execution) + * @param block operation executed under the given cost + * @tparam R result type of the operation + */ + @inline + final def addSeqCost[R](costKind: PerItemCost, nItems: Int) + (block: () => R)(implicit E: ErgoTreeEvaluator): R = { + E.addSeqCost(costKind, nItems, this.companion.opDesc)(block) + } +} + +object Value { + type PropositionCode = Byte + + implicit def liftByte(n: Byte): Value[SByte.type] = ByteConstant(n) + + implicit def liftShort(n: Short): Value[SShort.type] = ShortConstant(n) + + implicit def liftInt(n: Int): Value[SInt.type] = IntConstant(n) + + implicit def liftLong(n: Long): Value[SLong.type] = LongConstant(n) + + implicit def liftByteArray(arr: Array[Byte]): Value[SByteArray] = ByteArrayConstant(arr) + + implicit def liftBigInt(arr: BigInt): Value[SBigInt.type] = BigIntConstant(arr) + + implicit def liftGroupElement(g: GroupElement): Value[SGroupElement.type] = GroupElementConstant(g) + + implicit def liftECPoint(g: EcPointType): Value[SGroupElement.type] = GroupElementConstant(g) + + implicit def liftSigmaProp(g: SigmaProp): Value[SSigmaProp.type] = SigmaPropConstant(g) + + implicit def liftSigmaBoolean(sb: SigmaBoolean): Value[SSigmaProp.type] = SigmaPropConstant(SigmaDsl.SigmaProp(sb)) + + object Typed { + def unapply(v: SValue): Option[(SValue, SType)] = Some((v, v.tpe)) + } + + def notSupportedError(v: Any, opName: String) = + throw new IllegalArgumentException(s"Method $opName is not supported for node $v") + + /** Immutable empty array of values. Can be used to avoid allocation. */ + val EmptyArray = Array.empty[SValue] + + /** Immutable empty Seq of values. Can be used to avoid allocation. */ + val EmptySeq: IndexedSeq[SValue] = EmptyArray + + /** Traverses the given expression tree and counts the number of deserialization + * operations. If it is non-zero, returns true. */ + def hasDeserialize(exp: SValue): Boolean = { + val deserializeNode: PartialFunction[Any, Int] = { + case _: DeserializeContext[_] => 1 + case _: DeserializeRegister[_] => 1 + } + val c = count(deserializeNode)(exp) + c > 0 + } + + def typeError(node: SValue, evalResult: Any) = { + val tpe = node.tpe + throw new InterpreterException( + s"""Invalid type returned by evaluator: + | expression: $node + | expected type: $tpe + | resulting value: $evalResult + """.stripMargin) + } + + def typeError(tpe: SType, evalResult: Any) = { + throw new InterpreterException( + s"""Invalid type returned by evaluator: + | expected type: $tpe + | resulting value: $evalResult + """.stripMargin) + } + + def checkType(node: SValue, evalResult: Any) = { + val tpe = node.tpe + if (!SType.isValueOfType(evalResult, tpe)) + typeError(node, evalResult) + } + + def checkType(tpe: SType, evalResult: Any) = { + if (!SType.isValueOfType(evalResult, tpe)) + typeError(tpe, evalResult) + } +} + +/** Base class for all companion objects which are used as operation descriptors. */ +trait ValueCompanion extends SigmaNodeCompanion { + import ValueCompanion._ + + /** Unique id of the node class used in serialization of ErgoTree. */ + def opCode: OpCode + + /** Returns cost descriptor of this operation. */ + def costKind: CostKind + + override def toString: String = s"${this.getClass.getSimpleName}(${opCode.toUByte})" + + def typeName: String = this.getClass.getSimpleName.replace("$", "") + + def init() { + if (this.opCode != 0 && _allOperations.contains(this.opCode)) + throw sys.error(s"Operation $this already defined") + _allOperations += (this.opCode -> this) + } + + init() + val opDesc = CompanionDesc(this) +} + +object ValueCompanion { + private val _allOperations: mutable.HashMap[Byte, ValueCompanion] = mutable.HashMap.empty + + lazy val allOperations = _allOperations.toMap +} + +/** Should be inherited by companion objects of operations with fixed cost kind. */ +trait FixedCostValueCompanion extends ValueCompanion { + /** Returns cost descriptor of this operation. */ + override def costKind: FixedCost +} + +/** Should be inherited by companion objects of operations with per-item cost kind. */ +trait PerItemCostValueCompanion extends ValueCompanion { + /** Returns cost descriptor of this operation. */ + override def costKind: PerItemCost +} + +/** Base class for ErgoTree nodes which represents a data value which has already been + * evaluated and no further evaluation (aka reduction) is necessary by the interpreter. + * + * @see Constant, ConcreteCollection, Tuple + */ +abstract class EvaluatedValue[+S <: SType] extends Value[S] { + /** The evaluated data value of the corresponding underlying data type. */ + val value: S#WrappedType + + override def opType: SFunc = { + val resType = tpe match { + case ct: SCollection[_] => + SCollection(ct.typeParams.head.ident) + case ft @ SFunc(_, _, _) => + ft.getGenericType + case _ => tpe + } + SFunc(ArraySeq.empty, resType) + } +} + +/** Base class for all constant literals whose data value is already known and never + * changes. + * + * @see ConstantNode + */ +abstract class Constant[+S <: SType] extends EvaluatedValue[S] + +/** ErgoTree node which represents data literals, i.e. data values embedded in an + * expression. + * + * @param value data value of the underlying Scala type + * @param tpe type descriptor of the data value and also the type of the value + * represented by this node. + * @see Constant + */ +case class ConstantNode[S <: SType](value: S#WrappedType, tpe: S) extends Constant[S] { + require(sigma.crypto.Platform.isCorrectType(value, tpe), + s"Invalid type of constant value $value, expected type $tpe") + + override def companion: ValueCompanion = Constant + + override def opCode: OpCode = companion.opCode + + override def opName: String = s"Const" + + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(Constant.costKind) + value + } + + override def equals(obj: scala.Any): Boolean = (obj != null) && (this.eq(obj.asInstanceOf[AnyRef]) || (obj match { + case c: Constant[_] => tpe == c.tpe && Objects.deepEquals(value, c.value) + case _ => false + })) + + override def hashCode(): Int = Arrays.deepHashCode(Array(value.asInstanceOf[AnyRef], tpe)) + + override def toString: String = tpe.asInstanceOf[SType] match { + case SGroupElement if value.isInstanceOf[GroupElement] => + s"ConstantNode(${value.asInstanceOf[GroupElement].showToString},$tpe)" + case SGroupElement => + sys.error(s"Invalid value in Constant($value, $tpe)") + case SInt => s"IntConstant($value)" + case SLong => s"LongConstant($value)" + case SBoolean if value == true => "TrueLeaf" + case SBoolean if value == false => "FalseLeaf" + case _ => s"ConstantNode($value,$tpe)" + } +} + +object Constant extends FixedCostValueCompanion { + override def opCode: OpCode = OpCode @@ ConstantCode + + /** Cost of: returning value from Constant node. */ + override val costKind = FixedCost(JitCost(5)) + + /** Immutable empty array, can be used to save allocations in many places. */ + val EmptyArray = Array.empty[Constant[SType]] + + /** Immutable empty IndexedSeq, can be used to save allocations in many places. */ + val EmptySeq: IndexedSeq[Constant[SType]] = Array.empty[Constant[SType]] + + /** Helper factory method. */ + def apply[S <: SType]( + value: S#WrappedType, + tpe: S): Constant[S] = ConstantNode(value, tpe) + + /** Recognizer of Constant tree nodes used in patterns. */ + def unapply[S <: SType](v: EvaluatedValue[S]): Option[(S#WrappedType, S)] = v match { + case ConstantNode(value, tpe) => Some((value, tpe)) + case _ => None + } +} + +/** Placeholder for a constant in ErgoTree. Zero based index in ErgoTree.constants array. */ +case class ConstantPlaceholder[S <: SType]( + id: Int, + override val tpe: S) extends Value[S] { + def opType = SFunc(SInt, tpe) + + override def companion: ValueCompanion = ConstantPlaceholder + + override protected def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + val c = E.constants(id) + addCost(ConstantPlaceholder.costKind) + val res = c.value + Value.checkType(c, res) + res + } +} + +object ConstantPlaceholder extends ValueCompanion { + override def opCode: OpCode = ConstantPlaceholderCode + + /** Cost of: accessing Constant in array by index. */ + override val costKind = FixedCost(JitCost(1)) +} + +trait NotReadyValue[S <: SType] extends Value[S] { +} + +// TODO v6.0: remove these TaggedVariable and TaggedVariableNode (https://github.com/ScorexFoundation/sigmastate-interpreter/issues/584) + +/** Reference a context variable by id. */ +trait TaggedVariable[T <: SType] extends NotReadyValue[T] { + val varId: Byte +} + +case class TaggedVariableNode[T <: SType](varId: Byte, override val tpe: T) + extends TaggedVariable[T] { + override def companion = TaggedVariable + + def opType: SFunc = Value.notSupportedError(this, "opType") +} + +object TaggedVariable extends ValueCompanion { + override def opCode: OpCode = TaggedVariableCode + + override def costKind: CostKind = FixedCost(JitCost(1)) + + def apply[T <: SType](varId: Byte, tpe: T): TaggedVariable[T] = + TaggedVariableNode(varId, tpe) +} + +/** High-level interface to internal representation of Unit constants in ErgoTree. */ +object UnitConstant { + /** ErgoTree node that represent a literal of Unit type. It is global immutable value + * which should be reused wherever necessary to avoid allocations. + */ + val instance = apply() + + /** Constucts a fresh new instance of Unit literal node. */ + def apply() = Constant[SUnit.type]((), SUnit) + + /** Recognizer to pattern match on Unit constant literal nodes (aka Unit constants). */ + def unapply(node: SValue): Boolean = node match { + case ConstantNode(_, SUnit) => true + case _ => false + } +} + +object ByteConstant { + def apply(value: Byte): Constant[SByte.type] = Constant[SByte.type](value, SByte) +} + +object ShortConstant { + def apply(value: Short): Constant[SShort.type] = Constant[SShort.type](value, SShort) +} + +object IntConstant { + def apply(value: Int): Constant[SInt.type] = Constant[SInt.type](value, SInt) + + def unapply(v: SValue): Option[Int] = v match { + case Constant(value: Int, SInt) => Some(value) + case _ => None + } + + def Zero = IntConstant(0) +} + +object LongConstant { + def apply(value: Long): Constant[SLong.type] = Constant[SLong.type](value, SLong) + + def unapply(v: SValue): Option[Long] = v match { + case Constant(value: Long, SLong) => Some(value) + case _ => None + } +} + +object BigIntConstant { + def apply(value: BigInt): Constant[SBigInt.type] = Constant[SBigInt.type](value, SBigInt) + + def apply(value: BigInteger): Constant[SBigInt.type] = Constant[SBigInt.type](SigmaDsl.BigInt(value), SBigInt) + + def apply(value: Long): Constant[SBigInt.type] = Constant[SBigInt.type](SigmaDsl.BigInt(BigInteger.valueOf(value)), SBigInt) +} + +object StringConstant { + def apply(value: String): Constant[SString.type] = Constant[SString.type](value, SString) + + def unapply(v: SValue): Option[String] = v match { + case Constant(value: String, SString) => Some(value) + case _ => None + } +} + +object BoxConstant { + def apply(value: Box): Constant[SBox.type] = Constant[SBox.type](value, SBox) +} + +object GroupElementConstant { + def apply(value: EcPointType): Constant[SGroupElement.type] = apply(SigmaDsl.GroupElement(value)) + + def apply(value: GroupElement): Constant[SGroupElement.type] = Constant[SGroupElement.type](value, SGroupElement) + + def unapply(v: SValue): Option[GroupElement] = v match { + case Constant(value: GroupElement, SGroupElement) => Some(value) + case _ => None + } +} + +object SigmaPropConstant { + def apply(value: SigmaProp): Constant[SSigmaProp.type] = Constant[SSigmaProp.type](value, SSigmaProp) + + def apply(value: SigmaBoolean): Constant[SSigmaProp.type] = Constant[SSigmaProp.type](CSigmaProp(value), SSigmaProp) + + def unapply(v: SValue): Option[SigmaProp] = v match { + case Constant(value: SigmaProp, SSigmaProp) => Some(value) + case _ => None + } +} + +object AvlTreeConstant { + def apply(value: AvlTree): Constant[SAvlTree.type] = Constant[SAvlTree.type](value, SAvlTree) +} + +object PreHeaderConstant { + def apply(value: PreHeader): Constant[SPreHeader.type] = Constant[SPreHeader.type](value, SPreHeader) + + def unapply(v: SValue): Option[PreHeader] = v match { + case Constant(value: PreHeader, SPreHeader) => Some(value) + case _ => None + } +} + +object HeaderConstant { + def apply(value: Header): Constant[SHeader.type] = Constant[SHeader.type](value, SHeader) + + def unapply(v: SValue): Option[Header] = v match { + case Constant(value: Header, SHeader) => Some(value) + case _ => None + } +} + +trait NotReadyValueInt extends NotReadyValue[SInt.type] { + override def tpe = SInt +} + +trait NotReadyValueLong extends NotReadyValue[SLong.type] { + override def tpe = SLong +} + +trait NotReadyValueBigInt extends NotReadyValue[SBigInt.type] { + override def tpe = SBigInt +} + +/** Base type for evaluated tree nodes of Coll type. */ +trait EvaluatedCollection[T <: SType, C <: SCollection[T]] extends EvaluatedValue[C] { + /** Type descriptor of the collection elements. */ + def elementType: T +} + +object CollectionConstant { + def apply[T <: SType]( + value: Coll[T#WrappedType], + elementType: T): Constant[SCollection[T]] = + Constant[SCollection[T]](value, SCollection(elementType)) + + def unapply[T <: SType](node: Value[SCollection[T]]): Option[(Coll[T#WrappedType], T)] = node match { + case c: Constant[SCollection[a]]@unchecked if c.tpe.isCollection => + val v = c.value.asInstanceOf[Coll[T#WrappedType]] + val t = c.tpe.elemType + Some((v, t)) + case _ => None + } +} + +object ByteArrayConstant { + val ByteArrayTypeCode = (SCollectionType.CollectionTypeCode + SByte.typeCode).toByte + + def apply(value: Coll[Byte]): CollectionConstant[SByte.type] = CollectionConstant[SByte.type](value, SByte) + + def apply(value: Array[Byte]): CollectionConstant[SByte.type] = CollectionConstant[SByte.type](value.toColl, SByte) + + def unapply(node: SValue): Option[Coll[Byte]] = node match { + case coll: CollectionConstant[SByte.type]@unchecked => coll match { + case CollectionConstant(arr, SByte) => Some(arr) + case _ => None + } + case _ => None + } +} + +object ShortArrayConstant { + def apply(value: Coll[Short]): CollectionConstant[SShort.type] = CollectionConstant[SShort.type](value, SShort) + + def apply(value: Array[Short]): CollectionConstant[SShort.type] = CollectionConstant[SShort.type](value.toColl, SShort) + + def unapply(node: SValue): Option[Coll[Short]] = node match { + case coll: CollectionConstant[SShort.type]@unchecked => coll match { + case CollectionConstant(arr, SShort) => Some(arr) + case _ => None + } + case _ => None + } +} + +object IntArrayConstant { + def apply(value: Coll[Int]): CollectionConstant[SInt.type] = CollectionConstant[SInt.type](value, SInt) + + def apply(value: Array[Int]): CollectionConstant[SInt.type] = CollectionConstant[SInt.type](value.toColl, SInt) + + def unapply(node: SValue): Option[Coll[Int]] = node match { + case coll: CollectionConstant[SInt.type]@unchecked => coll match { + case CollectionConstant(arr, SInt) => Some(arr) + case _ => None + } + case _ => None + } +} + +object LongArrayConstant { + def apply(value: Coll[Long]): CollectionConstant[SLong.type] = CollectionConstant[SLong.type](value, SLong) + + def apply(value: Array[Long]): CollectionConstant[SLong.type] = CollectionConstant[SLong.type](value.toColl, SLong) + + def unapply(node: SValue): Option[Coll[Long]] = node match { + case coll: CollectionConstant[SLong.type]@unchecked => coll match { + case CollectionConstant(arr, SLong) => Some(arr) + case _ => None + } + case _ => None + } +} + +object BigIntArrayConstant { + def apply(value: Coll[BigInt]): CollectionConstant[SBigInt.type] = CollectionConstant[SBigInt.type](value, SBigInt) + + def apply(value: Array[BigInt]): CollectionConstant[SBigInt.type] = CollectionConstant[SBigInt.type](value.toColl, SBigInt) + + def unapply(node: SValue): Option[Coll[BigInt]] = node match { + case coll: CollectionConstant[SBigInt.type]@unchecked => coll match { + case CollectionConstant(arr, SBigInt) => Some(arr) + case _ => None + } + case _ => None + } +} + +object BoolArrayConstant { + val BoolArrayTypeCode = (SCollectionType.CollectionTypeCode + SBoolean.typeCode).toByte + + def apply(value: Coll[Boolean]): CollectionConstant[SBoolean.type] = CollectionConstant[SBoolean.type](value, SBoolean) + + def apply(value: Array[Boolean]): CollectionConstant[SBoolean.type] = apply(value.toColl) + + def unapply(node: SValue): Option[Coll[Boolean]] = node match { + case coll: CollectionConstant[SBoolean.type]@unchecked => coll match { + case CollectionConstant(arr, SBoolean) => Some(arr) + case _ => None + } + case _ => None + } +} + +trait NotReadyValueByteArray extends NotReadyValue[SByteArray] { + override def tpe = SByteArray +} + +trait NotReadyValueAvlTree extends NotReadyValue[SAvlTree.type] { + override def tpe = SAvlTree +} + +/** ErgoTree node that represents the operation of obtaining the generator of elliptic curve group. + * The generator g of the group is an element of the group such that, when written + * multiplicative form, every element of the group is a power of g. + */ +case object GroupGenerator extends EvaluatedValue[SGroupElement.type] with ValueCompanion { + override def opCode: OpCode = OpCodes.GroupGeneratorCode + + override val costKind = FixedCost(JitCost(10)) + + override def tpe = SGroupElement + + override val value = SigmaDsl.GroupElement(CryptoConstants.dlogGroup.generator) + + override def companion = this + + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(costKind) + SigmaDsl.groupGenerator + } +} + +trait NotReadyValueGroupElement extends NotReadyValue[SGroupElement.type] { + override def tpe = SGroupElement +} + +object BooleanConstant { + def fromBoolean(v: Boolean): BooleanConstant = if (v) TrueLeaf else FalseLeaf + + def apply(value: Boolean): BooleanConstant = Constant[SBoolean.type](value, SBoolean) + + def unapply(v: SValue): Option[Boolean] = v match { + case Constant(value: Boolean, SBoolean) => Some(value) + case _ => None + } +} + +/** ErgoTree node which represents `true` literal. */ +object TrueLeaf extends ConstantNode[SBoolean.type](true, SBoolean) with ValueCompanion { + override def companion = this + + override def opCode: OpCode = TrueCode + + override def costKind: FixedCost = Constant.costKind + + override def toString: String = "TrueLeaf" +} + +/** ErgoTree node which represents `false` literal. */ +object FalseLeaf extends ConstantNode[SBoolean.type](false, SBoolean) with ValueCompanion { + override def companion = this + + override def opCode: OpCode = FalseCode + + override def costKind: FixedCost = Constant.costKind + + override def toString: String = "FalseLeaf" +} + +trait NotReadyValueBoolean extends NotReadyValue[SBoolean.type] { + override def tpe = SBoolean +} + +trait NotReadyValueBox extends NotReadyValue[SBox.type] { + def tpe = SBox +} + +/** ErgoTree node which converts a collection of expressions into a tuple of data values + * of different types. Each data value of the resulting collection is obtained by + * evaluating the corresponding expression in `items`. All items may have different + * types. + * + * @param items source collection of expressions + */ +case class Tuple(items: IndexedSeq[Value[SType]]) + extends EvaluatedValue[STuple] // note, this superclass is required as Tuple can be in a register + with EvaluatedCollection[SAny.type, STuple] { + override def companion = Tuple + + override lazy val tpe = STuple(items.map(_.tpe)) + + override def opType: SFunc = ??? + + override def elementType: SAny.type = SAny + + override lazy val value = { + val xs = items.cast[EvaluatedValue[SAny.type]].map(_.value) + implicit val tAny: RType[Any] = sigma.AnyType + Colls.fromArray(xs.toArray) + } + + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + // in v5.0 version we support only tuples of 2 elements to be equivalent with v4.x + if (items.length != 2) + syntax.error(s"Invalid tuple $this") + val item0 = items(0) + val x = item0.evalTo[Any](env) + Value.checkType(item0, x) + val item1 = items(1) + val y = item1.evalTo[Any](env) + Value.checkType(item1, y) + val res = (x, y) // special representation for pairs (to pass directly to Coll primitives) + addCost(Tuple.costKind) + res + } +} + +object Tuple extends FixedCostValueCompanion { + override def opCode: OpCode = TupleCode + + /** Cost of: 1) allocating a new tuple (of limited max size) */ + override val costKind = FixedCost(JitCost(15)) + + def apply(items: Value[SType]*): Tuple = Tuple(items.toIndexedSeq) +} + +/** ErgoTree node which converts a collection of expressions into a collection of data + * values. Each data value of the resulting collection is obtained by evaluating the + * corresponding expression in `items`. All items must have the same type. + * + * @param items source collection of expressions + * @param elementType type descriptor of elements in the resulting collection + */ +case class ConcreteCollection[V <: SType](items: Seq[Value[V]], elementType: V) + extends EvaluatedCollection[V, SCollection[V]] { + // TODO uncomment and make sure Ergo works with it, i.e. complex data types are never used for `items`. + // There is nothing wrong in using List, Vector and other fancy types as a concrete representation + // of `items`, but these types have sub-optimal performance (2-3x overhead comparing to WrappedArray) + // which is immediately visible in profile. + // NOTE, the assert below should be commented before production release. + // Is it there for debuging only, basically to catch call stacks where the fancy types may + // occasionally be used. + // assert( + // items.isInstanceOf[mutable.WrappedArray[_]] || + // items.isInstanceOf[ArrayBuffer[_]] || + // items.isInstanceOf[mutable.ArraySeq[_]], + // s"Invalid types of items ${items.getClass}") + + private val isBooleanConstants = elementType == SBoolean && items.forall(_.isInstanceOf[Constant[_]]) + + override def companion = + if (isBooleanConstants) ConcreteCollectionBooleanConstant + else ConcreteCollection + + val tpe = SCollection[V](elementType) + + implicit lazy val tElement: RType[V#WrappedType] = Evaluation.stypeToRType(elementType) + + // TODO refactor: this method is not used and can be removed + lazy val value = { + val xs = items.cast[EvaluatedValue[V]].map(_.value) + Colls.fromArray(xs.toArray(tElement.classTag)) + } + + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + val len = items.length + addCost(ConcreteCollection.costKind) + val is = Array.ofDim[V#WrappedType](len)(tElement.classTag) + cfor(0)(_ < len, _ + 1) { i => + val item = items(i) + val itemV = item.evalTo[V#WrappedType](env) + Value.checkType(item, itemV) // necessary because cast to V#WrappedType is erased + is(i) = itemV + } + Colls.fromArray(is) + } +} + +object ConcreteCollection extends FixedCostValueCompanion { + override def opCode: OpCode = ConcreteCollectionCode + + /** Cost of: allocating new collection + * + * @see ConcreteCollection_PerItem */ + override val costKind = FixedCost(JitCost(20)) + + def fromSeq[V <: SType](items: Seq[Value[V]])(implicit tV: V): ConcreteCollection[V] = + ConcreteCollection(items, tV) + + def fromItems[V <: SType](items: Value[V]*)(implicit tV: V): ConcreteCollection[V] = + ConcreteCollection(items, tV) +} + +object ConcreteCollectionBooleanConstant extends ValueCompanion { + override def opCode: OpCode = ConcreteCollectionBooleanConstantCode + + override def costKind = ConcreteCollection.costKind +} + +trait LazyCollection[V <: SType] extends NotReadyValue[SCollection[V]] + +sealed trait BlockItem extends NotReadyValue[SType] { + def id: Int + + def rhs: SValue + + def isValDef: Boolean +} + +object BlockItem { + /** Immutable empty array, can be used to save allocations in many places. */ + val EmptyArray = Array.empty[BlockItem] + + /** Immutable empty IndexedSeq to save allocations in many places. */ + val EmptySeq: IndexedSeq[BlockItem] = EmptyArray +} + +/** IR node for let-bound expressions `let x = rhs` which is ValDef, or `let f[T] = rhs` which is FunDef. + * These nodes are used to represent ErgoTrees after common sub-expression elimination. + * This representation is more compact in serialized form. + * + * @param id unique identifier of the variable in the current scope. */ +case class ValDef( + override val id: Int, + tpeArgs: Seq[STypeVar], + override val rhs: SValue) extends BlockItem { + require(id >= 0, "id must be >= 0") + + override def companion = if (tpeArgs.isEmpty) ValDef else FunDef + + override def tpe: SType = rhs.tpe + + override def isValDef: Boolean = tpeArgs.isEmpty + + /** This is not used as operation, but rather to form a program structure */ + override def opType: SFunc = Value.notSupportedError(this, "opType") +} + +object ValDef extends ValueCompanion { + override def opCode: OpCode = ValDefCode + + override def costKind = Value.notSupportedError(this, "costKind") + + def apply(id: Int, rhs: SValue): ValDef = ValDef(id, Nil, rhs) +} + +object FunDef extends ValueCompanion { + override def opCode: OpCode = FunDefCode + + override def costKind = Value.notSupportedError(this, "costKind") + + def unapply(d: BlockItem): Option[(Int, Seq[STypeVar], SValue)] = d match { + case ValDef(id, targs, rhs) if !d.isValDef => Some((id, targs, rhs)) + case _ => None + } +} + +/** Special node which represents a reference to ValDef it was introduced as result of + * CSE. */ +case class ValUse[T <: SType](valId: Int, tpe: T) extends NotReadyValue[T] { + override def companion = ValUse + + /** This is not used as operation, but rather to form a program structure */ + def opType: SFunc = Value.notSupportedError(this, "opType") + + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(ValUse.costKind) + val res = env.getOrElse(valId, syntax.error(s"cannot resolve $this")) + Value.checkType(this, res) + res + } +} + +object ValUse extends FixedCostValueCompanion { + override def opCode: OpCode = ValUseCode + + /** Cost of: 1) Lookup in immutable HashMap by valId: Int 2) alloc of Some(v) */ + override val costKind = FixedCost(JitCost(5)) +} + +/** The order of ValDefs in the block is used to assign ids to ValUse(id) nodes + * For all i: items(i).id == {number of ValDefs preceded in a graph} with respect to topological order. + * Specific topological order doesn't really matter, what is important is to preserve semantic linkage + * between ValUse(id) and ValDef with the corresponding id. + * This convention allow to valid serializing ids because we always serializing and deserializing + * in a fixed well defined order. + */ +case class BlockValue( + items: IndexedSeq[BlockItem], + result: SValue) extends NotReadyValue[SType] { + override def companion = BlockValue + + def tpe: SType = result.tpe + + /** This is not used as operation, but rather to form a program structure */ + def opType: SFunc = Value.notSupportedError(this, "opType") + + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + var curEnv = env + val len = items.length + addSeqCostNoOp(BlockValue.costKind, len) + cfor(0)(_ < len, _ + 1) { i => + val vd = items(i).asInstanceOf[ValDef] + val v = vd.rhs.evalTo[Any](curEnv) + Value.checkType(vd, v) + E.addFixedCost(FuncValue.AddToEnvironmentDesc_CostKind, + FuncValue.AddToEnvironmentDesc) { + curEnv = curEnv + (vd.id -> v) + } + } + val res = result.evalTo[Any](curEnv) + Value.checkType(result, res) + res + } +} + +object BlockValue extends ValueCompanion { + override def opCode: OpCode = BlockValueCode + + override val costKind = PerItemCost( + baseCost = JitCost(1), perChunkCost = JitCost(1), chunkSize = 10) +} + +/** + * @param args parameters list, where each parameter has an id and a type. + * @param body expression, which refers function parameters with ValUse. + */ +case class FuncValue( + args: IndexedSeq[(Int, SType)], + body: Value[SType]) extends NotReadyValue[SFunc] { + import FuncValue._ + + override def companion = FuncValue + + lazy val tpe: SFunc = { + val nArgs = args.length + val argTypes = new Array[SType](nArgs) + cfor(0)(_ < nArgs, _ + 1) { i => + argTypes(i) = args(i)._2 + } + SFunc(argTypes, body.tpe) + } + + /** This is not used as operation, but rather to form a program structure */ + override def opType: SFunc = SFunc(ArraySeq.empty, tpe) + + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(FuncValue.costKind) + if (args.length == 1) { + val arg0 = args(0) + (vArg: Any) => { + Value.checkType(arg0._2, vArg) + var env1: DataEnv = null + E.addFixedCost(AddToEnvironmentDesc_CostKind, AddToEnvironmentDesc) { + env1 = env + (arg0._1 -> vArg) + } + val res = body.evalTo[Any](env1) + Value.checkType(body, res) + res + } + } else { + syntax.error(s"Function must have 1 argument, but was: $this") + } + } +} + +object FuncValue extends FixedCostValueCompanion { + val AddToEnvironmentDesc = NamedDesc("AddToEnvironment") + + /** Cost of: adding value to evaluator environment */ + val AddToEnvironmentDesc_CostKind = FixedCost(JitCost(5)) + + override def opCode: OpCode = FuncValueCode + + /** Cost of: 1) switch on the number of args 2) allocating a new Scala closure + * Old cost: ("Lambda", "() => (D1) => R", lambdaCost), */ + override val costKind = FixedCost(JitCost(5)) + + def apply(argId: Int, tArg: SType, body: SValue): FuncValue = + FuncValue(IndexedSeq((argId, tArg)), body) +} + +/** Frontend representation of a block of Val definitions. + * { val x = ...; val y = ... } + * This node is not part of ErgoTree and hence have Undefined opCode. */ +case class Block(bindings: Seq[Val], result: SValue) extends Value[SType] { + override def companion = Block + + override def tpe: SType = result.tpe + + /** This is not used as operation, but rather to form a program structure */ + override def opType: SFunc = Value.notSupportedError(this, "opType") +} + +object Block extends ValueCompanion { + override def opCode: OpCode = OpCodes.Undefined + + override def costKind: CostKind = Value.notSupportedError(this, "costKind") + + /** Create a Block node with a single Val definition. */ + def apply(let: Val, result: SValue)(implicit @unused o1: Overloaded1): Block = + Block(Seq(let), result) +} + +/** IR node to represent explicit Zero Knowledge scope in ErgoTree. + * Compiler checks Zero Knowledge properties and issue error message is case of violations. + * ZK-scoping is optional, it can be used when the user want to ensure Zero Knowledge of + * specific set of operations. + * Usually it will require simple restructuring of the code to make the scope body explicit. + * Invariants checked by the compiler: + * - single ZKProof in ErgoTree in a root position + * - no boolean operations in the body, because otherwise the result may be disclosed + * - all the operations are over SigmaProp values + * + * For motivation and details see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/236 + * */ +case class ZKProofBlock(body: SigmaPropValue) extends BoolValue { + override def companion = ZKProofBlock + + override def tpe = SBoolean + + override def opType: SFunc = ZKProofBlock.OpType +} + +object ZKProofBlock extends ValueCompanion { + override def opCode: OpCode = OpCodes.Undefined + + override def costKind: CostKind = Value.notSupportedError(this, "costKind") + + val OpType = SFunc(SSigmaProp, SBoolean) +} + +trait Val extends Value[SType] { + val name : String + val givenType: SType + val body : SValue +} + +object Val { + def apply(name: String, body: SValue): Val = ValNode(name, NoType, body) + + def apply( + name: String, + givenType: SType, + body: SValue): Val = ValNode(name, givenType, body) + + def unapply(v: SValue): Option[(String, SType, SValue)] = v match { + case ValNode(name, givenType, body) => Some((name, givenType, body)) + case _ => None + } +} + +case class ValNode( + name: String, + givenType: SType, + body: SValue) extends Val { + override def companion = ValNode + + override def tpe: SType = givenType ?: body.tpe + + /** This is not used as operation, but rather to form a program structure */ + override def opType: SFunc = Value.notSupportedError(this, "opType") +} + +object ValNode extends ValueCompanion { + override def opCode: OpCode = OpCodes.Undefined + + override def costKind: CostKind = Value.notSupportedError(this, "costKind") +} + +/** Frontend node to select a field from an object. Should be transformed to SelectField */ +case class Select( + obj: Value[SType], + field: String, + resType: Option[SType] = None) extends Value[SType] { + override def companion = Select + + override val tpe: SType = resType.getOrElse(obj.tpe match { + case p: SProduct => + MethodsContainer.getMethod(p, field) match { + case Some(m) => m.stype + case None => NoType + } + case _ => NoType + }) + + override def opType: SFunc = SFunc(obj.tpe, tpe) +} + +object Select extends ValueCompanion { + override def opCode: OpCode = OpCodes.Undefined + + override def costKind: CostKind = Value.notSupportedError(this, "costKind") +} + +/** Frontend node to represent variable names parsed in a source code. + * Should be resolved during compilation to lambda argument, Val definition or + * compilation environment value. */ +case class Ident(name: String, tpe: SType = NoType) extends Value[SType] { + override def companion = Ident + + override def opType: SFunc = SFunc(ArraySeq.empty, tpe) +} + +object Ident extends ValueCompanion { + override def opCode: OpCode = OpCodes.Undefined + + override def costKind: CostKind = Value.notSupportedError(this, "costKind") + + def apply(name: String): Ident = Ident(name, NoType) +} + +// TODO refactor: move to sigma.ast + +/** ErgoTree node which represents application of function `func` to the given arguments. + * + * @param func expression which evaluates to a function + * @param args arguments of the function application + */ +case class Apply( + func: Value[SType], + args: IndexedSeq[Value[SType]]) extends Value[SType] { + override def companion = Apply + + override lazy val tpe : SType = func.tpe match { + case SFunc(_, r, _) => r + case tColl: SCollectionType[_] => tColl.elemType + case _ => NoType + } + + override lazy val opType: SFunc = { + val nArgs = args.length + val argTypes = new Array[SType](nArgs + 1) + argTypes(0) = func.tpe + cfor(0)(_ < nArgs, _ + 1) { i => + argTypes(i + 1) = args(i).tpe + } + SFunc(argTypes, tpe) + } + + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(Apply.costKind) + if (args.length == 1) { + val fV = func.evalTo[Any => Any](env) + val argV = args(0).evalTo[Any](env) + fV(argV) + } else { + // zero or more than 1 argument functions are not supported in v4.x, v5.0 + // see `case Terms.Apply(f, Seq(x))` in RuntimeCosting which means other cases are not supported. + syntax.error(s"Function application must have 1 argument, but was: $this") + } + } +} + +object Apply extends FixedCostValueCompanion { + override def opCode: OpCode = OpCodes.FuncApplyCode + + /** Cost of: 1) switch on the number of args 2) Scala method call 3) add args to env + * Old cost: lambdaInvoke == 30 */ + override val costKind = FixedCost(JitCost(30)) +} + +/** Apply types for type parameters of input value. */ +case class ApplyTypes( + input: Value[SType], + tpeArgs: Seq[SType]) extends Value[SType] { node => + override def companion = ApplyTypes + + override lazy val tpe: SType = input.tpe match { + case funcType: SFunc => + val subst = funcType.tpeParams.map(_.ident).zip(tpeArgs).toMap + applySubst(input.tpe, subst) + case _ => input.tpe + } + + /** This is not used as operation, but rather to form a program structure */ + override def opType: SFunc = Value.notSupportedError(this, "opType") +} + +object ApplyTypes extends ValueCompanion { + override def opCode: OpCode = OpCodes.Undefined + + override def costKind: CostKind = Value.notSupportedError(this, "costKind") +} + +/** Frontend node to represent potential method call in a source code. + * Should be resolved during compilation to MethodCall. + * Cannot be serialized to ErgoTree. */ +case class MethodCallLike( + obj: Value[SType], + name: String, + args: IndexedSeq[Value[SType]], + tpe: SType = NoType) extends Value[SType] { + override def companion = MethodCallLike + + override def opType: SFunc = SFunc(obj.tpe +: args.map(_.tpe), tpe) +} + +object MethodCallLike extends ValueCompanion { + override def opCode: OpCode = OpCodes.Undefined + + override def costKind: CostKind = Value.notSupportedError(this, "costKind") +} + +/** Represents in ErgoTree an invocation of method of the object `obj` with arguments `args`. + * The SMethod instances in STypeCompanions may have type STypeIdent in methods types, + * but valid ErgoTree should have SMethod instances specialized for specific types of + * obj and args using `specializeFor`. + * This means, if we save typeId, methodId, and we save all the arguments, + * we can restore the specialized SMethod instance. + * This work by induction, if we assume all arguments are monomorphic, + * then we can make MethodCall monomorphic. + * Thus, all ErgoTree instances are monomorphic by construction. + * + * @param obj object on which method will be invoked + * @param method method to be invoked + * @param args arguments passed to the method on invocation + * @param typeSubst a map of concrete type for each generic type parameter + */ +case class MethodCall( + obj: Value[SType], + method: SMethod, + args: IndexedSeq[Value[SType]], + typeSubst: Map[STypeVar, SType]) extends Value[SType] { + override def companion = if (args.isEmpty) PropertyCall else MethodCall + + override def opType: SFunc = SFunc(obj.tpe +: args.map(_.tpe), tpe) + + override val tpe: SType = method.stype match { + case f: SFunc => f.tRange.withSubstTypes(typeSubst) + case t => t.withSubstTypes(typeSubst) + } + + /** @hotspot don't beautify this code */ + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + val objV = obj.evalTo[Any](env) + addCost(MethodCall.costKind) // MethodCall overhead + method.costKind match { + case fixed: FixedCost => + val extra = method.extraDescriptors + val extraLen = extra.length + val len = args.length + val argsBuf = new Array[Any](len + extraLen) + cfor(0)(_ < len, _ + 1) { i => + argsBuf(i) = args(i).evalTo[Any](env) + } + cfor(0)(_ < extraLen, _ + 1) { i => + argsBuf(len + i) = extra(i) + } + var res: Any = null + E.addFixedCost(fixed, method.opDesc) { + res = method.invokeFixed(objV, argsBuf) + } + res + case _ => + val len = args.length + val argsBuf = new Array[Any](len + 3) + argsBuf(0) = this + argsBuf(1) = objV + cfor(0)(_ < len, _ + 1) { i => + argsBuf(i + 2) = args(i).evalTo[Any](env) + } + argsBuf(argsBuf.length - 1) = E + val evalMethod = method.genericMethod.evalMethod + evalMethod.invoke(method.objType, argsBuf.asInstanceOf[Array[AnyRef]]: _*) + } + } +} + +object MethodCall extends FixedCostValueCompanion { + override def opCode: OpCode = OpCodes.MethodCallCode + + /** Cost of: 1) packing args into Array 2) RMethod.invoke */ + override val costKind = FixedCost(JitCost(4)) + + /** Helper constructor which allows to cast the resulting node to the specified + * [[sigma.ast.Value]] type `T`. + * + * @see [[sigmastate.lang.Terms.MethodCall]] + */ + def typed[T <: SValue]( + obj: Value[SType], + method: SMethod, + args: IndexedSeq[Value[SType]], + typeSubst: Map[STypeVar, SType]): T = { + MethodCall(obj, method, args, typeSubst).asInstanceOf[T] + } +} + +object PropertyCall extends FixedCostValueCompanion { + override def opCode: OpCode = OpCodes.PropertyCallCode + + /** Cost of: 1) packing args into Array 2) RMethod.invoke */ + override val costKind = FixedCost(JitCost(4)) +} + +/** Frontend implementation of lambdas. Should be transformed to FuncValue. */ +case class Lambda( + tpeParams: Seq[STypeParam], + args: IndexedSeq[(String, SType)], + givenResType: SType, + body: Option[Value[SType]]) extends Value[SFunc] { + require(!(tpeParams.nonEmpty && body.nonEmpty), s"Generic function definitions are not supported, but found $this") + + override def companion = Lambda + + override lazy val tpe: SFunc = { + val sRange = givenResType ?: body.fold(NoType: SType)(_.tpe) + SFunc(args.map(_._2), sRange, tpeParams) + } + + /** This is not used as operation, but rather to form a program structure */ + override def opType: SFunc = SFunc(Vector(), tpe) +} + +object Lambda extends ValueCompanion { + override def opCode: OpCode = OpCodes.Undefined + + override def costKind: CostKind = Value.notSupportedError(this, "costKind") + + def apply( + args: IndexedSeq[(String, SType)], + resTpe: SType, + body: Value[SType]): Lambda = + Lambda(Nil, args, resTpe, Some(body)) + + def apply( + args: IndexedSeq[(String, SType)], + resTpe: SType, + body: Option[Value[SType]]): Lambda = + Lambda(Nil, args, resTpe, body) + + def apply( + args: IndexedSeq[(String, SType)], + body: Value[SType]): Lambda = Lambda(Nil, args, NoType, Some(body)) +} + +/** When interpreted evaluates to a ByteArrayConstant built from Context.minerPubkey */ +case object MinerPubkey extends NotReadyValueByteArray with ValueCompanion { + override def opCode: OpCode = OpCodes.MinerPubkeyCode + /** Cost of calling Context.minerPubkey Scala method. */ + override val costKind = FixedCost(JitCost(20)) + override val opType = SFunc(SContext, SCollection.SByteArray) + override def companion = this + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(this.costKind) + E.context.minerPubKey + } +} + +/** When interpreted evaluates to a IntConstant built from Context.currentHeight */ +case object Height extends NotReadyValueInt with FixedCostValueCompanion { + override def companion = this + override def opCode: OpCode = OpCodes.HeightCode + /** Cost of: 1) Calling Context.HEIGHT Scala method. */ + override val costKind = FixedCost(JitCost(26)) + override val opType = SFunc(SContext, SInt) + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(this.costKind) + E.context.HEIGHT + } +} + +/** When interpreted evaluates to a collection of BoxConstant built from Context.boxesToSpend */ +case object Inputs extends LazyCollection[SBox.type] with FixedCostValueCompanion { + override def companion = this + override def opCode: OpCode = OpCodes.InputsCode + /** Cost of: 1) Calling Context.INPUTS Scala method. */ + override val costKind = FixedCost(JitCost(10)) + override def tpe = SCollection.SBoxArray + override val opType = SFunc(SContext, tpe) + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(this.costKind) + E.context.INPUTS + } +} + +/** When interpreted evaluates to a collection of BoxConstant built from Context.spendingTransaction.outputs */ +case object Outputs extends LazyCollection[SBox.type] with FixedCostValueCompanion { + override def companion = this + override def opCode: OpCode = OpCodes.OutputsCode + /** Cost of: 1) Calling Context.OUTPUTS Scala method. */ + override val costKind = FixedCost(JitCost(10)) + override def tpe = SCollection.SBoxArray + override val opType = SFunc(SContext, tpe) + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(this.costKind) + E.context.OUTPUTS + } +} + +/** When interpreted evaluates to a AvlTreeConstant built from Context.lastBlockUtxoRoot */ +case object LastBlockUtxoRootHash extends NotReadyValueAvlTree with ValueCompanion { + override def companion = this + override def opCode: OpCode = OpCodes.LastBlockUtxoRootHashCode + + /** Cost of: 1) Calling Context.LastBlockUtxoRootHash Scala method. */ + override val costKind = FixedCost(JitCost(15)) + + override val opType = SFunc(SContext, tpe) + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(this.costKind) + E.context.LastBlockUtxoRootHash + } +} + +/** When interpreted evaluates to a BoxConstant built from context.boxesToSpend(context.selfIndex) */ +case object Self extends NotReadyValueBox with FixedCostValueCompanion { + override def companion = this + override def opCode: OpCode = OpCodes.SelfCode + /** Cost of: 1) Calling Context.SELF Scala method. */ + override val costKind = FixedCost(JitCost(10)) + override val opType = SFunc(SContext, SBox) + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(this.costKind) + E.context.SELF + } +} + +/** When interpreted evaluates to the singleton instance of [[sigma.Context]]. + * Corresponds to `CONTEXT` variable in ErgoScript which can be used like `CONTEXT.headers`. + */ +case object Context extends NotReadyValue[SContext.type] with ValueCompanion { + override def companion = this + override def opCode: OpCode = OpCodes.ContextCode + + /** Cost of: 1) accessing global Context instance. */ + override val costKind = FixedCost(JitCost(1)) + + override def tpe: SContext.type = SContext + override val opType: SFunc = SFunc(SUnit, SContext) + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(this.costKind) + E.context + } +} + +/** When interpreted evaluates to the singleton instance of [[sigma.SigmaDslBuilder]]. + * Corresponds to `Global` variable in ErgoScript which can be used like `Global.groupGenerator`. + */ +case object Global extends NotReadyValue[SGlobal.type] with FixedCostValueCompanion { + override def companion = this + override def opCode: OpCode = OpCodes.GlobalCode + /** Cost of: 1) accessing Global instance. */ + override val costKind = FixedCost(JitCost(5)) + override def tpe: SGlobal.type = SGlobal + override val opType: SFunc = SFunc(SUnit, SGlobal) + protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { + addCost(this.costKind) + CSigmaDslBuilder + } +} + + diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/BcDlogGroup.scala b/data/shared/src/main/scala/sigma/crypto/BcDlogGroup.scala similarity index 98% rename from interpreter/shared/src/main/scala/sigmastate/crypto/BcDlogGroup.scala rename to data/shared/src/main/scala/sigma/crypto/BcDlogGroup.scala index afe7e95c49..721cd74f5e 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/BcDlogGroup.scala +++ b/data/shared/src/main/scala/sigma/crypto/BcDlogGroup.scala @@ -1,10 +1,7 @@ -package sigmastate.crypto +package sigma.crypto -import java.math.BigInteger -import sigmastate.crypto.BigIntegers import debox.cfor -import sigma.crypto.{CryptoContext, CryptoFacade} - +import java.math.BigInteger import scala.collection.mutable diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/BigIntegers.scala b/data/shared/src/main/scala/sigma/crypto/BigIntegers.scala similarity index 98% rename from interpreter/shared/src/main/scala/sigmastate/crypto/BigIntegers.scala rename to data/shared/src/main/scala/sigma/crypto/BigIntegers.scala index f3fa71a418..4465184580 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/BigIntegers.scala +++ b/data/shared/src/main/scala/sigma/crypto/BigIntegers.scala @@ -1,7 +1,6 @@ -package sigmastate.crypto +package sigma.crypto import java.math.BigInteger -import sigma.crypto.SecureRandom /** Re-implementation in Scala of select set of utility methods from * org.bouncycastle.util.BigIntegers. diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/CryptoConstants.scala b/data/shared/src/main/scala/sigma/crypto/CryptoConstants.scala similarity index 96% rename from interpreter/shared/src/main/scala/sigmastate/crypto/CryptoConstants.scala rename to data/shared/src/main/scala/sigma/crypto/CryptoConstants.scala index dd348a1903..682ef83076 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/CryptoConstants.scala +++ b/data/shared/src/main/scala/sigma/crypto/CryptoConstants.scala @@ -1,6 +1,4 @@ -package sigmastate.crypto - -import sigma.crypto.Ecp +package sigma.crypto import java.math.BigInteger diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/DlogGroup.scala b/data/shared/src/main/scala/sigma/crypto/DlogGroup.scala similarity index 98% rename from interpreter/shared/src/main/scala/sigmastate/crypto/DlogGroup.scala rename to data/shared/src/main/scala/sigma/crypto/DlogGroup.scala index ef0d6941fa..5c8c94ddd2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/DlogGroup.scala +++ b/data/shared/src/main/scala/sigma/crypto/DlogGroup.scala @@ -1,6 +1,4 @@ -package sigmastate.crypto - -import sigma.crypto.{CryptoFacade, Ecp, SecureRandom} +package sigma.crypto import java.math.BigInteger diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/BigIntegerOps.scala b/data/shared/src/main/scala/sigma/data/BigIntegerOps.scala similarity index 97% rename from interpreter/shared/src/main/scala/sigmastate/eval/BigIntegerOps.scala rename to data/shared/src/main/scala/sigma/data/BigIntegerOps.scala index 55d0d0e8f7..168b2f8266 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/BigIntegerOps.scala +++ b/data/shared/src/main/scala/sigma/data/BigIntegerOps.scala @@ -1,10 +1,9 @@ -package sigmastate.eval +package sigma.data -import sigma.data.{CBigInt, ExactIntegral, ExactOrderingImpl} +import sigma._ +import sigma.eval.Extensions.IntExt import scala.math.{Integral, Ordering} -import sigma._ -import sigmastate.eval.Extensions._ object OrderingOps { def apply[T](implicit ord: Ordering[T]) = ord diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/CBox.scala b/data/shared/src/main/scala/sigma/data/CBox.scala similarity index 92% rename from interpreter/shared/src/main/scala/sigmastate/eval/CBox.scala rename to data/shared/src/main/scala/sigma/data/CBox.scala index e544faea31..9d350c5c6b 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/CBox.scala +++ b/data/shared/src/main/scala/sigma/data/CBox.scala @@ -1,15 +1,15 @@ -package sigmastate.eval +package sigma.data import org.ergoplatform.ErgoBox import scorex.utils.Ints import sigma.Evaluation.stypeToRType import sigma.ast.SCollection.SByteArray -import sigma.ast.{SInt, STuple, SType} -import sigma.data.{CAnyValue, RType, WrapperOf} +import sigma.ast.syntax._ +import sigma.ast.{ConstantNode, EvaluatedValue, SInt, STuple, SType} +import sigma.data.CBox.regs +import sigma.eval.Extensions.toAnyValue +import sigma.exceptions.InvalidType import sigma.{AnyValue, Box, Coll, Colls} -import sigmastate.Values.{ConstantNode, EvaluatedValue, SValue} -import sigmastate.eval.CBox.regs -import sigmastate.eval.Extensions.toAnyValue import java.util.Arrays diff --git a/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala b/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala new file mode 100644 index 0000000000..3938feacd3 --- /dev/null +++ b/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala @@ -0,0 +1,206 @@ +package sigma.data + +import debox.cfor +import org.ergoplatform.ErgoBox +import org.ergoplatform.validation.ValidationRules +import scorex.crypto.hash.{Blake2b256, Sha256} +import scorex.utils.Longs +import sigma.ast.{AtLeast, SubstConstants} +import sigma.crypto.{CryptoConstants, EcPointType, Ecp} +import sigma.eval.Extensions.EvalCollOps +import sigma.serialization.{GroupElementSerializer, SigmaSerializer} +import sigma.util.Extensions.BigIntegerOps +import sigma.validation.SigmaValidationSettings +import sigma.{AvlTree, BigInt, Box, Coll, CollBuilder, GroupElement, SigmaDslBuilder, SigmaProp, VersionContext} + +import java.math.BigInteger + +/** A default implementation of [[SigmaDslBuilder]] interface. + * + * @see [[SigmaDslBuilder]] for detailed descriptions + */ +class CSigmaDslBuilder extends SigmaDslBuilder { dsl => + implicit val validationSettings: SigmaValidationSettings = ValidationRules.currentSettings + + override val Colls: CollBuilder = sigma.Colls + + override def BigInt(n: BigInteger): BigInt = CBigInt(n) + + override def toBigInteger(n: BigInt): BigInteger = n.asInstanceOf[CBigInt].wrappedValue + + /** Wraps the given elliptic curve point into GroupElement type. */ + def GroupElement(p: Ecp): GroupElement = p match { + case ept: EcPointType => CGroupElement(ept) + case m => sys.error(s"Point of type ${m.getClass} is not supported") + } + + /** Wraps the given sigma proposition into SigmaDsl value of type SigmaProp. */ + def SigmaProp(sigmaTree: SigmaBoolean): SigmaProp = new CSigmaProp(sigmaTree) + + /** Extract `sigma.data.SigmaBoolean` from DSL's `SigmaProp` type. */ + @inline def toSigmaBoolean(p: SigmaProp): SigmaBoolean = p.asInstanceOf[CSigmaProp].sigmaTree + + /** Extract `sigmastate.AvlTreeData` from DSL's `AvlTree` type. */ + def toAvlTreeData(p: AvlTree): AvlTreeData = p.asInstanceOf[CAvlTree].treeData + + /** Extract `sigmastate.crypto.Ecp` from DSL's `GroupElement` type. */ + def toECPoint(ge: GroupElement): Ecp = ge.asInstanceOf[CGroupElement].wrappedValue + + /** Creates a new AvlTree instance with the given parameters. + * + * @see AvlTreeData for details + */ + override def avlTree( + operationFlags: Byte, + digest: Coll[Byte], + keyLength: Int, + valueLengthOpt: Option[Int]): CAvlTree = { + val treeData = AvlTreeData(digest, AvlTreeFlags(operationFlags), keyLength, valueLengthOpt) + CAvlTree(treeData) + } + + /** Wraps the given tree data into SigmaDsl value of type [[AvlTree]]. */ + def avlTree(treeData: AvlTreeData): AvlTree = { + CAvlTree(treeData) + } + + /** Wraps the given [[ErgoBox]] into SigmaDsl value of type [[Box]]. + * + * @param ebox the value to be wrapped + * @see [[sigmastate.SBox]], [[sigma.Box]] + */ + def Box(ebox: ErgoBox): Box = CBox(ebox) + + /** Extracts [[ErgoBox]] from the given [[Box]] instance. This is inverse to the Box method. */ + def toErgoBox(b: Box): ErgoBox = b.asInstanceOf[CBox].ebox + + /** HOTSPOT: don't beautify this code */ + private def toSigmaTrees(props: Array[SigmaProp]): Array[SigmaBoolean] = { + val len = props.length + val res = new Array[SigmaBoolean](len) + cfor(0)(_ < len, _ + 1) { i => + res(i) = toSigmaBoolean(props(i)) + } + res + } + + @inline private def toEcPointType(ge: GroupElement): EcPointType = + toECPoint(ge).asInstanceOf[EcPointType] + + override def atLeast(bound: Int, props: Coll[SigmaProp]): SigmaProp = { + if (props.length > AtLeast.MaxChildrenCount) + throw new IllegalArgumentException(s"Expected input elements count should not exceed ${AtLeast.MaxChildrenCount}, actual: ${props.length}") + val sigmaTrees = toSigmaTrees(props.toArray) + val tree = AtLeast.reduce(bound, sigmaTrees) + CSigmaProp(tree) + } + + override def allOf(conditions: Coll[Boolean]): Boolean = + conditions.forall(c => c) + + override def anyOf(conditions: Coll[Boolean]): Boolean = + conditions.exists(c => c) + + override def xorOf(conditions: Coll[Boolean]): Boolean = { + if (VersionContext.current.isJitActivated) { + val len = conditions.length + if (len == 0) false + else if (len == 1) conditions(0) + else { + var res = conditions(0) + cfor(1)(_ < len, _ + 1) { i => + res ^= conditions(i) + } + res + } + } else { + // This is buggy version used in v4.x interpreter (for ErgoTrees v0, v1) + conditions.toArray.distinct.length == 2 + } + } + + override def allZK(props: Coll[SigmaProp]): SigmaProp = { + val sigmaTrees = toSigmaTrees(props.toArray) + val tree = CAND.normalized(sigmaTrees) + CSigmaProp(tree) + } + + override def anyZK(props: Coll[SigmaProp]): SigmaProp = { + val sigmaTrees = toSigmaTrees(props.toArray) + val tree = COR.normalized(sigmaTrees) + CSigmaProp(tree) + } + + override def xor(l: Coll[Byte], r: Coll[Byte]): Coll[Byte] = + Colls.xor(l, r) + + override def sigmaProp(b: Boolean): SigmaProp = { + CSigmaProp(TrivialProp(b)) + } + + override def blake2b256(bytes: Coll[Byte]): Coll[Byte] = { + val h = Blake2b256.hash(bytes.toArray) + Colls.fromArray(h) + } + + override def sha256(bytes: Coll[Byte]): Coll[Byte] = { + val h = Sha256.hash(bytes.toArray) + Colls.fromArray(h) + } + + override def byteArrayToBigInt(bytes: Coll[Byte]): BigInt = { + val bi = new BigInteger(bytes.toArray).to256BitValueExact + this.BigInt(bi) + } + + override def longToByteArray(l: Long): Coll[Byte] = + Colls.fromArray(Longs.toByteArray(l)) + + override def byteArrayToLong(bytes: Coll[Byte]): Long = + Longs.fromByteArray(bytes.toArray) + + override def proveDlog(ge: GroupElement): SigmaProp = + CSigmaProp(ProveDlog(toECPoint(ge).asInstanceOf[EcPointType])) + + override def proveDHTuple( + g: GroupElement, + h: GroupElement, + u: GroupElement, + v: GroupElement): SigmaProp = { + val dht = ProveDHTuple(toEcPointType(g), toEcPointType(h), toEcPointType(u), toEcPointType(v)) + CSigmaProp(dht) + } + + private lazy val _generatorElement = this.GroupElement(CryptoConstants.dlogGroup.generator) + + override def groupGenerator: GroupElement = _generatorElement + + /** + * @return the identity of the Dlog group used in ErgoTree + */ + def groupIdentity: GroupElement = { + this.GroupElement(CryptoConstants.dlogGroup.identity) + } + + override def substConstants[T]( + scriptBytes: Coll[Byte], + positions: Coll[Int], + newValues: Coll[T]): Coll[Byte] = { + val constants = try newValues.toArrayOfConstants + catch { + case e: Throwable => + throw new RuntimeException(s"Cannot evaluate substConstants($scriptBytes, $positions, $newValues)", e) + } + val (res, _) = SubstConstants.eval(scriptBytes.toArray, positions.toArray, constants)(validationSettings) + Colls.fromArray(res) + } + + override def decodePoint(encoded: Coll[Byte]): GroupElement = { + val r = SigmaSerializer.startReader(encoded.toArray) + val p = GroupElementSerializer.parse(r) + this.GroupElement(p) + } +} + +/** Default singleton instance of Global object, which implements global ErgoTree functions. */ +object CSigmaDslBuilder extends CSigmaDslBuilder \ No newline at end of file diff --git a/interpreter/shared/src/main/scala/sigmastate/DataValueComparer.scala b/data/shared/src/main/scala/sigma/data/DataValueComparer.scala similarity index 98% rename from interpreter/shared/src/main/scala/sigmastate/DataValueComparer.scala rename to data/shared/src/main/scala/sigma/data/DataValueComparer.scala index a8b25b25ec..21ca85012f 100644 --- a/interpreter/shared/src/main/scala/sigmastate/DataValueComparer.scala +++ b/data/shared/src/main/scala/sigma/data/DataValueComparer.scala @@ -1,11 +1,10 @@ -package sigmastate +package sigma.data import debox.{cfor, sp} import sigma._ +import sigma.ast.{FixedCost, JitCost, NamedDesc, OperationCostInfo, PerItemCost} import sigma.crypto.EcPointType -import sigma.data._ -import sigmastate.eval.SigmaDsl -import sigmastate.interpreter.{ErgoTreeEvaluator, NamedDesc, OperationCostInfo} +import sigma.eval.{ErgoTreeEvaluator, SigmaDsl} /** Implementation of data equality for two arbitrary ErgoTree data types. * @see [[DataValueComparer.equalDataValues]] @@ -276,7 +275,7 @@ object DataValueComparer { val sb2 = r.asInstanceOf[CTHRESHOLD] k == sb2.k && equalSigmaBooleans(children, sb2.children) case _ => - ErgoTreeEvaluator.error( + sys.error( s"Cannot compare SigmaBoolean values $l and $r: unknown type") } } @@ -405,7 +404,7 @@ object DataValueComparer { okEqual = r.isInstanceOf[Unit] case _ => - ErgoTreeEvaluator.error(s"Cannot compare $l and $r: unknown type") + sys.error(s"Cannot compare $l and $r: unknown type") } okEqual } diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/ExactIntegral.scala b/data/shared/src/main/scala/sigma/data/ExactIntegral.scala similarity index 100% rename from interpreter/shared/src/main/scala/sigmastate/eval/ExactIntegral.scala rename to data/shared/src/main/scala/sigma/data/ExactIntegral.scala diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/ExactNumeric.scala b/data/shared/src/main/scala/sigma/data/ExactNumeric.scala similarity index 100% rename from interpreter/shared/src/main/scala/sigmastate/eval/ExactNumeric.scala rename to data/shared/src/main/scala/sigma/data/ExactNumeric.scala diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/ExactOrdering.scala b/data/shared/src/main/scala/sigma/data/ExactOrdering.scala similarity index 90% rename from interpreter/shared/src/main/scala/sigmastate/eval/ExactOrdering.scala rename to data/shared/src/main/scala/sigma/data/ExactOrdering.scala index 7c65b53075..a7b002cb80 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/ExactOrdering.scala +++ b/data/shared/src/main/scala/sigma/data/ExactOrdering.scala @@ -1,6 +1,6 @@ package sigma.data -import scala.math.Numeric.{ByteIsIntegral, LongIsIntegral, ShortIsIntegral, IntIsIntegral} +import scala.math.Numeric.{ByteIsIntegral, IntIsIntegral, LongIsIntegral, ShortIsIntegral} /** Ordering operations to be used with other Exact traits. * All methods are implemented by delegating to the corresponding Ordering instance from diff --git a/data/shared/src/main/scala/sigma/eval/AvlTreeVerifier.scala b/data/shared/src/main/scala/sigma/eval/AvlTreeVerifier.scala new file mode 100644 index 0000000000..bc4a625458 --- /dev/null +++ b/data/shared/src/main/scala/sigma/eval/AvlTreeVerifier.scala @@ -0,0 +1,76 @@ +package sigma.eval + +import scala.util.Try + +/** Represents a verifier of authenticated AVL+ tree created from a proof. + * The verifier holds the tree data parsed from the proof. + */ +trait AvlTreeVerifier { + /** Height of the tree. */ + def treeHeight: Int + + /** Looks up a key in the tree. + * If `key` exists in the tree and the operation succeeds, + * returns `Success(Some(v))`, where v is the value associated with `key`. + * If `key` does not exists in the tree and the operation succeeds, returns Success(None). + * Returns Failure if the operation fails or the proof does not verify. + * After one failure, all subsequent operations with this verifier will fail and digest + * is None. + * + * @param key key to look up + * @return Success(Some(value)), Success(None), or Failure + */ + def performLookup(key: Array[Byte]): Try[Option[Array[Byte]]] + + /** Check the key-value pair has been inserted in the tree. + * If `key` exists in the tree and the operation succeeds, + * returns `Success(Some(value))`, where value is associated with `key`. + * If `key` does not exists in the tree and the operation succeeds, returns Success(None). + * Returns Failure if the operation fails or the proof does not verify. + * After one failure, all subsequent operations with this verifier will fail and digest + * is None. + * + * @param key key to look up + * @param value value to check it was inserted + * @return Success(Some(inserted value)), Success(None), or Failure + */ + def performInsert(key: Array[Byte], value: Array[Byte]): Try[Option[Array[Byte]]] + + /** Check the key-value pair has been updated in the tree. + * If `key` exists in the tree and the operation succeeds, + * returns `Success(Some(value))`, where value is associated with `key`. + * If `key` does not exists in the tree and the operation succeeds, returns Success(None). + * Returns Failure if the operation fails or the proof does not verify. + * After one failure, all subsequent operations with this verifier will fail and digest + * is None. + * + * @param key key to look up + * @param value value to check it was updated + * @return Success(Some(value)), Success(None), or Failure + */ + def performUpdate(key: Array[Byte], value: Array[Byte]): Try[Option[Array[Byte]]] + + /** Check the key has been removed in the tree. + * If `key` exists in the tree and the operation succeeds, + * returns `Success(Some(v))`, where v is old value associated with `key`. + * If `key` does not exists in the tree and the operation succeeds, returns Success(None). + * Returns Failure if the operation fails or the proof does not verify. + * After one failure, all subsequent operations with this verifier will fail and digest + * is None. + * + * @param key key to look up + * @return Success(Some(old value)), Success(None), or Failure + */ + def performRemove(key: Array[Byte]): Try[Option[Array[Byte]]] + + /** + * Returns Some(d), where d - the current digest of the authenticated data structure. + * The digest contains the root hash and the root height. + * + * Returns None if the proof verification failed at construction + * or during any of the operations with this verifier. + * + * @return - Some[digest] or None + */ + def digest: Option[Array[Byte]] +} diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/CostDetails.scala b/data/shared/src/main/scala/sigma/eval/CostDetails.scala similarity index 97% rename from interpreter/shared/src/main/scala/sigmastate/interpreter/CostDetails.scala rename to data/shared/src/main/scala/sigma/eval/CostDetails.scala index 6bffb8ff8e..89d522833b 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/CostDetails.scala +++ b/data/shared/src/main/scala/sigma/eval/CostDetails.scala @@ -1,8 +1,7 @@ -package sigmastate.interpreter +package sigma.eval -import sigmastate.JitCost import debox.cfor - +import sigma.ast.{CostItem, JitCost} import scala.collection.compat.immutable.ArraySeq /** Abstract representation of cost results obtained during evaluation. */ diff --git a/data/shared/src/main/scala/sigma/eval/ErgoTreeEvaluator.scala b/data/shared/src/main/scala/sigma/eval/ErgoTreeEvaluator.scala new file mode 100644 index 0000000000..52f839354c --- /dev/null +++ b/data/shared/src/main/scala/sigma/eval/ErgoTreeEvaluator.scala @@ -0,0 +1,146 @@ +package sigma.eval + +import sigma.{AvlTree, Coll, Context} +import sigma.ast.{Constant, FixedCost, MethodCall, OperationCostInfo, OperationDesc, PerItemCost, SType, TypeBasedCost} +import sigma.data.KeyValueColl + +abstract class ErgoTreeEvaluator { + /** Adds the given cost to the `coster`. If tracing is enabled, creates a new cost item + * with the given operation. + * + * @param costKind the cost to be added to `coster` for each item + * @param nItems the number of items + * @param opDesc the operation to associate the cost with (when costTracingEnabled) + * @param block operation executed under the given cost + * @tparam R result type of the operation + * @hotspot don't beautify the code + */ + def addSeqCost[R](costKind: PerItemCost, nItems: Int, opDesc: OperationDesc) + (block: () => R): R + + /** Adds the cost to the `coster`. See the other overload for details. */ + def addSeqCost[R](costInfo: OperationCostInfo[PerItemCost], nItems: Int) + (block: () => R): R + + /** Adds the cost to the `coster`. If tracing is enabled, creates a new cost item with + * the given operation descriptor and cost kind. If time measuring is enabled also + * performs profiling. + * + * WARNING: The cost is accumulated AFTER the block is executed. + * Each usage of this method should be accompanied with a proof of why this cannot lead + * to unbounded execution (see all usages). + * + * @param costKind the cost descriptor to be used to compute the cost based on the + * actual number of items returned by the `block` + * @param opDesc the operation to associate the cost with (when costTracingEnabled) + * @param block operation executed under the given cost descriptors, returns the + * actual number of items processed + * @hotspot don't beautify the code + */ + def addSeqCost(costKind: PerItemCost, opDesc: OperationDesc)(block: () => Int): Unit + + /** Adds the cost to the `coster`. See the other overload for details. */ + def addSeqCost(costInfo: OperationCostInfo[PerItemCost])(block: () => Int): Unit + + /** Adds the given cost to the `coster`. If tracing is enabled, associates the cost with + * the given operation. + * + * @param costKind kind of the cost to be added to `coster` + * @param opDesc operation descriptor to associate the cost with (when costTracingEnabled) + */ + def addCost(costKind: FixedCost, opDesc: OperationDesc): Unit + + def addCost(costInfo: OperationCostInfo[FixedCost]): Unit + + /** Adds the given cost to the `coster`. If tracing is enabled, associates the cost with + * the given operation. + * + * @param costKind kind of the cost to be added to `coster` + * @param opDesc the operation descriptor to associate the cost with (when costTracingEnabled) + * @param block operation executed under the given cost + */ + def addFixedCost(costKind: FixedCost, opDesc: OperationDesc)(block: => Unit): Unit + + def addFixedCost(costInfo: OperationCostInfo[FixedCost])(block: => Unit): Unit + + /** Adds the given cost to the `coster`. If tracing is enabled, creates a new cost item + * with the given operation. + * + * @param costKind the cost to be added to `coster` for each item + * @param nItems the number of items + * @param opDesc the operation to associate the cost with (when costTracingEnabled) + */ + def addSeqCostNoOp(costKind: PerItemCost, nItems: Int, opDesc: OperationDesc): Unit + + /** Add the cost given by the cost descriptor and the type to the accumulator and + * associate it with this operation descriptor. + * + * @param costKind descriptor of the cost + * @param tpe specific type for which the cost should be computed by this descriptor + * (see costFunc method) + * @param opDesc operation which is associated with this cost + */ + def addTypeBasedCost[R]( + costKind: TypeBasedCost, + tpe: SType, opDesc: OperationDesc)(block: () => R): R + + /** Settings to be used during evaluation. */ + def settings: EvalSettings + + /** Performs operations profiling and time measurements (if enabled in settings). */ + def profiler: Profiler + + /** Segregated constants from ErgoTree, to lookup them from + * [[ConstantPlaceholder]] evaluation. + */ + def constants: Seq[Constant[SType]] + + /** Represents blockchain data context for ErgoTree evaluation. */ + def context: Context + + /** Create an instance of [[AvlTreeVerifier]] for the given tree and proof. */ + def createTreeVerifier(tree: AvlTree, proof: Coll[Byte]): AvlTreeVerifier + + /** Implements evaluation of AvlTree.contains method call ErgoTree node. */ + def contains_eval( + mc: MethodCall, + tree: AvlTree, + key: Coll[Byte], + proof: Coll[Byte]): Boolean + + /** Implements evaluation of AvlTree.get method call ErgoTree node. */ + def get_eval( + mc: MethodCall, + tree: AvlTree, + key: Coll[Byte], + proof: Coll[Byte]): Option[Coll[Byte]] + + /** Implements evaluation of AvlTree.getMany method call ErgoTree node. */ + def getMany_eval( + mc: MethodCall, + tree: AvlTree, + keys: Coll[Coll[Byte]], + proof: Coll[Byte]): Coll[Option[Coll[Byte]]] + + /** Implements evaluation of AvlTree.insert method call ErgoTree node. */ + def insert_eval( + mc: MethodCall, + tree: AvlTree, + entries: KeyValueColl, + proof: Coll[Byte]): Option[AvlTree] + + /** Implements evaluation of AvlTree.update method call ErgoTree node. */ + def update_eval( + mc: MethodCall, tree: AvlTree, + operations: KeyValueColl, proof: Coll[Byte]): Option[AvlTree] + + /** Implements evaluation of AvlTree.remove method call ErgoTree node. */ + def remove_eval( + mc: MethodCall, tree: AvlTree, + operations: Coll[Coll[Byte]], proof: Coll[Byte]): Option[AvlTree] +} + +object ErgoTreeEvaluator { + /** Immutable data environment used to assign data values to graph nodes. */ + type DataEnv = Map[Int, Any] +} \ No newline at end of file diff --git a/data/shared/src/main/scala/sigma/eval/EvalSettings.scala b/data/shared/src/main/scala/sigma/eval/EvalSettings.scala new file mode 100644 index 0000000000..6567d0cdec --- /dev/null +++ b/data/shared/src/main/scala/sigma/eval/EvalSettings.scala @@ -0,0 +1,83 @@ +package sigma.eval + +import sigma.eval.EvalSettings.EvaluationMode +import supertagged.TaggedType + +/** Configuration parameters of the evaluation run. */ +case class EvalSettings( + /** Used together with [[ErgoTreeEvaluator.profiler]] to measure individual operations timings. */ + isMeasureOperationTime: Boolean, + + /** Used together with [[ErgoTreeEvaluator.profiler]] to measure script timings. */ + isMeasureScriptTime: Boolean, + + /** Used by [[ErgoTreeEvaluator]] to conditionally perform debug mode operations. */ + isDebug: Boolean = false, + + /** Used by [[ErgoTreeEvaluator]] to conditionally emit log messages. */ + isLogEnabled: Boolean = false, + + /** Used by [[ErgoTreeEvaluator]] to conditionally build a trace of added costs. + * + * @see Value.addCost + */ + costTracingEnabled: Boolean = false, + + /** Profiler which, when defined, should be used in [[ErgoTreeEvaluator]] constructor. */ + profilerOpt: Option[Profiler] = None, + + /** Should be set to true, if evaluation is performed as part of test suite. + * In such a case, additional operations may be performed (such as sanity checks). */ + isTestRun: Boolean = false, + + /** If true, then expected test vectors are pretty-printed. */ + printTestVectors: Boolean = false, + + /** When Some(mode) is specified then it defines which version of the Interpreter.verify + * and Interpreter.prove methods should use. + * The default value is None, which means the version is defined by ErgoTree.version + * and Context.activatedScriptVersion. + */ + evaluationMode: Option[EvaluationMode] = None, + + /** Maximum execution cost of a script used by profiler. + * + * @see ErgoTreeEvaluator + */ + scriptCostLimitInEvaluator: Int = 1000000 +) + +object EvalSettings { + /** Enumeration type of evaluation modes of [[Interpreter]]. + * This type can be removed in v5.x releases together with AOT implementation once v5.0 + * protocol is activated. + */ + object EvaluationMode extends TaggedType[Int] { + implicit class EvaluationModeOps(val x: EvaluationMode) extends AnyVal { + def name: String = x match { + case AotEvaluationMode => "AotEvaluationMode" + case JitEvaluationMode => "JitEvaluationMode" + } + + /** Returns true if AOT interpreter should be evaluated. */ + def okEvaluateAot: Boolean = { + x == AotEvaluationMode + } + + /** Returns true if JIT interpreter should be evaluated. */ + def okEvaluateJit: Boolean = { + x == JitEvaluationMode + } + } + } + + type EvaluationMode = EvaluationMode.Type + + /** Evaluation mode when the interpreter is executing using AOT costing implementation + * of v4.x protocol. */ + val AotEvaluationMode: EvaluationMode = EvaluationMode @@ 1 // first bit + + /** Evaluation mode when the interpreter is executing using JIT costing implementation + * of v5.x protocol. */ + val JitEvaluationMode: EvaluationMode = EvaluationMode @@ 2 // second bit +} \ No newline at end of file diff --git a/data/shared/src/main/scala/sigma/eval/Extensions.scala b/data/shared/src/main/scala/sigma/eval/Extensions.scala new file mode 100644 index 0000000000..def9086e02 --- /dev/null +++ b/data/shared/src/main/scala/sigma/eval/Extensions.scala @@ -0,0 +1,75 @@ +package sigma.eval + +import sigma.ast.syntax.SigmaPropValue +import sigma.data.{CAnyValue, CSigmaDslBuilder, Nullable, RType, SigmaBoolean} +import sigma.{BigInt, Coll, Colls, Evaluation, Platform} +import sigma.ast.{Constant, ConstantNode, SBoolean, SCollection, SCollectionType, SType, SigmaPropConstant, SigmaPropIsProven, TransformingSigmaBuilder, Value} + +import java.math.BigInteger + +object Extensions { + implicit class ByteExt(val b: Byte) extends AnyVal { + @inline def toBigInt: BigInt = CSigmaDslBuilder.BigInt(BigInteger.valueOf(b.toLong)) + } + + implicit class ShortExt(val b: Short) extends AnyVal { + @inline def toBigInt: BigInt = CSigmaDslBuilder.BigInt(BigInteger.valueOf(b.toLong)) + } + + implicit class IntExt(val x: Int) extends AnyVal { + /** Convert this value to BigInt. */ + @inline def toBigInt: BigInt = CSigmaDslBuilder.BigInt(BigInteger.valueOf(x.toLong)) + } + + implicit class LongExt(val x: Long) extends AnyVal { + /** Convert this value to BigInt. */ + @inline def toBigInt: BigInt = CSigmaDslBuilder.BigInt(BigInteger.valueOf(x)) + } + + def toAnyValue[A: RType](x: A) = new CAnyValue(x, RType[A].asInstanceOf[RType[Any]]) + + implicit class EvalCollOps[T](val coll: Coll[T]) extends AnyVal { + /** Helper type synonym. */ + type ElemTpe = SType {type WrappedType = T} + + /** Wraps the collection into ConstantNode using collection's element type. */ + def toConstant: Constant[SCollection[ElemTpe]] = { + val elemTpe = Evaluation.rtypeToSType(coll.tItem).asInstanceOf[ElemTpe] + ConstantNode[SCollection[ElemTpe]](coll, SCollectionType(elemTpe)) + } + + /** Transforms this collection into array of constants. + * + * This method have exactly the same semantics on JS and JVM IF `coll.tItem` + * precisely describes the type of elements in `call`. (Which is the case for all + * collections created by ErgoTree interpreter). + * + * However, if it is not the case, then JVM and JS will have different semantics for Byte and Short. + * + * The JVM version preserves v5.0 consensus protocol semantics. + * The JS version is a reasonable approximation of the JVM version. + */ + def toArrayOfConstants: Array[Constant[SType]] = { + val constants = coll.toArray.map { v => + // see ScalaDoc for ensureTypeCarringValue + val valToLift = ensureTypeCarringValue(v, coll.tItem.asInstanceOf[RType[Any]]) + // call platform-specific method to transform the value to a Constant + Platform.liftToConstant(valToLift, TransformingSigmaBuilder) match { + case Nullable(c) => c + case _ => sys.error(s"Cannot liftToConstant($valToLift)") + } + } + constants + } + } + + implicit class SigmaBooleanOps(val sb: SigmaBoolean) extends AnyVal { + def toSigmaPropValue: SigmaPropValue = SigmaPropConstant(sb) + + def isProven: Value[SBoolean.type] = SigmaPropIsProven(SigmaPropConstant(sb)) + } + + implicit class EvalIterableOps[T: RType](seq: Iterable[T]) { + @inline def toColl: Coll[T] = Colls.fromArray[T](seq.toArray(RType[T].classTag)) + } +} diff --git a/data/shared/src/main/scala/sigma/eval/Profiler.scala b/data/shared/src/main/scala/sigma/eval/Profiler.scala new file mode 100644 index 0000000000..ac4c7a299d --- /dev/null +++ b/data/shared/src/main/scala/sigma/eval/Profiler.scala @@ -0,0 +1,28 @@ +package sigma.eval + +import sigma.ast.{CostItem, JitCost} +import sigma.ast.syntax.SValue + +abstract class Profiler { + /** Called from evaluator immediately before the evaluator start recursive evaluation of + * the given node. + */ + def onBeforeNode(node: SValue): Unit + + /** Called from evaluator immediately after the evaluator finishes recursive evaluation + * of the given node. + */ + def onAfterNode(node: SValue): Unit + + /** Add new measurement point to the stats of this profiler. + * + * @param costItem executed cost item + * @param time time spent to execute this cost item + */ + def addCostItem(costItem: CostItem, time: Long): Unit + + /** Adds estimated cost and actual measured time data point to the StatCollection for + * the given script. + */ + def addJitEstimation(script: String, cost: JitCost, actualTimeNano: Long): Unit +} diff --git a/data/shared/src/main/scala/sigma/eval/package.scala b/data/shared/src/main/scala/sigma/eval/package.scala new file mode 100644 index 0000000000..d2c6415fde --- /dev/null +++ b/data/shared/src/main/scala/sigma/eval/package.scala @@ -0,0 +1,30 @@ +package sigma + +import sigma.data.{CAnyValue, CSigmaDslBuilder, OverloadHack, RType} + +package object eval { + /** The primary reference to Global instance of SigmaDsl. + * Besides operations of SigmaDslBuilder class, this instance also contains methods, + * which are not available in Dsl code, and which are not in SigmaDslBuilder interface. + * For example methods like `Box`, `toErgoBox` are available here, but not available in Dsl. + * + * @see SigmaDslBuilder + */ + val SigmaDsl = CSigmaDslBuilder + + /** Encapsulate platform-specific logic of ensuring the value carries its precise type. + * For JVM this is identity function. + * For JS it can transform to AnyValue, if the type is numeric + */ + def ensureTypeCarringValue(v: Any, tT: RType[Any]): Any = + if (Environment.current.isJVM) v + else { // JS + v match { + case _: Byte | _: Short | _: Int => + // this is necessary for JS where Byte, Short, Int have the same runtime class + // and hence we need to pass the type information explicitly + CAnyValue(v)(tT, OverloadHack.overloaded1) + case _ => v + } + } +} diff --git a/interpreter/shared/src/main/scala/sigmastate/exceptions/CompilerExceptions.scala b/data/shared/src/main/scala/sigma/exceptions/CompilerExceptions.scala similarity index 96% rename from interpreter/shared/src/main/scala/sigmastate/exceptions/CompilerExceptions.scala rename to data/shared/src/main/scala/sigma/exceptions/CompilerExceptions.scala index 3fe149170c..8b650256a9 100644 --- a/interpreter/shared/src/main/scala/sigmastate/exceptions/CompilerExceptions.scala +++ b/data/shared/src/main/scala/sigma/exceptions/CompilerExceptions.scala @@ -1,7 +1,7 @@ -package sigmastate.exceptions +package sigma.exceptions import sigma.SigmaException -import sigmastate.lang.SourceContext +import sigma.ast.SourceContext /** Base class for exceptions thrown by the compiler. * diff --git a/interpreter/shared/src/main/scala/sigmastate/exceptions/ConstraintFailed.scala b/data/shared/src/main/scala/sigma/exceptions/ConstraintFailed.scala similarity index 66% rename from interpreter/shared/src/main/scala/sigmastate/exceptions/ConstraintFailed.scala rename to data/shared/src/main/scala/sigma/exceptions/ConstraintFailed.scala index bddd2a6951..eb77f8c31b 100644 --- a/interpreter/shared/src/main/scala/sigmastate/exceptions/ConstraintFailed.scala +++ b/data/shared/src/main/scala/sigma/exceptions/ConstraintFailed.scala @@ -1,6 +1,6 @@ -package sigmastate.exceptions +package sigma.exceptions -import sigmastate.lang.SourceContext +import sigma.ast.SourceContext final class ConstraintFailed(message: String, source: Option[SourceContext] = None) extends BuilderException(message, source) diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/Exceptions.scala b/data/shared/src/main/scala/sigma/exceptions/Exceptions.scala similarity index 73% rename from interpreter/shared/src/main/scala/sigmastate/eval/Exceptions.scala rename to data/shared/src/main/scala/sigma/exceptions/Exceptions.scala index 2949fb6815..a1584d8d71 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/Exceptions.scala +++ b/data/shared/src/main/scala/sigma/exceptions/Exceptions.scala @@ -1,4 +1,4 @@ -package sigmastate.eval +package sigma.exceptions final class InvalidType(message: String) extends Exception(message) diff --git a/interpreter/shared/src/main/scala/sigmastate/exceptions/InvalidArguments.scala b/data/shared/src/main/scala/sigma/exceptions/InvalidArguments.scala similarity index 65% rename from interpreter/shared/src/main/scala/sigmastate/exceptions/InvalidArguments.scala rename to data/shared/src/main/scala/sigma/exceptions/InvalidArguments.scala index b154fdb6d4..38db5ceeec 100644 --- a/interpreter/shared/src/main/scala/sigmastate/exceptions/InvalidArguments.scala +++ b/data/shared/src/main/scala/sigma/exceptions/InvalidArguments.scala @@ -1,6 +1,6 @@ -package sigmastate.exceptions +package sigma.exceptions -import sigmastate.lang.SourceContext +import sigma.ast.SourceContext final class InvalidArguments(message: String, source: Option[SourceContext] = None) extends BinderException(message, source) diff --git a/interpreter/shared/src/main/scala/sigmastate/exceptions/SigmaExceptions.scala b/data/shared/src/main/scala/sigma/exceptions/SigmaExceptions.scala similarity index 94% rename from interpreter/shared/src/main/scala/sigmastate/exceptions/SigmaExceptions.scala rename to data/shared/src/main/scala/sigma/exceptions/SigmaExceptions.scala index 4183646296..befb497dde 100644 --- a/interpreter/shared/src/main/scala/sigmastate/exceptions/SigmaExceptions.scala +++ b/data/shared/src/main/scala/sigma/exceptions/SigmaExceptions.scala @@ -1,7 +1,7 @@ -package sigmastate.exceptions +package sigma.exceptions import sigma.SigmaException -import sigmastate.JitCost +import sigma.ast.JitCost /** Exception thrown by [[sigmastate.interpreter.Interpreter]]. * diff --git a/data/shared/src/main/scala/sigma/interpreter/ContextExtension.scala b/data/shared/src/main/scala/sigma/interpreter/ContextExtension.scala new file mode 100644 index 0000000000..a721001c10 --- /dev/null +++ b/data/shared/src/main/scala/sigma/interpreter/ContextExtension.scala @@ -0,0 +1,51 @@ +package sigma.interpreter + +import sigma.ast.{EvaluatedValue, SType} +import sigma.interpreter.ContextExtension.VarBinding +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} + +import scala.collection.mutable + +/** + * User-defined variables to be put into context. + * Each variable is identified by `id: Byte` and can be accessed from a script + * using `getVar[T](id)` operation. + * The value of the variable is represented by [[sigma.ast.Constant]] instance, + * which contains both data value and [[SType]] descriptor. The descriptor is checked + * against the type `T` expected in the script operation. If the types don't match, + * exception is thrown and the box spending (protected by the script) fails. + * + * @param values internal container of the key-value pairs + */ +case class ContextExtension(values: scala.collection.Map[Byte, EvaluatedValue[_ <: SType]]) { + def add(bindings: VarBinding*): ContextExtension = + ContextExtension(values ++ bindings) +} + +object ContextExtension { + /** Immutable instance of empty ContextExtension, which can be shared to avoid + * allocations. */ + val empty = ContextExtension(Map()) + + /** Type of context variable binding. */ + type VarBinding = (Byte, EvaluatedValue[_ <: SType]) + + object serializer extends SigmaSerializer[ContextExtension, ContextExtension] { + override def serialize(obj: ContextExtension, w: SigmaByteWriter): Unit = { + val size = obj.values.size + if (size > Byte.MaxValue) + error(s"Number of ContextExtension values $size exceeds ${Byte.MaxValue}.") + w.putUByte(size) + obj.values.foreach { case (id, v) => w.put(id).putValue(v) } + } + + override def parse(r: SigmaByteReader): ContextExtension = { + val extSize = r.getByte() + if (extSize < 0) + error(s"Negative amount of context extension values: $extSize") + val ext = (0 until extSize) + .map(_ => (r.getByte(), r.getValue().asInstanceOf[EvaluatedValue[_ <: SType]])) + ContextExtension(mutable.LinkedHashMap(ext: _*)) + } + } +} \ No newline at end of file diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverResult.scala b/data/shared/src/main/scala/sigma/interpreter/ProverResult.scala similarity index 92% rename from interpreter/shared/src/main/scala/sigmastate/interpreter/ProverResult.scala rename to data/shared/src/main/scala/sigma/interpreter/ProverResult.scala index 45d6159d8c..f04b972cb5 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverResult.scala +++ b/data/shared/src/main/scala/sigma/interpreter/ProverResult.scala @@ -1,10 +1,7 @@ -package sigmastate.interpreter - -import java.util +package sigma.interpreter import scorex.util.encode.Base16 -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} /** * Proof of correctness of tx spending diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ApplySerializer.scala b/data/shared/src/main/scala/sigma/serialization/ApplySerializer.scala similarity index 71% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ApplySerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ApplySerializer.scala index bbf50c045e..5a76f56298 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ApplySerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ApplySerializer.scala @@ -1,15 +1,14 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType -import sigmastate.Values._ -import sigmastate.lang.Terms.Apply -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast.{SType, Value} +import sigma.ast.syntax._ +import sigma.ast.Apply import sigma.serialization.CoreByteWriter._ -import sigmastate.utils.SigmaByteWriter._ +import SigmaByteWriter._ case class ApplySerializer(cons: (Value[SType], IndexedSeq[Value[SType]]) => Value[SType]) extends ValueSerializer[Apply] { - import sigmastate.Operations.ApplyInfo._ + import sigma.ast.Operations.ApplyInfo._ override def opDesc = Apply val funcInfo: DataInfo[SValue] = funcArg val argsInfo: DataInfo[Seq[SValue]] = argsArg diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala b/data/shared/src/main/scala/sigma/serialization/BlockValueSerializer.scala similarity index 89% rename from interpreter/shared/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/BlockValueSerializer.scala index ea517c0f1c..a8a2ac359c 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/BlockValueSerializer.scala @@ -1,12 +1,11 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values._ -import sigmastate._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast._ +import sigma.ast.syntax._ import ValueSerializer._ import sigma.util.safeNewArray import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo, U, Vlq} -import sigmastate.utils.SigmaByteWriter._ +import SigmaByteWriter._ import debox.cfor import sigma.ast.SType diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala b/data/shared/src/main/scala/sigma/serialization/BoolToSigmaPropSerializer.scala similarity index 51% rename from interpreter/shared/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/BoolToSigmaPropSerializer.scala index 199ed8ac60..4032157a02 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/BoolToSigmaPropSerializer.scala @@ -1,15 +1,12 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType +import sigma.ast._ +import sigma.ast.syntax._ import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.Values.{BoolValue, SValue, SigmaPropValue} -import sigmastate.lang.Terms._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{BoolToSigmaProp, Values} +import SigmaByteWriter._ case class BoolToSigmaPropSerializer(cons: BoolValue => SigmaPropValue) extends ValueSerializer[BoolToSigmaProp] { - import sigmastate.Operations.BoolToSigmaPropInfo._ + import Operations.BoolToSigmaPropInfo._ override def opDesc = BoolToSigmaProp val conditionInfo: DataInfo[SValue] = conditionArg @@ -17,7 +14,7 @@ case class BoolToSigmaPropSerializer(cons: BoolValue => SigmaPropValue) extends w.putValue(obj.value, conditionInfo) } - def parse(r: SigmaByteReader): Values.Value[SType] = { + def parse(r: SigmaByteReader): Value[SType] = { val p = r.getValue().asBoolValue cons(p) } diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala b/data/shared/src/main/scala/sigma/serialization/CaseObjectSerialization.scala similarity index 65% rename from interpreter/shared/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala rename to data/shared/src/main/scala/sigma/serialization/CaseObjectSerialization.scala index 479cabd01c..56efa0bd52 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala +++ b/data/shared/src/main/scala/sigma/serialization/CaseObjectSerialization.scala @@ -1,8 +1,7 @@ -package sigmastate.serialization +package sigma.serialization import sigma.ast.SType -import sigmastate.Values.{Value, ValueCompanion} -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast.{Value, ValueCompanion} case class CaseObjectSerialization[V <: Value[SType]](override val opDesc: ValueCompanion, obj: V) extends ValueSerializer[V] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ConcreteCollectionBooleanConstantSerializer.scala similarity index 93% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ConcreteCollectionBooleanConstantSerializer.scala index ad168cc61c..6d747f627f 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ConcreteCollectionBooleanConstantSerializer.scala @@ -1,7 +1,7 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast._ +import sigma.ast.syntax._ import sigma.util.safeNewArray import debox.cfor import sigma.ast.{SBoolean, SCollection} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ConcreteCollectionSerializer.scala similarity index 90% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ConcreteCollectionSerializer.scala index 9eef813960..a415b4a567 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ConcreteCollectionSerializer.scala @@ -1,10 +1,10 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast._ +import sigma.ast.syntax._ import ValueSerializer._ import sigma.util.safeNewArray -import sigmastate.utils.SigmaByteWriter._ +import SigmaByteWriter._ import debox.cfor import sigma.ast.{SCollection, SType} import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo, U, Vlq} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ConstantPlaceholderSerializer.scala similarity index 82% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ConstantPlaceholderSerializer.scala index 0cb771f370..7cda3713a4 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ConstantPlaceholderSerializer.scala @@ -1,12 +1,11 @@ -package sigmastate.serialization +package sigma.serialization import sigma.ast.SType -import sigmastate.Values._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast._ case class ConstantPlaceholderSerializer(cons: (Int, SType) => Value[SType]) extends ValueSerializer[ConstantPlaceholder[SType]] { - import sigmastate.Operations.ConstantPlaceholderInfo._ + import Operations.ConstantPlaceholderInfo._ override def opDesc = ConstantPlaceholder override def serialize(obj: ConstantPlaceholder[SType], w: SigmaByteWriter): Unit = { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ConstantSerializer.scala similarity index 77% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ConstantSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ConstantSerializer.scala index e23cfc984d..eccc2d79ca 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ConstantSerializer.scala @@ -1,9 +1,7 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType -import sigmastate.Values._ -import sigmastate.lang.SigmaBuilder -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast.{SType, SigmaBuilder} +import sigma.ast._ /** This works in tandem with DataSerializer, if you change one make sure to check the other.*/ case class ConstantSerializer(builder: SigmaBuilder) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantStore.scala b/data/shared/src/main/scala/sigma/serialization/ConstantStore.scala similarity index 77% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ConstantStore.scala rename to data/shared/src/main/scala/sigma/serialization/ConstantStore.scala index 45ac168ef4..dd91c9a7b1 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantStore.scala +++ b/data/shared/src/main/scala/sigma/serialization/ConstantStore.scala @@ -1,7 +1,6 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values.{Constant, ConstantNode, ConstantPlaceholder} -import sigmastate.lang.SigmaBuilder +import sigma.ast.{Constant, ConstantNode, ConstantPlaceholder, SigmaBuilder} import debox.Buffer import sigma.ast.SType @@ -14,7 +13,7 @@ class ConstantStore(private val constants: IndexedSeq[Constant[SType]] = Constan store += c.asInstanceOf[Constant[SType]] val tpe = c.asInstanceOf[ConstantNode[T]].tpe builder.mkConstantPlaceholder[tpe.type](store.length - 1, tpe) - .asInstanceOf[sigmastate.Values.ConstantPlaceholder[T]] + .asInstanceOf[sigma.ast.ConstantPlaceholder[T]] } @inline final def get(index: Int): Constant[SType] = store(index) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala b/data/shared/src/main/scala/sigma/serialization/CreateAvlTreeSerializer.scala similarity index 80% rename from interpreter/shared/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/CreateAvlTreeSerializer.scala index f623be7588..018b63376b 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/CreateAvlTreeSerializer.scala @@ -1,21 +1,20 @@ -package sigmastate.serialization +package sigma.serialization import sigma.ast.SCollection.SByteArray import sigma.ast.SInt import sigma.ast.SOption.SIntOption import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate._ -import sigmastate.Values._ -import sigmastate.lang.Terms.ValueOps -import sigmastate.utils.SigmaByteWriter._ +import sigma.ast._ +import sigma.ast.syntax._ +import sigma.ast.syntax.ValueOps +import SigmaByteWriter._ case class CreateAvlTreeSerializer( cons: (ByteValue, Value[SByteArray], IntValue, Value[SIntOption]) => AvlTreeValue ) extends ValueSerializer[CreateAvlTree] { - import sigmastate.Operations.CreateAvlTreeInfo._ + import Operations.CreateAvlTreeInfo._ override def opDesc = CreateAvlTree val operationFlagsInfo: DataInfo[SValue] = operationFlagsArg val digestInfo: DataInfo[SValue] = digestArg diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/CreateProveDlogSerializer.scala b/data/shared/src/main/scala/sigma/serialization/CreateProveDlogSerializer.scala similarity index 59% rename from interpreter/shared/src/main/scala/sigmastate/serialization/CreateProveDlogSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/CreateProveDlogSerializer.scala index bc59806dac..5135cd1e37 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/CreateProveDlogSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/CreateProveDlogSerializer.scala @@ -1,16 +1,15 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SGroupElement +import sigma.ast.{CreateProveDlog, SGroupElement} import sigma.serialization.CoreByteWriter._ -import sigmastate.CreateProveDlog -import sigmastate.Values.{SValue, SigmaPropValue, Value} -import sigmastate.lang.Terms.ValueOps -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utils.SigmaByteWriter._ +import sigma.ast.Value +import sigma.ast.syntax._ +import sigma.ast.syntax.ValueOps +import SigmaByteWriter._ case class CreateProveDlogSerializer(cons: Value[SGroupElement.type] => SigmaPropValue) extends ValueSerializer[CreateProveDlog] { - import sigmastate.Operations.CreateProveDlogInfo._ + import sigma.ast.Operations.CreateProveDlogInfo._ override def opDesc = CreateProveDlog diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/DataSerializer.scala b/data/shared/src/main/scala/sigma/serialization/DataSerializer.scala similarity index 73% rename from interpreter/shared/src/main/scala/sigmastate/serialization/DataSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/DataSerializer.scala index 491ffb2be8..5f554e96a1 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/DataSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/DataSerializer.scala @@ -1,11 +1,8 @@ -package sigmastate.serialization +package sigma.serialization import org.ergoplatform.ErgoBox -import sigma._ import sigma.ast._ -import sigma.serialization.{CoreByteReader, CoreByteWriter, CoreDataSerializer} -import sigmastate.eval.SigmaDsl -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.data.CBox /** This works in tandem with ConstantSerializer, if you change one make sure to check the other.*/ object DataSerializer extends CoreDataSerializer { @@ -16,8 +13,8 @@ object DataSerializer extends CoreDataSerializer { */ override def serialize[T <: SType](v: T#WrappedType, tpe: T, w: CoreByteWriter): Unit = tpe match { case SBox => - val b = v.asInstanceOf[Box] - ErgoBox.sigmaSerializer.serialize(SigmaDsl.toErgoBox(b), w.asInstanceOf[SigmaByteWriter]) + val b = v.asInstanceOf[CBox] + ErgoBox.sigmaSerializer.serialize(b.ebox, w.asInstanceOf[SigmaByteWriter]) case _ => super.serialize(v, tpe, w) } @@ -32,7 +29,7 @@ object DataSerializer extends CoreDataSerializer { case SBox => val depth = r.level r.level = depth + 1 - val res = SigmaDsl.Box(ErgoBox.sigmaSerializer.parse(r.asInstanceOf[SigmaByteReader])) + val res = CBox(ErgoBox.sigmaSerializer.parse(r.asInstanceOf[SigmaByteReader])) r.level = r.level - 1 res case t => diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala similarity index 95% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala index 45cbc863eb..820c3a70a5 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala @@ -1,20 +1,14 @@ -package sigmastate.serialization +package sigma.serialization import org.ergoplatform.validation.ValidationRules.{CheckDeserializedScriptIsSigmaProp, CheckHeaderSizeBit} -import sigmastate.Values.Constant -import sigmastate.lang.DeserializationSigmaBuilder -import sigmastate.lang.Terms.ValueOps -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.ErgoTree.{EmptyConstants, HeaderType} +import sigma.ast.{ComplexityTable, Constant, DeserializationSigmaBuilder, ErgoTree, SType, SubstConstants, UnparsedErgoTree} +import sigma.ast.syntax.ValueOps +import sigma.ast.ErgoTree.{EmptyConstants, HeaderType} import sigma.util.safeNewArray -import sigmastate.utxo.ComplexityTable import debox.cfor import sigma.VersionContext -import sigma.ast.SType -import sigma.serialization.{ReaderPositionLimitExceeded, SerializerException} import sigma.validation.{SigmaValidationSettings, ValidationException} import sigma.validation.ValidationRules.CheckPositionLimit -import sigmastate.{ErgoTree, UnparsedErgoTree} /** * Rationale for soft-forkable ErgoTree serialization. @@ -138,7 +132,7 @@ class ErgoTreeSerializer { deserializeErgoTree(r, maxTreeSizeBytes, true) } - private[sigmastate] def deserializeErgoTree(r: SigmaByteReader, maxTreeSizeBytes: Int, checkType: Boolean): ErgoTree = { + private[sigma] def deserializeErgoTree(r: SigmaByteReader, maxTreeSizeBytes: Int, checkType: Boolean): ErgoTree = { val startPos = r.position val previousPositionLimit = r.positionLimit val previousComplexity = r.complexity @@ -272,7 +266,7 @@ class ErgoTreeSerializer { * positions(r(i)) == i whenever r(i) != -1. When r(i) == -1 then backreference * is not defined (which means the constant with the index `i` is not substituted. */ - private[sigmastate] def getPositionsBackref(positions: Array[Int], positionsRange: Int): Array[Int] = { + private[sigma] def getPositionsBackref(positions: Array[Int], positionsRange: Int): Array[Int] = { // allocate array of back references: forall i: positionsBackref(i) is index in `positions` val positionsBackref = safeNewArray[Int](positionsRange) // mark all positions are not assigned @@ -291,7 +285,7 @@ class ErgoTreeSerializer { /** Transforms serialized bytes of ErgoTree with segregated constants by * replacing constants at given positions with new values. This operation * allow to use serialized scripts as pre-defined templates. - * See [[sigmastate.SubstConstants]] for details. + * See [[SubstConstants]] for details. * * @param scriptBytes serialized ErgoTree with ConstantSegregationFlag set to 1. * @param positions zero based indexes in ErgoTree.constants array which diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala b/data/shared/src/main/scala/sigma/serialization/FuncValueSerializer.scala similarity index 91% rename from interpreter/shared/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/FuncValueSerializer.scala index 1ae6cab038..7f9b8cc927 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/FuncValueSerializer.scala @@ -1,11 +1,10 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values._ -import sigmastate._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast._ +import sigma.ast.syntax._ import ValueSerializer._ import sigma.util.safeNewArray -import sigmastate.utils.SigmaByteWriter._ +import SigmaByteWriter._ import debox.cfor import sigma.ast.SType import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo, U, Vlq} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/GetVarSerializer.scala b/data/shared/src/main/scala/sigma/serialization/GetVarSerializer.scala similarity index 68% rename from interpreter/shared/src/main/scala/sigmastate/serialization/GetVarSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/GetVarSerializer.scala index 2e449c47c8..c3618ac0bf 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/GetVarSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/GetVarSerializer.scala @@ -1,16 +1,11 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.{SOption, SType} +import sigma.ast._ import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo} -import sigmastate.Values._ -import sigmastate._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.GetVar case class GetVarSerializer(cons: (Byte, SType) => Value[SOption[SType]]) extends ValueSerializer[GetVar[_ <: SType]] { - import sigmastate.Operations.GetVarInfo._ + import Operations.GetVarInfo._ override def opDesc = GetVar val typeInfo: DataInfo[SType] = ArgInfo("type", "expected type of context variable") val varIdInfo: DataInfo[Byte] = varIdArg diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/LogicalNotSerializer.scala b/data/shared/src/main/scala/sigma/serialization/LogicalNotSerializer.scala similarity index 59% rename from interpreter/shared/src/main/scala/sigmastate/serialization/LogicalNotSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/LogicalNotSerializer.scala index 6bc395a97e..0130d58d83 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/LogicalNotSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/LogicalNotSerializer.scala @@ -1,12 +1,10 @@ -package sigmastate.serialization +package sigma.serialization +import sigma.ast.LogicalNot import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.LogicalNot -import sigmastate.Operations.LogicalNotInfo.inputArg -import sigmastate.Values.{BoolValue, SValue} -import sigmastate.lang.Terms._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast.Operations.LogicalNotInfo.inputArg +import sigma.ast.syntax._ +import SigmaByteWriter._ case class LogicalNotSerializer(cons: BoolValue => BoolValue) extends ValueSerializer[LogicalNot] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala b/data/shared/src/main/scala/sigma/serialization/MethodCallSerializer.scala similarity index 90% rename from interpreter/shared/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/MethodCallSerializer.scala index 9a4a0c6690..49ea712e80 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/MethodCallSerializer.scala @@ -1,14 +1,11 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values._ -import sigmastate._ -import sigmastate.lang.Terms.MethodCall +import sigma.ast.syntax._ +import sigma.ast.MethodCall import sigma.util.safeNewArray -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.ComplexityTable +import SigmaByteWriter._ import debox.cfor -import sigma.ast.{SType, STypeSubst} +import sigma.ast.{ComplexityTable, SMethod, SType, STypeSubst, Value, ValueCompanion} import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo} case class MethodCallSerializer(cons: (Value[SType], SMethod, IndexedSeq[Value[SType]], STypeSubst) => Value[SType]) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ModQArithOpSerializer.scala similarity index 72% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ModQArithOpSerializer.scala index bad08986a1..181c3f7c5e 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ModQArithOpSerializer.scala @@ -1,12 +1,10 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType +import sigma.ast.{ModQArithOp, ModQArithOpCompanion, SType} +import sigma.ast.syntax.{BigIntValue, SValue, ValueOps} import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.Values.{BigIntValue, SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{ModQArithOp, ModQArithOpCompanion} +import sigma.ast.Value +import SigmaByteWriter._ // TODO v6.0: make sure it is covered with tests (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/327) case class ModQArithOpSerializer(override val opDesc: ModQArithOpCompanion, cons: (BigIntValue, BigIntValue) => BigIntValue) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ModQSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ModQSerializer.scala similarity index 62% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ModQSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ModQSerializer.scala index 676b9bc43f..346f1ef6e2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ModQSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ModQSerializer.scala @@ -1,11 +1,9 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType -import sigmastate.ModQ -import sigmastate.Values.Value -import sigmastate.lang.Terms._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast.{ModQ, SType} +import sigma.ast.Value +import SigmaByteWriter._ +import sigma.ast.syntax.ValueOps // TODO v6.0: make sure it is covered with tests (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/327) object ModQSerializer extends ValueSerializer[ModQ] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala b/data/shared/src/main/scala/sigma/serialization/OneArgumentOperationSerializer.scala similarity index 62% rename from interpreter/shared/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/OneArgumentOperationSerializer.scala index e522fcb23f..15b5d89cb5 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/OneArgumentOperationSerializer.scala @@ -1,12 +1,10 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType +import sigma.ast.{OneArgumentOperation, OneArgumentOperationCompanion, SType} import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{OneArgumentOperation, OneArgumentOperationCompanion} +import sigma.ast.Value +import sigma.ast.syntax._ +import SigmaByteWriter._ case class OneArgumentOperationSerializer[T <: SType](opDesc: OneArgumentOperationCompanion, cons: Value[T] => SValue) extends ValueSerializer[OneArgumentOperation[T, SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/OpCodes.scala b/data/shared/src/main/scala/sigma/serialization/OpCodes.scala similarity index 99% rename from interpreter/shared/src/main/scala/sigmastate/serialization/OpCodes.scala rename to data/shared/src/main/scala/sigma/serialization/OpCodes.scala index 6a05091e3e..70050d00ba 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/OpCodes.scala +++ b/data/shared/src/main/scala/sigma/serialization/OpCodes.scala @@ -1,4 +1,4 @@ -package sigmastate.serialization +package sigma.serialization import sigma.ast.TypeCodes.LastConstantCode import supertagged.TaggedType diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala b/data/shared/src/main/scala/sigma/serialization/OptionGetOrElseSerializer.scala similarity index 66% rename from interpreter/shared/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/OptionGetOrElseSerializer.scala index 0ad016c3b4..ef00ad48ff 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/OptionGetOrElseSerializer.scala @@ -1,17 +1,13 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.{SOption, SType} +import sigma.ast._ import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.Values._ -import sigmastate._ -import sigmastate.lang.Terms._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.OptionGetOrElse +import sigma.ast.syntax._ +import SigmaByteWriter._ case class OptionGetOrElseSerializer(cons: (Value[SOption[SType]], Value[SType]) => Value[SType]) extends ValueSerializer[OptionGetOrElse[_ <: SType]] { - import sigmastate.Operations.OptionGetOrElseInfo._ + import Operations.OptionGetOrElseInfo._ override def opDesc = OptionGetOrElse val thisInfo: DataInfo[SValue] = thisArg val defaultInfo: DataInfo[SValue] = defaultArg diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala b/data/shared/src/main/scala/sigma/serialization/PropertyCallSerializer.scala similarity index 79% rename from interpreter/shared/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/PropertyCallSerializer.scala index e3c27d3277..9ced87e8e8 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/PropertyCallSerializer.scala @@ -1,14 +1,10 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.{EmptySubst, SType, STypeSubst} +import sigma.ast.{ComplexityTable, EmptySubst, SType, STypeSubst} import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo} -import sigmastate.Values._ -import sigmastate._ -import sigmastate.lang.Terms -import sigmastate.lang.Terms.{MethodCall, PropertyCall} -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.ComplexityTable +import sigma.ast._ +import sigma.ast.syntax.SValue +import SigmaByteWriter._ case class PropertyCallSerializer(cons: (Value[SType], SMethod, IndexedSeq[Value[SType]], STypeSubst) => Value[SType]) extends ValueSerializer[MethodCall] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala b/data/shared/src/main/scala/sigma/serialization/SelectFieldSerializer.scala similarity index 70% rename from interpreter/shared/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/SelectFieldSerializer.scala index 488bfe08f9..95e692c85a 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/SelectFieldSerializer.scala @@ -1,14 +1,12 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Operations.SelectFieldInfo -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.SelectField +import sigma.ast.Operations.SelectFieldInfo +import sigma.ast.{SelectField, Value} +import sigma.ast.syntax._ import SelectFieldInfo._ import sigma.ast.{STuple, SType} import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.utils.SigmaByteWriter._ +import SigmaByteWriter._ case class SelectFieldSerializer(cons: (Value[STuple], Byte) => Value[SType]) extends ValueSerializer[SelectField] { override def opDesc = SelectField diff --git a/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteReader.scala b/data/shared/src/main/scala/sigma/serialization/SigmaByteReader.scala similarity index 88% rename from interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteReader.scala rename to data/shared/src/main/scala/sigma/serialization/SigmaByteReader.scala index c937fcf12d..8cbeeb1cc1 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteReader.scala +++ b/data/shared/src/main/scala/sigma/serialization/SigmaByteReader.scala @@ -1,11 +1,10 @@ -package sigmastate.utils +package sigma.serialization import debox.cfor import scorex.util.serialization.Reader -import sigma.serialization.CoreByteReader +import sigma.ast._ +import sigma.ast.syntax._ import sigma.util.safeNewArray -import sigmastate.Values.{SValue, Value} -import sigmastate.serialization._ /** Reader used in the concrete implementations of [[SigmaSerializer]]. * It decorates the given reader, delegates most of the methods to it, but also adds new @@ -13,7 +12,7 @@ import sigmastate.serialization._ * * @param r the underlying reader this reader reads from * @param constantStore the store of constants which is used to resolve - * [[sigmastate.Values.ConstantPlaceholder]] + * [[sigma.ast.ConstantPlaceholder]] * @param resolvePlaceholdersToConstants if true then resolved constants will be * substituted in the tree instead of the placeholder. * @param maxTreeDepth limit on the tree depth (recursive invocations) @@ -36,7 +35,7 @@ class SigmaByteReader(override val r: Reader, /** Returns all bytes of the underlying ByteBuffer. */ - private[sigmastate] def getAllBufferBytes: Array[Byte] = { + private[sigma] def getAllBufferBytes: Array[Byte] = { val savedPos = position position = 0 val res = getBytesUnsafe(remaining) diff --git a/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteWriter.scala b/data/shared/src/main/scala/sigma/serialization/SigmaByteWriter.scala similarity index 93% rename from interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteWriter.scala rename to data/shared/src/main/scala/sigma/serialization/SigmaByteWriter.scala index 802cd56e32..35d5e0c9b9 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteWriter.scala +++ b/data/shared/src/main/scala/sigma/serialization/SigmaByteWriter.scala @@ -1,11 +1,9 @@ -package sigmastate.utils +package sigma.serialization import scorex.util.serialization.Writer -import sigma.ast.SType -import sigma.serialization.CoreByteWriter +import sigma.ast.syntax._ +import sigma.ast._ import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo, FormatDescriptor, SeqFmt} -import sigmastate.Values.{SValue, Value} -import sigmastate.serialization.{ConstantStore, TypeSerializer, ValueSerializer} class SigmaByteWriter(override val w: Writer, val constantExtractionStore: Option[ConstantStore]) diff --git a/data/shared/src/main/scala/sigma/serialization/SigmaPropBytesSerializer.scala b/data/shared/src/main/scala/sigma/serialization/SigmaPropBytesSerializer.scala new file mode 100644 index 0000000000..fc55e7b5ca --- /dev/null +++ b/data/shared/src/main/scala/sigma/serialization/SigmaPropBytesSerializer.scala @@ -0,0 +1,21 @@ +package sigma.serialization + +import sigma.ast.{SType, SigmaPropBytes, Value} +import sigma.serialization.CoreByteWriter.DataInfo +import sigma.ast.syntax._ +import SigmaByteWriter._ + +object SigmaPropBytesSerializer extends ValueSerializer[SigmaPropBytes] { + import sigma.ast.Operations.SigmaPropBytesInfo._ + override def opDesc = SigmaPropBytes + val thisInfo: DataInfo[SValue] = thisArg + + def serialize(obj: SigmaPropBytes, w: SigmaByteWriter): Unit = { + w.putValue(obj.input, thisInfo) + } + + def parse(r: SigmaByteReader): Value[SType] = { + val p = r.getValue().asSigmaProp + SigmaPropBytes(p) + } +} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala b/data/shared/src/main/scala/sigma/serialization/SigmaPropIsProvenSerializer.scala similarity index 52% rename from interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/SigmaPropIsProvenSerializer.scala index fb7892f940..66e7491dfd 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/SigmaPropIsProvenSerializer.scala @@ -1,10 +1,7 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType -import sigmastate.Values -import sigmastate.lang.Terms._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.SigmaPropIsProven +import sigma.ast.{SType, SigmaPropIsProven, Value} +import sigma.ast.syntax._ object SigmaPropIsProvenSerializer extends ValueSerializer[SigmaPropIsProven] { override def opDesc = SigmaPropIsProven @@ -13,7 +10,7 @@ object SigmaPropIsProvenSerializer extends ValueSerializer[SigmaPropIsProven] { w.putValue(obj.input) } - def parse(r: SigmaByteReader): Values.Value[SType] = { + def parse(r: SigmaByteReader): Value[SType] = { val p = r.getValue().asSigmaProp SigmaPropIsProven(p) } diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaSerializer.scala b/data/shared/src/main/scala/sigma/serialization/SigmaSerializer.scala similarity index 94% rename from interpreter/shared/src/main/scala/sigmastate/serialization/SigmaSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/SigmaSerializer.scala index 78c60afba9..cdb28d724b 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/SigmaSerializer.scala @@ -1,13 +1,11 @@ -package sigmastate.serialization +package sigma.serialization import java.nio.ByteBuffer import scorex.util.ByteArrayBuilder -import sigmastate.utils._ import scorex.util.serialization._ import sigma.data.SigmaConstants -import sigma.serialization.SerializerException import sigma.validation.SigmaValidationSettings -import sigmastate.serialization.ValueCodes.OpCode +import sigma.serialization.ValueCodes.OpCode object SigmaSerializer { type Position = Int diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala b/data/shared/src/main/scala/sigma/serialization/SubstConstantsSerializer.scala similarity index 75% rename from interpreter/shared/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/SubstConstantsSerializer.scala index 94d7e20dc2..f019d35b59 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/SubstConstantsSerializer.scala @@ -1,16 +1,14 @@ -package sigmastate.serialization +package sigma.serialization import sigma.ast.SCollection.{SByteArray, SIntArray} -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast.{SubstConstants, Value} +import sigma.ast.syntax._ +import SigmaByteWriter._ import sigma.ast.{SCollection, SType} import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.SubstConstants object SubstConstantsSerializer extends ValueSerializer[SubstConstants[SType]] { - import sigmastate.Operations.SubstConstantsInfo._ + import sigma.ast.Operations.SubstConstantsInfo._ override def opDesc = SubstConstants val scriptBytesInfo: DataInfo[SValue] = scriptBytesArg val positionsInfo: DataInfo[SValue] = positionsArg diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala b/data/shared/src/main/scala/sigma/serialization/TaggedVariableSerializer.scala similarity index 75% rename from interpreter/shared/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/TaggedVariableSerializer.scala index 6f233bf10c..cd6f33eacb 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/TaggedVariableSerializer.scala @@ -1,10 +1,9 @@ -package sigmastate.serialization +package sigma.serialization import sigma.ast.SType -import sigmastate.Values._ -import sigmastate._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast._ +// TODO v6.0: remove this class (https://github.com/ScorexFoundation/sigmastate-interpreter/issues/584) case class TaggedVariableSerializer(cons: (Byte, SType) => Value[SType]) extends ValueSerializer[TaggedVariable[_ <: SType]] { override def opDesc = TaggedVariable diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/TupleSerializer.scala b/data/shared/src/main/scala/sigma/serialization/TupleSerializer.scala similarity index 84% rename from interpreter/shared/src/main/scala/sigmastate/serialization/TupleSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/TupleSerializer.scala index 1ab9c83094..89a7ea457c 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/TupleSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/TupleSerializer.scala @@ -1,12 +1,12 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.serialization.ValueSerializer._ +import sigma.ast._ +import sigma.serialization.ValueSerializer._ import sigma.util.safeNewArray -import sigmastate.utils.SigmaByteWriter._ +import SigmaByteWriter._ import debox.cfor import sigma.ast.SType +import sigma.ast.syntax.{CollectionOps, SValue} import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo, U} case class TupleSerializer(cons: Seq[Value[SType]] => Value[SType]) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala b/data/shared/src/main/scala/sigma/serialization/TwoArgumentsSerializer.scala similarity index 72% rename from interpreter/shared/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/TwoArgumentsSerializer.scala index 4fcba5c174..b6f4561ba0 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/TwoArgumentsSerializer.scala @@ -1,12 +1,10 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType +import sigma.ast.{SType, TwoArgumentOperationCompanion, TwoArgumentsOperation} import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{TwoArgumentOperationCompanion, TwoArgumentsOperation} +import sigma.ast.Value +import sigma.ast.syntax._ +import SigmaByteWriter._ case class TwoArgumentsSerializer[LIV <: SType, RIV <: SType, OV <: Value[SType]] (override val opDesc: TwoArgumentOperationCompanion, constructor: (Value[LIV], Value[RIV]) => Value[SType]) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ValDefSerializer.scala similarity index 86% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ValDefSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ValDefSerializer.scala index 023d9fe590..b775c14327 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ValDefSerializer.scala @@ -1,14 +1,11 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values._ -import sigmastate._ -import sigmastate.serialization.OpCodes._ +import debox.cfor import scorex.util.Extensions._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import ValueSerializer._ +import sigma.ast._ import sigma.util.safeNewArray -import debox.cfor -import sigma.ast.{SType, STypeVar} +import sigma.serialization.OpCodes._ +import sigma.serialization.ValueSerializer._ case class ValDefSerializer(override val opDesc: ValueCompanion) extends ValueSerializer[ValDef] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala b/data/shared/src/main/scala/sigma/serialization/ValDefTypeStore.scala similarity index 87% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala rename to data/shared/src/main/scala/sigma/serialization/ValDefTypeStore.scala index 2fc0373a02..8ae41ebb99 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala +++ b/data/shared/src/main/scala/sigma/serialization/ValDefTypeStore.scala @@ -1,4 +1,4 @@ -package sigmastate.serialization +package sigma.serialization import sigma.ast.SType diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ValUseSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ValUseSerializer.scala similarity index 82% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ValUseSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ValUseSerializer.scala index 8091f9bef0..49aae39843 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ValUseSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ValUseSerializer.scala @@ -1,9 +1,6 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType -import sigmastate.Values._ -import sigmastate._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast._ case class ValUseSerializer(cons: (Int, SType) => Value[SType]) extends ValueSerializer[ValUse[SType]] { override def opDesc = ValUse diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ValueSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ValueSerializer.scala similarity index 97% rename from interpreter/shared/src/main/scala/sigmastate/serialization/ValueSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/ValueSerializer.scala index 0efbd5234b..fc8341ee3a 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ValueSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ValueSerializer.scala @@ -1,21 +1,16 @@ -package sigmastate.serialization +package sigma.serialization -import org.ergoplatform._ import org.ergoplatform.validation.ValidationRules.CheckValidOpCode import sigma.ast.SCollection.SByteArray import sigma.ast.TypeCodes.LastConstantCode import sigma.ast._ import sigma.serialization.CoreByteWriter.DataInfo import sigma.util.Extensions.toUByte -import sigmastate.Values._ -import sigmastate._ -import sigmastate.lang.DeserializationSigmaBuilder -import sigmastate.serialization.ValueCodes.OpCode -import sigmastate.serialization.transformers._ -import sigmastate.serialization.trees.{QuadrupleSerializer, Relation2Serializer} -import sigmastate.utils._ -import sigmastate.utxo.ComplexityTable._ -import sigmastate.utxo._ +import sigma.serialization.ValueCodes.OpCode +import sigma.serialization.transformers._ +import sigma.serialization.trees.{QuadrupleSerializer, Relation2Serializer} +import ComplexityTable._ +import sigma.utils.SparseArrayContainer import scala.collection.mutable @@ -101,7 +96,7 @@ object ValueSerializer extends SigmaSerializerCompanion[Value[SType]] { LogicalTransformerSerializer(AND, mkAND), LogicalTransformerSerializer(OR, mkOR), LogicalTransformerSerializer(XorOf, mkXorOf), - TaggedVariableSerializer(mkTaggedVariable), + TaggedVariableSerializer(mkTaggedVariable), // TODO v6.0: remove this serializer https://github.com/ScorexFoundation/sigmastate-interpreter/issues/584 GetVarSerializer(mkGetVar), MapCollectionSerializer(mkMapCollection), BooleanTransformerSerializer[SType](Exists, mkExists), diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/AppendSerializer.scala similarity index 64% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/AppendSerializer.scala index 3cd438cab8..c5995cfe7d 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/AppendSerializer.scala @@ -1,12 +1,10 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigmastate.Operations.AppendInfo -import sigmastate.Values.Value -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utxo.Append +import sigma.ast.Operations.AppendInfo +import sigma.ast.{Append, Value} +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ import sigma.ast.{SCollection, SType} case class AppendSerializer(cons: (Value[SCollection[SType]], Value[SCollection[SType]]) => Value[SCollection[SType]]) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/AtLeastSerializer.scala similarity index 58% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/AtLeastSerializer.scala index 9cde3c1437..876f83f2d1 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/AtLeastSerializer.scala @@ -1,13 +1,11 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigma.ast.{SCollection, SInt, SSigmaProp} -import sigmastate.Operations.AtLeastInfo -import sigmastate.Values.{SigmaPropValue, Value} -import sigmastate.lang.Terms._ -import sigmastate._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utils.SigmaByteWriter._ +import sigma.ast.syntax.SigmaPropValue +import sigma.ast.{AtLeast, SCollection, SInt, SSigmaProp, Value} +import sigma.ast.Operations.AtLeastInfo +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ case class AtLeastSerializer(cons: (Value[SInt.type], Value[SCollection[SSigmaProp.type]]) => SigmaPropValue) extends ValueSerializer[AtLeast] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/BooleanTransformerSerializer.scala similarity index 69% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/BooleanTransformerSerializer.scala index 746435c3cd..be3b91dcca 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/BooleanTransformerSerializer.scala @@ -1,11 +1,10 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.{BooleanTransformer, BooleanTransformerCompanion} +import sigma.ast.syntax.SValue +import sigma.ast.{BooleanTransformer, BooleanTransformerCompanion, Value} +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ import sigma.ast.{SBoolean, SCollection, SFunc, SType} import sigma.serialization.CoreByteWriter.DataInfo diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/ByIndexSerializer.scala similarity index 72% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/ByIndexSerializer.scala index 99e24b4288..e0c43d1cc5 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/ByIndexSerializer.scala @@ -1,13 +1,12 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer +import sigma.ast.{ByIndex, Value} +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} import ValueSerializer._ -import sigmastate.Operations.ByIndexInfo._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.ByIndex +import sigma.ast.syntax.SValue +import sigma.ast.Operations.ByIndexInfo._ +import sigma.serialization.SigmaByteWriter._ import sigma.ast.{SCollection, SInt, SType} import sigma.serialization.CoreByteWriter.DataInfo diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/CreateProveDHTupleSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/CreateProveDHTupleSerializer.scala similarity index 66% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/CreateProveDHTupleSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/CreateProveDHTupleSerializer.scala index 67b6dfb990..5a16d35365 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/CreateProveDHTupleSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/CreateProveDHTupleSerializer.scala @@ -1,19 +1,18 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigma.ast.SGroupElement -import sigmastate.CreateProveDHTuple -import sigmastate.Values.{SigmaPropValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.serialization._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.ast.{CreateProveDHTuple, SGroupElement} +import sigma.ast.syntax.SigmaPropValue +import sigma.ast.Value +import sigma.ast.syntax._ +import sigma.serialization._ +import SigmaByteWriter._ case class CreateProveDHTupleSerializer(cons: (Value[SGroupElement.type], Value[SGroupElement.type], Value[SGroupElement.type], Value[SGroupElement.type]) => SigmaPropValue) extends ValueSerializer[CreateProveDHTuple] { - import sigmastate.Operations.CreateProveDHTupleInfo._ + import sigma.ast.Operations.CreateProveDHTupleInfo._ override def opDesc = CreateProveDHTuple override def serialize(obj: CreateProveDHTuple, w: SigmaByteWriter): Unit = { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/DeserializeContextSerializer.scala similarity index 73% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/DeserializeContextSerializer.scala index f482341b7f..9058617601 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/DeserializeContextSerializer.scala @@ -1,12 +1,10 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigmastate.Values._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.DeserializeContext +import sigma.ast._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} import sigma.ast.SType import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo} -import sigmastate.Operations.DeserializeContextInfo +import Operations.DeserializeContextInfo case class DeserializeContextSerializer(cons: (Byte, SType) => Value[SType]) extends ValueSerializer[DeserializeContext[SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/DeserializeRegisterSerializer.scala similarity index 76% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/DeserializeRegisterSerializer.scala index 436302f357..05d5f7b4db 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/DeserializeRegisterSerializer.scala @@ -1,16 +1,15 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers import org.ergoplatform.ErgoBox import org.ergoplatform.ErgoBox.RegisterId -import sigmastate.Values.{SValue, Value} -import sigmastate.serialization.ValueSerializer +import sigma.ast.{DeserializeRegister, Value} +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} import ValueSerializer._ import sigma.ast.SType +import sigma.ast.syntax.SValue import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo} -import sigmastate.Operations.DeserializeRegisterInfo._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.DeserializeRegister +import sigma.ast.Operations.DeserializeRegisterInfo._ +import sigma.serialization.SigmaByteWriter._ case class DeserializeRegisterSerializer(cons: (RegisterId, SType, Option[Value[SType]]) => Value[SType]) extends ValueSerializer[DeserializeRegister[SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/ExtractRegisterAsSerializer.scala similarity index 75% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/ExtractRegisterAsSerializer.scala index f93db97178..e2b09e2a84 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/ExtractRegisterAsSerializer.scala @@ -1,18 +1,17 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers import org.ergoplatform.ErgoBox import org.ergoplatform.ErgoBox.RegisterId -import sigmastate.Values.{SValue, Value} -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.ExtractRegisterAs +import sigma.ast.syntax.SValue +import sigma.ast.{ExtractRegisterAs, Value} +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ import sigma.ast.{SBox, SOption, SType} import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo} case class ExtractRegisterAsSerializer(cons: (Value[SBox.type], RegisterId, SOption[SType]) => Value[SType]) extends ValueSerializer[ExtractRegisterAs[SType]] { - import sigmastate.Operations.ExtractRegisterAsInfo._ + import sigma.ast.Operations.ExtractRegisterAsInfo._ override def opDesc = ExtractRegisterAs val thisInfo: DataInfo[SValue] = thisArg val regIdInfo: DataInfo[Byte] = regIdArg diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/FilterSerializer.scala similarity index 69% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/FilterSerializer.scala index 54aba2b7cc..ba8c82a56e 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/FilterSerializer.scala @@ -1,10 +1,8 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigmastate.Values.Value -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.Filter +import sigma.ast.{Filter, Value} +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} import sigma.ast.{SCollection, SType, SFunc} case class FilterSerializer(cons: (Value[SCollection[SType]], Value[SFunc]) => Value[SCollection[SType]]) extends ValueSerializer[Filter[SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/FoldSerializer.scala similarity index 70% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/FoldSerializer.scala index df55f68650..a1f59f04d3 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/FoldSerializer.scala @@ -1,18 +1,17 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.Fold +import sigma.ast.syntax.SValue +import sigma.ast.{Fold, Value} +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ import sigma.ast.{SCollection, SFunc, SType} import sigma.serialization.CoreByteWriter.DataInfo case class FoldSerializer(cons: (Value[SCollection[SType]], Value[SType], Value[SFunc]) => Value[SType]) extends ValueSerializer[Fold[SType, SType]] { override def opDesc = Fold - import sigmastate.Operations.FoldInfo._ + import sigma.ast.Operations.FoldInfo._ val thisInfo: DataInfo[SValue] = thisArg val zeroInfo: DataInfo[SValue] = zeroArg val opInfo: DataInfo[SValue] = opArg diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/LogicalTransformerSerializer.scala similarity index 60% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/LogicalTransformerSerializer.scala index 0e0ace10c8..29c323341d 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/LogicalTransformerSerializer.scala @@ -1,14 +1,12 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigma.ast.{SBoolean, SCollection} +import sigma.ast.syntax.SValue +import sigma.ast.{LogicalTransformerCompanion, SBoolean, SCollection, Transformer} import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.Transformer -import sigmastate.LogicalTransformerCompanion +import sigma.ast.Value +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ case class LogicalTransformerSerializer[I <: SCollection[SBoolean.type], O <: SBoolean.type] (opDesc: LogicalTransformerCompanion, diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/MapCollectionSerializer.scala similarity index 66% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/MapCollectionSerializer.scala index 906d33976d..de289b6f64 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/MapCollectionSerializer.scala @@ -1,17 +1,16 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.MapCollection +import sigma.ast.syntax.SValue +import sigma.ast.{MapCollection, Value} +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ import sigma.ast.{SCollection, SFunc, SType} import sigma.serialization.CoreByteWriter.DataInfo case class MapCollectionSerializer(cons: (Value[SCollection[SType]], Value[SFunc]) => Value[SType]) extends ValueSerializer[MapCollection[SType, SType]] { - import sigmastate.Operations.MapCollectionInfo._ + import sigma.ast.Operations.MapCollectionInfo._ override def opDesc = MapCollection val thisInfo: DataInfo[SValue] = thisArg val fInfo: DataInfo[SValue] = fArg diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/NumericCastSerializer.scala similarity index 68% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/NumericCastSerializer.scala index 59ad911600..34730c1a39 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/NumericCastSerializer.scala @@ -1,14 +1,11 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigma.ast.{SNumericType, SType} +import sigma.ast.syntax.SValue +import sigma.ast.{NumericCastCompanion, SNumericType, SType, Transformer, Value} import sigma.serialization.CoreByteWriter.{ArgInfo, DataInfo} -import sigmastate.Values.{SValue, Value} -import sigmastate._ -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.Transformer +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ case class NumericCastSerializer(opDesc: NumericCastCompanion, cons: (Value[SNumericType], SNumericType) => Value[SNumericType]) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SigmaTransformerSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/SigmaTransformerSerializer.scala similarity index 77% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SigmaTransformerSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/SigmaTransformerSerializer.scala index bc19a1c8fa..afcbec4a4a 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SigmaTransformerSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/SigmaTransformerSerializer.scala @@ -1,12 +1,11 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigmastate.{SigmaTransformer, SigmaTransformerCompanion} -import sigmastate.Values.{SValue, SigmaPropValue} -import sigmastate.serialization.ValueSerializer +import sigma.ast.syntax.{SValue, SigmaPropValue} +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} import sigma.util.safeNewArray -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.serialization.SigmaByteWriter._ import debox.cfor +import sigma.ast.{SigmaTransformer, SigmaTransformerCompanion} import sigma.serialization.CoreByteWriter.DataInfo case class SigmaTransformerSerializer[I <: SigmaPropValue, O <: SigmaPropValue] diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/SimpleTransformerSerializer.scala similarity index 57% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/SimpleTransformerSerializer.scala index 236e4bfcaf..38fb571a41 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/SimpleTransformerSerializer.scala @@ -1,13 +1,11 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigma.ast.SType +import sigma.ast.{SType, SimpleTransformerCompanion, Transformer} import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.{SimpleTransformerCompanion, Transformer} +import sigma.ast.Value +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ case class SimpleTransformerSerializer[I <: SType, O <: SType] (opDesc: SimpleTransformerCompanion, diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala b/data/shared/src/main/scala/sigma/serialization/transformers/SliceSerializer.scala similarity index 71% rename from interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/transformers/SliceSerializer.scala index 8ac06ec05e..3b159788ba 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/transformers/SliceSerializer.scala @@ -1,17 +1,15 @@ -package sigmastate.serialization.transformers +package sigma.serialization.transformers -import sigmastate.Values.{SValue, Value} -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.Slice +import sigma.ast.{Slice, Value} +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ import sigma.ast.{SCollection, SInt, SType} import sigma.serialization.CoreByteWriter.DataInfo case class SliceSerializer(cons: (Value[SCollection[SType]], Value[SInt.type], Value[SInt.type]) => Value[SCollection[SType]]) extends ValueSerializer[Slice[SType]] { - import sigmastate.Operations.SliceInfo._ + import sigma.ast.Operations.SliceInfo._ override def opDesc = Slice val thisInfo: DataInfo[SValue] = thisArg val fromInfo: DataInfo[SValue] = fromArg diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala b/data/shared/src/main/scala/sigma/serialization/trees/QuadrupleSerializer.scala similarity index 74% rename from interpreter/shared/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala rename to data/shared/src/main/scala/sigma/serialization/trees/QuadrupleSerializer.scala index 586a353f0c..d3bdf580a0 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/trees/QuadrupleSerializer.scala @@ -1,13 +1,10 @@ -package sigmastate.serialization.trees +package sigma.serialization.trees -import sigma.ast.SType import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.Values._ -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{Quadruple, _} +import sigma.ast._ +import sigma.ast.syntax._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.SigmaByteWriter._ case class QuadrupleSerializer[S1 <: SType, S2 <: SType, S3 <: SType, S4 <: SType] (override val opDesc: QuadrupleCompanion, diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala b/data/shared/src/main/scala/sigma/serialization/trees/Relation2Serializer.scala similarity index 88% rename from interpreter/shared/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala rename to data/shared/src/main/scala/sigma/serialization/trees/Relation2Serializer.scala index 4887a1a1ae..6b7bca6426 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/trees/Relation2Serializer.scala @@ -1,13 +1,12 @@ -package sigmastate.serialization.trees +package sigma.serialization.trees import sigma.ast.{SBoolean, SType} import sigma.serialization.CoreByteWriter.{ArgInfo, Bits, DataInfo, maxBitsInfo} -import sigmastate.Values._ -import sigmastate._ -import sigmastate.serialization.OpCodes._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.serialization.ValueSerializer._ +import sigma.ast._ +import sigma.ast.syntax.SValue +import sigma.serialization.OpCodes._ +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, ValueSerializer} +import sigma.serialization.ValueSerializer._ import sigma.util.Extensions._ case class Relation2Serializer[S1 <: SType, S2 <: SType, R <: Value[SBoolean.type]] diff --git a/interpreter/shared/src/main/scala/sigmastate/utils/SparseArrayContainer.scala b/data/shared/src/main/scala/sigma/utils/SparseArrayContainer.scala similarity index 94% rename from interpreter/shared/src/main/scala/sigmastate/utils/SparseArrayContainer.scala rename to data/shared/src/main/scala/sigma/utils/SparseArrayContainer.scala index 4d159f89a6..dd65676687 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utils/SparseArrayContainer.scala +++ b/data/shared/src/main/scala/sigma/utils/SparseArrayContainer.scala @@ -1,8 +1,7 @@ -package sigmastate.utils +package sigma.utils -import sigma.ast.SType -import sigmastate.Values.Value -import sigmastate.serialization.ValueSerializer +import sigma.ast.{SType, Value} +import sigma.serialization.ValueSerializer import scala.reflect.ClassTag diff --git a/interpreter/jvm/src/main/scala/sigmastate/crypto/package.scala b/interpreter/jvm/src/main/scala/sigmastate/crypto/package.scala deleted file mode 100644 index 1b262e6639..0000000000 --- a/interpreter/jvm/src/main/scala/sigmastate/crypto/package.scala +++ /dev/null @@ -1,11 +0,0 @@ -package sigmastate - -import sigma.crypto.CryptoContextJvm -import sigma.crypto.Platform.Curve - -package object crypto { - /** This JVM specific methods are used in Ergo node which won't be JS cross-compiled. */ - implicit class BcDlogGroupOps(val group: BcDlogGroup) extends AnyVal { - def curve: Curve = group.ctx.asInstanceOf[CryptoContextJvm].curve - } -} diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala index d28afd59e9..f11981702d 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala @@ -1,22 +1,18 @@ package org.ergoplatform -import sigmastate.Values._ -import sigmastate._ -import sigmastate.eval.Extensions._ -import sigmastate.eval._ -import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv -import sigmastate.interpreter.{ContextExtension, ErgoTreeEvaluator, Interpreter, InterpreterContext} -import sigmastate.exceptions.InterpreterException -import sigmastate.serialization.OpCodes -import sigma.Coll -import sigma.{AnyValue, Header, PreHeader} import debox.cfor import sigma.Extensions.ArrayOps -import sigma.ast.{SBox, SCollection, SContext, SFunc, SGlobal, SInt, SType, SUnit} import sigma.ast.SType.{AnyOps, TypeCode} -import sigma.data.{AvlTreeData, CAvlTree, SigmaConstants} +import sigma.ast._ +import sigma.data.{AvlTreeData, CAvlTree, CSigmaDslBuilder, SigmaConstants} +import sigma.eval.Extensions.toAnyValue +import sigma.exceptions.InterpreterException +import sigma.interpreter.ContextExtension import sigma.validation.SigmaValidationSettings -import sigmastate.serialization.ValueCodes.OpCode +import sigma.{AnyValue, Coll, Header, PreHeader} +import sigmastate.eval.Extensions._ +import sigmastate.eval._ +import sigmastate.interpreter.InterpreterContext /** Represents a script evaluation context to be passed to a prover and a verifier to execute and * validate guarding proposition of input boxes of a transaction. @@ -170,7 +166,7 @@ class ErgoLikeContext(val lastBlockUtxoRoot: AvlTreeData, // as result selfBoxIndex is always (erroneously) returns -1 in ErgoTree v0, v1 val selfBox = boxesToSpend(selfIndex).toTestBox val ergoTreeVersion = currentErgoTreeVersion.getOrElse( - Interpreter.error(s"Undefined context property: currentErgoTreeVersion")) + syntax.error(s"Undefined context property: currentErgoTreeVersion")) CContext( dataInputs, headers, preHeader, inputs, outputs, preHeader.height, selfBox, selfIndex, avlTree, preHeader.minerPk.getEncoded, vars, activatedScriptVersion, ergoTreeVersion) @@ -246,119 +242,4 @@ object ErgoLikeContext { } } -/** When interpreted evaluates to a ByteArrayConstant built from Context.minerPubkey */ -case object MinerPubkey extends NotReadyValueByteArray with ValueCompanion { - override def opCode: OpCode = OpCodes.MinerPubkeyCode - /** Cost of calling Context.minerPubkey Scala method. */ - override val costKind = FixedCost(JitCost(20)) - override val opType = SFunc(SContext, SCollection.SByteArray) - override def companion = this - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(this.costKind) - E.context.minerPubKey - } -} - -/** When interpreted evaluates to a IntConstant built from Context.currentHeight */ -case object Height extends NotReadyValueInt with FixedCostValueCompanion { - override def companion = this - override def opCode: OpCode = OpCodes.HeightCode - /** Cost of: 1) Calling Context.HEIGHT Scala method. */ - override val costKind = FixedCost(JitCost(26)) - override val opType = SFunc(SContext, SInt) - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(this.costKind) - E.context.HEIGHT - } -} - -/** When interpreted evaluates to a collection of BoxConstant built from Context.boxesToSpend */ -case object Inputs extends LazyCollection[SBox.type] with FixedCostValueCompanion { - override def companion = this - override def opCode: OpCode = OpCodes.InputsCode - /** Cost of: 1) Calling Context.INPUTS Scala method. */ - override val costKind = FixedCost(JitCost(10)) - override def tpe = SCollection.SBoxArray - override val opType = SFunc(SContext, tpe) - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(this.costKind) - E.context.INPUTS - } -} - -/** When interpreted evaluates to a collection of BoxConstant built from Context.spendingTransaction.outputs */ -case object Outputs extends LazyCollection[SBox.type] with FixedCostValueCompanion { - override def companion = this - override def opCode: OpCode = OpCodes.OutputsCode - /** Cost of: 1) Calling Context.OUTPUTS Scala method. */ - override val costKind = FixedCost(JitCost(10)) - override def tpe = SCollection.SBoxArray - override val opType = SFunc(SContext, tpe) - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(this.costKind) - E.context.OUTPUTS - } -} - -/** When interpreted evaluates to a AvlTreeConstant built from Context.lastBlockUtxoRoot */ -case object LastBlockUtxoRootHash extends NotReadyValueAvlTree with ValueCompanion { - override def companion = this - override def opCode: OpCode = OpCodes.LastBlockUtxoRootHashCode - - /** Cost of: 1) Calling Context.LastBlockUtxoRootHash Scala method. */ - override val costKind = FixedCost(JitCost(15)) - override val opType = SFunc(SContext, tpe) - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(this.costKind) - E.context.LastBlockUtxoRootHash - } -} - - -/** When interpreted evaluates to a BoxConstant built from context.boxesToSpend(context.selfIndex) */ -case object Self extends NotReadyValueBox with FixedCostValueCompanion { - override def companion = this - override def opCode: OpCode = OpCodes.SelfCode - /** Cost of: 1) Calling Context.SELF Scala method. */ - override val costKind = FixedCost(JitCost(10)) - override val opType = SFunc(SContext, SBox) - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(this.costKind) - E.context.SELF - } -} - -/** When interpreted evaluates to the singleton instance of [[sigma.Context]]. - * Corresponds to `CONTEXT` variable in ErgoScript which can be used like `CONTEXT.headers`. - */ -case object Context extends NotReadyValue[SContext.type] with ValueCompanion { - override def companion = this - override def opCode: OpCode = OpCodes.ContextCode - - /** Cost of: 1) accessing global Context instance. */ - override val costKind = FixedCost(JitCost(1)) - - override def tpe: SContext.type = SContext - override val opType: SFunc = SFunc(SUnit, SContext) - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(this.costKind) - E.context - } -} - -/** When interpreted evaluates to the singleton instance of [[sigma.SigmaDslBuilder]]. - * Corresponds to `Global` variable in ErgoScript which can be used like `Global.groupGenerator`. - */ -case object Global extends NotReadyValue[SGlobal.type] with FixedCostValueCompanion { - override def companion = this - override def opCode: OpCode = OpCodes.GlobalCode - /** Cost of: 1) accessing Global instance. */ - override val costKind = FixedCost(JitCost(5)) - override def tpe: SGlobal.type = SGlobal - override val opType: SFunc = SFunc(SUnit, SGlobal) - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(this.costKind) - CSigmaDslBuilder - } -} diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala index 2a5898d888..e986905fb0 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala @@ -1,9 +1,9 @@ package org.ergoplatform import sigma.ast.SCollection.SByteArray -import sigmastate.Values._ +import sigma.ast._ +import sigma.ast.syntax._ import sigmastate.interpreter.Interpreter -import sigmastate.utxo._ /** Base class of verifying interpreter which expects ErgoLikeContext as input of diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoTreePredef.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoTreePredef.scala index 29a4b2738f..8bba479745 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoTreePredef.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoTreePredef.scala @@ -2,15 +2,13 @@ package org.ergoplatform import org.ergoplatform.settings.MonetarySettings import sigma.ast.SCollection.SByteArray -import sigma.ast.{SBox, SInt, SLong, SSigmaProp} +import sigma.ast._ +import sigma.ast.syntax._ import sigma.data.ProveDlog -import sigmastate.ErgoTree.{HeaderType, ZeroHeader} -import sigmastate.crypto.CryptoConstants -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.Values.{FalseSigmaProp, IntArrayConstant, IntConstant, LongConstant, SigmaPropConstant, SigmaPropValue, TrueSigmaProp, Value} -import sigmastate.utxo._ -import sigmastate.{ErgoTree, _} -import sigmastate.lang.Terms.ValueOps +import ErgoTree.{HeaderType, ZeroHeader} +import sigma.crypto.CryptoConstants +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer +import sigmastate._ object ErgoTreePredef { /** Create ErgoTree with `false` proposition, which is never true. @@ -43,7 +41,7 @@ object ErgoTreePredef { // first segregated constant is delta, so key is second constant val positions = IntArrayConstant(Array[Int](1)) val minerPubkeySigmaProp = CreateProveDlog(DecodePoint(minerPkBytesVal)) - val newVals = Values.ConcreteCollection(Array[SigmaPropValue](minerPubkeySigmaProp), SSigmaProp) + val newVals = ConcreteCollection(Array[SigmaPropValue](minerPubkeySigmaProp), SSigmaProp) SubstConstants(genericMinerPropBytes, positions, newVals) } diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/dsl/AvlTreeHelpers.scala b/interpreter/shared/src/main/scala/org/ergoplatform/dsl/AvlTreeHelpers.scala index 69fea7f015..c3e1ad43af 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/dsl/AvlTreeHelpers.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/dsl/AvlTreeHelpers.scala @@ -1,13 +1,12 @@ package org.ergoplatform.dsl import sigma.Coll -import sigmastate.eval.CSigmaDslBuilder import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.AvlTree import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert} -import CSigmaDslBuilder.Colls -import sigma.data.{AvlTreeData, AvlTreeFlags, CAvlTree} +import sigma.data.CSigmaDslBuilder.Colls +import sigma.data.{AvlTreeData, AvlTreeFlags, CAvlTree, CSigmaDslBuilder} object AvlTreeHelpers { diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/settings/MonetarySettings.scala b/interpreter/shared/src/main/scala/org/ergoplatform/settings/MonetarySettings.scala index a20bdd8baa..60ced82c88 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/settings/MonetarySettings.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/settings/MonetarySettings.scala @@ -1,8 +1,8 @@ package org.ergoplatform.settings -import sigmastate.ErgoTree import org.ergoplatform.ErgoTreePredef import org.ergoplatform.mining.emission.EmissionRules +import sigma.ast.ErgoTree /** * Configuration file for monetary settings of Ergo chain diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/validation/RuleStatusSerializer.scala b/interpreter/shared/src/main/scala/org/ergoplatform/validation/RuleStatusSerializer.scala index deff794ba6..081d573cf1 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/validation/RuleStatusSerializer.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/validation/RuleStatusSerializer.scala @@ -1,8 +1,7 @@ package org.ergoplatform.validation import sigma.validation.{ChangedRule, DisabledRule, EnabledRule, ReplacedRule, RuleStatus} -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} object RuleStatusSerializer extends SigmaSerializer[RuleStatus, RuleStatus] { import RuleStatus._ diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializer.scala b/interpreter/shared/src/main/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializer.scala index d4d01f9a52..23c18a7b05 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializer.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializer.scala @@ -1,8 +1,7 @@ package org.ergoplatform.validation -import sigma.serialization.SerializerException -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.serialization.{SerializerException, SigmaByteReader, SigmaByteWriter} +import sigma.serialization.SigmaSerializer import sigma.util.Extensions.IntOps import sigma.validation.{MapSigmaValidationSettings, SigmaValidationSettings} diff --git a/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala b/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala index e66547222a..8b18e20459 100644 --- a/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala +++ b/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala @@ -1,21 +1,11 @@ package sigmastate -import org.ergoplatform.ErgoBox.RegisterId -import sigma.reflection.ReflectionData.registerClassEntry -import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} -import sigma.Coll -import sigma.ast.SCollection.{SBooleanArray, SByteArray, SIntArray} -import sigma.ast.{SAny, SAvlTree, SCollectionType, SFunc, SNumericType, SOption, SSigmaProp, STuple, SType, STypeParam, STypeVar} +import sigma.SigmaDataReflection import sigma.data.{CAND, COR, CTHRESHOLD} -import sigma.{AvlTree, SigmaDslBuilder} -import sigmastate.SAvlTreeMethods.KeyValueColl -import sigmastate.Values._ -import sigmastate.crypto.VerifierMessage.Challenge +import sigma.reflection.mkConstructor +import sigma.reflection.ReflectionData.registerClassEntry import sigmastate.crypto.GF2_192_Poly -import sigmastate.interpreter.ErgoTreeEvaluator -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueCodes.OpCode -import sigmastate.utxo._ +import sigmastate.crypto.VerifierMessage.Challenge /** Reflection metadata for `interpreter` module. * For each class of this module that needs reflection metadata, @@ -23,71 +13,7 @@ import sigmastate.utxo._ * Only information that is needed at runtime is registered. */ object InterpreterReflection { - val reflection = ReflectionData - - registerClassEntry(classOf[AND], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new AND(args(0).asInstanceOf[Value[SBooleanArray]]) - } - ) - ) - - registerClassEntry(classOf[ArithOp[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Byte])) { args => - new ArithOp(args(0).asInstanceOf[SValue], args(1).asInstanceOf[SValue], args(2).asInstanceOf[OpCode]) - } - ) - ) - - registerClassEntry(classOf[AtLeast], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new AtLeast(args(0).asInstanceOf[IntValue], args(1).asInstanceOf[CollectionValue[SSigmaProp.type]]) - } - ) - ) - - registerClassEntry(classOf[BinAnd], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new BinAnd(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[BoolValue]) - } - ) - ) - - registerClassEntry(classOf[BinOr], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new BinOr(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[BoolValue]) - } - ) - ) - - registerClassEntry(classOf[BinXor], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new BinXor(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[BoolValue]) - } - ) - ) - - registerClassEntry(classOf[BoolToSigmaProp], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new BoolToSigmaProp(args(0).asInstanceOf[BoolValue]) - } - ) - ) - - registerClassEntry(classOf[ByteArrayToBigInt], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new ByteArrayToBigInt(args(0).asInstanceOf[Value[SByteArray]]) - } - ) - ) + val reflection = SigmaDataReflection registerClassEntry(classOf[CAndUncheckedNode], constructors = Array( @@ -153,555 +79,4 @@ object InterpreterReflection { } ) ) - - registerClassEntry(classOf[CalcBlake2b256], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new CalcBlake2b256(args(0).asInstanceOf[Value[SByteArray]]) - } - ) - ) - - registerClassEntry(classOf[CalcSha256], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new CalcSha256(args(0).asInstanceOf[Value[SByteArray]]) - } - ) - ) - - registerClassEntry(classOf[CreateProveDHTuple], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => - new CreateProveDHTuple(args(0).asInstanceOf[GroupElementValue], - args(1).asInstanceOf[GroupElementValue], - args(2).asInstanceOf[GroupElementValue], - args(3).asInstanceOf[GroupElementValue]) - } - ) - ) - - registerClassEntry(classOf[Downcast[_,_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[SNumericType])) { args => - new Downcast(args(0).asInstanceOf[Value[SNumericType]], args(1).asInstanceOf[SNumericType]) - } - ) - ) - - registerClassEntry(classOf[EQ[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new EQ(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) - } - ) - ) - - registerClassEntry(classOf[Exponentiate], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new Exponentiate(args(0).asInstanceOf[GroupElementValue], args(1).asInstanceOf[BigIntValue]) - } - ) - ) - - registerClassEntry(classOf[GE[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new GE(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) - } - ) - ) - - registerClassEntry(classOf[GT[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new GT(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) - } - ) - ) - - registerClassEntry(classOf[If[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => - new If(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[SAnyValue], args(2).asInstanceOf[SAnyValue]) - } - ) - ) - - registerClassEntry(classOf[LE[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new LE(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) - } - ) - ) - - registerClassEntry(classOf[LT[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new LT(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) - } - ) - ) - - registerClassEntry(classOf[LogicalNot], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new LogicalNot(args(0).asInstanceOf[BoolValue]) - } - ) - ) - - registerClassEntry(classOf[MultiplyGroup], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new MultiplyGroup(args(0).asInstanceOf[GroupElementValue], args(1).asInstanceOf[GroupElementValue]) - } - ) - ) - - registerClassEntry(classOf[NEQ[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new NEQ(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) - } - ) - ) - - registerClassEntry(classOf[Negation[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new Negation(args(0).asInstanceOf[SAnyValue]) - } - ) - ) - - registerClassEntry(classOf[OR], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new OR(args(0).asInstanceOf[Value[SBooleanArray]]) - } - ) - ) - - { val clazz = SAvlTreeMethods.getClass - registerClassEntry(clazz, - methods = Map( - mkMethod(clazz, "update_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTreeMethods.type].update_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[AvlTree], - args(2).asInstanceOf[KeyValueColl], - args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "contains_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTreeMethods.type].contains_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[AvlTree], - args(2).asInstanceOf[Coll[Byte]], - args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "get_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTreeMethods.type].get_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[AvlTree], - args(2).asInstanceOf[Coll[Byte]], - args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "getMany_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTreeMethods.type].getMany_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[AvlTree], - args(2).asInstanceOf[Coll[Coll[Byte]]], - args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "remove_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTreeMethods.type].remove_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[AvlTree], - args(2).asInstanceOf[Coll[Coll[Byte]]], - args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "insert_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTreeMethods.type].insert_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[AvlTree], - args(2).asInstanceOf[KeyValueColl], - args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) - } - ) - ) - } - - { val clazz = SCollectionMethods.getClass - registerClassEntry(clazz, - methods = Map( - mkMethod(clazz, "zip_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollectionMethods.type].zip_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[Coll[Any]], - args(2).asInstanceOf[Coll[Any]])(args(3).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "getOrElse_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Int], classOf[java.lang.Object], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollectionMethods.type].getOrElse_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[Coll[Any]], - args(2).asInstanceOf[Int], - args(3).asInstanceOf[Any])(args(4).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "patch_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Int], classOf[Coll[_]], classOf[Int], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollectionMethods.type].patch_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[Coll[Any]], - args(2).asInstanceOf[Int], - args(3).asInstanceOf[Coll[Any]], - args(4).asInstanceOf[Int])(args(5).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "map_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Function1[_,_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollectionMethods.type].map_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[Coll[Any]], - args(2).asInstanceOf[Any => Any])(args(3).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "updated_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Int], classOf[java.lang.Object], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollectionMethods.type].updated_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[Coll[Any]], - args(2).asInstanceOf[Int], - args(3))(args(4).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "indexOf_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[java.lang.Object], classOf[Int], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollectionMethods.type].indexOf_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[Coll[Any]], args(2), args(3).asInstanceOf[Int])(args(4).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "updateMany_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollectionMethods.type].updateMany_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[Coll[Any]], - args(2).asInstanceOf[Coll[Int]], - args(3).asInstanceOf[Coll[Any]])(args(4).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "indices_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollectionMethods.type].indices_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[Coll[Any]])(args(2).asInstanceOf[ErgoTreeEvaluator]) - }, - mkMethod(clazz, "flatMap_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Function1[_,_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollectionMethods.type].flatMap_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[Coll[Any]], args(2).asInstanceOf[Any => Coll[Any]])(args(3).asInstanceOf[ErgoTreeEvaluator]) - } - ) - ) - } - - { val clazz = SGlobalMethods.getClass - registerClassEntry(clazz, - methods = Map( - mkMethod(clazz, "xor_eval", Array[Class[_]](classOf[MethodCall], classOf[SigmaDslBuilder], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SGlobalMethods.type].xor_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[SigmaDslBuilder], - args(2).asInstanceOf[Coll[Byte]], - args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) - } - ) - ) - } - - registerClassEntry(classOf[SigmaAnd], - constructors = Array( - mkConstructor(Array(classOf[Seq[_]])) { args => - new SigmaAnd(args(0).asInstanceOf[Seq[SigmaPropValue]]) - } - ) - ) - - registerClassEntry(classOf[SigmaOr], - constructors = Array( - mkConstructor(Array(classOf[Seq[_]])) { args => - new SigmaOr(args(0).asInstanceOf[Seq[SigmaPropValue]]) - } - ) - ) - - registerClassEntry(classOf[SubstConstants[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => - new SubstConstants(args(0).asInstanceOf[Value[SByteArray]], - args(1).asInstanceOf[Value[SIntArray]], - args(2).asInstanceOf[CollectionValue[SType]]) - } - ) - ) - - registerClassEntry(classOf[Upcast[_,_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[SNumericType])) { args => - new Upcast(args(0).asInstanceOf[Value[SNumericType]], args(1).asInstanceOf[SNumericType]) - } - ) - ) - - registerClassEntry(classOf[BlockValue], - constructors = Array( - mkConstructor(Array(classOf[IndexedSeq[_]], classOf[Value[_]])) { args => - new BlockValue(args(0).asInstanceOf[IndexedSeq[BlockItem]], args(1).asInstanceOf[SValue]) - } - ) - ) - - registerClassEntry(classOf[ConcreteCollection[_]], - constructors = Array( - mkConstructor(Array(classOf[Seq[_]], classOf[SType])) { args => - new ConcreteCollection(args(0).asInstanceOf[Seq[SValue]], args(1).asInstanceOf[SType]) - } - ) - ) - - registerClassEntry(classOf[FuncValue], - constructors = Array( - mkConstructor(Array(classOf[IndexedSeq[_]], classOf[Value[_]])) { args => - new FuncValue(args(0).asInstanceOf[IndexedSeq[(Int, SType)]], args(1).asInstanceOf[SValue]) - } - ) - ) - - registerClassEntry(classOf[Tuple], - constructors = Array( - mkConstructor(Array(classOf[IndexedSeq[_]])) { args => - new Tuple(args(0).asInstanceOf[IndexedSeq[SValue]]) - } - ) - ) - - registerClassEntry(classOf[ValDef], - constructors = Array( - mkConstructor(Array(classOf[Int], classOf[Seq[_]], classOf[Value[_]])) { args => - new ValDef(args(0).asInstanceOf[Int], args(1).asInstanceOf[Seq[STypeVar]], args(2).asInstanceOf[SValue]) - } - ) - ) - - registerClassEntry(classOf[Apply], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[IndexedSeq[_]])) { args => - new Apply(args(0).asInstanceOf[SValue], args(1).asInstanceOf[IndexedSeq[SValue]]) - } - ) - ) - - registerClassEntry(classOf[ApplyTypes], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Seq[_]])) { args => - new ApplyTypes(args(0).asInstanceOf[SValue], args(1).asInstanceOf[Seq[SType]]) - } - ) - ) - - registerClassEntry(classOf[Block], - constructors = Array( - mkConstructor(Array(classOf[Seq[_]], classOf[Value[_]])) { args => - new Block(args(0).asInstanceOf[Seq[Val]], args(1).asInstanceOf[SValue]) - } - ) - ) - - registerClassEntry(classOf[Lambda], - constructors = Array( - mkConstructor(Array(classOf[Seq[_]], classOf[IndexedSeq[_]], classOf[SType], classOf[Option[_]])) { args => - new Lambda(args(0).asInstanceOf[Seq[STypeParam]], - args(1).asInstanceOf[IndexedSeq[(String, SType)]], - args(2).asInstanceOf[SType], - args(3).asInstanceOf[Option[SValue]]) - } - ) - ) - - registerClassEntry(classOf[MethodCall], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[SMethod], classOf[IndexedSeq[_]], classOf[scala.collection.immutable.Map[_,_]])) { args => - new MethodCall(args(0).asInstanceOf[SValue], - args(1).asInstanceOf[SMethod], - args(2).asInstanceOf[IndexedSeq[SValue]], - args(3).asInstanceOf[Map[STypeVar,SType]]) - } - ) - ) - - registerClassEntry(classOf[MethodCallLike], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[java.lang.String], classOf[IndexedSeq[_]], classOf[SType])) { args => - new MethodCallLike(args(0).asInstanceOf[SValue], - args(1).asInstanceOf[String], - args(2).asInstanceOf[IndexedSeq[SValue]], - args(3).asInstanceOf[SType]) - } - ) - ) - - registerClassEntry(classOf[Select], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[java.lang.String], classOf[Option[_]])) { args => - new Select(args(0).asInstanceOf[SValue], args(1).asInstanceOf[String], args(2).asInstanceOf[Option[SType]]) - } - ) - ) - - registerClassEntry(classOf[ValNode], - constructors = Array( - mkConstructor(Array(classOf[java.lang.String], classOf[SType], classOf[Value[_]])) { args => - new ValNode(args(0).asInstanceOf[String], args(1).asInstanceOf[SType], args(2).asInstanceOf[SValue]) - } - ) - ) - - registerClassEntry(classOf[Append[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new Append(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[CollectionValue[SType]]) - } - ) - ) - - registerClassEntry(classOf[ByIndex[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Option[_]])) { args => - new ByIndex(args(0).asInstanceOf[CollectionValue[SType]], - args(1).asInstanceOf[IntValue], args(2).asInstanceOf[Option[SValue]]) - } - ) - ) - - registerClassEntry(classOf[Exists[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new Exists(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) - } - ) - ) - - registerClassEntry(classOf[ExtractAmount], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new ExtractAmount(args(0).asInstanceOf[BoxValue]) - } - ) - ) - - registerClassEntry(classOf[ExtractBytesWithNoRef], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new ExtractBytesWithNoRef(args(0).asInstanceOf[BoxValue]) - } - ) - ) - - registerClassEntry(classOf[ExtractCreationInfo], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new ExtractCreationInfo(args(0).asInstanceOf[BoxValue]) - } - ) - ) - - registerClassEntry(classOf[ExtractId], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new ExtractId(args(0).asInstanceOf[BoxValue]) - } - ) - ) - - registerClassEntry(classOf[ExtractRegisterAs[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[org.ergoplatform.ErgoBox.RegisterId], classOf[SOption[_]])) { args => - new ExtractRegisterAs(args(0).asInstanceOf[BoxValue], args(1).asInstanceOf[RegisterId], args(2).asInstanceOf[SOption[SAny.type]]) - } - ) - ) - - registerClassEntry(classOf[ExtractScriptBytes], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new ExtractScriptBytes(args(0).asInstanceOf[BoxValue]) - } - ) - ) - - registerClassEntry(classOf[Filter[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new Filter(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) - } - ) - ) - - registerClassEntry(classOf[Fold[_,_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => - new Fold(args(0).asInstanceOf[CollectionValue[SType]], - args(1).asInstanceOf[SValue], args(2).asInstanceOf[Value[SFunc]]) - } - ) - ) - - registerClassEntry(classOf[ForAll[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new ForAll(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) - } - ) - ) - - registerClassEntry(classOf[MapCollection[_,_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new MapCollection(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) - } - ) - ) - - registerClassEntry(classOf[OptionGet[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new OptionGet(args(0).asInstanceOf[Value[SOption[SType]]]) - } - ) - ) - - registerClassEntry(classOf[OptionGetOrElse[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => - new OptionGetOrElse(args(0).asInstanceOf[Value[SOption[SType]]], args(1).asInstanceOf[SValue]) - } - ) - ) - - registerClassEntry(classOf[OptionIsDefined[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new OptionIsDefined(args(0).asInstanceOf[Value[SOption[SType]]]) - } - ) - ) - - registerClassEntry(classOf[SelectField], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Byte])) { args => - new SelectField(args(0).asInstanceOf[Value[STuple]], args(1).asInstanceOf[Byte]) - } - ) - ) - - registerClassEntry(classOf[SigmaPropBytes], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new SigmaPropBytes(args(0).asInstanceOf[SigmaPropValue]) - } - ) - ) - - registerClassEntry(classOf[SizeOf[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]])) { args => - new SizeOf(args(0).asInstanceOf[CollectionValue[SType]]) - } - ) - ) - - registerClassEntry(classOf[Slice[_]], - constructors = Array( - mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => - new Slice(args(0).asInstanceOf[CollectionValue[SType]], - args(1).asInstanceOf[IntValue], args(2).asInstanceOf[IntValue]) - } - ) - ) } diff --git a/interpreter/shared/src/main/scala/sigmastate/SigSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/SigSerializer.scala index 1823189bd0..fabd120d1c 100644 --- a/interpreter/shared/src/main/scala/sigmastate/SigSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/SigSerializer.scala @@ -1,18 +1,19 @@ -package sigmastate +package sigma.serialization import debox.cfor import scorex.util.encode.Base16 import sigma.Extensions.ArrayOps +import sigma.ast.{FixedCost, JitCost, NamedDesc, OperationCostInfo, PerItemCost} +import sigma.crypto.{BigIntegers, CryptoConstants} import sigma.data.{CAND, COR, CTHRESHOLD, ProveDHTuple, ProveDlog, SigmaBoolean} -import sigma.serialization.SerializerException import sigma.util.safeNewArray +import sigmastate.{CAndUncheckedNode, COrUncheckedNode, CThresholdUncheckedNode, NoProof, UncheckedDiffieHellmanTuple, UncheckedSchnorr, UncheckedSigmaTree, UncheckedTree} import sigmastate.crypto.DLogProtocol.SecondDLogProverMessage import sigmastate.crypto.VerifierMessage.Challenge -import sigmastate.crypto.{BigIntegers, CryptoConstants, GF2_192_Poly, SecondDHTupleProverMessage} -import sigmastate.interpreter.ErgoTreeEvaluator.{fixedCostOp, perItemCostOp} -import sigmastate.interpreter.{ErgoTreeEvaluator, NamedDesc, OperationCostInfo} -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{Helpers, SigmaByteReader, SigmaByteWriter} +import sigmastate.crypto.{GF2_192_Poly, SecondDHTupleProverMessage} +import sigmastate.interpreter.CErgoTreeEvaluator.{fixedCostOp, perItemCostOp} +import sigmastate.interpreter.CErgoTreeEvaluator +import sigmastate.utils.Helpers /** Contains implementation of signature (aka proof) serialization. * @@ -118,7 +119,7 @@ class SigSerializer { * the execution. * @return An instance of [[UncheckedTree]] i.e. either [[NoProof]] or [[UncheckedSigmaTree]] */ - def parseAndComputeChallenges(exp: SigmaBoolean, proof: Array[Byte])(implicit E: ErgoTreeEvaluator): UncheckedTree = { + def parseAndComputeChallenges(exp: SigmaBoolean, proof: Array[Byte])(implicit E: CErgoTreeEvaluator): UncheckedTree = { if (proof.isEmpty) NoProof else { @@ -180,7 +181,7 @@ class SigSerializer { def parseAndComputeChallenges( exp: SigmaBoolean, r: SigmaByteReader, - challengeOpt: Challenge = null)(implicit E: ErgoTreeEvaluator): UncheckedSigmaTree = { + challengeOpt: Challenge = null)(implicit E: CErgoTreeEvaluator): UncheckedSigmaTree = { // Verifier Step 2: Let e_0 be the challenge in the node here (e_0 is called "challenge" in the code) val challenge = if (challengeOpt == null) { Challenge @@ readBytesChecked(r, hashSize, diff --git a/interpreter/shared/src/main/scala/sigmastate/UnprovenTree.scala b/interpreter/shared/src/main/scala/sigmastate/UnprovenTree.scala index b3d72e9d87..fef3b963ec 100644 --- a/interpreter/shared/src/main/scala/sigmastate/UnprovenTree.scala +++ b/interpreter/shared/src/main/scala/sigmastate/UnprovenTree.scala @@ -2,16 +2,16 @@ package sigmastate import debox.cfor import sigma.data.{CAND, COR, CTHRESHOLD, ProveDHTuple, ProveDlog, SigmaBoolean, SigmaLeaf} -import sigmastate.ErgoTree.ZeroHeader -import sigmastate.Values.SigmaPropConstant +import sigma.ast.ErgoTree.ZeroHeader +import sigma.ast.{ErgoTree, FixedCost, JitCost, NamedDesc, OperationCostInfo, SigmaPropConstant} +import sigma.eval.ErgoTreeEvaluator import sigmastate.crypto.DLogProtocol.FirstDLogProverMessage import sigmastate.crypto.VerifierMessage.Challenge import sigmastate.crypto.{FirstDHTupleProverMessage, FirstProverMessage, GF2_192_Poly} -import sigmastate.interpreter.ErgoTreeEvaluator.fixedCostOp -import sigmastate.interpreter.{ErgoTreeEvaluator, NamedDesc, OperationCostInfo} -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.SigmaByteWriter +import sigmastate.interpreter.CErgoTreeEvaluator.fixedCostOp +import sigmastate.interpreter.CErgoTreeEvaluator +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer +import sigma.serialization.{SigmaByteWriter, SigmaSerializer} import java.math.BigInteger import scala.language.existentials diff --git a/interpreter/shared/src/main/scala/sigmastate/Values.scala b/interpreter/shared/src/main/scala/sigmastate/Values.scala deleted file mode 100644 index 8fc8c0de1f..0000000000 --- a/interpreter/shared/src/main/scala/sigmastate/Values.scala +++ /dev/null @@ -1,1032 +0,0 @@ -package sigmastate - -import debox.cfor -import sigma.Extensions.ArrayOps -import sigma.ast.SCollection.{SByteArray, SIntArray} -import sigma.ast.TypeCodes.ConstantCode -import sigma.ast._ -import sigma.crypto.EcPointType -import sigma.data.{Nullable, RType, SigmaBoolean, TrivialProp} -import sigma.kiama.rewriting.Rewriter.count -import sigma.util.CollectionUtil._ -import sigma.util.Extensions._ -import sigma.{AvlTree, Coll, Colls, Header, PreHeader, _} -import sigmastate.ErgoTree.HeaderType -import sigmastate.crypto.CryptoConstants -import sigmastate.eval._ -import sigmastate.exceptions.InterpreterException -import sigmastate.interpreter.ErgoTreeEvaluator._ -import sigmastate.interpreter.{CompanionDesc, ErgoTreeEvaluator, Interpreter, NamedDesc} -import sigmastate.lang.CheckingSigmaBuilder._ -import sigmastate.lang.SourceContext -import sigmastate.lang.Terms._ -import sigmastate.serialization.OpCodes._ -import sigmastate.serialization.ValueCodes.OpCode -import sigmastate.serialization._ -import sigmastate.utxo._ - -import java.math.BigInteger -import java.util.{Arrays, Objects} -import scala.collection.compat.immutable.ArraySeq -import scala.collection.mutable -import scala.language.implicitConversions - -object Values { - /** Force initialization of reflection. */ - val reflection = InterpreterReflection - - type SValue = Value[SType] - - /** Base class for all ErgoTree expression nodes. - * @see [[sigmastate.Values.ErgoTree]] - */ - abstract class Value[+S <: SType] extends SigmaNode { - /** The companion node descriptor with opCode, cost and other metadata. */ - def companion: ValueCompanion - - /** Unique id of the node class used in serialization of ErgoTree. */ - def opCode: OpCode = companion.opCode - - /** The type of the value represented by this node. If the value is an operation it is - * the type of operation result. */ - def tpe: S - - /** Every value represents an operation and that operation can be associated with a function type, - * describing functional meaning of the operation, kind of operation signature. - * Thus, we can obtain global operation identifiers by combining Value.opName with Value.opType, - * so that if (v1.opName == v2.opName) && (v1.opType == v2.opType) then v1 and v2 are functionally - * point-wise equivalent. - * This in particular means that if two _different_ ops have the same opType they _should_ have - * different opNames. - * Thus defined op ids are used in a v4.x Cost Model - a table of all existing primitives coupled with - * performance parameters. - * */ - def opType: SFunc - - /** Name of the operation. */ - def opName: String = this.getClass.getSimpleName - - /** Transforms this expression to SigmaProp expression or throws an exception. */ - def toSigmaProp: SigmaPropValue = this match { - case b if b.tpe == SBoolean => BoolToSigmaProp(this.asBoolValue) - case p if p.tpe == SSigmaProp => p.asSigmaProp - case _ => sys.error(s"Expected SBoolean or SSigmaProp typed value, but was: $this") - } - - /** Parser has some source information like line,column in the text. We need to keep it up until RuntimeCosting. - * The way to do this is to add Nullable property to every Value. Since Parser is always using SigmaBuilder - * to create nodes, - * Adding additional (implicit source: SourceContext) parameter to every builder method would pollute its API - * and also doesn't make sence during deserialization, where Builder is also used. - * We can assume some indirect mechanism to pass current source context into every mkXXX method of Builder. - * We can pass it using `scala.util.DynamicVariable` by wrapping each mkXXX call into `withValue { }` calls. - * The same will happen in Typer. - * We can take sourceContext from untyped nodes and use it while creating typed nodes. - * And we can make sourceContext of every Value writeOnce value, i.e. it will be Nullable.Null by default, - * but can be set afterwards, but only once. - * This property will not participate in equality and other operations, so will be invisible for existing code. - * But Builder can use it to set sourceContext if it is present. - */ - private[sigmastate] var _sourceContext: Nullable[SourceContext] = Nullable.None - def sourceContext: Nullable[SourceContext] = _sourceContext - def sourceContext_=(srcCtx: Nullable[SourceContext]): Unit = - if (_sourceContext.isEmpty) { - _sourceContext = srcCtx - } else { - sys.error("_sourceContext can be set only once") - } - - /** Defines an evaluation semantics of this tree node (aka Value or expression) in the given data environment. - * Should be implemented by all the ErgoTree nodes (aka operations). - * Thus, the ErgoTree interpreter implementation consists of combined implementations of this method. - * NOTE, this method shouldn't be called directly, instead use `evalTo` method. - * - * @param E Evaluator which defines evaluation context, cost accumulator, settings etc. - * @param env immutable map, which binds variables (given by ids) to the values - * @return the data value which is the result of evaluation - */ - protected def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = - sys.error(s"Should be overriden in ${this.getClass}: $this") - - /** Evaluates this node to the value of the given expected type. - * This method should called from all `eval` implementations. - * - * @tparam T expected type of the resulting value - * @param E Evaluator which defines evaluation context, cost accumulator, settings etc. - * @param env immutable map, which binds variables (given by ids) to the values - * @return the data value which is the result of evaluation - */ - @inline - final def evalTo[T](env: DataEnv)(implicit E: ErgoTreeEvaluator): T = { - if (E.settings.isMeasureOperationTime) E.profiler.onBeforeNode(this) - val v = eval(env) - if (E.settings.isMeasureOperationTime) E.profiler.onAfterNode(this) - v.asInstanceOf[T] - } - - /** Add the cost given by the kind to the accumulator and associate it with this operation - * node. - */ - @inline - final def addCost(costKind: FixedCost)(implicit E: ErgoTreeEvaluator): Unit = { - E.addCost(costKind, this.companion.opDesc) - } - - /** Add the cost given by the descriptor to the accumulator and associate it with this operation - * node. - */ - @inline - final def addCost[R](costKind: TypeBasedCost, tpe: SType)(block: () => R)(implicit E: ErgoTreeEvaluator): R = { - E.addTypeBasedCost(costKind, tpe, this.companion.opDesc)(block) - } - - /** Add the cost of a repeated operation to the accumulator and associate it with this - * operation. The number of items (loop iterations) is known in advance (like in - * Coll.map operation) - * - * @param costKind cost descriptor of the operation - * @param nItems number of operations known in advance (before loop execution) - */ - @inline - final def addSeqCostNoOp(costKind: PerItemCost, nItems: Int) - (implicit E: ErgoTreeEvaluator): Unit = { - E.addSeqCostNoOp(costKind, nItems, this.companion.opDesc) - } - - /** Add the cost of a repeated operation to the accumulator and associate it with this - * operation. The number of items (loop iterations) is known in advance (like in - * Coll.map operation) - * - * @param costKind cost descriptor of the operation - * @param nItems number of operations known in advance (before loop execution) - * @param block operation executed under the given cost - * @tparam R result type of the operation - */ - @inline - final def addSeqCost[R](costKind: PerItemCost, nItems: Int) - (block: () => R)(implicit E: ErgoTreeEvaluator): R = { - E.addSeqCost(costKind, nItems, this.companion.opDesc)(block) - } - } - - object Value { - type PropositionCode = Byte - - implicit def liftByte (n: Byte) : Value[SByte.type] = ByteConstant(n) - implicit def liftShort(n: Short): Value[SShort.type] = ShortConstant(n) - implicit def liftInt (n: Int) : Value[SInt.type] = IntConstant(n) - implicit def liftLong (n: Long) : Value[SLong.type] = LongConstant(n) - - implicit def liftByteArray(arr: Array[Byte]): Value[SByteArray] = ByteArrayConstant(arr) - - implicit def liftBigInt(arr: BigInt): Value[SBigInt.type] = BigIntConstant(arr) - - implicit def liftGroupElement(g: GroupElement): Value[SGroupElement.type] = GroupElementConstant(g) - implicit def liftECPoint(g: EcPointType): Value[SGroupElement.type] = GroupElementConstant(g) - - implicit def liftSigmaProp(g: SigmaProp): Value[SSigmaProp.type] = SigmaPropConstant(g) - implicit def liftSigmaBoolean(sb: SigmaBoolean): Value[SSigmaProp.type] = SigmaPropConstant(SigmaDsl.SigmaProp(sb)) - - object Typed { - def unapply(v: SValue): Option[(SValue, SType)] = Some((v, v.tpe)) - } - def notSupportedError(v: Any, opName: String) = - throw new IllegalArgumentException(s"Method $opName is not supported for node $v") - - /** Immutable empty array of values. Can be used to avoid allocation. */ - val EmptyArray = Array.empty[SValue] - - /** Immutable empty Seq of values. Can be used to avoid allocation. */ - val EmptySeq: IndexedSeq[SValue] = EmptyArray - - /** Traverses the given expression tree and counts the number of deserialization - * operations. If it is non-zero, returns true. */ - def hasDeserialize(exp: SValue): Boolean = { - val deserializeNode: PartialFunction[Any, Int] = { - case _: DeserializeContext[_] => 1 - case _: DeserializeRegister[_] => 1 - } - val c = count(deserializeNode)(exp) - c > 0 - } - - def typeError(node: SValue, evalResult: Any) = { - val tpe = node.tpe - throw new InterpreterException( - s"""Invalid type returned by evaluator: - | expression: $node - | expected type: $tpe - | resulting value: $evalResult - """.stripMargin) - } - - def typeError(tpe: SType, evalResult: Any) = { - throw new InterpreterException( - s"""Invalid type returned by evaluator: - | expected type: $tpe - | resulting value: $evalResult - """.stripMargin) - } - - def checkType(node: SValue, evalResult: Any) = { - val tpe = node.tpe - if (!SType.isValueOfType(evalResult, tpe)) - typeError(node, evalResult) - } - - def checkType(tpe: SType, evalResult: Any) = { - if (!SType.isValueOfType(evalResult, tpe)) - typeError(tpe, evalResult) - } - } - - /** Base class for all companion objects which are used as operation descriptors. */ - trait ValueCompanion extends SigmaNodeCompanion { - import ValueCompanion._ - /** Unique id of the node class used in serialization of ErgoTree. */ - def opCode: OpCode - - /** Returns cost descriptor of this operation. */ - def costKind: CostKind - - override def toString: String = s"${this.getClass.getSimpleName}(${opCode.toUByte})" - - def typeName: String = this.getClass.getSimpleName.replace("$", "") - - def init() { - if (this.opCode != 0 && _allOperations.contains(this.opCode)) - throw sys.error(s"Operation $this already defined") - _allOperations += (this.opCode -> this) - } - - init() - - val opDesc = CompanionDesc(this) - } - object ValueCompanion { - private val _allOperations: mutable.HashMap[Byte, ValueCompanion] = mutable.HashMap.empty - lazy val allOperations = _allOperations.toMap - } - - /** Should be inherited by companion objects of operations with fixed cost kind. */ - trait FixedCostValueCompanion extends ValueCompanion { - /** Returns cost descriptor of this operation. */ - override def costKind: FixedCost - } - - /** Should be inherited by companion objects of operations with per-item cost kind. */ - trait PerItemCostValueCompanion extends ValueCompanion { - /** Returns cost descriptor of this operation. */ - override def costKind: PerItemCost - } - - /** Base class for ErgoTree nodes which represents a data value which has already been - * evaluated and no further evaluation (aka reduction) is necessary by the interpreter. - * - * @see Constant, ConcreteCollection, Tuple - */ - abstract class EvaluatedValue[+S <: SType] extends Value[S] { - /** The evaluated data value of the corresponding underlying data type. */ - val value: S#WrappedType - - override def opType: SFunc = { - val resType = tpe match { - case ct : SCollection[_] => - SCollection(ct.typeParams.head.ident) - case ft @ SFunc(_, _, _) => - ft.getGenericType - case _ => tpe - } - SFunc(ArraySeq.empty, resType) - } - } - - /** Base class for all constant literals whose data value is already known and never - * changes. - * @see ConstantNode - */ - abstract class Constant[+S <: SType] extends EvaluatedValue[S] - - /** ErgoTree node which represents data literals, i.e. data values embedded in an - * expression. - * - * @param value data value of the underlying Scala type - * @param tpe type descriptor of the data value and also the type of the value - * represented by this node. - * @see Constant - */ - case class ConstantNode[S <: SType](value: S#WrappedType, tpe: S) extends Constant[S] { - require(sigma.crypto.Platform.isCorrectType(value, tpe), - s"Invalid type of constant value $value, expected type $tpe") - override def companion: ValueCompanion = Constant - override def opCode: OpCode = companion.opCode - override def opName: String = s"Const" - - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(Constant.costKind) - value - } - - override def equals(obj: scala.Any): Boolean = (obj != null) && (this.eq(obj.asInstanceOf[AnyRef]) || (obj match { - case c: Constant[_] => tpe == c.tpe && Objects.deepEquals(value, c.value) - case _ => false - })) - - override def hashCode(): Int = Arrays.deepHashCode(Array(value.asInstanceOf[AnyRef], tpe)) - - override def toString: String = tpe.asInstanceOf[SType] match { - case SGroupElement if value.isInstanceOf[GroupElement] => - s"ConstantNode(${value.asInstanceOf[GroupElement].showToString},$tpe)" - case SGroupElement => - sys.error(s"Invalid value in Constant($value, $tpe)") - case SInt => s"IntConstant($value)" - case SLong => s"LongConstant($value)" - case SBoolean if value == true => "TrueLeaf" - case SBoolean if value == false => "FalseLeaf" - case _ => s"ConstantNode($value,$tpe)" - } - } - - object Constant extends FixedCostValueCompanion { - override def opCode: OpCode = OpCode @@ ConstantCode - /** Cost of: returning value from Constant node. */ - override val costKind = FixedCost(JitCost(5)) - - /** Immutable empty array, can be used to save allocations in many places. */ - val EmptyArray = Array.empty[Constant[SType]] - - /** Immutable empty IndexedSeq, can be used to save allocations in many places. */ - val EmptySeq: IndexedSeq[Constant[SType]] = Array.empty[Constant[SType]] - - /** Helper factory method. */ - def apply[S <: SType](value: S#WrappedType, tpe: S): Constant[S] = ConstantNode(value, tpe) - - /** Recognizer of Constant tree nodes used in patterns. */ - def unapply[S <: SType](v: EvaluatedValue[S]): Option[(S#WrappedType, S)] = v match { - case ConstantNode(value, tpe) => Some((value, tpe)) - case _ => None - } - - } - - /** Placeholder for a constant in ErgoTree. Zero based index in ErgoTree.constants array. */ - case class ConstantPlaceholder[S <: SType](id: Int, override val tpe: S) extends Value[S] { - def opType = SFunc(SInt, tpe) - override def companion: ValueCompanion = ConstantPlaceholder - override protected def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - val c = E.constants(id) - addCost(ConstantPlaceholder.costKind) - val res = c.value - Value.checkType(c, res) - res - } - } - object ConstantPlaceholder extends ValueCompanion { - override def opCode: OpCode = ConstantPlaceholderCode - /** Cost of: accessing Constant in array by index. */ - override val costKind = FixedCost(JitCost(1)) - } - - trait NotReadyValue[S <: SType] extends Value[S] { - } - - /** Base class for references to context variables. */ - trait ContextVariable[S <: SType] extends NotReadyValue[S] { - } - - /** Reference a context variable by id. */ - trait TaggedVariable[T <: SType] extends ContextVariable[T] { - val varId: Byte - } - - case class TaggedVariableNode[T <: SType](varId: Byte, override val tpe: T) - extends TaggedVariable[T] { - override def companion = TaggedVariable - def opType: SFunc = Value.notSupportedError(this, "opType") - } - - object TaggedVariable extends ValueCompanion { - override def opCode: OpCode = TaggedVariableCode - override def costKind: CostKind = FixedCost(JitCost(1)) - def apply[T <: SType](varId: Byte, tpe: T): TaggedVariable[T] = - TaggedVariableNode(varId, tpe) - } - - /** High-level interface to internal representation of Unit constants in ErgoTree. */ - object UnitConstant { - /** ErgoTree node that represent a literal of Unit type. It is global immutable value - * which should be reused wherever necessary to avoid allocations. - */ - val instance = apply() - - /** Constucts a fresh new instance of Unit literal node. */ - def apply() = Constant[SUnit.type]((), SUnit) - - /** Recognizer to pattern match on Unit constant literal nodes (aka Unit constants). */ - def unapply(node: SValue): Boolean = node match { - case ConstantNode(_, SUnit) => true - case _ => false - } - } - - type BoolValue = Value[SBoolean.type] - type ByteValue = Value[SByte.type] - type ShortValue = Value[SShort.type] - type IntValue = Value[SInt.type] - type LongValue = Value[SLong.type] - type StringValue = Value[SString.type] - type BigIntValue = Value[SBigInt.type] - type BoxValue = Value[SBox.type] - type GroupElementValue = Value[SGroupElement.type] - type SigmaPropValue = Value[SSigmaProp.type] - type AvlTreeValue = Value[SAvlTree.type] - type SAnyValue = Value[SAny.type] - - type ByteConstant = Constant[SByte.type] - type ShortConstant = Constant[SShort.type] - type IntConstant = Constant[SInt.type] - type LongConstant = Constant[SLong.type] - type StringConstant = Constant[SString.type] - type BigIntConstant = Constant[SBigInt.type] - type BoxConstant = Constant[SBox.type] - type GroupElementConstant = Constant[SGroupElement.type] - type SigmaPropConstant = Constant[SSigmaProp.type] - type AvlTreeConstant = Constant[SAvlTree.type] - - object ByteConstant { - def apply(value: Byte): Constant[SByte.type] = Constant[SByte.type](value, SByte) - } - object ShortConstant { - def apply(value: Short): Constant[SShort.type] = Constant[SShort.type](value, SShort) - } - object IntConstant { - def apply(value: Int): Constant[SInt.type] = Constant[SInt.type](value, SInt) - def unapply(v: SValue): Option[Int] = v match { - case Constant(value: Int, SInt) => Some(value) - case _ => None - } - - def Zero = IntConstant(0) - } - object LongConstant { - def apply(value: Long): Constant[SLong.type] = Constant[SLong.type](value, SLong) - def unapply(v: SValue): Option[Long] = v match { - case Constant(value: Long, SLong) => Some(value) - case _ => None - } - } - object BigIntConstant { - def apply(value: BigInt): Constant[SBigInt.type] = Constant[SBigInt.type](value, SBigInt) - def apply(value: BigInteger): Constant[SBigInt.type] = Constant[SBigInt.type](SigmaDsl.BigInt(value), SBigInt) - def apply(value: Long): Constant[SBigInt.type] = Constant[SBigInt.type](SigmaDsl.BigInt(BigInteger.valueOf(value)), SBigInt) - } - - object StringConstant { - def apply(value: String): Constant[SString.type] = Constant[SString.type](value, SString) - def unapply(v: SValue): Option[String] = v match { - case Constant(value: String, SString) => Some(value) - case _ => None - } - } - - object BoxConstant { - def apply(value: Box): Constant[SBox.type] = Constant[SBox.type](value, SBox) - } - - object GroupElementConstant { - def apply(value: EcPointType): Constant[SGroupElement.type] = apply(SigmaDsl.GroupElement(value)) - def apply(value: GroupElement): Constant[SGroupElement.type] = Constant[SGroupElement.type](value, SGroupElement) - def unapply(v: SValue): Option[GroupElement] = v match { - case Constant(value: GroupElement, SGroupElement) => Some(value) - case _ => None - } - } - - val FalseSigmaProp = SigmaPropConstant(SigmaDsl.SigmaProp(TrivialProp.FalseProp)) - val TrueSigmaProp = SigmaPropConstant(SigmaDsl.SigmaProp(TrivialProp.TrueProp)) - - implicit def boolToSigmaProp(b: BoolValue): SigmaPropValue = BoolToSigmaProp(b) - - object SigmaPropConstant { - def apply(value: SigmaProp): Constant[SSigmaProp.type] = Constant[SSigmaProp.type](value, SSigmaProp) - def apply(value: SigmaBoolean): Constant[SSigmaProp.type] = Constant[SSigmaProp.type](SigmaDsl.SigmaProp(value), SSigmaProp) - def unapply(v: SValue): Option[SigmaProp] = v match { - case Constant(value: SigmaProp, SSigmaProp) => Some(value) - case _ => None - } - } - - object AvlTreeConstant { - def apply(value: AvlTree): Constant[SAvlTree.type] = Constant[SAvlTree.type](value, SAvlTree) - } - - object PreHeaderConstant { - def apply(value: PreHeader): Constant[SPreHeader.type] = Constant[SPreHeader.type](value, SPreHeader) - def unapply(v: SValue): Option[PreHeader] = v match { - case Constant(value: PreHeader, SPreHeader) => Some(value) - case _ => None - } - } - - object HeaderConstant { - def apply(value: Header): Constant[SHeader.type] = Constant[SHeader.type](value, SHeader) - def unapply(v: SValue): Option[Header] = v match { - case Constant(value: Header, SHeader) => Some(value) - case _ => None - } - } - - trait NotReadyValueInt extends NotReadyValue[SInt.type] { - override def tpe = SInt - } - - trait NotReadyValueLong extends NotReadyValue[SLong.type] { - override def tpe = SLong - } - - trait NotReadyValueBigInt extends NotReadyValue[SBigInt.type] { - override def tpe = SBigInt - } - - type TaggedBoolean = TaggedVariable[SBoolean.type] - type TaggedByte = TaggedVariable[SByte.type] - type TaggedShort = TaggedVariable[SShort.type] - type TaggedInt = TaggedVariable[SInt.type] - type TaggedLong = TaggedVariable[SLong.type] - type TaggedBigInt = TaggedVariable[SBigInt.type] - type TaggedBox = TaggedVariable[SBox.type] - type TaggedGroupElement = TaggedVariable[SGroupElement.type] - type TaggedSigmaProp = TaggedVariable[SSigmaProp.type] - type TaggedAvlTree = TaggedVariable[SAvlTree.type] - type TaggedByteArray = TaggedVariable[SCollection[SByte.type]] - - def TaggedBox(id: Byte): Value[SBox.type] = mkTaggedVariable(id, SBox) - def TaggedAvlTree(id: Byte): Value[SAvlTree.type] = mkTaggedVariable(id, SAvlTree) - - /** Base type for evaluated tree nodes of Coll type. */ - trait EvaluatedCollection[T <: SType, C <: SCollection[T]] extends EvaluatedValue[C] { - /** Type descriptor of the collection elements. */ - def elementType: T - } - - type CollectionConstant[T <: SType] = Constant[SCollection[T]] - type CollectionValue[T <: SType] = Value[SCollection[T]] - - object CollectionConstant { - def apply[T <: SType](value: Coll[T#WrappedType], elementType: T): Constant[SCollection[T]] = - Constant[SCollection[T]](value, SCollection(elementType)) - def unapply[T <: SType](node: Value[SCollection[T]]): Option[(Coll[T#WrappedType], T)] = node match { - case c: Constant[SCollection[a]] @unchecked if c.tpe.isCollection => - val v = c.value.asInstanceOf[Coll[T#WrappedType]] - val t = c.tpe.elemType - Some((v, t)) - case _ => None - } - } - - val ByteArrayTypeCode = (SCollectionType.CollectionTypeCode + SByte.typeCode).toByte - - object ByteArrayConstant { - def apply(value: Coll[Byte]): CollectionConstant[SByte.type] = CollectionConstant[SByte.type](value, SByte) - def apply(value: Array[Byte]): CollectionConstant[SByte.type] = CollectionConstant[SByte.type](value.toColl, SByte) - def unapply(node: SValue): Option[Coll[Byte]] = node match { - case coll: CollectionConstant[SByte.type] @unchecked => coll match { - case CollectionConstant(arr, SByte) => Some(arr) - case _ => None - } - case _ => None - } - } - - object ShortArrayConstant { - def apply(value: Coll[Short]): CollectionConstant[SShort.type] = CollectionConstant[SShort.type](value, SShort) - def apply(value: Array[Short]): CollectionConstant[SShort.type] = CollectionConstant[SShort.type](value.toColl, SShort) - def unapply(node: SValue): Option[Coll[Short]] = node match { - case coll: CollectionConstant[SShort.type] @unchecked => coll match { - case CollectionConstant(arr, SShort) => Some(arr) - case _ => None - } - case _ => None - } - } - - object IntArrayConstant { - def apply(value: Coll[Int]): CollectionConstant[SInt.type] = CollectionConstant[SInt.type](value, SInt) - def apply(value: Array[Int]): CollectionConstant[SInt.type] = CollectionConstant[SInt.type](value.toColl, SInt) - def unapply(node: SValue): Option[Coll[Int]] = node match { - case coll: CollectionConstant[SInt.type] @unchecked => coll match { - case CollectionConstant(arr, SInt) => Some(arr) - case _ => None - } - case _ => None - } - } - - object LongArrayConstant { - def apply(value: Coll[Long]): CollectionConstant[SLong.type] = CollectionConstant[SLong.type](value, SLong) - def apply(value: Array[Long]): CollectionConstant[SLong.type] = CollectionConstant[SLong.type](value.toColl, SLong) - def unapply(node: SValue): Option[Coll[Long]] = node match { - case coll: CollectionConstant[SLong.type] @unchecked => coll match { - case CollectionConstant(arr, SLong) => Some(arr) - case _ => None - } - case _ => None - } - } - - object BigIntArrayConstant { - def apply(value: Coll[BigInt]): CollectionConstant[SBigInt.type] = CollectionConstant[SBigInt.type](value, SBigInt) - def apply(value: Array[BigInt]): CollectionConstant[SBigInt.type] = CollectionConstant[SBigInt.type](value.toColl, SBigInt) - def unapply(node: SValue): Option[Coll[BigInt]] = node match { - case coll: CollectionConstant[SBigInt.type] @unchecked => coll match { - case CollectionConstant(arr, SBigInt) => Some(arr) - case _ => None - } - case _ => None - } - } - - val BoolArrayTypeCode = (SCollectionType.CollectionTypeCode + SBoolean.typeCode).toByte - - object BoolArrayConstant { - def apply(value: Coll[Boolean]): CollectionConstant[SBoolean.type] = CollectionConstant[SBoolean.type](value, SBoolean) - def apply(value: Array[Boolean]): CollectionConstant[SBoolean.type] = apply(value.toColl) - def unapply(node: SValue): Option[Coll[Boolean]] = node match { - case coll: CollectionConstant[SBoolean.type] @unchecked => coll match { - case CollectionConstant(arr, SBoolean) => Some(arr) - case _ => None - } - case _ => None - } - } - - trait NotReadyValueByteArray extends NotReadyValue[SByteArray] { - override def tpe = SByteArray - } - - trait NotReadyValueAvlTree extends NotReadyValue[SAvlTree.type] { - override def tpe = SAvlTree - } - - /** ErgoTree node that represents the operation of obtaining the generator of elliptic curve group. - * The generator g of the group is an element of the group such that, when written - * multiplicative form, every element of the group is a power of g. - */ - case object GroupGenerator extends EvaluatedValue[SGroupElement.type] with ValueCompanion { - override def opCode: OpCode = OpCodes.GroupGeneratorCode - override val costKind = FixedCost(JitCost(10)) - override def tpe = SGroupElement - override val value = SigmaDsl.GroupElement(CryptoConstants.dlogGroup.generator) - override def companion = this - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(costKind) - SigmaDsl.groupGenerator - } - } - - - trait NotReadyValueGroupElement extends NotReadyValue[SGroupElement.type] { - override def tpe = SGroupElement - } - - type BooleanConstant = Constant[SBoolean.type] - - object BooleanConstant { - def fromBoolean(v: Boolean): BooleanConstant = if (v) TrueLeaf else FalseLeaf - def apply(value: Boolean): BooleanConstant = Constant[SBoolean.type](value, SBoolean) - def unapply(v: SValue): Option[Boolean] = v match { - case Constant(value: Boolean, SBoolean) => Some(value) - case _ => None - } - } - - /** ErgoTree node which represents `true` literal. */ - object TrueLeaf extends ConstantNode[SBoolean.type](true, SBoolean) with ValueCompanion { - override def companion = this - override def opCode: OpCode = TrueCode - override def costKind: FixedCost = Constant.costKind - override def toString: String = "TrueLeaf" - } - - /** ErgoTree node which represents `false` literal. */ - object FalseLeaf extends ConstantNode[SBoolean.type](false, SBoolean) with ValueCompanion { - override def companion = this - override def opCode: OpCode = FalseCode - override def costKind: FixedCost = Constant.costKind - override def toString: String = "FalseLeaf" - } - - trait NotReadyValueBoolean extends NotReadyValue[SBoolean.type] { - override def tpe = SBoolean - } - - trait NotReadyValueBox extends NotReadyValue[SBox.type] { - def tpe = SBox - } - - /** ErgoTree node which converts a collection of expressions into a tuple of data values - * of different types. Each data value of the resulting collection is obtained by - * evaluating the corresponding expression in `items`. All items may have different - * types. - * - * @param items source collection of expressions - */ - case class Tuple(items: IndexedSeq[Value[SType]]) - extends EvaluatedValue[STuple] // note, this superclass is required as Tuple can be in a register - with EvaluatedCollection[SAny.type, STuple] { - override def companion = Tuple - override lazy val tpe = STuple(items.map(_.tpe)) - override def opType: SFunc = ??? - override def elementType: SAny.type = SAny - - override lazy val value = { - val xs = items.cast[EvaluatedValue[SAny.type]].map(_.value) - implicit val tAny: RType[Any] = sigma.AnyType - Colls.fromArray(xs.toArray) - } - - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - // in v5.0 version we support only tuples of 2 elements to be equivalent with v4.x - if (items.length != 2) - Interpreter.error(s"Invalid tuple $this") - - val item0 = items(0) - val x = item0.evalTo[Any](env) - Value.checkType(item0, x) - - val item1 = items(1) - val y = item1.evalTo[Any](env) - Value.checkType(item1, y) - - val res = (x, y) // special representation for pairs (to pass directly to Coll primitives) - - addCost(Tuple.costKind) - res - } - } - - object Tuple extends FixedCostValueCompanion { - override def opCode: OpCode = TupleCode - /** Cost of: 1) allocating a new tuple (of limited max size)*/ - override val costKind = FixedCost(JitCost(15)) - def apply(items: Value[SType]*): Tuple = Tuple(items.toIndexedSeq) - } - - /** ErgoTree node which converts a collection of expressions into a collection of data - * values. Each data value of the resulting collection is obtained by evaluating the - * corresponding expression in `items`. All items must have the same type. - * - * @param items source collection of expressions - * @param elementType type descriptor of elements in the resulting collection - */ - case class ConcreteCollection[V <: SType](items: Seq[Value[V]], elementType: V) - extends EvaluatedCollection[V, SCollection[V]] { -// TODO uncomment and make sure Ergo works with it, i.e. complex data types are never used for `items`. -// There is nothing wrong in using List, Vector and other fancy types as a concrete representation -// of `items`, but these types have sub-optimal performance (2-3x overhead comparing to WrappedArray) -// which is immediately visible in profile. -// NOTE, the assert below should be commented before production release. -// Is it there for debuging only, basically to catch call stacks where the fancy types may -// occasionally be used. -// assert( -// items.isInstanceOf[mutable.WrappedArray[_]] || -// items.isInstanceOf[ArrayBuffer[_]] || -// items.isInstanceOf[mutable.ArraySeq[_]], -// s"Invalid types of items ${items.getClass}") - - private val isBooleanConstants = elementType == SBoolean && items.forall(_.isInstanceOf[Constant[_]]) - override def companion = - if (isBooleanConstants) ConcreteCollectionBooleanConstant - else ConcreteCollection - - val tpe = SCollection[V](elementType) - implicit lazy val tElement: RType[V#WrappedType] = Evaluation.stypeToRType(elementType) - - // TODO refactor: this method is not used and can be removed - lazy val value = { - val xs = items.cast[EvaluatedValue[V]].map(_.value) - Colls.fromArray(xs.toArray(tElement.classTag)) - } - - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - val len = items.length - addCost(ConcreteCollection.costKind) - val is = Array.ofDim[V#WrappedType](len)(tElement.classTag) - cfor(0)(_ < len, _ + 1) { i => - val item = items(i) - val itemV = item.evalTo[V#WrappedType](env) - Value.checkType(item, itemV) // necessary because cast to V#WrappedType is erased - is(i) = itemV - } - Colls.fromArray(is) - } - } - object ConcreteCollection extends FixedCostValueCompanion { - override def opCode: OpCode = ConcreteCollectionCode - /** Cost of: allocating new collection - * @see ConcreteCollection_PerItem */ - override val costKind = FixedCost(JitCost(20)) - - def fromSeq[V <: SType](items: Seq[Value[V]])(implicit tV: V): ConcreteCollection[V] = - ConcreteCollection(items, tV) - - def fromItems[V <: SType](items: Value[V]*)(implicit tV: V): ConcreteCollection[V] = - ConcreteCollection(items, tV) - } - object ConcreteCollectionBooleanConstant extends ValueCompanion { - override def opCode: OpCode = ConcreteCollectionBooleanConstantCode - override def costKind = ConcreteCollection.costKind - } - - trait LazyCollection[V <: SType] extends NotReadyValue[SCollection[V]] - - implicit class CollectionOps[T <: SType](val coll: Value[SCollection[T]]) extends AnyVal { - def length: Int = matchCase(_.items.length, _.value.length, _.items.length) - def items = matchCase(_.items, _ => sys.error(s"Cannot get 'items' property of node $coll"), _.items) -// def isEvaluatedCollection = -// coll.evaluated && matchCase(_.items.forall(_.evaluated), _ => true, _.items.forall(_.evaluated)) - def matchCase[R]( - whenConcrete: ConcreteCollection[T] => R, - whenConstant: CollectionConstant[T] => R, - whenTuple: Tuple => R - ): R = coll match { - case cc: ConcreteCollection[T]@unchecked => whenConcrete(cc) - case const: CollectionConstant[T]@unchecked => whenConstant(const) - case tuple: Tuple => whenTuple(tuple) - case _ => sys.error(s"Unexpected node $coll") - } - } - - implicit class SigmaPropValueOps(val p: Value[SSigmaProp.type]) extends AnyVal { - def isProven: Value[SBoolean.type] = SigmaPropIsProven(p) - def propBytes: Value[SByteArray] = SigmaPropBytes(p) - def treeWithSegregation(header: HeaderType): ErgoTree = - ErgoTree.withSegregation(header, p) - } - - sealed trait BlockItem extends NotReadyValue[SType] { - def id: Int - def rhs: SValue - def isValDef: Boolean - } - object BlockItem { - /** Immutable empty array, can be used to save allocations in many places. */ - val EmptyArray = Array.empty[BlockItem] - - /** Immutable empty IndexedSeq to save allocations in many places. */ - val EmptySeq: IndexedSeq[BlockItem] = EmptyArray - } - - /** IR node for let-bound expressions `let x = rhs` which is ValDef, or `let f[T] = rhs` which is FunDef. - * These nodes are used to represent ErgoTrees after common sub-expression elimination. - * This representation is more compact in serialized form. - * @param id unique identifier of the variable in the current scope. */ - case class ValDef(override val id: Int, - tpeArgs: Seq[STypeVar], - override val rhs: SValue) extends BlockItem { - require(id >= 0, "id must be >= 0") - override def companion = if (tpeArgs.isEmpty) ValDef else FunDef - override def tpe: SType = rhs.tpe - override def isValDef: Boolean = tpeArgs.isEmpty - /** This is not used as operation, but rather to form a program structure */ - override def opType: SFunc = Value.notSupportedError(this, "opType") - } - object ValDef extends ValueCompanion { - override def opCode: OpCode = ValDefCode - override def costKind = Value.notSupportedError(this, "costKind") - def apply(id: Int, rhs: SValue): ValDef = ValDef(id, Nil, rhs) - } - object FunDef extends ValueCompanion { - override def opCode: OpCode = FunDefCode - override def costKind = Value.notSupportedError(this, "costKind") - def unapply(d: BlockItem): Option[(Int, Seq[STypeVar], SValue)] = d match { - case ValDef(id, targs, rhs) if !d.isValDef => Some((id, targs, rhs)) - case _ => None - } - } - - /** Special node which represents a reference to ValDef it was introduced as result of - * CSE. */ - case class ValUse[T <: SType](valId: Int, tpe: T) extends NotReadyValue[T] { - override def companion = ValUse - /** This is not used as operation, but rather to form a program structure */ - def opType: SFunc = Value.notSupportedError(this, "opType") - - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(ValUse.costKind) - val res = env.getOrElse(valId, error(s"cannot resolve $this")) - Value.checkType(this, res) - res - } - } - object ValUse extends FixedCostValueCompanion { - override def opCode: OpCode = ValUseCode - /** Cost of: 1) Lookup in immutable HashMap by valId: Int 2) alloc of Some(v) */ - override val costKind = FixedCost(JitCost(5)) - } - - /** The order of ValDefs in the block is used to assign ids to ValUse(id) nodes - * For all i: items(i).id == {number of ValDefs preceded in a graph} with respect to topological order. - * Specific topological order doesn't really matter, what is important is to preserve semantic linkage - * between ValUse(id) and ValDef with the corresponding id. - * This convention allow to valid serializing ids because we always serializing and deserializing - * in a fixed well defined order. - */ - case class BlockValue(items: IndexedSeq[BlockItem], result: SValue) extends NotReadyValue[SType] { - override def companion = BlockValue - def tpe: SType = result.tpe - - /** This is not used as operation, but rather to form a program structure */ - def opType: SFunc = Value.notSupportedError(this, "opType") - - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - var curEnv = env - val len = items.length - addSeqCostNoOp(BlockValue.costKind, len) - cfor(0)(_ < len, _ + 1) { i => - val vd = items(i).asInstanceOf[ValDef] - val v = vd.rhs.evalTo[Any](curEnv) - Value.checkType(vd, v) - E.addFixedCost(FuncValue.AddToEnvironmentDesc_CostKind, - FuncValue.AddToEnvironmentDesc) { - curEnv = curEnv + (vd.id -> v) - } - } - val res = result.evalTo[Any](curEnv) - Value.checkType(result, res) - res - } - } - object BlockValue extends ValueCompanion { - override def opCode: OpCode = BlockValueCode - override val costKind = PerItemCost( - baseCost = JitCost(1), perChunkCost = JitCost(1), chunkSize = 10) - } - /** - * @param args parameters list, where each parameter has an id and a type. - * @param body expression, which refers function parameters with ValUse. - */ - case class FuncValue(args: IndexedSeq[(Int,SType)], body: Value[SType]) extends NotReadyValue[SFunc] { - import FuncValue._ - override def companion = FuncValue - lazy val tpe: SFunc = { - val nArgs = args.length - val argTypes = new Array[SType](nArgs) - cfor(0)(_ < nArgs, _ + 1) { i => - argTypes(i) = args(i)._2 - } - SFunc(argTypes, body.tpe) - } - /** This is not used as operation, but rather to form a program structure */ - override def opType: SFunc = SFunc(ArraySeq.empty, tpe) - - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(FuncValue.costKind) - if (args.length == 1) { - val arg0 = args(0) - (vArg: Any) => { - Value.checkType(arg0._2, vArg) - var env1: DataEnv = null - E.addFixedCost(AddToEnvironmentDesc_CostKind, AddToEnvironmentDesc) { - env1 = env + (arg0._1 -> vArg) - } - val res = body.evalTo[Any](env1) - Value.checkType(body, res) - res - } - } else { - Interpreter.error(s"Function must have 1 argument, but was: $this") - } - } - } - object FuncValue extends FixedCostValueCompanion { - val AddToEnvironmentDesc = NamedDesc("AddToEnvironment") - /** Cost of: adding value to evaluator environment */ - val AddToEnvironmentDesc_CostKind = FixedCost(JitCost(5)) - override def opCode: OpCode = FuncValueCode - /** Cost of: 1) switch on the number of args 2) allocating a new Scala closure - * Old cost: ("Lambda", "() => (D1) => R", lambdaCost),*/ - override val costKind = FixedCost(JitCost(5)) - def apply(argId: Int, tArg: SType, body: SValue): FuncValue = - FuncValue(IndexedSeq((argId,tArg)), body) - } - - implicit class OptionValueOps[T <: SType](val p: Value[SOption[T]]) extends AnyVal { - def get: Value[T] = OptionGet(p) - def getOrElse(default: Value[T]): Value[T] = OptionGetOrElse(p, default) - def isDefined: Value[SBoolean.type] = OptionIsDefined(p) - } - - def GetVarBoolean(varId: Byte): GetVar[SBoolean.type] = GetVar(varId, SBoolean) - def GetVarByte(varId: Byte): GetVar[SByte.type] = GetVar(varId, SByte) - def GetVarShort(varId: Byte): GetVar[SShort.type] = GetVar(varId, SShort) - def GetVarInt(varId: Byte): GetVar[SInt.type] = GetVar(varId, SInt) - def GetVarLong(varId: Byte): GetVar[SLong.type] = GetVar(varId, SLong) - def GetVarBigInt(varId: Byte): GetVar[SBigInt.type] = GetVar(varId, SBigInt) - def GetVarBox(varId: Byte): GetVar[SBox.type] = GetVar(varId, SBox) - def GetVarSigmaProp(varId: Byte): GetVar[SSigmaProp.type] = GetVar(varId, SSigmaProp) - def GetVarByteArray(varId: Byte): GetVar[SCollection[SByte.type]] = GetVar(varId, SByteArray) - def GetVarIntArray(varId: Byte): GetVar[SCollection[SInt.type]] = GetVar(varId, SIntArray) - - -} diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/CryptoFunctions.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/CryptoFunctions.scala index ff8d395d44..5a579ffb2c 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/CryptoFunctions.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/CryptoFunctions.scala @@ -1,6 +1,7 @@ package sigmastate.crypto import scorex.crypto.hash.Blake2b256 +import sigma.crypto.CryptoConstants object CryptoFunctions { lazy val soundnessBytes: Int = CryptoConstants.soundnessBits / 8 diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/DLogProtocol.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/DLogProtocol.scala index f78578d4b1..7fa2dae3a1 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/DLogProtocol.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/DLogProtocol.scala @@ -1,36 +1,25 @@ package sigmastate.crypto import scorex.util.encode.Base16 -import sigma.SigmaProp -import sigma.crypto.EcPointType +import sigma.crypto.{BigIntegers, EcPointType} import sigma.data.ProveDlog import sigma.serialization.GroupElementSerializer -import sigmastate._ -import sigmastate.crypto.CryptoConstants.dlogGroup +import sigma.crypto.CryptoConstants.dlogGroup import sigmastate.crypto.VerifierMessage.Challenge -import sigmastate.eval._ import java.math.BigInteger +/** Implementation of sigma protocol steps using discrete logarithm problem in EC group. */ object DLogProtocol { - trait DLogSigmaProtocol extends SigmaProtocol[DLogSigmaProtocol] { - override type A = FirstDLogProverMessage - override type Z = SecondDLogProverMessage - } - - /** Helper extractor to match SigmaProp values and extract ProveDlog out of it. */ - object ProveDlogProp { - def unapply(p: SigmaProp): Option[ProveDlog] = SigmaDsl.toSigmaBoolean(p) match { - case d: ProveDlog => Some(d) - case _ => None - } - } - + /** Secret key of discrete logarithm signature protocol. + * @param w secret number in [0, q-1] + * where q - an order of DLog group. + */ case class DLogProverInput(w: BigInteger) extends SigmaProtocolPrivateInput[ProveDlog] { - import CryptoConstants.dlogGroup + import sigma.crypto.CryptoConstants.dlogGroup override lazy val publicImage: ProveDlog = { val g = dlogGroup.generator @@ -40,7 +29,7 @@ object DLogProtocol { object DLogProverInput { - import CryptoConstants.dlogGroup + import sigma.crypto.CryptoConstants.dlogGroup /** Create random secret in a range 0..q-1, where q - an order of DLog group. */ def random(): DLogProverInput = { @@ -50,8 +39,13 @@ object DLogProtocol { } } + /** First message of dlog-based sigma protocol. + * @param ecData commitment to randomness ecData = G^r, where + * G - generator of EC group, + * r - random number known only to prover from [0, q-1] range, + * where q - order of EC group. + */ case class FirstDLogProverMessage(ecData: EcPointType) extends FirstProverMessage { - override type SP = DLogSigmaProtocol override def bytes: Array[Byte] = { GroupElementSerializer.toBytes(ecData) } @@ -59,23 +53,35 @@ object DLogProtocol { override def toString = s"FirstDLogProverMessage(${Base16.encode(bytes)})" } - case class SecondDLogProverMessage(z: BigInt) extends SecondProverMessage { - override type SP = DLogSigmaProtocol - } + /** Second message of dlog-based sigma protocol. + * @param z response to the challenge from the verifier + * @see responseToChallenge() + */ + case class SecondDLogProverMessage(z: BigInt) extends SecondProverMessage - object DLogInteractiveProver extends SigmaProtocolProver { - import CryptoConstants.secureRandom + /** Prover operations of dlog-based sigma protocol. */ + object DLogProver extends SigmaProtocolProver { + import sigma.crypto.CryptoConstants.secureRandom + /** Generate a first prover message with a commitment to a secret random number. */ def firstMessage(): (BigInteger, FirstDLogProverMessage) = { - import CryptoConstants.dlogGroup + import sigma.crypto.CryptoConstants.dlogGroup - val qMinusOne = dlogGroup.order.subtract(BigInteger.ONE) - val r = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, secureRandom) - val a = dlogGroup.exponentiate(dlogGroup.generator, r) + val qMinusOne = dlogGroup.order.subtract(BigInteger.ONE) // q - 1 + val r = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, secureRandom) // r <- [0, q-1] + val a = dlogGroup.exponentiate(dlogGroup.generator, r) // g^r r -> FirstDLogProverMessage(a) } + /** Creates a second message of sigma protocol by computing + * `z = rnd + challenge * privateInput.w mod q`, where q - order of EC group. + * + * @param privateInput secret known only to prover from [0, q-1] range, + * @param rnd random number generated by the prover (secret random number used to + * compute commitment) + * @param challenge from the verifier (also computed by the prover in non-interactive case) + */ def secondMessage(privateInput: DLogProverInput, rnd: BigInteger, challenge: Challenge): SecondDLogProverMessage = { val z = responseToChallenge(privateInput, rnd, challenge) SecondDLogProverMessage(z) @@ -104,9 +110,9 @@ object DLogProtocol { * * g^z = a*h^e => a = g^z/h^e * - * @param proposition - * @param challenge - * @param secondMessage + * @param proposition proposition being proved + * @param challenge challenge from verifier + * @param secondMessage prover's response to the challenge * @return */ def computeCommitment(proposition: ProveDlog, @@ -115,6 +121,7 @@ object DLogProtocol { val g = dlogGroup.generator val h = proposition.value + // COMPUTE a = g^z / h^e dlogGroup.multiplyGroupElements( dlogGroup.exponentiate(g, secondMessage.z.underlying()), dlogGroup.inverseOf(dlogGroup.exponentiate(h, new BigInteger(1, challenge.toArray)))) diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/DiffieHellmanTupleProtocol.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/DiffieHellmanTupleProtocol.scala index 1a02d92020..ba1a6c2e0a 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/DiffieHellmanTupleProtocol.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/DiffieHellmanTupleProtocol.scala @@ -1,22 +1,13 @@ package sigmastate.crypto -import sigma.SigmaProp -import sigma.crypto.EcPointType +import sigma.crypto.{BigIntegers, CryptoConstants, EcPointType} import sigma.data.ProveDHTuple import sigma.serialization.GroupElementSerializer -import sigmastate.Values.Value.PropositionCode -import sigmastate._ import sigmastate.crypto.VerifierMessage.Challenge -import sigmastate.eval.SigmaDsl import java.math.BigInteger -trait DiffieHellmanTupleProtocol extends SigmaProtocol[DiffieHellmanTupleProtocol] { - override type A = FirstDHTupleProverMessage - override type Z = SecondDHTupleProverMessage -} - case class DiffieHellmanTupleProverInput(w: BigInteger, commonInput: ProveDHTuple) extends SigmaProtocolPrivateInput[ProveDHTuple] { @@ -43,13 +34,10 @@ object DiffieHellmanTupleProverInput { /** First message of Diffie Hellman tuple sigma protocol. * @param a commitment to secret randomness `a = g^r`, where `g` is default generator of the group * @param b commitment to secret randomness `b = h^r`, where `h` is another random generator of the group - * @see createRandomGenerator in [[sigmastate.crypto.CryptoConstants.dlogGroup]] + * @see createRandomGenerator in [[CryptoConstants.dlogGroup]] */ case class FirstDHTupleProverMessage(a: EcPointType, b: EcPointType) extends FirstProverMessage { - - override type SP = DiffieHellmanTupleProtocol - override def bytes: Array[Byte] = { GroupElementSerializer.toBytes(a) ++ GroupElementSerializer.toBytes(b) } @@ -62,19 +50,9 @@ case class FirstDHTupleProverMessage(a: EcPointType, b: EcPointType) * `w` is the prover's secret. * `q` is the group order */ -case class SecondDHTupleProverMessage(z: BigInteger) extends SecondProverMessage { - override type SP = DiffieHellmanTupleProtocol -} - -/** Helper extractor to match SigmaProp values and extract ProveDHTuple out of it. */ -object ProveDHTupleProp { - def unapply(p: SigmaProp): Option[ProveDHTuple] = SigmaDsl.toSigmaBoolean(p) match { - case d: ProveDHTuple => Some(d) - case _ => None - } -} +case class SecondDHTupleProverMessage(z: BigInteger) extends SecondProverMessage -object DiffieHellmanTupleInteractiveProver extends SigmaProtocolProver { +object DiffieHellmanTupleProver extends SigmaProtocolProver { import CryptoConstants.dlogGroup diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/SigmaProtocolFunctions.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/SigmaProtocolFunctions.scala index edfcf6bd68..3473f1e017 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/SigmaProtocolFunctions.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/SigmaProtocolFunctions.scala @@ -1,6 +1,6 @@ package sigmastate.crypto -import sigmastate.crypto.CryptoConstants.dlogGroup +import sigma.crypto.CryptoConstants.dlogGroup import sigmastate.crypto.VerifierMessage.Challenge import sigma.Coll import sigma.data.SigmaLeaf @@ -11,7 +11,6 @@ import java.math.BigInteger /* Abstracting Sigma protocols Functionality to get: - - Interactive Sigma protocols(via actors) - Zero-knowledge proof from a Sigma protocol - Non-interactive Sigma protocols - Commitment from any Sigma protocol @@ -37,24 +36,11 @@ object VerifierMessage { /** First message from the prover (message `a` of `SigmaProtocol`)*/ trait FirstProverMessage extends ProverMessage { - type SP <: SigmaProtocol[SP] - def bytes: Array[Byte] } /** Second message from the prover (message `z` of `SigmaProtocol`)*/ -trait SecondProverMessage extends ProverMessage { - type SP <: SigmaProtocol[SP] -} - -/** Abstract template for sigma protocols. - * For details see the following book - * [1] Efficient Secure Two-Party Protocols - Techniques and Constructions, p.150)*/ -trait SigmaProtocol[SP <: SigmaProtocol[SP]] { - type A <: FirstProverMessage - type Z <: SecondProverMessage -} - +trait SecondProverMessage extends ProverMessage trait SigmaProtocolPrivateInput[CI <: SigmaLeaf] { /** Public image generated from the secret. @@ -66,6 +52,9 @@ trait SigmaProtocolPrivateInput[CI <: SigmaLeaf] { def w: BigInteger } +/** Represents any prover of a sigma protocol. + * @see DLogInteractiveProver, DiffieHellmanTupleProver + */ trait SigmaProtocolProver { /** Computes response for the challenge in non-interactive sigma protocol. * @@ -79,10 +68,10 @@ trait SigmaProtocolProver { privateInput: SigmaProtocolPrivateInput[_ <: SigmaLeaf], rnd: BigInteger, challenge: Challenge): BigInteger = { - val q: BigInteger = dlogGroup.order + val q: BigInteger = dlogGroup.order // order of the group val e: BigInteger = new BigInteger(1, challenge.toArray) - val ew: BigInteger = e.multiply(privateInput.w).mod(q) - val z: BigInteger = rnd.add(ew).mod(q) + val ew: BigInteger = e.multiply(privateInput.w).mod(q) // e * w mod q + val z: BigInteger = rnd.add(ew).mod(q) // r + ew mod q z } } diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/CAvlTreeVerifier.scala b/interpreter/shared/src/main/scala/sigmastate/eval/CAvlTreeVerifier.scala new file mode 100644 index 0000000000..5739e65ade --- /dev/null +++ b/interpreter/shared/src/main/scala/sigmastate/eval/CAvlTreeVerifier.scala @@ -0,0 +1,59 @@ +package sigmastate.eval + +import scorex.crypto.authds.avltree.batch.{BatchAVLVerifier, Insert, Lookup, Remove, Update} +import scorex.crypto.authds.{ADDigest, ADKey, ADValue, SerializedAdProof} +import scorex.crypto.hash.{Blake2b256, Digest32} +import sigma.data.CAvlTree +import sigma.eval.AvlTreeVerifier +import sigma.{AvlTree, Coll} + +import scala.util.Try + +/** Implements operations of AVL tree verifier based on + * [[scorex.crypto.authds.avltree.batch.BatchAVLVerifier]]. + * + * @see BatchAVLVerifier, CAvlTreeVerifier + */ +class CAvlTreeVerifier private( + startingDigest: ADDigest, + proof: SerializedAdProof, + override val keyLength: Int, + override val valueLengthOpt: Option[Int]) + extends BatchAVLVerifier[Digest32, Blake2b256.type]( + startingDigest, proof, keyLength, valueLengthOpt) with AvlTreeVerifier { + def treeHeight: Int = rootNodeHeight + + override def performLookup(key: Array[Byte]): Try[Option[Array[Byte]]] = + performOneOperation(Lookup(ADKey @@ key)) + + override def performInsert(key: Array[Byte], value: Array[Byte]): Try[Option[Array[Byte]]] = + performOneOperation(Insert(ADKey @@ key, ADValue @@ value)) + + override def performUpdate(key: Array[Byte], value: Array[Byte]): Try[Option[Array[Byte]]] = + performOneOperation(Update(ADKey @@ key, ADValue @@ value)) + + override def performRemove(key: Array[Byte]): Try[Option[Array[Byte]]] = + performOneOperation(Remove(ADKey @@ key)) + + override def digest: Option[ADDigest] = super.digest + + /** Override default logging which outputs stack trace to the console. */ + override protected def logError(t: Throwable): Unit = {} +} + +object CAvlTreeVerifier { + /** Create an instance of [[CAvlTreeVerifier]] for the given tree and proof. + * Both tree and proof are immutable. + * + * @param tree represents a tree state to verify + * @param proof proof of tree operations leading to the state digest in the tree + * @return a new verifier instance + */ + def apply(tree: AvlTree, proof: Coll[Byte]): CAvlTreeVerifier = { + val treeData = tree.asInstanceOf[CAvlTree].treeData + val adProof = SerializedAdProof @@ proof.toArray + val bv = new CAvlTreeVerifier( + ADDigest @@ treeData.digest.toArray, adProof, treeData.keyLength, treeData.valueLengthOpt) + bv + } +} \ No newline at end of file diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/CContext.scala b/interpreter/shared/src/main/scala/sigmastate/eval/CContext.scala index a89ff4b4d4..418f9e8959 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/CContext.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/CContext.scala @@ -1,64 +1,14 @@ package sigmastate.eval import debox.cfor -import org.ergoplatform.ErgoBox -import org.ergoplatform.validation.ValidationRules -import scorex.crypto.authds.avltree.batch._ -import scorex.crypto.authds.{ADDigest, SerializedAdProof} -import scorex.crypto.hash.{Blake2b256, Digest32, Sha256} -import scorex.utils.{Ints, Longs} import sigma.Extensions.ArrayOps -import sigma.ast.SCollection.SByteArray -import sigma.ast.{SInt, STuple, SType} -import sigma.crypto.{EcPointType, Ecp} -import sigma.data.OverloadHack.Overloaded1 +import sigma._ import sigma.data._ -import sigma.serialization.GroupElementSerializer -import sigma.util.Extensions.BigIntegerOps -import sigma.validation.SigmaValidationSettings -import sigma.{VersionContext, _} -import sigmastate.Values.{ConstantNode, EvaluatedValue, SValue} -import sigmastate._ -import sigmastate.crypto.CryptoConstants -import sigmastate.eval.Extensions._ -import sigmastate.serialization.SigmaSerializer +import sigma.exceptions.InvalidType -import java.math.BigInteger -import java.util.Arrays import scala.annotation.unused import scala.reflect.ClassTag -/** Implements operations of AVL tree verifier based on - * [[scorex.crypto.authds.avltree.batch.BatchAVLVerifier]]. - * - * @see BatchAVLVerifier - */ -class AvlTreeVerifier private (startingDigest: ADDigest, - proof: SerializedAdProof, - override val keyLength: Int, - override val valueLengthOpt: Option[Int]) - extends BatchAVLVerifier[Digest32, Blake2b256.type]( - startingDigest, proof, keyLength, valueLengthOpt) { - def treeHeight: Int = rootNodeHeight - - /** Override default logging which outputs stack trace to the console. */ - override protected def logError(t: Throwable): Unit = {} -} -object AvlTreeVerifier { - /** Create an instance of [[AvlTreeVerifier]] for the given tree and proof. - * Both tree and proof are immutable. - * @param tree represents a tree state to verify - * @param proof proof of tree operations leading to the state digest in the tree - * @return a new verifier instance - */ - def apply(tree: AvlTree, proof: Coll[Byte]): AvlTreeVerifier = { - val treeData = tree.asInstanceOf[CAvlTree].treeData - val adProof = SerializedAdProof @@ proof.toArray - val bv = new AvlTreeVerifier( - ADDigest @@ treeData.digest.toArray, adProof, treeData.keyLength, treeData.valueLengthOpt) - bv - } -} /** This class represents context variable and register value of a functional type A => B. * When variable or register is accessed using `getVar[A => B](id).get` or @@ -115,224 +65,6 @@ object CFunc { val maxCost = 1000 } -/** A default implementation of [[PreHeader]] interface. - * @see [[PreHeader]] for detailed descriptions - */ -case class CPreHeader( - version: Byte, - parentId: Coll[Byte], - timestamp: Long, - nBits: Long, - height: Int, - minerPk: GroupElement, - votes: Coll[Byte] - ) extends PreHeader {} - -/** A default implementation of [[Header]] interface. - * @see [[Header]] for detailed descriptions - */ -case class CHeader( - id: Coll[Byte], - version: Byte, - parentId: Coll[Byte], - ADProofsRoot: Coll[Byte], - stateRoot: AvlTree, - transactionsRoot: Coll[Byte], - timestamp: Long, - nBits: Long, - height: Int, - extensionRoot: Coll[Byte], - minerPk: GroupElement, - powOnetimePk: GroupElement, - powNonce: Coll[Byte], - powDistance: BigInt, - votes: Coll[Byte] - ) extends Header { -} - -object CHeader { - val VotesSize: Int = SigmaConstants.VotesArraySize.value - val NonceSize: Int = SigmaConstants.AutolykosPowSolutionNonceArraySize.value -} - -/** A default implementation of [[SigmaDslBuilder]] interface. - * @see [[SigmaDslBuilder]] for detailed descriptions - */ -class CSigmaDslBuilder extends SigmaDslBuilder { dsl => - implicit val validationSettings: SigmaValidationSettings = ValidationRules.currentSettings - - override val Colls: CollBuilder = sigma.Colls - - override def BigInt(n: BigInteger): BigInt = CBigInt(n) - - override def toBigInteger(n: BigInt): BigInteger = n.asInstanceOf[CBigInt].wrappedValue - - /** Wraps the given elliptic curve point into GroupElement type. */ - def GroupElement(p: Ecp): GroupElement = p match { - case ept: EcPointType => CGroupElement(ept) - case m => sys.error(s"Point of type ${m.getClass} is not supported") - } - - /** Wraps the given sigma proposition into SigmaDsl value of type SigmaProp. */ - def SigmaProp(sigmaTree: SigmaBoolean): SigmaProp = new CSigmaProp(sigmaTree) - - /** Extract `sigmastate.Values.SigmaBoolean` from DSL's `SigmaProp` type. */ - @inline def toSigmaBoolean(p: SigmaProp): SigmaBoolean = p.asInstanceOf[CSigmaProp].sigmaTree - - /** Extract `sigmastate.AvlTreeData` from DSL's `AvlTree` type. */ - def toAvlTreeData(p: AvlTree): AvlTreeData = p.asInstanceOf[CAvlTree].treeData - - /** Extract `sigmastate.crypto.Ecp` from DSL's `GroupElement` type. */ - def toECPoint(ge: GroupElement): Ecp = ge.asInstanceOf[CGroupElement].wrappedValue - - /** Creates a new AvlTree instance with the given parameters. - * @see AvlTreeData for details - */ - override def avlTree(operationFlags: Byte, digest: Coll[Byte], keyLength: Int, valueLengthOpt: Option[Int]): CAvlTree = { - val treeData = AvlTreeData(digest, AvlTreeFlags(operationFlags), keyLength, valueLengthOpt) - CAvlTree(treeData) - } - - /** Wraps the given tree data into SigmaDsl value of type [[AvlTree]]. */ - def avlTree(treeData: AvlTreeData): AvlTree = { - CAvlTree(treeData) - } - - /** Wraps the given [[ErgoBox]] into SigmaDsl value of type [[Box]]. - * @param ebox the value to be wrapped - * @see [[sigmastate.SBox]], [[sigma.Box]] - */ - def Box(ebox: ErgoBox): Box = CBox(ebox) - - /** Extracts [[ErgoBox]] from the given [[Box]] instance. This is inverse to the Box method. */ - def toErgoBox(b: Box): ErgoBox = b.asInstanceOf[CBox].ebox - - /** HOTSPOT: don't beautify this code */ - private def toSigmaTrees(props: Array[SigmaProp]): Array[SigmaBoolean] = { - val len = props.length - val res = new Array[SigmaBoolean](len) - cfor(0)(_ < len, _ + 1) { i => - res(i) = toSigmaBoolean(props(i)) - } - res - } - - @inline private def toEcPointType(ge: GroupElement): EcPointType = - toECPoint(ge).asInstanceOf[EcPointType] - - override def atLeast(bound: Int, props: Coll[SigmaProp]): SigmaProp = { - if (props.length > AtLeast.MaxChildrenCount) - throw new IllegalArgumentException(s"Expected input elements count should not exceed ${AtLeast.MaxChildrenCount}, actual: ${props.length}") - val sigmaTrees = toSigmaTrees(props.toArray) - val tree = AtLeast.reduce(bound, sigmaTrees) - CSigmaProp(tree) - } - - override def allOf(conditions: Coll[Boolean]): Boolean = - conditions.forall(c => c) - - override def anyOf(conditions: Coll[Boolean]): Boolean = - conditions.exists(c => c) - - override def xorOf(conditions: Coll[Boolean]): Boolean = { - if (VersionContext.current.isJitActivated) { - val len = conditions.length - if (len == 0) false - else if (len == 1) conditions(0) - else { - var res = conditions(0) - cfor(1)(_ < len, _ + 1) { i => - res ^= conditions(i) - } - res - } - } else { - // This is buggy version used in v4.x interpreter (for ErgoTrees v0, v1) - conditions.toArray.distinct.length == 2 - } - } - - override def allZK(props: Coll[SigmaProp]): SigmaProp = { - val sigmaTrees = toSigmaTrees(props.toArray) - val tree = CAND.normalized(sigmaTrees) - CSigmaProp(tree) - } - - override def anyZK(props: Coll[SigmaProp]): SigmaProp = { - val sigmaTrees = toSigmaTrees(props.toArray) - val tree = COR.normalized(sigmaTrees) - CSigmaProp(tree) - } - - override def xor(l: Coll[Byte], r: Coll[Byte]): Coll[Byte] = - Colls.xor(l, r) - - override def sigmaProp(b: Boolean): SigmaProp = { - CSigmaProp(TrivialProp(b)) - } - - override def blake2b256(bytes: Coll[Byte]): Coll[Byte] = { - val h = Blake2b256.hash(bytes.toArray) - Colls.fromArray(h) - } - - override def sha256(bytes: Coll[Byte]): Coll[Byte] = { - val h = Sha256.hash(bytes.toArray) - Colls.fromArray(h) - } - - override def byteArrayToBigInt(bytes: Coll[Byte]): BigInt = { - val bi = new BigInteger(bytes.toArray).to256BitValueExact - this.BigInt(bi) - } - - override def longToByteArray(l: Long): Coll[Byte] = - Colls.fromArray(Longs.toByteArray(l)) - - override def byteArrayToLong(bytes: Coll[Byte]): Long = - Longs.fromByteArray(bytes.toArray) - - override def proveDlog(ge: GroupElement): SigmaProp = - CSigmaProp(ProveDlog(toECPoint(ge).asInstanceOf[EcPointType])) - - override def proveDHTuple(g: GroupElement, h: GroupElement, u: GroupElement, v: GroupElement): SigmaProp = { - val dht = ProveDHTuple(toEcPointType(g), toEcPointType(h), toEcPointType(u), toEcPointType(v)) - CSigmaProp(dht) - } - - private lazy val _generatorElement = this.GroupElement(CryptoConstants.dlogGroup.generator) - override def groupGenerator: GroupElement = _generatorElement - - /** - * @return the identity of the Dlog group used in ErgoTree - */ - def groupIdentity: GroupElement = { - this.GroupElement(CryptoConstants.dlogGroup.identity) - } - - override def substConstants[T](scriptBytes: Coll[Byte], - positions: Coll[Int], - newValues: Coll[T]): Coll[Byte] = { - val constants = try newValues.toArrayOfConstants - catch { - case e: Throwable => - throw new RuntimeException(s"Cannot evaluate substConstants($scriptBytes, $positions, $newValues)", e) - } - val (res, _) = SubstConstants.eval(scriptBytes.toArray, positions.toArray, constants)(validationSettings) - Colls.fromArray(res) - } - - override def decodePoint(encoded: Coll[Byte]): GroupElement = { - val r = SigmaSerializer.startReader(encoded.toArray) - val p = GroupElementSerializer.parse(r) - this.GroupElement(p) - } - -} - -/** Default singleton instance of Global object, which implements global ErgoTree functions. */ -object CSigmaDslBuilder extends CSigmaDslBuilder - /** A default implementation of [[Context]] interface. * @see [[Context]] for detailed descriptions */ diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/CHeader.scala b/interpreter/shared/src/main/scala/sigmastate/eval/CHeader.scala new file mode 100644 index 0000000000..7062fa0f0e --- /dev/null +++ b/interpreter/shared/src/main/scala/sigmastate/eval/CHeader.scala @@ -0,0 +1,34 @@ +package sigmastate.eval + +import sigma.data.SigmaConstants +import sigma.{AvlTree, BigInt, Coll, GroupElement, Header} + +/** A default implementation of [[Header]] interface. + * + * @see [[Header]] for detailed descriptions + */ +case class CHeader( + id: Coll[Byte], + version: Byte, + parentId: Coll[Byte], + ADProofsRoot: Coll[Byte], + stateRoot: AvlTree, + transactionsRoot: Coll[Byte], + timestamp: Long, + nBits: Long, + height: Int, + extensionRoot: Coll[Byte], + minerPk: GroupElement, + powOnetimePk: GroupElement, + powNonce: Coll[Byte], + powDistance: BigInt, + votes: Coll[Byte] +) extends Header + +object CHeader { + /** Size of of Header.votes array. */ + val VotesSize: Int = SigmaConstants.VotesArraySize.value + + /** Size of nonce array from Autolykos POW solution in Header.powNonce array. */ + val NonceSize: Int = SigmaConstants.AutolykosPowSolutionNonceArraySize.value +} \ No newline at end of file diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/CPreHeader.scala b/interpreter/shared/src/main/scala/sigmastate/eval/CPreHeader.scala new file mode 100644 index 0000000000..8076ab5a9c --- /dev/null +++ b/interpreter/shared/src/main/scala/sigmastate/eval/CPreHeader.scala @@ -0,0 +1,17 @@ +package sigmastate.eval + +import sigma.{Coll, GroupElement, PreHeader} + +/** A default implementation of [[PreHeader]] interface. + * + * @see [[PreHeader]] for detailed descriptions + */ +case class CPreHeader( + version: Byte, + parentId: Coll[Byte], + timestamp: Long, + nBits: Long, + height: Int, + minerPk: GroupElement, + votes: Coll[Byte] +) extends PreHeader diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala b/interpreter/shared/src/main/scala/sigmastate/eval/CProfiler.scala similarity index 94% rename from interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala rename to interpreter/shared/src/main/scala/sigmastate/eval/CProfiler.scala index 5a28c5ea0b..ced8a357b8 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/CProfiler.scala @@ -1,17 +1,15 @@ package sigmastate.eval -import sigmastate.{FixedCost, JitCost, SMethod} -import sigmastate.Values.SValue -import sigmastate.serialization.{OpCodes, ValueCodes, ValueSerializer} -import sigmastate.serialization.ValueSerializer.getSerializer -import sigma.util.Extensions.ByteOps -import debox.{Buffer => DBuffer, Map => DMap} -import debox.sp +import debox.{sp, Buffer => DBuffer, Map => DMap} +import sigma.ast.{CostItem, FixedCost, FixedCostItem, JitCost, SMethod, SeqCostItem, TypeBasedCostItem} import sigma.ast.TypeCodes.LastConstantCode -import sigma.util.Extensions.DBufferOps -import sigmastate.interpreter.{CostItem, FixedCostItem, SeqCostItem, TypeBasedCostItem} -import sigmastate.lang.Terms.{MethodCall, PropertyCall} -import sigmastate.serialization.ValueCodes.OpCode +import sigma.ast.syntax._ +import sigma.util.Extensions.{ByteOps, DBufferOps} +import sigma.ast.{MethodCall, PropertyCall} +import sigma.eval.Profiler +import sigma.serialization.ValueCodes.OpCode +import sigma.serialization.ValueSerializer +import sigma.serialization.ValueSerializer.getSerializer import scala.reflect.ClassTag @@ -106,7 +104,7 @@ class StatCollection[@sp(Int) K, @sp(Long, Double) V] } /** A simple profiler to measure average execution times of ErgoTree operations. */ -class Profiler { +class CProfiler extends Profiler { // NOTE: this class is mutable so better to keep it private private class OpStat( @@ -200,7 +198,7 @@ class Profiler { /** Timings of cost items */ private val costItemsStat = new StatCollection[CostItemKey, Long]() - def addCostItem(costItem: CostItem, time: Long) = { + override def addCostItem(costItem: CostItem, time: Long) = { costItemsStat.addPoint(new CostItemKey(costItem), time) } diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/Extensions.scala b/interpreter/shared/src/main/scala/sigmastate/eval/Extensions.scala index 6aea56fc5d..f9cb0e9f75 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/Extensions.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/Extensions.scala @@ -7,39 +7,14 @@ import scorex.crypto.authds.avltree.batch.{Insert, Lookup, Remove, Update} import scorex.crypto.authds.{ADKey, ADValue} import scorex.util.encode.Base16 import sigma.ast.SType.AnyOps -import sigma.ast.{SBoolean, SCollection, SCollectionType, SType} -import sigma.data.{CAnyValue, Digest32Coll, Nullable, RType, SigmaBoolean} -import sigma.{Coll, _} -import sigmastate.Platform -import sigmastate.Values.{Constant, ConstantNode, SigmaPropConstant, SigmaPropValue, Value} -import sigmastate.interpreter.Interpreter -import sigmastate.lang.{CheckingSigmaBuilder, TransformingSigmaBuilder} -import sigmastate.utils.Helpers -import sigmastate.utxo.SigmaPropIsProven +import sigma.ast._ +import sigma.data.{CBox, Digest32Coll, RType} +import sigma._ -import java.math.BigInteger import scala.util.{Failure, Success} object Extensions { - implicit class ByteExt(val b: Byte) extends AnyVal { - @inline def toBigInt: BigInt = CSigmaDslBuilder.BigInt(BigInteger.valueOf(b.toLong)) - } - - implicit class ShortExt(val b: Short) extends AnyVal { - @inline def toBigInt: BigInt = CSigmaDslBuilder.BigInt(BigInteger.valueOf(b.toLong)) - } - - implicit class IntExt(val x: Int) extends AnyVal { - /** Convert this value to BigInt. */ - @inline def toBigInt: BigInt = CSigmaDslBuilder.BigInt(BigInteger.valueOf(x.toLong)) - } - - implicit class LongExt(val x: Long) extends AnyVal { - /** Convert this value to BigInt. */ - @inline def toBigInt: BigInt = CSigmaDslBuilder.BigInt(BigInteger.valueOf(x)) - } - /** Extension methods for `Array[Byte]` not available for generic `Array[T]`. */ implicit class ArrayByteOps(val arr: Array[Byte]) extends AnyVal { /** Wraps array into TokenId instance. The source array in not cloned. */ @@ -48,53 +23,12 @@ object Extensions { @inline def toHex: String = Base16.encode(arr) } - implicit class EvalIterableOps[T: RType](seq: Iterable[T]) { - @inline def toColl: Coll[T] = Colls.fromArray[T](seq.toArray(RType[T].classTag)) - } - - implicit class EvalCollOps[T](val coll: Coll[T]) extends AnyVal { - /** Helper type synonym. */ - type ElemTpe = SType { type WrappedType = T} - - /** Wraps the collection into ConstantNode using collection's element type. */ - def toConstant: Constant[SCollection[ElemTpe]] = { - val elemTpe = Evaluation.rtypeToSType(coll.tItem).asInstanceOf[ElemTpe] - ConstantNode[SCollection[ElemTpe]](coll, SCollectionType(elemTpe)) - } - - /** Transforms this collection into array of constants. - * - * This method have exactly the same semantics on JS and JVM IF `coll.tItem` - * precisely describes the type of elements in `call`. (Which is the case for all - * collections created by ErgoTree interpreter). - * - * However, if it is not the case, then JVM and JS will have different semantics for Byte and Short. - * - * The JVM version preserves v5.0 consensus protocol semantics. - * The JS version is a reasonable approximation of the JVM version. - */ - def toArrayOfConstants: Array[Constant[SType]] = { - val constants = coll.toArray.map { v => - // see ScalaDoc for ensureTypeCarringValue - val valToLift = Helpers.ensureTypeCarringValue(v, coll.tItem.asInstanceOf[RType[Any]]) - // call platform-specific method to transform the value to a Constant - Platform.liftToConstant(valToLift, TransformingSigmaBuilder) match { - case Nullable(c) => c - case _ => sys.error(s"Cannot liftToConstant($valToLift)") - } - } - constants - } - } - implicit class DslDataOps[A](data: A)(implicit tA: RType[A]) { def toTreeData: Constant[SType] = { CheckingSigmaBuilder.mkConstant(data.asWrappedType, Evaluation.rtypeToSType(tA)) } } - def toAnyValue[A:RType](x: A) = new CAnyValue(x, RType[A].asInstanceOf[RType[Any]]) - implicit class ErgoBoxOps(val ebox: ErgoBox) extends AnyVal { def toTestBox: Box = { /* NOHF PROOF: @@ -107,17 +41,11 @@ object Extensions { } } - implicit class SigmaBooleanOps(val sb: SigmaBoolean) extends AnyVal { - def toSigmaPropValue: SigmaPropValue = SigmaPropConstant(sb) - - def isProven: Value[SBoolean.type] = SigmaPropIsProven(SigmaPropConstant(sb)) - } - implicit class AvlTreeOps(val tree: AvlTree) extends AnyVal { def contains(key: Coll[Byte], proof: Coll[Byte]): Boolean = { val keyBytes = key.toArray - val bv = AvlTreeVerifier(tree, proof) + val bv = CAvlTreeVerifier(tree, proof) bv.performOneOperation(Lookup(ADKey @@ keyBytes)) match { case Success(r) => r match { case Some(_) => true @@ -129,27 +57,27 @@ object Extensions { def get(key: Coll[Byte], proof: Coll[Byte]): Option[Coll[Byte]] = { val keyBytes = key.toArray - val bv = AvlTreeVerifier(tree, proof) + val bv = CAvlTreeVerifier(tree, proof) bv.performOneOperation(Lookup(ADKey @@ keyBytes)) match { case Success(r) => r match { case Some(v) => Some(Colls.fromArray(v)) case _ => None } - case Failure(_) => Interpreter.error(s"Tree proof is incorrect $tree") + case Failure(_) => syntax.error(s"Tree proof is incorrect $tree") } } def getMany( keys: Coll[Coll[Byte]], proof: Coll[Byte]): Coll[Option[Coll[Byte]]] = { - val bv = AvlTreeVerifier(tree, proof) + val bv = CAvlTreeVerifier(tree, proof) keys.map { key => bv.performOneOperation(Lookup(ADKey @@ key.toArray)) match { case Success(r) => r match { case Some(v) => Some(Colls.fromArray(v)) case _ => None } - case Failure(_) => Interpreter.error(s"Tree proof is incorrect $tree") + case Failure(_) => syntax.error(s"Tree proof is incorrect $tree") } } } @@ -160,11 +88,11 @@ object Extensions { if (!tree.isInsertAllowed) { None } else { - val bv = AvlTreeVerifier(tree, proof) + val bv = CAvlTreeVerifier(tree, proof) entries.forall { case (key, value) => val insertRes = bv.performOneOperation(Insert(ADKey @@ key.toArray, ADValue @@ value.toArray)) if (insertRes.isFailure) { - Interpreter.error(s"Incorrect insert for $tree (key: $key, value: $value, digest: ${tree.digest}): ${insertRes.failed.get}}") + syntax.error(s"Incorrect insert for $tree (key: $key, value: $value, digest: ${tree.digest}): ${insertRes.failed.get}}") } insertRes.isSuccess } @@ -181,7 +109,7 @@ object Extensions { if (!tree.isUpdateAllowed) { None } else { - val bv = AvlTreeVerifier(tree, proof) + val bv = CAvlTreeVerifier(tree, proof) operations.forall { case (key, value) => bv.performOneOperation(Update(ADKey @@ key.toArray, ADValue @@ value.toArray)).isSuccess } @@ -196,7 +124,7 @@ object Extensions { if (!tree.isRemoveAllowed) { None } else { - val bv = AvlTreeVerifier(tree, proof) + val bv = CAvlTreeVerifier(tree, proof) cfor(0)(_ < operations.length, _ + 1) { i => val key = operations(i).toArray bv.performOneOperation(Remove(ADKey @@ key)) diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/package.scala b/interpreter/shared/src/main/scala/sigmastate/eval/package.scala index 6b97167d59..089e11c0b8 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/package.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/package.scala @@ -1,24 +1,14 @@ package sigmastate import org.ergoplatform.ErgoBox -import sigma.{Coll, _} -import sigma.crypto.EcPointType -import sigma.data.{AvlTreeData, RType, SigmaBoolean} -import sigmastate.exceptions.CostLimitException -import supertagged.TaggedType +import sigma._ +import sigma.data.{AvlTreeData, SigmaBoolean} +import sigma.eval.SigmaDsl +import sigma.exceptions.CostLimitException -import java.math.BigInteger import scala.language.implicitConversions package object eval { - /** The primary reference to Global instance of SigmaDsl. - * Besides operations of SigmaDslBuilder class, this instance also contains methods, - * which are not available in Dsl code, and which are not in SigmaDslBuilder interface. - * For example methods like `Box`, `toErgoBox` are available here, but not available in Dsl. - * @see SigmaDslBuilder - */ - val SigmaDsl = CSigmaDslBuilder - /** Implicit conversions between Dsl type and the type wrapped by the corresponding type Dsl type. * Here BigInt is Dsl type and BigInteger is wrapped type. * @see `sigma.CBigInt` diff --git a/interpreter/shared/src/main/scala/sigmastate/exceptions/SigmaTyperExceptions.scala b/interpreter/shared/src/main/scala/sigmastate/exceptions/SigmaTyperExceptions.scala index b5802e39ca..8ff9cb370f 100644 --- a/interpreter/shared/src/main/scala/sigmastate/exceptions/SigmaTyperExceptions.scala +++ b/interpreter/shared/src/main/scala/sigmastate/exceptions/SigmaTyperExceptions.scala @@ -1,6 +1,7 @@ package sigmastate.exceptions -import sigmastate.lang.SourceContext +import sigma.ast.SourceContext +import sigma.exceptions.TyperException final class InvalidBinaryOperationParameters(message: String, source: Option[SourceContext] = None) extends TyperException(message, source) diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/CErgoTreeEvaluator.scala similarity index 64% rename from interpreter/shared/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala rename to interpreter/shared/src/main/scala/sigmastate/interpreter/CErgoTreeEvaluator.scala index 5e4f278b5d..de8aa6b620 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/CErgoTreeEvaluator.scala @@ -1,89 +1,22 @@ package sigmastate.interpreter import org.ergoplatform.ErgoLikeContext -import sigmastate.{ErgoTree, FixedCost, JitCost, PerItemCost, TypeBasedCost} -import sigmastate.Values._ -import sigmastate.eval.Profiler -import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv +import sigma.ast._ +import sigma.ast.syntax._ +import sigmastate.eval.{CAvlTreeVerifier, CProfiler} import sigmastate.interpreter.Interpreter.ReductionResult -import sigma.{Context, SigmaProp} +import sigma.{AvlTree, Coll, Colls, Context, VersionContext} import sigma.util.Extensions._ -import sigmastate.interpreter.EvalSettings._ -import supertagged.TaggedType -import debox.{Buffer => DBuffer} -import sigma.VersionContext +import debox.{cfor, Buffer => DBuffer} +import scorex.crypto.authds.ADKey +import sigma.ast.SAvlTreeMethods._ import sigma.ast.SType -import sigma.data.SigmaBoolean +import sigma.data.{CSigmaProp, KeyValueColl, SigmaBoolean} +import sigma.eval.{AvlTreeVerifier, ErgoTreeEvaluator, EvalSettings, Profiler} +import sigma.eval.ErgoTreeEvaluator.DataEnv import scala.collection.compat.immutable.ArraySeq -import scala.util.DynamicVariable - -/** Configuration parameters of the evaluation run. */ -case class EvalSettings( - /** Used together with [[ErgoTreeEvaluator.profiler]] to measure individual operations timings. */ - isMeasureOperationTime: Boolean, - /** Used together with [[ErgoTreeEvaluator.profiler]] to measure script timings. */ - isMeasureScriptTime: Boolean, - /** Used by [[ErgoTreeEvaluator]] to conditionally perform debug mode operations. */ - isDebug: Boolean = false, - /** Used by [[ErgoTreeEvaluator]] to conditionally emit log messages. */ - isLogEnabled: Boolean = false, - /** Used by [[ErgoTreeEvaluator]] to conditionally build a trace of added costs. - * @see Value.addCost - */ - costTracingEnabled: Boolean = false, - /** Profiler which, when defined, should be used in [[ErgoTreeEvaluator]] constructor. */ - profilerOpt: Option[Profiler] = None, - /** Should be set to true, if evaluation is performed as part of test suite. - * In such a case, additional operations may be performed (such as sanity checks). */ - isTestRun: Boolean = false, - /** If true, then expected test vectors are pretty-printed. */ - printTestVectors: Boolean = false, - /** When Some(mode) is specified then it defines which version of the Interpreter.verify - * and Interpreter.prove methods should use. - * The default value is None, which means the version is defined by ErgoTree.version - * and Context.activatedScriptVersion. - */ - evaluationMode: Option[EvaluationMode] = None, - /** Maximum execution cost of a script used by profiler. - * @see ErgoTreeEvaluator - */ - scriptCostLimitInEvaluator: Int = 1000000 -) - -object EvalSettings { - /** Enumeration type of evaluation modes of [[Interpreter]]. - * This type can be removed in v5.x releases together with AOT implementation once v5.0 - * protocol is activated. - */ - object EvaluationMode extends TaggedType[Int] { - implicit class EvaluationModeOps(val x: EvaluationMode) extends AnyVal { - def name: String = x match { - case AotEvaluationMode => "AotEvaluationMode" - case JitEvaluationMode => "JitEvaluationMode" - } - - /** Returns true if AOT interpreter should be evaluated. */ - def okEvaluateAot: Boolean = { - x == AotEvaluationMode - } - - /** Returns true if JIT interpreter should be evaluated. */ - def okEvaluateJit: Boolean = { - x == JitEvaluationMode - } - } - } - type EvaluationMode = EvaluationMode.Type - - /** Evaluation mode when the interpreter is executing using AOT costing implementation - * of v4.x protocol. */ - val AotEvaluationMode: EvaluationMode = EvaluationMode @@ 1 // first bit - - /** Evaluation mode when the interpreter is executing using JIT costing implementation - * of v5.x protocol. */ - val JitEvaluationMode: EvaluationMode = EvaluationMode @@ 2 // second bit -} +import scala.util.{DynamicVariable, Failure, Success} /** Result of JITC evaluation with costing. */ case class JitEvalResult[A](value: A, cost: JitCost) @@ -124,17 +57,169 @@ case class JitEvalResult[A](value: A, cost: JitCost) * @param profiler Performs operations profiling and time measurements (if enabled in settings). * @param settings Settings to be used during evaluation. */ -class ErgoTreeEvaluator( +class CErgoTreeEvaluator( val context: Context, val constants: Seq[Constant[SType]], protected val coster: CostAccumulator, val profiler: Profiler, - val settings: EvalSettings) { + val settings: EvalSettings) extends ErgoTreeEvaluator { + + override def createTreeVerifier(tree: AvlTree, proof: Coll[Byte]): AvlTreeVerifier = + CAvlTreeVerifier(tree, proof) + + /** Creates [[sigma.eval.AvlTreeVerifier]] for the given tree and proof. */ + def createVerifier(tree: AvlTree, proof: Coll[Byte]) = { + // the cost of tree reconstruction from proof is O(proof.length) + addSeqCost(CreateAvlVerifier_Info, proof.length) { () => + CAvlTreeVerifier(tree, proof) + } + } + + override def contains_eval(mc: MethodCall, tree: AvlTree, key: Coll[Byte], proof: Coll[Byte]): Boolean = { + val bv = createVerifier(tree, proof) + val nItems = bv.treeHeight + var res = false + // the cost of tree lookup is O(bv.treeHeight) + addSeqCost(LookupAvlTree_Info, nItems) { () => + res = bv.performLookup(ADKey @@ key.toArray) match { + case Success(r) => r match { + case Some(_) => true + case _ => false + } + case Failure(_) => false + } + } + res + } + + override def get_eval(mc: MethodCall, tree: AvlTree, key: Coll[Byte], proof: Coll[Byte]): Option[Coll[Byte]] = { + val bv = createVerifier(tree, proof) + val nItems = bv.treeHeight + + // the cost of tree lookup is O(bv.treeHeight) + addSeqCost(LookupAvlTree_Info, nItems) { () => + bv.performLookup(ADKey @@ key.toArray) match { + case Success(r) => r match { + case Some(v) => Some(Colls.fromArray(v)) + case _ => None + } + case Failure(_) => syntax.error(s"Tree proof is incorrect $tree") + } + } + } + + override def getMany_eval( + mc: MethodCall, + tree: AvlTree, + keys: Coll[Coll[Byte]], + proof: Coll[Byte]): Coll[Option[Coll[Byte]]] = { + val bv = createVerifier(tree, proof) + val nItems = bv.treeHeight + keys.map { key => + // the cost of tree lookup is O(bv.treeHeight) + addSeqCost(LookupAvlTree_Info, nItems) { () => + bv.performLookup(ADKey @@ key.toArray) match { + case Success(r) => r match { + case Some(v) => Some(Colls.fromArray(v)) + case _ => None + } + case Failure(_) => syntax.error(s"Tree proof is incorrect $tree") + } + } + } + } + + override def insert_eval(mc: MethodCall, tree: AvlTree, entries: KeyValueColl, proof: Coll[Byte]): Option[AvlTree] = { + addCost(isInsertAllowed_Info) + if (!tree.isInsertAllowed) { + None + } else { + val bv = createVerifier(tree, proof) + // when the tree is empty we still need to add the insert cost + val nItems = Math.max(bv.treeHeight, 1) + entries.forall { case (key, value) => + var res = true + // the cost of tree lookup is O(bv.treeHeight) + addSeqCost(InsertIntoAvlTree_Info, nItems) { () => + val insertRes = bv.performInsert(key.toArray, value.toArray) + // TODO v6.0: throwing exception is not consistent with update semantics + // however it preserves v4.0 semantics (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/908) + if (insertRes.isFailure) { + syntax.error(s"Incorrect insert for $tree (key: $key, value: $value, digest: ${tree.digest}): ${insertRes.failed.get}}") + } + res = insertRes.isSuccess + } + res + } + bv.digest match { + case Some(d) => + addCost(updateDigest_Info) + Some(tree.updateDigest(Colls.fromArray(d))) + case _ => None + } + } + } + + override def update_eval( + mc: MethodCall, tree: AvlTree, + operations: KeyValueColl, proof: Coll[Byte]): Option[AvlTree] = { + addCost(isUpdateAllowed_Info) + if (!tree.isUpdateAllowed) { + None + } else { + val bv = createVerifier(tree, proof) + // when the tree is empty we still need to add the insert cost + val nItems = Math.max(bv.treeHeight, 1) + + // here we use forall as looping with fast break on first failed tree oparation + operations.forall { case (key, value) => + var res = true + // the cost of tree update is O(bv.treeHeight) + addSeqCost(UpdateAvlTree_Info, nItems) { () => + val updateRes = bv.performUpdate(key.toArray, value.toArray) + res = updateRes.isSuccess + } + res + } + bv.digest match { + case Some(d) => + addCost(updateDigest_Info) + Some(tree.updateDigest(Colls.fromArray(d))) + case _ => None + } + } + } + + override def remove_eval( + mc: MethodCall, tree: AvlTree, + operations: Coll[Coll[Byte]], proof: Coll[Byte]): Option[AvlTree] = { + addCost(isRemoveAllowed_Info) + if (!tree.isRemoveAllowed) { + None + } else { + val bv = createVerifier(tree, proof) + // when the tree is empty we still need to add the insert cost + val nItems = Math.max(bv.treeHeight, 1) + cfor(0)(_ < operations.length, _ + 1) { i => + addSeqCost(RemoveAvlTree_Info, nItems) { () => + val key = operations(i).toArray + bv.performRemove(key) + } + } + addCost(digest_Info) + bv.digest match { + case Some(d) => + addCost(updateDigest_Info) + Some(tree.updateDigest(Colls.fromArray(d))) + case _ => None + } + } + } /** Evaluates the given expression in the given data environment. */ def eval(env: DataEnv, exp: SValue): Any = { VersionContext.checkVersions(context.activatedScriptVersion, context.currentErgoTreeVersion) - ErgoTreeEvaluator.currentEvaluator.withValue(this) { + CErgoTreeEvaluator.currentEvaluator.withValue(this) { exp.evalTo[Any](env)(this) } } @@ -171,33 +256,18 @@ class ErgoTreeEvaluator( costTrace.clear() } - /** Adds the given cost to the `coster`. If tracing is enabled, associates the cost with - * the given operation. - * - * @param costKind kind of the cost to be added to `coster` - * @param opDesc operation descriptor to associate the cost with (when costTracingEnabled) - */ - final def addCost(costKind: FixedCost, opDesc: OperationDesc): Unit = { + override def addCost(costKind: FixedCost, opDesc: OperationDesc): Unit = { coster.add(costKind.cost) if (settings.costTracingEnabled) { costTrace += FixedCostItem(opDesc, costKind) } } - @inline final def addCost(costInfo: OperationCostInfo[FixedCost]): Unit = { + override def addCost(costInfo: OperationCostInfo[FixedCost]): Unit = { addCost(costInfo.costKind, costInfo.opDesc) } - /** Add the cost given by the cost descriptor and the type to the accumulator and - * associate it with this operation descriptor. - * - * @param costKind descriptor of the cost - * @param tpe specific type for which the cost should be computed by this descriptor - * (see costFunc method) - * @param opDesc operation which is associated with this cost - */ - @inline - final def addTypeBasedCost[R](costKind: TypeBasedCost, + override def addTypeBasedCost[R](costKind: TypeBasedCost, tpe: SType, opDesc: OperationDesc)(block: () => R): R = { var costItem: TypeBasedCostItem = null if (settings.costTracingEnabled) { @@ -222,14 +292,8 @@ class ErgoTreeEvaluator( } } - /** Adds the given cost to the `coster`. If tracing is enabled, associates the cost with - * the given operation. - * @param costKind kind of the cost to be added to `coster` - * @param opDesc the operation descriptor to associate the cost with (when costTracingEnabled) - * @param block operation executed under the given cost - * @hotspot don't beautify the code - */ - final def addFixedCost(costKind: FixedCost, opDesc: OperationDesc)(block: => Unit): Unit = { + /** @hotspot don't beautify the code */ + override def addFixedCost(costKind: FixedCost, opDesc: OperationDesc)(block: => Unit): Unit = { var costItem: FixedCostItem = null if (settings.costTracingEnabled) { costItem = FixedCostItem(opDesc, costKind) @@ -250,20 +314,12 @@ class ErgoTreeEvaluator( } } - @inline - final def addFixedCost(costInfo: OperationCostInfo[FixedCost])(block: => Unit): Unit = { + override def addFixedCost(costInfo: OperationCostInfo[FixedCost])(block: => Unit): Unit = { addFixedCost(costInfo.costKind, costInfo.opDesc)(block) } - /** Adds the given cost to the `coster`. If tracing is enabled, creates a new cost item - * with the given operation. - * - * @param costKind the cost to be added to `coster` for each item - * @param nItems the number of items - * @param opDesc the operation to associate the cost with (when costTracingEnabled) - * @hotspot don't beautify the code - */ - final def addSeqCostNoOp(costKind: PerItemCost, nItems: Int, opDesc: OperationDesc): Unit = { + /** @hotspot don't beautify the code */ + override def addSeqCostNoOp(costKind: PerItemCost, nItems: Int, opDesc: OperationDesc): Unit = { var costItem: SeqCostItem = null if (settings.costTracingEnabled) { costItem = SeqCostItem(opDesc, costKind, nItems) @@ -273,17 +329,7 @@ class ErgoTreeEvaluator( coster.add(cost) } - /** Adds the given cost to the `coster`. If tracing is enabled, creates a new cost item - * with the given operation. - * - * @param costKind the cost to be added to `coster` for each item - * @param nItems the number of items - * @param opDesc the operation to associate the cost with (when costTracingEnabled) - * @param block operation executed under the given cost - * @tparam R result type of the operation - * @hotspot don't beautify the code - */ - final def addSeqCost[R](costKind: PerItemCost, nItems: Int, opDesc: OperationDesc)(block: () => R): R = { + override def addSeqCost[R](costKind: PerItemCost, nItems: Int, opDesc: OperationDesc)(block: () => R): R = { var costItem: SeqCostItem = null if (settings.costTracingEnabled) { costItem = SeqCostItem(opDesc, costKind, nItems) @@ -307,29 +353,12 @@ class ErgoTreeEvaluator( } } - /** Adds the cost to the `coster`. See the other overload for details. */ - @inline - final def addSeqCost[R](costInfo: OperationCostInfo[PerItemCost], nItems: Int) + override def addSeqCost[R](costInfo: OperationCostInfo[PerItemCost], nItems: Int) (block: () => R): R = { addSeqCost(costInfo.costKind, nItems, costInfo.opDesc)(block) } - /** Adds the cost to the `coster`. If tracing is enabled, creates a new cost item with - * the given operation descriptor and cost kind. If time measuring is enabled also - * performs profiling. - * - * WARNING: The cost is accumulated AFTER the block is executed. - * Each usage of this method should be accompanied with a proof of why this cannot lead - * to unbounded execution (see all usages). - * - * @param costKind the cost descriptor to be used to compute the cost based on the - * actual number of items returned by the `block` - * @param opDesc the operation to associate the cost with (when costTracingEnabled) - * @param block operation executed under the given cost descriptors, returns the - * actual number of items processed - * @hotspot don't beautify the code - */ - final def addSeqCost(costKind: PerItemCost, opDesc: OperationDesc)(block: () => Int): Unit = { + override def addSeqCost(costKind: PerItemCost, opDesc: OperationDesc)(block: () => Int): Unit = { var costItem: SeqCostItem = null var nItems = 0 if (settings.isMeasureOperationTime) { @@ -353,18 +382,15 @@ class ErgoTreeEvaluator( } } - /** Adds the cost to the `coster`. See the other overload for details. */ - final def addSeqCost(costInfo: OperationCostInfo[PerItemCost])(block: () => Int): Unit = { + override def addSeqCost(costInfo: OperationCostInfo[PerItemCost])(block: () => Int): Unit = { addSeqCost(costInfo.costKind, costInfo.opDesc)(block) } } -object ErgoTreeEvaluator { - /** Immutable data environment used to assign data values to graph nodes. */ - type DataEnv = Map[Int, Any] +object CErgoTreeEvaluator { /** Size of data block in bytes. Used in JIT cost calculations. - * @see [[sigmastate.NEQ]], + * @see [[NEQ]], */ val DataBlockSize: Int = 512 @@ -372,7 +398,7 @@ object ErgoTreeEvaluator { val EmptyDataEnv: DataEnv = Map.empty /** A profiler which is used by default if [[EvalSettings.isMeasureOperationTime]] is enabled. */ - val DefaultProfiler = new Profiler + val DefaultProfiler = new CProfiler /** Default global [[EvalSettings]] instance. */ val DefaultEvalSettings = EvalSettings( @@ -381,26 +407,27 @@ object ErgoTreeEvaluator { /** Evaluator currently is being executed on the current thread. * This variable is set in a single place, specifically in the `eval` method of - * [[ErgoTreeEvaluator]]. + * [[CErgoTreeEvaluator]]. + * * @see getCurrentEvaluator */ - private[sigmastate] val currentEvaluator = new DynamicVariable[ErgoTreeEvaluator](null) + private[sigmastate] val currentEvaluator = new DynamicVariable[CErgoTreeEvaluator](null) /** Returns a current evaluator for the current thread. */ - def getCurrentEvaluator: ErgoTreeEvaluator = currentEvaluator.value + def getCurrentEvaluator: CErgoTreeEvaluator = currentEvaluator.value - /** Creates a new [[ErgoTreeEvaluator]] instance with the given profiler and settings. + /** Creates a new [[CErgoTreeEvaluator]] instance with the given profiler and settings. * The returned evaluator can be used to initialize the `currentEvaluator` variable. * As a result, cost-aware operations (code blocks) can be implemented, even when those * operations don't involve ErgoTree evaluation. * As an example, see methods in [[sigmastate.SigSerializer]] and * [[sigmastate.FiatShamirTree]] where cost-aware code blocks are used. */ - def forProfiling(profiler: Profiler, evalSettings: EvalSettings): ErgoTreeEvaluator = { + def forProfiling(profiler: CProfiler, evalSettings: EvalSettings): CErgoTreeEvaluator = { val acc = new CostAccumulator( initialCost = JitCost(0), costLimit = Some(JitCost.fromBlockCost(evalSettings.scriptCostLimitInEvaluator))) - new ErgoTreeEvaluator( + new CErgoTreeEvaluator( context = null, constants = ArraySeq.empty, acc, profiler, evalSettings.copy(profilerOpt = Some(profiler))) @@ -409,7 +436,7 @@ object ErgoTreeEvaluator { /** Executes [[FixedCost]] code `block` and use the given evaluator `E` to perform * profiling and cost tracing. * This helper method allows implementation of cost-aware code blocks by using - * thread-local instance of [[ErgoTreeEvaluator]]. + * thread-local instance of [[CErgoTreeEvaluator]]. * If the `currentEvaluator` [[DynamicVariable]] is not initialized (equals to null), * then the block is executed with minimal overhead. * @@ -437,7 +464,7 @@ object ErgoTreeEvaluator { /** Executes [[PerItemCost]] code `block` and use the given evaluator `E` to perform * profiling and cost tracing. * This helper method allows implementation of cost-aware code blocks by using - * thread-local instance of [[ErgoTreeEvaluator]]. + * thread-local instance of [[CErgoTreeEvaluator]]. * If the `currentEvaluator` [[DynamicVariable]] is not initialized (equals to null), * then the block is executed with minimal overhead. * @@ -470,8 +497,7 @@ object ErgoTreeEvaluator { def evalToCrypto(context: ErgoLikeContext, ergoTree: ErgoTree, evalSettings: EvalSettings): ReductionResult = { val (res, cost) = eval(context, ergoTree.constants, ergoTree.toProposition(replaceConstants = false), evalSettings) val sb = res match { - case sp: SigmaProp => - sigmastate.eval.SigmaDsl.toSigmaBoolean(sp) + case sp: CSigmaProp => sp.wrappedValue case sb: SigmaBoolean => sb case _ => error(s"Expected SigmaBoolean but was: $res") } @@ -507,7 +533,7 @@ object ErgoTreeEvaluator { * @param costAccumulator [[CostAccumulator]] instance used for accumulating costs * @param constants collection of segregated constants which can be refered by * [[ConstantPlaceholder]]s in `exp` - * @param exp ErgoTree expression represented as [[sigmastate.Values.Value]] + * @param exp ErgoTree expression represented as [[sigma.ast.Value]] * @param evalSettings evaluation settings * @return 1) the result of evaluating `exp` in a given context and * 2) an accumulated JIT cost estimation. @@ -517,9 +543,9 @@ object ErgoTreeEvaluator { constants: Seq[Constant[SType]], exp: SValue, evalSettings: EvalSettings): (Any, Int) = { - val evaluator = new ErgoTreeEvaluator( + val evaluator = new CErgoTreeEvaluator( sigmaContext, constants, costAccumulator, DefaultProfiler, evalSettings) - val res = evaluator.eval(Map(), exp) + val res = evaluator.eval(Map(), exp) val cost = costAccumulator.totalCost.toBlockCost // scale to block cost (res, cost) } diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/CostAccumulator.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/CostAccumulator.scala index fe86acf9a4..c79a9b77df 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/CostAccumulator.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/CostAccumulator.scala @@ -1,7 +1,7 @@ package sigmastate.interpreter -import sigmastate.JitCost -import sigmastate.exceptions.CostLimitException +import sigma.ast.JitCost +import sigma.exceptions.CostLimitException /** Encapsulate simple monotonic (add only) counter with reset. */ class CostCounter(val initialCost: JitCost) { diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala index 1cc7dddd19..55f159b7e1 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala @@ -1,31 +1,32 @@ package sigmastate.interpreter -import java.util -import sigma.kiama.rewriting.Rewriter.{everywherebu, rule, strategy} +import debox.cfor import org.ergoplatform.ErgoLikeContext -import sigma.validation.SigmaValidationSettings import org.ergoplatform.validation.ValidationRules._ -import sigmastate.Values._ -import sigmastate.crypto.DLogProtocol.{DLogInteractiveProver, FirstDLogProverMessage} -import sigmastate.crypto._ -import sigmastate.interpreter.Interpreter._ -import sigmastate.serialization.{SigmaSerializer, ValueSerializer} -import sigmastate.utxo.DeserializeContext -import sigmastate._ -import sigmastate.eval.{Profiler, SigmaDsl, addCostChecked} -import sigmastate.FiatShamirTree._ -import sigmastate.SigSerializer._ -import sigmastate.interpreter.ErgoTreeEvaluator.fixedCostOp -import sigmastate.utils.Helpers._ -import sigmastate.lang.Terms.ValueOps -import debox.cfor +import sigma.VersionContext import sigma.ast.SCollection.SByteArray -import sigma.ast.{SBoolean, SSigmaProp, SType} +import sigma.ast.syntax._ +import sigma.ast._ import sigma.data.{CAND, COR, CTHRESHOLD, ProveDHTuple, ProveDlog, SigmaBoolean, TrivialProp} -import sigma.{Evaluation, VersionContext} +import sigma.kiama.rewriting.Rewriter.{everywherebu, rule, strategy} import sigma.kiama.rewriting.Strategy +import sigma.serialization.SigSerializer._ +import sigma.serialization.{SigSerializer, SigmaSerializer, ValueSerializer} +import sigma.validation.SigmaValidationSettings import sigma.validation.ValidationRules.trySoftForkable -import sigmastate.exceptions.{CostLimitException, InterpreterException} +import sigmastate.FiatShamirTree._ +import sigmastate._ +import sigmastate.crypto.DLogProtocol.{DLogProver, FirstDLogProverMessage} +import sigmastate.crypto._ +import sigmastate.eval.{CProfiler, addCostChecked} +import sigmastate.interpreter.CErgoTreeEvaluator.fixedCostOp +import sigmastate.interpreter.Interpreter._ +import sigma.ast.syntax.ValueOps +import sigma.eval.{EvalSettings, SigmaDsl} +import sigma.exceptions.{CostLimitException, InterpreterException} +import sigma.interpreter.ProverResult +import sigma.util.CollectionUtil +import sigmastate.utils.Helpers._ import scala.util.{Success, Try} @@ -56,10 +57,10 @@ trait Interpreter { /** Force initialization of reflection. */ private val _ = InterpreterReflection - /** Evaluation settings used by [[ErgoTreeEvaluator]] which is used by this + /** Evaluation settings used by [[CErgoTreeEvaluator]] which is used by this * interpreter to perform fullReduction. */ - protected def evalSettings: EvalSettings = ErgoTreeEvaluator.DefaultEvalSettings + protected def evalSettings: EvalSettings = CErgoTreeEvaluator.DefaultEvalSettings /** Logs the given message string. Can be overridden in the derived interpreter classes * to redefine the default behavior. */ @@ -74,13 +75,13 @@ trait Interpreter { /** The cost of Value[T] deserialization is O(n), where n is the length of its bytes * array. To evaluate [[DeserializeContext]] and - * [[sigmastate.utxo.DeserializeRegister]] we add the following cost of deserialization + * [[DeserializeRegister]] we add the following cost of deserialization * for each byte. */ val CostPerByteDeserialized = 2 /** The cost of substituting [[DeserializeContext]] and - * [[sigmastate.utxo.DeserializeRegister]] nodes with the deserialized expression is + * [[DeserializeRegister]] nodes with the deserialized expression is * O(n), where n is the number of bytes in ErgoTree. * The following is the cost added for each ErgoTree.bytes. */ @@ -174,7 +175,7 @@ trait Interpreter { val (resProp, cost) = { val ctx = context.asInstanceOf[ErgoLikeContext] - ErgoTreeEvaluator.eval(ctx, ErgoTree.EmptyConstants, exp, evalSettings) match { + CErgoTreeEvaluator.eval(ctx, ErgoTree.EmptyConstants, exp, evalSettings) match { case (p: sigma.SigmaProp, c) => (p, c) case (res, _) => sys.error(s"Invalid result type of $res: expected SigmaProp when evaluating $exp") @@ -219,7 +220,7 @@ trait Interpreter { case _ if !ergoTree.hasDeserialize => val ctx = context.asInstanceOf[ErgoLikeContext] val res = VersionContext.withVersions(ctx.activatedScriptVersion, ergoTree.version) { - ErgoTreeEvaluator.evalToCrypto(ctx, ergoTree, evalSettings) + CErgoTreeEvaluator.evalToCrypto(ctx, ergoTree, evalSettings) } res case _ => @@ -365,7 +366,7 @@ trait Interpreter { val fullCost = addCryptoCost(reduced.value, reduced.cost, context.costLimit) val ok = if (evalSettings.isMeasureOperationTime) { - val E = ErgoTreeEvaluator.forProfiling(verifySignatureProfiler, evalSettings) + val E = CErgoTreeEvaluator.forProfiling(verifySignatureProfiler, evalSettings) verifySignature(reduced.value, message, proof)(E) } else { verifySignature(reduced.value, message, proof)(null) @@ -378,10 +379,10 @@ trait Interpreter { } // Perform Verifier Steps 4-6 - private def checkCommitments(sp: UncheckedSigmaTree, message: Array[Byte])(implicit E: ErgoTreeEvaluator): Boolean = { + private def checkCommitments(sp: UncheckedSigmaTree, message: Array[Byte])(implicit E: CErgoTreeEvaluator): Boolean = { // Perform Verifier Step 4 val newRoot = computeCommitments(sp).get.asInstanceOf[UncheckedSigmaTree] - val bytes = concatArrays(FiatShamirTree.toBytes(newRoot), message) + val bytes = CollectionUtil.concatArrays_v5(FiatShamirTree.toBytes(newRoot), message) /** * Verifier Steps 5-6: Convert the tree to a string `s` for input to the Fiat-Shamir hash function, * using the same conversion as the prover in 7 @@ -397,20 +398,20 @@ trait Interpreter { * per the verifier algorithm of the leaf's Sigma-protocol. * If the verifier algorithm of the Sigma-protocol for any of the leaves rejects, then reject the entire proof. */ - private[sigmastate] val computeCommitments: Strategy = everywherebu(rule[Any] { + val computeCommitments: Strategy = everywherebu(rule[Any] { case c: UncheckedConjecture => c // Do nothing for internal nodes case sn: UncheckedSchnorr => - implicit val E = ErgoTreeEvaluator.getCurrentEvaluator + implicit val E = CErgoTreeEvaluator.getCurrentEvaluator fixedCostOp(ComputeCommitments_Schnorr) { - val a = DLogInteractiveProver.computeCommitment(sn.proposition, sn.challenge, sn.secondMessage) + val a = DLogProver.computeCommitment(sn.proposition, sn.challenge, sn.secondMessage) sn.copy(commitmentOpt = Some(FirstDLogProverMessage(a))) } case dh: UncheckedDiffieHellmanTuple => - implicit val E = ErgoTreeEvaluator.getCurrentEvaluator + implicit val E = CErgoTreeEvaluator.getCurrentEvaluator fixedCostOp(ComputeCommitments_DHT) { - val (a, b) = DiffieHellmanTupleInteractiveProver.computeCommitment(dh.proposition, dh.challenge, dh.secondMessage) + val (a, b) = DiffieHellmanTupleProver.computeCommitment(dh.proposition, dh.challenge, dh.secondMessage) dh.copy(commitmentOpt = Some(FirstDHTupleProverMessage(a, b))) } @@ -454,7 +455,7 @@ trait Interpreter { */ def verifySignature(sigmaTree: SigmaBoolean, message: Array[Byte], - signature: Array[Byte])(implicit E: ErgoTreeEvaluator): Boolean = { + signature: Array[Byte])(implicit E: CErgoTreeEvaluator): Boolean = { // Perform Verifier Steps 1-3 try { SigSerializer.parseAndComputeChallenges(sigmaTree, signature) match { @@ -586,7 +587,7 @@ object Interpreter { /** An instance of profiler used to measure cost parameters of verifySignature * operations. */ - val verifySignatureProfiler = new Profiler + val verifySignatureProfiler = new CProfiler private def toValidScriptTypeJITC(exp: SValue): SigmaPropValue = exp match { case v: Value[SBoolean.type]@unchecked if v.tpe == SBoolean => v.toSigmaProp @@ -594,7 +595,4 @@ object Interpreter { case x => throw new Error(s"Context-dependent pre-processing should produce tree of type Boolean or SigmaProp but was $x") } - /** Helper method to throw errors from Interpreter. */ - def error(msg: String) = throw new InterpreterException(msg) - } \ No newline at end of file diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/InterpreterContext.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/InterpreterContext.scala index 3388defe1a..e6c7d540ab 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/InterpreterContext.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/InterpreterContext.scala @@ -1,61 +1,13 @@ package sigmastate.interpreter -import sigmastate.Values.EvaluatedValue -import sigmastate.interpreter.ContextExtension.VarBinding -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigma.AnyValue -import sigma.ast.SType +import sigma.interpreter.ContextExtension +import sigma.interpreter.ContextExtension.VarBinding import sigma.validation.SigmaValidationSettings -import scala.collection.mutable - -/** - * User-defined variables to be put into context. - * Each variable is identified by `id: Byte` and can be accessed from a script - * using `getVar[T](id)` operation. - * The value of the variable is represented by [[sigmastate.Values.Constant]] instance, - * which contains both data value and [[SType]] descriptor. The descriptor is checked - * against the type `T` expected in the script operation. If the types don't match, - * exception is thrown and the box spending (protected by the script) fails. - * - * @param values internal container of the key-value pairs - */ -case class ContextExtension(values: scala.collection.Map[Byte, EvaluatedValue[_ <: SType]]) { - def add(bindings: VarBinding*): ContextExtension = - ContextExtension(values ++ bindings) -} -object ContextExtension { - /** Immutable instance of empty ContextExtension, which can be shared to avoid - * allocations. */ - val empty = ContextExtension(Map()) - - /** Type of context variable binding. */ - type VarBinding = (Byte, EvaluatedValue[_ <: SType]) - - object serializer extends SigmaSerializer[ContextExtension, ContextExtension] { - - override def serialize(obj: ContextExtension, w: SigmaByteWriter): Unit = { - val size = obj.values.size - if (size > Byte.MaxValue) - error(s"Number of ContextExtension values $size exceeds ${Byte.MaxValue}.") - w.putUByte(size) - obj.values.foreach { case (id, v) => w.put(id).putValue(v) } - } - - override def parse(r: SigmaByteReader): ContextExtension = { - val extSize = r.getByte() - if (extSize < 0) - error(s"Negative amount of context extension values: $extSize") - val ext = (0 until extSize) - .map(_ => (r.getByte(), r.getValue().asInstanceOf[EvaluatedValue[_ <: SType]])) - ContextExtension(mutable.LinkedHashMap(ext:_*)) - } - } -} /** Base class of the context passed to verifier and prover. diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala index 26593f0160..37ed4a916c 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala @@ -5,18 +5,22 @@ import sigma.util.CollectionUtil._ import sigma.VersionContext import sigma.kiama.rewriting.Strategy import sigma.data.TrivialProp.{FalseProp, TrueProp} -import sigmastate.Values._ +import sigma.ast._ import sigma.VersionContext.MaxSupportedScriptVersion import sigmastate._ import sigmastate.crypto.DLogProtocol._ import sigmastate.crypto.VerifierMessage.Challenge import sigmastate.crypto._ import sigmastate.crypto.{GF2_192, GF2_192_Poly} -import sigmastate.exceptions.InterpreterException import sigmastate.utils.Helpers import sigma.Coll import sigma.Extensions.ArrayOps +import sigma.crypto.CryptoConstants import sigma.data.{CAND, COR, CTHRESHOLD, ProveDHTuple, ProveDlog, SigmaBoolean} +import sigma.exceptions.InterpreterException +import sigma.interpreter.CostedProverResult +import sigma.serialization.SigSerializer +import sigma.util.CollectionUtil import java.math.BigInteger import scala.util.Try @@ -27,7 +31,7 @@ import scala.util.Try */ trait ProverInterpreter extends Interpreter with ProverUtils { - import CryptoConstants.secureRandomBytes + import sigma.crypto.CryptoConstants.secureRandomBytes import Interpreter._ override type ProofT = UncheckedTree @@ -95,7 +99,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { // Prover Step 8: compute the challenge for the root of the tree as the Fiat-Shamir hash of propBytes // and the message being signed. - val rootChallenge = Challenge @@ CryptoFunctions.hashFn(Helpers.concatArrays(propBytes, message)).toColl + val rootChallenge = Challenge @@ CryptoFunctions.hashFn(CollectionUtil.concatArrays_v5(propBytes, message)).toColl val step8 = step6.withChallenge(rootChallenge) // Prover Step 9: complete the proof by computing challenges at real nodes and additionally responses at real leaves @@ -147,7 +151,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { hintsBag: HintsBag): Array[Byte] = { val proofTree = sb match { case TrueProp => NoProof - case FalseProp => error("Script reduced to false") + case FalseProp => syntax.error("Script reduced to false") case sigmaTree => val unprovenTree = convertToUnproven(sigmaTree) prove(unprovenTree, message, hintsBag) @@ -189,7 +193,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { } ul.withSimulated(!isReal) case t: UnprovenTree => - error(s"Don't know how to markReal($t)") + syntax.error(s"Don't know how to markReal($t)") }) /** @@ -386,11 +390,11 @@ trait ProverInterpreter extends Interpreter with ProverUtils { if (su.simulated) { // Step 5 (simulated leaf -- complete the simulation) assert(su.challengeOpt.isDefined) - val (fm, sm) = DLogInteractiveProver.simulate(su.proposition, su.challengeOpt.get) + val (fm, sm) = DLogProver.simulate(su.proposition, su.challengeOpt.get) UncheckedSchnorr(su.proposition, Some(fm), su.challengeOpt.get, sm) } else { // Step 6 -- compute the commitment - val (r, commitment) = DLogInteractiveProver.firstMessage() + val (r, commitment) = DLogProver.firstMessage() su.copy(commitmentOpt = Some(commitment), randomnessOpt = Some(r)) } } @@ -406,23 +410,23 @@ trait ProverInterpreter extends Interpreter with ProverUtils { if (dhu.simulated) { // Step 5 (simulated leaf -- complete the simulation) assert(dhu.challengeOpt.isDefined) - val (fm, sm) = DiffieHellmanTupleInteractiveProver.simulate(dhu.proposition, dhu.challengeOpt.get) + val (fm, sm) = DiffieHellmanTupleProver.simulate(dhu.proposition, dhu.challengeOpt.get) UncheckedDiffieHellmanTuple(dhu.proposition, Some(fm), dhu.challengeOpt.get, sm) } else { // Step 6 -- compute the commitment - val (r, fm) = DiffieHellmanTupleInteractiveProver.firstMessage(dhu.proposition) + val (r, fm) = DiffieHellmanTupleProver.firstMessage(dhu.proposition) dhu.copy(commitmentOpt = Some(fm), randomnessOpt = Some(r)) } } - case t: ProofTree => error(s"Don't know how to challengeSimulated($t)") + case t: ProofTree => syntax.error(s"Don't know how to challengeSimulated($t)") }) private def extractChallenge(pt: ProofTree): Option[Challenge] = pt match { case upt: UnprovenTree => upt.challengeOpt case sn: UncheckedSchnorr => Some(sn.challenge) case dh: UncheckedDiffieHellmanTuple => Some(dh.challenge) - case _ => error(s"Cannot extractChallenge($pt)") + case _ => syntax.error(s"Cannot extractChallenge($pt)") } /** @@ -494,12 +498,12 @@ trait ProverInterpreter extends Interpreter with ProverUtils { val z = privKeyOpt match { case Some(privKey: DLogProverInput) => hintsBag.ownCommitments.find(_.position == su.position).map { oc => - DLogInteractiveProver.secondMessage( + DLogProver.secondMessage( privKey, oc.secretRandomness, su.challengeOpt.get) }.getOrElse { - DLogInteractiveProver.secondMessage( + DLogProver.secondMessage( privKey, su.randomnessOpt.get, su.challengeOpt.get) @@ -527,12 +531,12 @@ trait ProverInterpreter extends Interpreter with ProverUtils { val z = privKeyOpt match { case Some(privKey) => hintsBag.ownCommitments.find(_.position == dhu.position).map { oc => - DiffieHellmanTupleInteractiveProver.secondMessage( + DiffieHellmanTupleProver.secondMessage( privKey.asInstanceOf[DiffieHellmanTupleProverInput], oc.secretRandomness, dhu.challengeOpt.get) }.getOrElse { - DiffieHellmanTupleInteractiveProver.secondMessage( + DiffieHellmanTupleProver.secondMessage( privKey.asInstanceOf[DiffieHellmanTupleProverInput], dhu.randomnessOpt.get, dhu.challengeOpt.get) @@ -580,7 +584,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { case dh: ProveDHTuple => UnprovenDiffieHellmanTuple(dh, None, None, None, simulated = false) case _ => - error(s"Cannot convertToUnproven($sigmaTree)") + syntax.error(s"Cannot convertToUnproven($sigmaTree)") } //converts ProofTree => UncheckedSigmaTree @@ -594,7 +598,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { case s: UncheckedSchnorr => s case d: UncheckedDiffieHellmanTuple => d case a: Any => - error(s"Cannot convertToUnproven($a)") + syntax.error(s"Cannot convertToUnproven($a)") } /** diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala index 64652b5158..15daaec382 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala @@ -1,10 +1,11 @@ package sigmastate.interpreter +import sigma.ast.ErgoTree import sigma.data.{ProveDHTuple, ProveDlog, SigmaBoolean, SigmaConjecture, SigmaLeaf} +import sigma.serialization.SigSerializer import sigmastate._ -import sigmastate.ErgoTree -import sigmastate.crypto.DLogProtocol.DLogInteractiveProver -import sigmastate.crypto.DiffieHellmanTupleInteractiveProver +import sigmastate.crypto.DLogProtocol.DLogProver +import sigmastate.crypto.DiffieHellmanTupleProver trait ProverUtils extends Interpreter { @@ -45,9 +46,9 @@ trait ProverUtils extends Interpreter { if (generateFor.contains(leaf)) { val (r, a) = leaf match { case _: ProveDlog => - DLogInteractiveProver.firstMessage() + DLogProver.firstMessage() case pdh: ProveDHTuple => - DiffieHellmanTupleInteractiveProver.firstMessage(pdh) + DiffieHellmanTupleProver.firstMessage(pdh) case _ => ??? } val hints = Seq(OwnCommitment(leaf, r, a, position), RealCommitment(leaf, a, position)) diff --git a/interpreter/shared/src/main/scala/sigmastate/lang/Terms.scala b/interpreter/shared/src/main/scala/sigmastate/lang/Terms.scala deleted file mode 100644 index 04403a3f83..0000000000 --- a/interpreter/shared/src/main/scala/sigmastate/lang/Terms.scala +++ /dev/null @@ -1,361 +0,0 @@ -package sigmastate.lang - -import sigma.kiama.rewriting.Rewriter._ -import sigma.data.Nullable -import sigma.ast.SCollection.{SByteArray, SIntArray} -import sigmastate.Values._ -import sigmastate.utils.Overloading.Overload1 -import sigmastate._ -import sigmastate.interpreter.{ErgoTreeEvaluator, Interpreter} -import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv -import sigmastate.serialization.OpCodes -import sigmastate.lang.TransformingSigmaBuilder._ - -import scala.language.implicitConversions -import scala.collection.compat.immutable.ArraySeq -import debox.cfor -import sigma.ast._ -import sigmastate.serialization.ValueCodes.OpCode - -object Terms { - - /** Frontend representation of a block of Val definitions. - * { val x = ...; val y = ... } - * This node is not part of ErgoTree and hence have Undefined opCode. */ - case class Block(bindings: Seq[Val], result: SValue) extends Value[SType] { - override def companion = Block - override def tpe: SType = result.tpe - - /** This is not used as operation, but rather to form a program structure */ - override def opType: SFunc = Value.notSupportedError(this, "opType") - } - object Block extends ValueCompanion { - override def opCode: OpCode = OpCodes.Undefined - override def costKind: CostKind = Value.notSupportedError(this, "costKind") - def apply(let: Val, result: SValue)(implicit o1: Overload1): Block = - Block(Seq(let), result) - } - - /** IR node to represent explicit Zero Knowledge scope in ErgoTree. - * Compiler checks Zero Knowledge properties and issue error message is case of violations. - * ZK-scoping is optional, it can be used when the user want to ensure Zero Knowledge of - * specific set of operations. - * Usually it will require simple restructuring of the code to make the scope body explicit. - * Invariants checked by the compiler: - * - single ZKProof in ErgoTree in a root position - * - no boolean operations in the body, because otherwise the result may be disclosed - * - all the operations are over SigmaProp values - * - * For motivation and details see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/236 - * */ - case class ZKProofBlock(body: SigmaPropValue) extends BoolValue { - override def companion = ZKProofBlock - override def tpe = SBoolean - override def opType: SFunc = ZKProofBlock.OpType - } - object ZKProofBlock extends ValueCompanion { - override def opCode: OpCode = OpCodes.Undefined - override def costKind: CostKind = Value.notSupportedError(this, "costKind") - val OpType = SFunc(SSigmaProp, SBoolean) - } - - trait Val extends Value[SType] { - val name: String - val givenType: SType - val body: SValue - } - object Val { - def apply(name: String, body: SValue): Val = ValNode(name, NoType, body) - def apply(name: String, givenType: SType, body: SValue): Val = ValNode(name, givenType, body) - def unapply(v: SValue): Option[(String, SType, SValue)] = v match { - case ValNode(name, givenType, body) => Some((name, givenType, body)) - case _ => None - } - } - - case class ValNode(name: String, - givenType: SType, - body: SValue) extends Val { - override def companion = ValNode - override def tpe: SType = givenType ?: body.tpe - /** This is not used as operation, but rather to form a program structure */ - override def opType: SFunc = Value.notSupportedError(this, "opType") - } - object ValNode extends ValueCompanion { - override def opCode: OpCode = OpCodes.Undefined - override def costKind: CostKind = Value.notSupportedError(this, "costKind") - } - - /** Frontend node to select a field from an object. Should be transformed to SelectField*/ - case class Select(obj: Value[SType], field: String, resType: Option[SType] = None) extends Value[SType] { - override def companion = Select - override val tpe: SType = resType.getOrElse(obj.tpe match { - case p: SProduct => - MethodsContainer.getMethod(p, field) match { - case Some(m) => m.stype - case None => NoType - } - case _ => NoType - }) - override def opType: SFunc = SFunc(obj.tpe, tpe) - } - object Select extends ValueCompanion { - override def opCode: OpCode = OpCodes.Undefined - override def costKind: CostKind = Value.notSupportedError(this, "costKind") - } - - /** Frontend node to represent variable names parsed in a source code. - * Should be resolved during compilation to lambda argument, Val definition or - * compilation environment value. */ - case class Ident(name: String, tpe: SType = NoType) extends Value[SType] { - override def companion = Ident - override def opType: SFunc = SFunc(ArraySeq.empty, tpe) - } - object Ident extends ValueCompanion { - override def opCode: OpCode = OpCodes.Undefined - override def costKind: CostKind = Value.notSupportedError(this, "costKind") - def apply(name: String): Ident = Ident(name, NoType) - } - - // TODO refactor: move to sigmastate.Values - /** ErgoTree node which represents application of function `func` to the given arguments. - * @param func expression which evaluates to a function - * @param args arguments of the function application - */ - case class Apply(func: Value[SType], args: IndexedSeq[Value[SType]]) extends Value[SType] { - override def companion = Apply - override lazy val tpe: SType = func.tpe match { - case SFunc(_, r, _) => r - case tColl: SCollectionType[_] => tColl.elemType - case _ => NoType - } - override lazy val opType: SFunc = { - val nArgs = args.length - val argTypes = new Array[SType](nArgs + 1) - argTypes(0) = func.tpe - cfor(0)(_ < nArgs, _ + 1) { i => - argTypes(i + 1) = args(i).tpe - } - SFunc(argTypes, tpe) - } - - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - addCost(Apply.costKind) - if (args.length == 1) { - val fV = func.evalTo[Any => Any](env) - val argV = args(0).evalTo[Any](env) - fV(argV) - } else { - // zero or more than 1 argument functions are not supported in v4.x, v5.0 - // see `case Terms.Apply(f, Seq(x))` in RuntimeCosting which means other cases are not supported. - Interpreter.error(s"Function application must have 1 argument, but was: $this") - } - } - } - object Apply extends FixedCostValueCompanion { - override def opCode: OpCode = OpCodes.FuncApplyCode - /** Cost of: 1) switch on the number of args 2) Scala method call 3) add args to env - * Old cost: lambdaInvoke == 30 */ - override val costKind = FixedCost(JitCost(30)) - } - - /** Apply types for type parameters of input value. */ - case class ApplyTypes(input: Value[SType], tpeArgs: Seq[SType]) extends Value[SType] { node => - override def companion = ApplyTypes - override lazy val tpe: SType = input.tpe match { - case funcType: SFunc => - val subst = funcType.tpeParams.map(_.ident).zip(tpeArgs).toMap - applySubst(input.tpe, subst) - case _ => input.tpe - } - /** This is not used as operation, but rather to form a program structure */ - override def opType: SFunc = Value.notSupportedError(this, "opType") - } - object ApplyTypes extends ValueCompanion { - override def opCode: OpCode = OpCodes.Undefined - override def costKind: CostKind = Value.notSupportedError(this, "costKind") - } - - /** Frontend node to represent potential method call in a source code. - * Should be resolved during compilation to MethodCall. - * Cannot be serialized to ErgoTree. */ - case class MethodCallLike(obj: Value[SType], name: String, args: IndexedSeq[Value[SType]], tpe: SType = NoType) extends Value[SType] { - override def companion = MethodCallLike - override def opType: SFunc = SFunc(obj.tpe +: args.map(_.tpe), tpe) - } - object MethodCallLike extends ValueCompanion { - override def opCode: OpCode = OpCodes.Undefined - override def costKind: CostKind = Value.notSupportedError(this, "costKind") - } - - /** Represents in ErgoTree an invocation of method of the object `obj` with arguments `args`. - * The SMethod instances in STypeCompanions may have type STypeIdent in methods types, - * but valid ErgoTree should have SMethod instances specialized for specific types of - * obj and args using `specializeFor`. - * This means, if we save typeId, methodId, and we save all the arguments, - * we can restore the specialized SMethod instance. - * This work by induction, if we assume all arguments are monomorphic, - * then we can make MethodCall monomorphic. - * Thus, all ErgoTree instances are monomorphic by construction. - * - * @param obj object on which method will be invoked - * @param method method to be invoked - * @param args arguments passed to the method on invocation - * @param typeSubst a map of concrete type for each generic type parameter - */ - case class MethodCall(obj: Value[SType], - method: SMethod, - args: IndexedSeq[Value[SType]], - typeSubst: Map[STypeVar, SType]) extends Value[SType] { - override def companion = if (args.isEmpty) PropertyCall else MethodCall - override def opType: SFunc = SFunc(obj.tpe +: args.map(_.tpe), tpe) - override val tpe: SType = method.stype match { - case f: SFunc => f.tRange.withSubstTypes(typeSubst) - case t => t.withSubstTypes(typeSubst) - } - - /** @hotspot don't beautify this code */ - protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { - val objV = obj.evalTo[Any](env) - addCost(MethodCall.costKind) // MethodCall overhead - method.costKind match { - case fixed: FixedCost => - val extra = method.extraDescriptors - val extraLen = extra.length - val len = args.length - val argsBuf = new Array[Any](len + extraLen) - cfor(0)(_ < len, _ + 1) { i => - argsBuf(i) = args(i).evalTo[Any](env) - } - cfor(0)(_ < extraLen, _ + 1) { i => - argsBuf(len + i) = extra(i) - } - var res: Any = null - E.addFixedCost(fixed, method.opDesc) { - res = method.invokeFixed(objV, argsBuf) - } - res - case _ => - val len = args.length - val argsBuf = new Array[Any](len + 3) - argsBuf(0) = this - argsBuf(1) = objV - cfor(0)(_ < len, _ + 1) { i => - argsBuf(i + 2) = args(i).evalTo[Any](env) - } - argsBuf(argsBuf.length - 1) = E - - val evalMethod = method.genericMethod.evalMethod - evalMethod.invoke(method.objType, argsBuf.asInstanceOf[Array[AnyRef]]:_*) - } - } - } - - object MethodCall extends FixedCostValueCompanion { - override def opCode: OpCode = OpCodes.MethodCallCode - /** Cost of: 1) packing args into Array 2) RMethod.invoke */ - override val costKind = FixedCost(JitCost(4)) - - /** Helper constructor which allows to cast the resulting node to the specified - * [[sigmastate.Values.Value]] type `T`. - * @see [[sigmastate.lang.Terms.MethodCall]] - */ - def typed[T <: SValue](obj: Value[SType], - method: SMethod, - args: IndexedSeq[Value[SType]], - typeSubst: Map[STypeVar, SType]): T = { - MethodCall(obj, method, args, typeSubst).asInstanceOf[T] - } - } - object PropertyCall extends FixedCostValueCompanion { - override def opCode: OpCode = OpCodes.PropertyCallCode - /** Cost of: 1) packing args into Array 2) RMethod.invoke */ - override val costKind = FixedCost(JitCost(4)) - } - - /** Frontend implementation of lambdas. Should be transformed to FuncValue. */ - case class Lambda( - tpeParams: Seq[STypeParam], - args: IndexedSeq[(String,SType)], - givenResType: SType, - body: Option[Value[SType]]) extends Value[SFunc] - { - require(!(tpeParams.nonEmpty && body.nonEmpty), s"Generic function definitions are not supported, but found $this") - override def companion = Lambda - override lazy val tpe: SFunc = { - val sRange = givenResType ?: body.fold(NoType: SType)(_.tpe) - SFunc(args.map(_._2), sRange, tpeParams) - } - /** This is not used as operation, but rather to form a program structure */ - override def opType: SFunc = SFunc(Vector(), tpe) - } - object Lambda extends ValueCompanion { - override def opCode: OpCode = OpCodes.Undefined - override def costKind: CostKind = Value.notSupportedError(this, "costKind") - def apply(args: IndexedSeq[(String,SType)], resTpe: SType, body: Value[SType]): Lambda = - Lambda(Nil, args, resTpe, Some(body)) - def apply(args: IndexedSeq[(String,SType)], resTpe: SType, body: Option[Value[SType]]): Lambda = - Lambda(Nil, args, resTpe, body) - def apply(args: IndexedSeq[(String,SType)], body: Value[SType]): Lambda = Lambda(Nil, args, NoType, Some(body)) - } - - /** Operation identity descriptor used in AOT costing (see usages in RuntimeCosting and - * CostTable) */ - case class OperationId(name: String, opType: SFunc) - - implicit class ValueOps(val v: Value[SType]) extends AnyVal { - def asValue[T <: SType]: Value[T] = v.asInstanceOf[Value[T]] - def asNumValue: Value[SNumericType] = v.asInstanceOf[Value[SNumericType]] - def asStringValue: Value[SString.type] = v.asInstanceOf[Value[SString.type]] - def asBoolValue: Value[SBoolean.type] = v.asInstanceOf[Value[SBoolean.type]] - def asByteValue: Value[SByte.type] = v.asInstanceOf[Value[SByte.type]] - def asShortValue: Value[SShort.type] = v.asInstanceOf[Value[SShort.type]] - def asIntValue: Value[SInt.type] = v.asInstanceOf[Value[SInt.type]] - def asLongValue: Value[SLong.type] = v.asInstanceOf[Value[SLong.type]] - def asBigInt: Value[SBigInt.type] = v.asInstanceOf[Value[SBigInt.type]] - def asBox: Value[SBox.type] = v.asInstanceOf[Value[SBox.type]] - def asGroupElement: Value[SGroupElement.type] = v.asInstanceOf[Value[SGroupElement.type]] - def asSigmaProp: Value[SSigmaProp.type] = v.asInstanceOf[Value[SSigmaProp.type]] - def asByteArray: Value[SByteArray] = v.asInstanceOf[Value[SByteArray]] - def asIntArray: Value[SIntArray] = v.asInstanceOf[Value[SIntArray]] - def asCollection[T <: SType]: Value[SCollection[T]] = v.asInstanceOf[Value[SCollection[T]]] - def asOption[T <: SType]: Value[SOption[T]] = v.asInstanceOf[Value[SOption[T]]] - def asTuple: Value[STuple] = v.asInstanceOf[Value[STuple]] - def asFunc: Value[SFunc] = v.asInstanceOf[Value[SFunc]] - def asConcreteCollection[T <: SType]: ConcreteCollection[T] = v.asInstanceOf[ConcreteCollection[T]] - def upcastTo[T <: SNumericType](targetType: T): Value[T] = { - assert(v.tpe.isInstanceOf[SNumericType], - s"Cannot upcast value of type ${v.tpe} to $targetType: only numeric types can be upcasted.") - val tV = v.asValue[SNumericType] - assert(targetType.max(tV.tpe) == targetType, - s"Invalid upcast from $tV to $targetType: target type should be larger than source type.") - if (targetType == tV.tpe) v.asValue[T] - else - mkUpcast(tV, targetType).withSrcCtx(v.sourceContext) - } - def withSrcCtx[T <: SType](sourceContext: Nullable[SourceContext]): Value[T] = { - v.sourceContext = sourceContext - v.asValue[T] - } - /** - * Set source context only if it's empty - */ - def withEnsuredSrcCtx[T <: SType](sourceContext: Nullable[SourceContext]): Value[T] = { - if (v.sourceContext.isEmpty) v.sourceContext = sourceContext - v.asValue[T] - } - /** - * Set source context to all nodes missing source context in the given tree. - * @param srcCtx source context to set - * @return AST where all nodes with missing source context are set to the given srcCtx - */ - def withPropagatedSrcCtx[T <: SType](srcCtx: Nullable[SourceContext]): Value[T] = { - rewrite(everywherebu(rule[Any] { - case node: SValue if node != null && node.sourceContext.isEmpty => - node.withSrcCtx(srcCtx) - }))(v).asValue[T] - } - - } - -} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala deleted file mode 100644 index 839727f705..0000000000 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala +++ /dev/null @@ -1,25 +0,0 @@ -package sigmastate.serialization - -import sigma.ast.SType -import sigma.serialization.CoreByteWriter.DataInfo -import sigmastate.Values.SValue -import sigmastate.Values -import sigmastate.lang.Terms._ -import sigmastate.utils.SigmaByteWriter._ -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.SigmaPropBytes - -object SigmaPropBytesSerializer extends ValueSerializer[SigmaPropBytes] { - import sigmastate.Operations.SigmaPropBytesInfo._ - override def opDesc = SigmaPropBytes - val thisInfo: DataInfo[SValue] = thisArg - - def serialize(obj: SigmaPropBytes, w: SigmaByteWriter): Unit = { - w.putValue(obj.input, thisInfo) - } - - def parse(r: SigmaByteReader): Values.Value[SType] = { - val p = r.getValue().asSigmaProp - SigmaPropBytes(p) - } -} diff --git a/interpreter/shared/src/main/scala/sigmastate/sigmastate.scala b/interpreter/shared/src/main/scala/sigmastate/sigmastate.scala index 7761264e20..1c7b8d5ab6 100644 --- a/interpreter/shared/src/main/scala/sigmastate/sigmastate.scala +++ b/interpreter/shared/src/main/scala/sigmastate/sigmastate.scala @@ -1,32 +1,13 @@ -import org.ergoplatform.{ErgoBox, ErgoBoxCandidate, ErgoLikeContext} +import org.ergoplatform.ErgoLikeContext import sigma.ast._ -import sigma.data.{AvlTreeData, GeneralType, RType, SigmaBoolean} -import sigmastate.Values._ -import sigmastate.lang.{CheckingSigmaBuilder, Terms} +import sigma.data.RType -import scala.annotation.nowarn import scala.reflect.classTag package object sigmastate { import CheckingSigmaBuilder._ - /** Shadow the implicit from sigma package so it doesn't interfere with the resolution - * of ClassTags below. - */ - @nowarn private def rtypeToClassTag = ??? - - /** RType descriptors for predefined types used in AOTC-based interpreter. */ - - implicit val SigmaBooleanRType : RType[SigmaBoolean] = RType.fromClassTag(classTag[SigmaBoolean]) - - implicit val ErgoBoxRType : RType[ErgoBox] = RType.fromClassTag(classTag[ErgoBox]) - - implicit val ErgoBoxCandidateRType: RType[ErgoBoxCandidate] = RType.fromClassTag(classTag[ErgoBoxCandidate]) - - implicit val AvlTreeDataRType : RType[AvlTreeData] = GeneralType(classTag[AvlTreeData]) - - implicit val ErgoLikeContextRType : RType[ErgoLikeContext] = RType.fromClassTag(classTag[ErgoLikeContext]) - + implicit val ErgoLikeContextRType: RType[ErgoLikeContext] = RType.fromClassTag(classTag[ErgoLikeContext]) /** Helper method to create "+" operation node. */ def Plus[T <: SNumericType](left: Value[T], right: Value[T]): Value[T] = @@ -55,5 +36,4 @@ package object sigmastate { /** Helper method to create "max" operation node. */ def Max[T <: SNumericType](left: Value[T], right: Value[T]): Value[T] = mkMax(left, right) - } diff --git a/interpreter/shared/src/main/scala/sigmastate/utils/Extensions.scala b/interpreter/shared/src/main/scala/sigmastate/utils/Extensions.scala index efc0db041a..54abc40f4e 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utils/Extensions.scala +++ b/interpreter/shared/src/main/scala/sigmastate/utils/Extensions.scala @@ -4,7 +4,7 @@ import org.ergoplatform.ErgoBox.TokenId import scorex.util.{ModifierId, idToBytes} import scorex.utils.{Ints, Longs, Shorts} import sigma.data.Digest32Coll -import sigmastate.eval.SigmaDsl +import sigma.eval.SigmaDsl import sigma.{Coll, Colls} object Extensions { diff --git a/interpreter/shared/src/main/scala/sigmastate/utils/Helpers.scala b/interpreter/shared/src/main/scala/sigmastate/utils/Helpers.scala index 1e867cff28..1741531dfb 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utils/Helpers.scala +++ b/interpreter/shared/src/main/scala/sigmastate/utils/Helpers.scala @@ -7,7 +7,7 @@ import sigma.data.{CAnyValue, OverloadHack, RType} import scorex.utils.Ints import sigma.crypto.EcPointType import sigma.{Coll, Colls, Environment, GroupElement} -import sigmastate.eval.SigmaDsl +import sigma.eval.SigmaDsl import java.util import java.util.concurrent.locks.Lock @@ -58,37 +58,6 @@ object Helpers { target } - /** Concatenates two arrays into a new resulting array. - * All items of both arrays are copied to the result using System.arraycopy. - */ - def concatArrays[T:ClassTag](arr1: Array[T], arr2: Array[T]): Array[T] = { - val l1 = arr1.length - val l2 = arr2.length - val length: Int = l1 + l2 - val result: Array[T] = new Array[T](length) - System.arraycopy(arr1, 0, result, 0, l1) - System.arraycopy(arr2, 0, result, l1, l2) - result - } - - def castArray[A, B >: A : ClassTag](array: Array[A]): Array[B] = { - val result: Array[B] = new Array[B](array.length) - System.arraycopy(array, 0, result, 0, array.length) - result - } - - def deepHashCode[T](arr: Array[T]): Int = arr match { - case arr: Array[AnyRef] => java.util.Arrays.deepHashCode(arr) - case arr: Array[Byte] => java.util.Arrays.hashCode(arr) - case arr: Array[Short] => java.util.Arrays.hashCode(arr) - case arr: Array[Int] => java.util.Arrays.hashCode(arr) - case arr: Array[Long] => java.util.Arrays.hashCode(arr) - case arr: Array[Char] => java.util.Arrays.hashCode(arr) - case arr: Array[Float] => java.util.Arrays.hashCode(arr) - case arr: Array[Double] => java.util.Arrays.hashCode(arr) - case arr: Array[Boolean] => java.util.Arrays.hashCode(arr) - } - /** Optimized hashCode for array of bytes when it represents some hash thus it have * enough randomness and we can use only first 4 bytes. * @param id result of some hash function @@ -174,29 +143,5 @@ object Helpers { res } - /** Encapsulate platform-specific logic of ensuring the value carries its precise type. - * For JVM this is identity function. - * For JS it can transform to AnyValue, if the type is numeric - */ - def ensureTypeCarringValue(v: Any, tT: RType[Any]): Any = - if (Environment.current.isJVM) v - else { // JS - v match { - case _: Byte | _: Short | _: Int => - // this is necessary for JS where Byte, Short, Int have the same runtime class - // and hence we need to pass the type information explicitly - CAnyValue(v)(tT, OverloadHack.overloaded1) - case _ => v - } - } } -object Overloading { - class Overload1 - class Overload2 - class Overload3 - - implicit val overload1: Overload1 = new Overload1 - implicit val overload2: Overload2 = new Overload2 - implicit val overload3: Overload3 = new Overload3 -} diff --git a/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala b/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala deleted file mode 100644 index be98a6affa..0000000000 --- a/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala +++ /dev/null @@ -1,94 +0,0 @@ -package sigmastate.utxo - -import sigma.ast.TypeCodes.LastConstantCode -import sigmastate.serialization.ValueSerializer.getSerializer -import sigma.util.Extensions.ByteOps -import sigmastate.SMethod -import sigmastate.serialization.ValueCodes.OpCode - -import scala.collection.mutable - -object ComplexityTableStat { - // NOTE: this class is mutable so better to keep it private - private class StatItem( - /** How many times the operation has been executed */ - var count: Long, - /** Sum of all execution times */ - var sum: Long - ) - - /** Timings of op codes */ - private val opStat = mutable.HashMap[OpCode, StatItem]() - - /** Timings of method calls */ - private val mcStat = mutable.HashMap[(Byte, Byte), StatItem]() - - def addOpTime(op: OpCode, time: Long) = { - opStat.get(op) match { - case Some(item) => - item.count += 1 - item.sum += time - case None => - opStat(op) = new StatItem(1, time) - } - } - - def addMcTime(typeId: Byte, methodId: Byte, time: Long) = { - mcStat.get((typeId, methodId)) match { - case Some(item) => - item.count += 1 - item.sum += time - case None => - mcStat((typeId, methodId)) = new StatItem(1, time) - } - } - - /** Prints the complexity table - * */ - def complexityTableString: String = { - val opCodeLines = opStat.map { case (opCode, item) => - val avgTime = item.sum / item.count - val time = avgTime / 1000 - val ser = getSerializer(opCode) - val opName = ser.opDesc.typeName - (opName, (opCode.toUByte - LastConstantCode).toString, time, item.count.toString) - }.toList.sortBy(_._3)(Ordering[Long].reverse) - - val mcLines = mcStat.map { case (id @ (typeId, methodId), item) => - val avgTime = item.sum / item.count - val time = avgTime / 1000 - val m = SMethod.fromIds(typeId, methodId) - val typeName = m.objType.typeName - (s"$typeName.${m.name}", typeId, methodId, time, item.count.toString) - }.toList.sortBy(r => (r._2,r._3))(Ordering[(Byte,Byte)].reverse) - -// val lines = (("Op", "OpCode", "Avg Time,us", "Count") :: opCodeLines ::: mcLines) -// .map { case (opName, opCode, time, count) => -// s"${opName.padTo(30, ' ')}\t${opCode.padTo(7, ' ')}\t${time.padTo(9, ' ')}\t${count}" -// } -// .mkString("\n") - - val rows = (opCodeLines) - .map { case (opName, opCode, time, count) => - val key = s"$opName.opCode".padTo(30, ' ') - s"$key -> $time, // count = $count " - } - .mkString("\n") - - val mcRows = (mcLines) - .map { case (opName, typeId, methodId, time, count) => - val key = s"($typeId.toByte, $methodId.toByte)".padTo(25, ' ') - s"$key -> $time, // count = $count, $opName " - } - .mkString("\n") - -// val total = opStat.values.foldLeft(0L) { (acc, item) => acc + item.sum } - s""" - |----------- - |$rows - |----------- - |$mcRows - |----------- - """.stripMargin - } -} diff --git a/interpreter/shared/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala b/interpreter/shared/src/test/scala/sigma/ast/SigmaBuilderTest.scala similarity index 96% rename from interpreter/shared/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala rename to interpreter/shared/src/test/scala/sigma/ast/SigmaBuilderTest.scala index 95ee94c680..acf8e74bd2 100644 --- a/interpreter/shared/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala +++ b/interpreter/shared/src/test/scala/sigma/ast/SigmaBuilderTest.scala @@ -1,18 +1,15 @@ -package sigmastate.lang +package sigma.ast import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import sigma.data.{CAnyValue, CAvlTree, Nullable, RType} -import sigma.{Environment, VersionContext} -import sigmastate.Values._ -import sigmastate._ import sigma.Extensions.ArrayOps -import sigmastate.eval.{CBox, SigmaDsl} -import sigmastate.exceptions.ConstraintFailed -import sigmastate.serialization.OpCodes -import sigma.SigmaTestingData -import sigma.ast._ +import sigma.data.{CAnyValue, CAvlTree, CBox, Nullable, RType} +import sigma.eval.SigmaDsl +import sigma.exceptions.ConstraintFailed +import sigma.serialization.OpCodes +import sigma.{Environment, SigmaTestingData, VersionContext} +import sigmastate._ import java.math.BigInteger @@ -80,7 +77,7 @@ class SigmaBuilderTest extends AnyPropSpec with ScalaCheckPropertyChecks with Ma an[ConstraintFailed] should be thrownBy mkDivide(LongConstant(1), IntConstant(1)) an[ConstraintFailed] should be thrownBy mkModulo(LongConstant(1), IntConstant(1)) } - import Platform.liftToConstant + import sigma.Platform.liftToConstant def testSuccess(v: Any, c: Constant[SType]): Unit = { liftToConstant(v, TransformingSigmaBuilder) shouldBe Nullable(c) diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/AndSerializerSpecification.scala similarity index 84% rename from interpreter/shared/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/AndSerializerSpecification.scala index 71e8c607ce..bc7e678062 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/AndSerializerSpecification.scala @@ -1,11 +1,10 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values.{BooleanConstant, Constant, IntConstant} -import sigmastate._ -import sigmastate.serialization.OpCodes._ +import sigma.ast.{AND, BooleanConstant, Constant, EQ, IntConstant, SBoolean, SCollection, SCollectionType, SInt} +import sigma.serialization.OpCodes._ import scorex.util.encode.ZigZagEncoder.encodeZigZagInt import sigma.Extensions.ArrayOps -import sigma.ast.{SBoolean, SCollection, SCollectionType, SInt} +import sigma.ast.syntax.BooleanConstant class AndSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/AvlTreeSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/AvlTreeSpecification.scala similarity index 95% rename from interpreter/shared/src/test/scala/sigmastate/serialization/AvlTreeSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/AvlTreeSpecification.scala index d068492625..1bd3b47983 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/AvlTreeSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/AvlTreeSpecification.scala @@ -1,13 +1,13 @@ -package sigmastate.serialization +package sigma.serialization import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert} import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.Colls import sigma.data.{AvlTreeData, AvlTreeFlags} -import sigmastate.Values.AvlTreeConstant -import sigmastate.eval._ +import sigma.ast.AvlTreeConstant import sigma.Extensions.ArrayOps +import sigma.eval.SigmaDsl import sigmastate.eval.Extensions.AvlTreeOps class AvlTreeSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/BlockSerializerSpecification.scala similarity index 87% rename from interpreter/shared/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/BlockSerializerSpecification.scala index 54b03ba188..4a242b6fb8 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/BlockSerializerSpecification.scala @@ -1,9 +1,8 @@ -package sigmastate.serialization +package sigma.serialization import org.scalacheck.Gen -import sigma.ast.SType -import sigmastate.Values.Constant -import sigmastate.lang.{DeserializationSigmaBuilder, SigmaBuilder} +import sigma.ast.{DeserializationSigmaBuilder, SType, SigmaBuilder} +import sigma.ast.Constant class BlockSerializerSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/ConcreteCollectionSerializerSpecification.scala similarity index 86% rename from interpreter/shared/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/ConcreteCollectionSerializerSpecification.scala index bb82ced30f..0c795ea4f4 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/ConcreteCollectionSerializerSpecification.scala @@ -1,10 +1,9 @@ -package sigmastate.serialization +package sigma.serialization import sigma.Evaluation -import sigma.ast.SType -import sigmastate.Values.{ConcreteCollection, Constant, FalseLeaf, IntConstant, TaggedInt, TrueLeaf} -import sigmastate.lang.Terms._ +import sigma.ast.syntax.{IntConstant, OptionValueOps} import sigma.ast._ +import sigma.ast.syntax._ import scala.util.Random class ConcreteCollectionSerializerSpecification extends TableSerializationSpecification { @@ -37,8 +36,8 @@ class ConcreteCollectionSerializerSpecification extends TableSerializationSpecif } property("ConcreteCollection: Serializer round trip with different types seq") { - forAll { (i: IntConstant, ti: TaggedInt) => - val seq = Random.shuffle(Seq(i.asIntValue, ti.asIntValue)).toArray + forAll(intConstGen, getVarIntGen) { (i: IntConstant, ti: GetVar[SInt.type]) => + val seq = Random.shuffle(Seq(i.asIntValue, ti.get)).toArray roundTripTest(ConcreteCollection.fromSeq(seq)) } } diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/ConstantSerializerSpecification.scala similarity index 95% rename from interpreter/shared/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/ConstantSerializerSpecification.scala index 788090fed6..7bc73643f2 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/ConstantSerializerSpecification.scala @@ -1,23 +1,22 @@ -package sigmastate.serialization +package sigma.serialization import java.math.BigInteger import org.ergoplatform._ import org.scalacheck.Arbitrary._ import sigma.data.{RType, SigmaBoolean, TupleColl} import sigma.ast.SCollection.SByteArray -import sigmastate.Values.{BigIntConstant, ByteArrayConstant, Constant, FalseLeaf, GroupGenerator, LongConstant, SValue, TrueLeaf} +import sigma.ast.{BigIntConstant, ByteArrayConstant, Constant, DeserializationSigmaBuilder, FalseLeaf, GroupGenerator, LongConstant, TrueLeaf} import sigmastate.eval._ import sigma.Extensions.ArrayOps -import sigmastate.Values._ +import sigma.ast._ import sigma.{AvlTree, Colls, Evaluation} import sigma.ast.SType.AnyOps import scorex.util.encode.Base16 -import sigma.ast._ +import sigma.ast.BoolArrayConstant.BoolArrayTypeCode +import sigma.ast.ByteArrayConstant.ByteArrayTypeCode +import sigma.ast.syntax.{BoolValue, SValue} import sigma.crypto.EcPointType -import sigma.serialization.SerializerException import sigma.util.Extensions.{BigIntegerOps, EcpOps, SigmaBooleanOps} -import sigmastate.lang.DeserializationSigmaBuilder - import scala.annotation.nowarn class ConstantSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/ConstantStoreSpecification.scala similarity index 86% rename from interpreter/shared/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/ConstantStoreSpecification.scala index 563c535ac5..f8ebeb34a6 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/ConstantStoreSpecification.scala @@ -1,9 +1,7 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SType -import sigmastate.Values.{Constant, IntConstant} -import sigmastate._ -import sigmastate.lang.{DeserializationSigmaBuilder, SigmaBuilder} +import sigma.ast.{DeserializationSigmaBuilder, SType, SigmaBuilder} +import sigma.ast.{Constant, IntConstant} class ConstantStoreSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala similarity index 93% rename from interpreter/shared/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala index fbad1b6320..ecb2d2ef70 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala @@ -1,11 +1,10 @@ -package sigmastate.serialization +package sigma.serialization import java.math.BigInteger import org.ergoplatform.ErgoBox import org.scalacheck.Arbitrary._ -import sigma.data.{RType, SigmaBoolean, TupleColl} +import sigma.data.{DataValueComparer, RType, SigmaBoolean, TupleColl} import sigma.ast.SCollection.SByteArray -import sigmastate.ErgoTree import sigmastate._ import sigmastate.eval._ import sigma.{AvlTree, Colls, Evaluation} @@ -14,10 +13,10 @@ import sigma.ast._ import org.scalacheck.Gen import sigma.Extensions.ArrayOps import sigma.crypto.EcPointType -import sigma.serialization.SerializerException +import sigma.eval.SigmaDsl import sigma.util.Extensions.{BigIntegerOps, EcpOps, SigmaBooleanOps} -import sigmastate.interpreter.{CostAccumulator, ErgoTreeEvaluator} -import sigmastate.interpreter.ErgoTreeEvaluator.DefaultProfiler +import sigmastate.interpreter.{CostAccumulator, CErgoTreeEvaluator} +import sigmastate.interpreter.CErgoTreeEvaluator.DefaultProfiler import sigmastate.utils.Helpers import scala.annotation.nowarn @@ -33,11 +32,11 @@ class DataSerializerSpecification extends SerializationSpecification { val res = DataSerializer.deserialize(tpe, r) res shouldBe obj - val es = ErgoTreeEvaluator.DefaultEvalSettings + val es = CErgoTreeEvaluator.DefaultEvalSettings val accumulator = new CostAccumulator( initialCost = JitCost(0), costLimit = Some(JitCost.fromBlockCost(es.scriptCostLimitInEvaluator))) - val evaluator = new ErgoTreeEvaluator( + val evaluator = new CErgoTreeEvaluator( context = null, constants = ErgoTree.EmptyConstants, coster = accumulator, DefaultProfiler, es) diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/GroupElementSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/GroupElementSerializerSpecification.scala similarity index 88% rename from interpreter/shared/src/test/scala/sigmastate/serialization/GroupElementSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/GroupElementSerializerSpecification.scala index c4e6bfd9e8..aaaeee2725 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/GroupElementSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/GroupElementSerializerSpecification.scala @@ -1,8 +1,6 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.crypto.CryptoConstants -import sigma.crypto.CryptoFacade -import sigma.serialization.GroupElementSerializer +import sigma.crypto.{CryptoConstants, CryptoFacade} import sigma.util.Extensions.{EcpOps, GroupElementOps} class GroupElementSerializerSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/MethodCallSerializerSpecification.scala similarity index 72% rename from interpreter/shared/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/MethodCallSerializerSpecification.scala index a8cb79f2d6..ac9c997d98 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/MethodCallSerializerSpecification.scala @@ -1,11 +1,6 @@ -package sigmastate.serialization +package sigma.serialization -import org.ergoplatform.Outputs -import sigma.ast.{SBox, SByte, SCollection} -import sigmastate.Values.{FuncValue, ValUse} -import sigmastate.lang.Terms.MethodCall -import sigmastate.utxo.ExtractScriptBytes -import sigmastate._ +import sigma.ast._ class MethodCallSerializerSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/ModQSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/ModQSerializerSpecification.scala similarity index 75% rename from interpreter/shared/src/test/scala/sigmastate/serialization/ModQSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/ModQSerializerSpecification.scala index cfeb881fc6..13cb1b07a2 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/ModQSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/ModQSerializerSpecification.scala @@ -1,7 +1,7 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values.BigIntConstant -import sigmastate._ +import sigma.ast.ModQ +import sigma.ast.syntax.BigIntConstant class ModQSerializerSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/OrSerializerSpecification.scala similarity index 84% rename from interpreter/shared/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/OrSerializerSpecification.scala index d2853f1985..ad61df8a71 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/OrSerializerSpecification.scala @@ -1,11 +1,10 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values.{BooleanConstant, Constant, IntConstant} -import sigmastate._ -import sigmastate.serialization.OpCodes._ +import sigma.ast.{BooleanConstant, Constant, EQ, IntConstant, OR, SBoolean, SCollection, SCollectionType, SInt} +import sigma.serialization.OpCodes._ import scorex.util.encode.ZigZagEncoder.encodeZigZagInt import sigma.Extensions.ArrayOps -import sigma.ast.{SBoolean, SCollection, SCollectionType, SInt} +import sigma.ast.syntax.BooleanConstant class OrSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/PDHTSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/PDHTSerializerSpecification.scala similarity index 90% rename from interpreter/shared/src/test/scala/sigmastate/serialization/PDHTSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/PDHTSerializerSpecification.scala index 1023f641ee..bc57decbf8 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/PDHTSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/PDHTSerializerSpecification.scala @@ -1,7 +1,7 @@ -package sigmastate.serialization +package sigma.serialization import sigma.data.ProveDHTuple -import sigmastate.eval.Extensions.SigmaBooleanOps +import sigma.eval.Extensions.SigmaBooleanOps class PDHTSerializerSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/ProveDlogSerializerSpec.scala b/interpreter/shared/src/test/scala/sigma/serialization/ProveDlogSerializerSpec.scala similarity index 73% rename from interpreter/shared/src/test/scala/sigmastate/serialization/ProveDlogSerializerSpec.scala rename to interpreter/shared/src/test/scala/sigma/serialization/ProveDlogSerializerSpec.scala index 06c4ebd865..cce194b3ce 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/ProveDlogSerializerSpec.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/ProveDlogSerializerSpec.scala @@ -1,7 +1,7 @@ -package sigmastate.serialization +package sigma.serialization import sigma.data.ProveDlog -import sigmastate.eval.Extensions.SigmaBooleanOps +import sigma.eval.Extensions.SigmaBooleanOps class ProveDlogSerializerSpec extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/RelationsSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/RelationsSpecification.scala similarity index 92% rename from interpreter/shared/src/test/scala/sigmastate/serialization/RelationsSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/RelationsSpecification.scala index 7526cebd49..44bdabebf8 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/RelationsSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/RelationsSpecification.scala @@ -1,9 +1,8 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values._ -import sigmastate._ -import sigmastate.serialization.OpCodes._ -import sigmastate.serialization.ValueSerializer._ +import sigma.ast._ +import sigma.serialization.OpCodes._ +import sigma.serialization.ValueSerializer._ import scorex.util.encode.ZigZagEncoder.encodeZigZagLong import sigma.ast.{SInt, SLong} diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/SelectFieldSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/SelectFieldSerializerSpecification.scala similarity index 79% rename from interpreter/shared/src/test/scala/sigmastate/serialization/SelectFieldSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/SelectFieldSerializerSpecification.scala index 678ff1a241..fb3bbcd326 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/SelectFieldSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/SelectFieldSerializerSpecification.scala @@ -1,9 +1,9 @@ -package sigmastate.serialization +package sigma.serialization import org.scalacheck.Gen -import sigmastate.Values.{FalseLeaf, IntConstant, Tuple} -import sigmastate.serialization.OpCodes.{SelectFieldCode, TupleCode} -import sigmastate.utxo.SelectField +import sigma.ast.syntax.CollectionOps +import sigma.ast.{FalseLeaf, IntConstant, SelectField, Tuple} +import sigma.serialization.OpCodes.{SelectFieldCode, TupleCode} class SelectFieldSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/SerializationSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/SerializationSpecification.scala similarity index 94% rename from interpreter/shared/src/test/scala/sigmastate/serialization/SerializationSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/SerializationSpecification.scala index dc7457ed74..30ae6af19b 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/SerializationSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/SerializationSpecification.scala @@ -1,4 +1,4 @@ -package sigmastate.serialization +package sigma.serialization import org.ergoplatform.validation.ValidationSpecification import org.scalacheck.Gen @@ -9,9 +9,9 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.{ScalaCheckDrivenPropertyChecks, ScalaCheckPropertyChecks} import sigma.ast.SType -import sigmastate.Values._ +import sigma.ast._ import sigmastate.helpers.NegativeTesting -import sigmastate.serialization.generators._ +import sigma.serialization.generators._ trait SerializationSpecification extends AnyPropSpec with ScalaCheckPropertyChecks diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/SigSerializerSpecification.scala similarity index 99% rename from interpreter/shared/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/SigSerializerSpecification.scala index c5f2837c99..69d85f16f2 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/SigSerializerSpecification.scala @@ -1,4 +1,4 @@ -package sigmastate.serialization +package sigma.serialization import java.math.BigInteger import org.ergoplatform.settings.ErgoAlgos @@ -6,15 +6,15 @@ import org.scalacheck.{Arbitrary, Gen} import org.scalatest.Assertion import sigma.Extensions.ArrayOps import sigma.data.{AvlTreeData, CAND, COR, CTHRESHOLD, ProveDHTuple, ProveDlog, SigmaBoolean, TrivialProp} +import sigma.eval.Extensions.SigmaBooleanOps import sigmastate._ import sigmastate.crypto.DLogProtocol.SecondDLogProverMessage import sigmastate.crypto.VerifierMessage.Challenge import sigmastate.crypto.SecondDHTupleProverMessage import sigmastate.crypto.GF2_192_Poly -import sigmastate.eval.Extensions.SigmaBooleanOps import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTransactionTesting, TestingCommons} import sigmastate.interpreter.Interpreter -import sigmastate.serialization.generators.ObjectGenerators +import sigma.serialization.generators.ObjectGenerators import sigmastate.utils.Helpers import scala.util.Random diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/SubstConstantsSerializerSpecification.scala similarity index 65% rename from interpreter/shared/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/SubstConstantsSerializerSpecification.scala index 67de9b89a2..9c56fe2d48 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/SubstConstantsSerializerSpecification.scala @@ -1,9 +1,10 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.SInt -import sigmastate.Values.{ConcreteCollection, IntConstant, IntArrayConstant, IntValue} -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.{CrossVersionProps, EQ, SubstConstants} +import sigma.ast.{EQ, SInt, SubstConstants} +import sigma.ast.syntax.IntValue +import sigma.ast.{ConcreteCollection, IntArrayConstant, IntConstant} +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer +import sigmastate.CrossVersionProps class SubstConstantsSerializerSpecification extends SerializationSpecification with CrossVersionProps { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/TableSerializationSpecification.scala similarity index 89% rename from interpreter/shared/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/TableSerializationSpecification.scala index ef60e4a051..6774d03f15 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/TableSerializationSpecification.scala @@ -1,8 +1,8 @@ -package sigmastate.serialization +package sigma.serialization import org.scalatest.prop.TableFor2 import sigma.ast.SType -import sigmastate.Values._ +import sigma.ast._ trait TableSerializationSpecification extends SerializationSpecification { def objects: TableFor2[_ <: Value[_ <: SType], Array[Byte]] diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala b/interpreter/shared/src/test/scala/sigma/serialization/TransformersSerializationSpec.scala similarity index 97% rename from interpreter/shared/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala rename to interpreter/shared/src/test/scala/sigma/serialization/TransformersSerializationSpec.scala index 96738e78ac..7de1f89512 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/TransformersSerializationSpec.scala @@ -1,8 +1,6 @@ -package sigmastate.serialization +package sigma.serialization -import sigma.ast.{SBoolean, SInt} -import sigmastate._ -import sigmastate.utxo._ +import sigma.ast._ class TransformersSerializationSpec extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TupleSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/TupleSerializerSpecification.scala similarity index 85% rename from interpreter/shared/src/test/scala/sigmastate/serialization/TupleSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/TupleSerializerSpecification.scala index c38a6fe94d..e72890cbb7 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TupleSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/TupleSerializerSpecification.scala @@ -1,6 +1,6 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values.{FalseLeaf, IntConstant, Tuple} +import sigma.ast.{FalseLeaf, IntConstant, Tuple} class TupleSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/TwoArgumentSerializerSpecification.scala similarity index 88% rename from interpreter/shared/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/TwoArgumentSerializerSpecification.scala index ed59095336..e0c04e33b8 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/TwoArgumentSerializerSpecification.scala @@ -1,13 +1,12 @@ -package sigmastate.serialization +package sigma.serialization -import sigmastate.Values.{BigIntConstant, ByteArrayConstant, GroupElementConstant, LongConstant} -import sigmastate._ -import sigmastate.Values._ -import sigmastate.utxo.Append -import OpCodes._ import scorex.util.encode.ZigZagEncoder.encodeZigZagLong -import sigma.ast.SLong -import sigmastate.serialization.ValueCodes.OpCode +import sigma.ast.ByteArrayConstant.ByteArrayTypeCode +import sigma.ast.syntax.{BigIntConstant, GroupElementConstant, LongConstant} +import sigma.ast._ +import sigmastate._ +import sigma.serialization.OpCodes._ +import sigma.serialization.ValueCodes.OpCode class TwoArgumentSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/TypeSerializerSpecification.scala similarity index 99% rename from interpreter/shared/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/TypeSerializerSpecification.scala index bcb045f687..6419faf364 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/TypeSerializerSpecification.scala @@ -1,4 +1,4 @@ -package sigmastate.serialization +package sigma.serialization import org.scalacheck.Arbitrary._ import org.scalatest.Assertion diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/UpcastOnDeserializationSpecification.scala similarity index 72% rename from interpreter/shared/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala rename to interpreter/shared/src/test/scala/sigma/serialization/UpcastOnDeserializationSpecification.scala index 17bce3e652..5a2f4dc1eb 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/UpcastOnDeserializationSpecification.scala @@ -1,11 +1,6 @@ -package sigmastate.serialization +package sigma.serialization -import org.ergoplatform.Outputs -import sigma.ast.{SInt, SLong} -import sigmastate.Values.{ByteConstant, IntConstant, LongConstant} -import sigmastate.lang.CheckingSigmaBuilder -import sigmastate.utxo.ByIndex -import sigmastate.Upcast +import sigma.ast._ class UpcastOnDeserializationSpecification extends SerializationSpecification { import CheckingSigmaBuilder._ diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala b/interpreter/shared/src/test/scala/sigma/serialization/generators/ConcreteCollectionGenerators.scala similarity index 86% rename from interpreter/shared/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala rename to interpreter/shared/src/test/scala/sigma/serialization/generators/ConcreteCollectionGenerators.scala index c59e0c58f4..a8d8c8bbf0 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/generators/ConcreteCollectionGenerators.scala @@ -1,9 +1,8 @@ -package sigmastate.serialization.generators +package sigma.serialization.generators import org.scalacheck.{Arbitrary, Gen} -import sigma.ast.{SBoolean, SInt, SSigmaProp, SType} -import sigmastate._ -import sigmastate.Values.{ConcreteCollection, IntConstant, Value} +import sigma.ast.syntax.IntConstant +import sigma.ast.{ConcreteCollection, SBoolean, SInt, SSigmaProp, SType, Value} trait ConcreteCollectionGenerators { self: ObjectGenerators => val minCollLength = 1 diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala b/interpreter/shared/src/test/scala/sigma/serialization/generators/ObjectGenerators.scala similarity index 95% rename from interpreter/shared/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala rename to interpreter/shared/src/test/scala/sigma/serialization/generators/ObjectGenerators.scala index 33a319d075..d4971f88c2 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/generators/ObjectGenerators.scala @@ -1,4 +1,4 @@ -package sigmastate.serialization.generators +package sigma.serialization.generators import org.ergoplatform.ErgoBox._ import sigma.data.SigmaConstants.MaxPropositionBytes @@ -12,24 +12,24 @@ import sigma.data._ import scorex.crypto.authds.{ADDigest, ADKey} import scorex.util.encode.{Base58, Base64} import scorex.util.{ModifierId, bytesToId} -import sigmastate.Values._ -import sigmastate.crypto.CryptoConstants -import sigmastate.eval.Extensions._ +import sigma.ast._ +import sigma.ast.syntax._ import sigmastate.eval._ -import sigmastate.crypto.CryptoConstants.dlogGroup -import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.lang.TransformingSigmaBuilder._ +import sigma.crypto.CryptoConstants.dlogGroup +import TransformingSigmaBuilder._ import sigmastate._ -import sigmastate.utxo._ import sigma.Coll import sigma.Extensions.ArrayOps import sigma._ -import sigma.ast._ -import sigma.crypto.EcPointType +import sigma.ast.syntax.SigmaPropValue +import sigma.crypto.{CryptoConstants, EcPointType} import sigma.util.Extensions.EcpOps import sigma.validation.{ChangedRule, DisabledRule, EnabledRule, ReplacedRule, RuleStatus} import sigma.validation.ValidationRules.FirstRuleId -import sigmastate.ErgoTree.ZeroHeader +import ErgoTree.ZeroHeader +import sigma.eval.Extensions.{EvalIterableOps, SigmaBooleanOps} +import sigma.eval.SigmaDsl +import sigma.interpreter.{ContextExtension, ProverResult} import java.math.BigInteger import scala.collection.compat.immutable.ArraySeq @@ -76,11 +76,9 @@ trait ObjectGenerators extends TypeGenerators implicit lazy val arbBoxConstant: Arbitrary[BoxConstant] = Arbitrary(boxConstantGen) implicit lazy val arbAvlTreeConstant: Arbitrary[AvlTreeConstant] = Arbitrary(avlTreeConstantGen) implicit lazy val arbBigIntConstant: Arbitrary[BigIntConstant] = Arbitrary(bigIntConstGen) - implicit lazy val arbTaggedInt: Arbitrary[TaggedInt] = Arbitrary(taggedVar[SInt.type]) - implicit lazy val arbTaggedLong: Arbitrary[TaggedLong] = Arbitrary(taggedVar[SLong.type]) - implicit lazy val arbTaggedBox: Arbitrary[TaggedBox] = Arbitrary(taggedVar[SBox.type]) - implicit lazy val arbTaggedAvlTree: Arbitrary[TaggedAvlTree] = Arbitrary(taggedAvlTreeGen) - implicit lazy val arbProveDlog: Arbitrary[ProveDlog] = Arbitrary(proveDlogGen) + implicit lazy val arbGetVarBox: Arbitrary[BoxValue] = Arbitrary(getVar[SBox.type]) + implicit lazy val arbGetVarAvlTree : Arbitrary[AvlTreeValue] = Arbitrary(getVarAvlTreeGen) + implicit lazy val arbProveDlog : Arbitrary[ProveDlog] = Arbitrary(proveDlogGen) implicit lazy val arbProveDHT: Arbitrary[ProveDHTuple] = Arbitrary(proveDHTGen) implicit lazy val arbRegisterIdentifier: Arbitrary[RegisterId] = Arbitrary(registerIdentifierGen) implicit lazy val arbBigInteger: Arbitrary[BigInteger] = Arbitrary(Arbitrary.arbBigInt.arbitrary.map(_.bigInteger)) @@ -168,10 +166,10 @@ trait ObjectGenerators extends TypeGenerators shortConstGen, intConstGen, longConstGen, bigIntConstGen, byteArrayConstGen, intArrayConstGen, groupElementConstGen).asInstanceOf[Gen[Constant[SType]]] - def taggedVar[T <: SType](implicit aT: Arbitrary[T]): Gen[TaggedVariable[T]] = for { + def getVar[T <: SType](implicit aT: Arbitrary[T]): Gen[Value[T]] = for { t <- aT.arbitrary id <- arbByte.arbitrary - } yield mkTaggedVariable(id, t) + } yield mkGetVar(id, t).get lazy val proveDlogGen: Gen[ProveDlog] = for {v <- groupElementGen} yield ProveDlog(v) @@ -210,8 +208,8 @@ trait ObjectGenerators extends TypeGenerators lazy val registerIdentifierGen: Gen[RegisterId] = Gen.oneOf(R0, R1, R2, R3, R4, R5, R6, R7, R8, R9) - lazy val taggedAvlTreeGen: Gen[TaggedAvlTree] = - arbByte.arbitrary.map { v => TaggedAvlTree(v).asInstanceOf[TaggedAvlTree] } + lazy val getVarAvlTreeGen: Gen[AvlTreeValue] = + arbByte.arbitrary.map { v => mkGetVar(v, SAvlTree).get } lazy val evaluatedValueGen: Gen[EvaluatedValue[SType]] = Gen.oneOf(booleanConstGen.asInstanceOf[Gen[EvaluatedValue[SType]]], byteArrayConstGen, longConstGen) @@ -327,10 +325,10 @@ trait ObjectGenerators extends TypeGenerators booleanConstGen, bigIntConstGen, groupElementConstGen, - taggedVar[SInt.type], - taggedVar[SLong.type], - taggedVar[SBox.type], - taggedVar(Arbitrary(sTupleGen(2, 10))) + getVar[SInt.type], + getVar[SLong.type], + getVar[SBox.type], + getVar(Arbitrary(sTupleGen(2, 10))) )) } yield mkTuple(values).asInstanceOf[Tuple] @@ -483,23 +481,23 @@ trait ObjectGenerators extends TypeGenerators } yield mkSizeOf(input).asInstanceOf[SizeOf[SInt.type]] lazy val extractAmountGen: Gen[ExtractAmount] = - arbTaggedBox.arbitrary.map { b => mkExtractAmount(b).asInstanceOf[ExtractAmount] } + arbGetVarBox.arbitrary.map { b => mkExtractAmount(b).asInstanceOf[ExtractAmount] } lazy val extractScriptBytesGen: Gen[ExtractScriptBytes] = - arbTaggedBox.arbitrary.map { b => mkExtractScriptBytes(b).asInstanceOf[ExtractScriptBytes] } + arbGetVarBox.arbitrary.map { b => mkExtractScriptBytes(b).asInstanceOf[ExtractScriptBytes] } lazy val extractBytesGen: Gen[ExtractBytes] = - arbTaggedBox.arbitrary.map { b => mkExtractBytes(b).asInstanceOf[ExtractBytes] } + arbGetVarBox.arbitrary.map { b => mkExtractBytes(b).asInstanceOf[ExtractBytes] } lazy val extractBytesWithNoRefGen: Gen[ExtractBytesWithNoRef] = - arbTaggedBox.arbitrary.map { b => + arbGetVarBox.arbitrary.map { b => mkExtractBytesWithNoRef(b).asInstanceOf[ExtractBytesWithNoRef] } lazy val extractIdGen: Gen[ExtractId] = - arbTaggedBox.arbitrary.map { b => mkExtractId(b).asInstanceOf[ExtractId] } + arbGetVarBox.arbitrary.map { b => mkExtractId(b).asInstanceOf[ExtractId] } lazy val extractRegisterAsGen: Gen[ExtractRegisterAs[SInt.type]] = for { - input <- arbTaggedBox.arbitrary + input <- arbGetVarBox.arbitrary r <- arbRegisterIdentifier.arbitrary } yield ExtractRegisterAs(input, r)(SInt) lazy val extractCreationInfoGen: Gen[ExtractCreationInfo] = - arbTaggedBox.arbitrary.map { b => mkExtractCreationInfo(b).asInstanceOf[ExtractCreationInfo] } + arbGetVarBox.arbitrary.map { b => mkExtractCreationInfo(b).asInstanceOf[ExtractCreationInfo] } lazy val deserializeContextGen: Gen[DeserializeContext[SBoolean.type]] = Arbitrary.arbitrary[Byte].map(b => diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala b/interpreter/shared/src/test/scala/sigma/serialization/generators/OpcodesGen.scala similarity index 56% rename from interpreter/shared/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala rename to interpreter/shared/src/test/scala/sigma/serialization/generators/OpcodesGen.scala index a11b80f5c8..c0bf5b97a2 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/generators/OpcodesGen.scala @@ -1,8 +1,8 @@ -package sigmastate.serialization.generators +package sigma.serialization.generators import org.scalacheck.Gen -import sigmastate.serialization.OpCodes._ -import sigmastate.serialization.ValueCodes.OpCode +import sigma.serialization.OpCodes._ +import sigma.serialization.ValueCodes.OpCode trait OpcodesGen { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala b/interpreter/shared/src/test/scala/sigma/serialization/generators/RelationGenerators.scala similarity index 77% rename from interpreter/shared/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala rename to interpreter/shared/src/test/scala/sigma/serialization/generators/RelationGenerators.scala index 7c50a84c26..0637f211d7 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/generators/RelationGenerators.scala @@ -1,15 +1,14 @@ -package sigmastate.serialization.generators +package sigma.serialization.generators import org.scalacheck.{Arbitrary, Gen} -import sigma.ast.SInt -import sigmastate.Values.{FalseLeaf, TrueLeaf} -import sigmastate.{If, TreeLookup} +import sigma.ast.{If, SInt, TreeLookup} +import sigma.ast.{FalseLeaf, TrueLeaf} trait RelationGenerators { this: ObjectGenerators with ConcreteCollectionGenerators => val treeLookupGen: Gen[TreeLookup] = for { - t <- arbTaggedAvlTree.arbitrary + t <- arbGetVarAvlTree.arbitrary b1 <- arbByteArrayConstant.arbitrary b2 <- arbByteArrayConstant.arbitrary } yield TreeLookup(t, b1, b2) diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TransformerGenerators.scala b/interpreter/shared/src/test/scala/sigma/serialization/generators/TransformerGenerators.scala similarity index 81% rename from interpreter/shared/src/test/scala/sigmastate/serialization/generators/TransformerGenerators.scala rename to interpreter/shared/src/test/scala/sigma/serialization/generators/TransformerGenerators.scala index 87256fea4e..22b51763fd 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TransformerGenerators.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/generators/TransformerGenerators.scala @@ -1,4 +1,4 @@ -package sigmastate.serialization.generators +package sigma.serialization.generators import org.ergoplatform.validation.ValidationSpecification diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala b/interpreter/shared/src/test/scala/sigma/serialization/generators/TypeGenerators.scala similarity index 97% rename from interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala rename to interpreter/shared/src/test/scala/sigma/serialization/generators/TypeGenerators.scala index d71de0b6b5..81073c4849 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/generators/TypeGenerators.scala @@ -1,4 +1,4 @@ -package sigmastate.serialization.generators +package sigma.serialization.generators import org.scalacheck.{Arbitrary, Gen} import org.scalacheck.Arbitrary.arbString diff --git a/interpreter/shared/src/test/scala/sigmastate/CalcSha256Specification.scala b/interpreter/shared/src/test/scala/sigmastate/CalcSha256Specification.scala index 637a84785a..ce070c6760 100644 --- a/interpreter/shared/src/test/scala/sigmastate/CalcSha256Specification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/CalcSha256Specification.scala @@ -2,9 +2,9 @@ package sigmastate import org.scalatest.prop.TableFor2 import scorex.util.encode.Base16 -import sigma.ast.SByte +import sigma.ast.{ByteArrayConstant, CalcSha256, EQ, SByte} +import sigma.ast.syntax.CollectionConstant import sigma.data.TrivialProp -import sigmastate.Values.{ByteArrayConstant, CollectionConstant} import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, TestingCommons} class CalcSha256Specification extends TestingCommons diff --git a/interpreter/shared/src/test/scala/sigmastate/CrossVersionProps.scala b/interpreter/shared/src/test/scala/sigmastate/CrossVersionProps.scala index 67f54e151d..87101a1f71 100644 --- a/interpreter/shared/src/test/scala/sigmastate/CrossVersionProps.scala +++ b/interpreter/shared/src/test/scala/sigmastate/CrossVersionProps.scala @@ -5,7 +5,7 @@ import org.scalactic.source.Position import scala.util.DynamicVariable import org.scalatest.Tag -import sigmastate.eval.Profiler +import sigmastate.eval.CProfiler import org.scalatest.propspec.AnyPropSpecLike import sigma.VersionContext @@ -13,9 +13,9 @@ trait CrossVersionProps extends AnyPropSpecLike with TestsBase { /** Number of times each test property is warmed up (i.e. executed before final execution). */ def perTestWarmUpIters: Int = 0 - private[sigmastate] val _warmupProfiler = new DynamicVariable[Option[Profiler]](None) + private[sigmastate] val _warmupProfiler = new DynamicVariable[Option[CProfiler]](None) - def warmupProfiler: Option[Profiler] = _warmupProfiler.value + def warmupProfiler: Option[CProfiler] = _warmupProfiler.value override protected def property(testName: String, testTags: Tag*) (testFun: => Any) @@ -23,7 +23,7 @@ trait CrossVersionProps extends AnyPropSpecLike with TestsBase { super.property(testName, testTags: _*) { // do warmup if necessary if (perTestWarmUpIters > 0) { - _warmupProfiler.withValue(Some(new Profiler)) { + _warmupProfiler.withValue(Some(new CProfiler)) { cfor(0)(_ < perTestWarmUpIters, _ + 1) { _ => testFun_Run(testName, testFun) } diff --git a/interpreter/shared/src/test/scala/sigmastate/JitCostSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/JitCostSpecification.scala index 4a434624a8..82ebe9a297 100644 --- a/interpreter/shared/src/test/scala/sigmastate/JitCostSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/JitCostSpecification.scala @@ -1,5 +1,6 @@ package sigmastate +import sigma.ast.JitCost import sigmastate.helpers.TestingCommons import scala.util.{Failure, Try} diff --git a/interpreter/shared/src/test/scala/sigmastate/TestsBase.scala b/interpreter/shared/src/test/scala/sigmastate/TestsBase.scala index 9ec6fae7c8..af9675c7f8 100644 --- a/interpreter/shared/src/test/scala/sigmastate/TestsBase.scala +++ b/interpreter/shared/src/test/scala/sigmastate/TestsBase.scala @@ -1,11 +1,12 @@ package sigmastate import org.scalatest.matchers.should.Matchers -import sigmastate.Values.SigmaPropValue +import sigma.ast.syntax.SigmaPropValue import org.ergoplatform.ErgoTreePredef import sigma.VersionTesting +import sigma.ast.ErgoTree import sigma.data.SigmaBoolean -import sigmastate.ErgoTree.{HeaderType, ZeroHeader} +import sigma.ast.ErgoTree.{HeaderType, ZeroHeader} trait TestsBase extends Matchers with VersionTesting { /** Set this to true to enable debug console output in tests */ diff --git a/interpreter/shared/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala index caa2bc1619..a5762444f6 100644 --- a/interpreter/shared/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala @@ -4,7 +4,7 @@ import java.math.BigInteger import org.scalacheck.Gen import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import sigma.crypto.{CryptoFacade, EcPointType, Ecp} +import sigma.crypto.{CryptoConstants, CryptoFacade, EcPointType, Ecp} import sigmastate.TestsBase import sigmastate.utils.Helpers diff --git a/interpreter/shared/src/test/scala/sigmastate/crypto/SigningSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/crypto/SigningSpecification.scala index 204147006b..16999e7457 100644 --- a/interpreter/shared/src/test/scala/sigmastate/crypto/SigningSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/crypto/SigningSpecification.scala @@ -2,12 +2,13 @@ package sigmastate.crypto import org.scalacheck.Gen import scorex.util.encode.Base16 +import sigma.ast.{AtLeast, ErgoTree} import sigma.data.{CAND, COR, ProveDHTuple, SigmaBoolean} +import sigma.interpreter.{ContextExtension, ProverResult} import sigma.serialization.ProveDHTupleSerializer -import sigmastate.{AtLeast, ErgoTree} import sigmastate.crypto.DLogProtocol.DLogProverInput import sigmastate.helpers.{ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter, TestingCommons} -import sigmastate.interpreter.{ContextExtension, HintsBag, ProverResult} +import sigmastate.interpreter.HintsBag class SigningSpecification extends TestingCommons { diff --git a/interpreter/shared/src/test/scala/sigmastate/eval/BasicOpsTests.scala b/interpreter/shared/src/test/scala/sigmastate/eval/BasicOpsTests.scala index 8dcfe7d9c8..ba996b0246 100644 --- a/interpreter/shared/src/test/scala/sigmastate/eval/BasicOpsTests.scala +++ b/interpreter/shared/src/test/scala/sigmastate/eval/BasicOpsTests.scala @@ -2,11 +2,11 @@ package sigmastate.eval import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers -import sigma.data.TrivialProp +import sigma.crypto.SecP256K1Group +import sigma.data.{CSigmaDslBuilder, TrivialProp} import sigma.util.Extensions.SigmaBooleanOps import java.math.BigInteger -import sigmastate.crypto.SecP256K1Group import sigma.{ContractsTestkit, SigmaDslBuilder, SigmaProp} import scala.language.implicitConversions diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala index 25b1c796c6..2eaac82790 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala @@ -1,10 +1,10 @@ package sigmastate.helpers -import sigma.ast.SType -import sigmastate.ErgoTree -import sigmastate.Values.EvaluatedValue +import sigma.ast.{ErgoTree, SType} +import sigma.ast.EvaluatedValue +import sigma.interpreter.{ContextExtension, CostedProverResult} import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.interpreter.{ContextExtension, CostedProverResult, HintsBag, ProverInterpreter} +import sigmastate.interpreter.{HintsBag, ProverInterpreter} import scala.util.Try diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala index 3d9e7192d3..0d4c1904ec 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala @@ -1,8 +1,7 @@ package sigmastate.helpers import scorex.utils.Random -import sigma.ast.SType -import sigmastate.Values._ +import sigma.ast._ import sigmastate.crypto.DLogProtocol.DLogProverInput import sigmastate.crypto.DiffieHellmanTupleProverInput diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala index 1e0a22874a..a353ff5e46 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala @@ -3,16 +3,16 @@ package sigmastate.helpers import org.ergoplatform.ErgoLikeContext.Height import org.ergoplatform._ import org.ergoplatform.validation.ValidationRules -import sigma.data.AvlTreeData +import sigma.crypto.CryptoConstants +import sigma.data.{AvlTreeData, CSigmaDslBuilder} +import sigma.interpreter.ContextExtension import sigma.serialization.GroupElementSerializer import sigma.util.Extensions.EcpOps import sigma.validation.SigmaValidationSettings import sigma.{Box, Coll, Colls, Header, PreHeader} -import sigmastate.crypto.CryptoConstants import sigmastate.eval._ -import sigmastate.interpreter.ContextExtension -import sigmastate.interpreter.ErgoTreeEvaluator.DefaultEvalSettings -import sigmastate.serialization.SigmaSerializer +import sigmastate.interpreter.CErgoTreeEvaluator.DefaultEvalSettings +import sigma.serialization.SigmaSerializer object ErgoLikeContextTesting { /* NO HF PROOF: diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala index 3203dfc13f..afacb3e6ee 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala @@ -1,8 +1,8 @@ package sigmastate.helpers import org.ergoplatform._ -import sigmastate.interpreter.ErgoTreeEvaluator.DefaultEvalSettings -import sigmastate.interpreter.EvalSettings +import sigma.eval.EvalSettings +import sigmastate.interpreter.CErgoTreeEvaluator.DefaultEvalSettings import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import scala.util.{Failure, Success} diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/TestingCommons.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/TestingCommons.scala index 06c38d93dc..d92ad87ccd 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/TestingCommons.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/TestingCommons.scala @@ -1,14 +1,14 @@ package sigmastate.helpers -import sigmastate.Values.GroupElementConstant import org.scalatest.propspec.AnyPropSpec import sigmastate.TestsBase import sigmastate.helpers.TestingHelpers.createBox import org.scalatestplus.scalacheck.{ScalaCheckDrivenPropertyChecks, ScalaCheckPropertyChecks} -import sigmastate.eval.SigmaDsl +import sigma.eval.SigmaDsl import scorex.crypto.hash.Blake2b256 import org.ergoplatform.{ErgoBox, ErgoLikeContext} import org.scalatest.matchers.should.Matchers +import sigma.ast.syntax.GroupElementConstant import sigma.crypto.EcPointType trait TestingCommons extends AnyPropSpec diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/TestingHelpers.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/TestingHelpers.scala index 27c8db01e5..392e319773 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/TestingHelpers.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/TestingHelpers.scala @@ -3,13 +3,11 @@ package sigmastate.helpers import org.ergoplatform.ErgoBox.{AdditionalRegisters, Token, allZerosModifierId} import org.ergoplatform._ import scorex.util.ModifierId -import sigma.data.{AvlTreeData, CollOverArray, PairOfCols} +import sigma.ast.ErgoTree +import sigma.data.{AvlTreeData, CSigmaDslBuilder, CollOverArray, PairOfCols} +import sigma.interpreter.ContextExtension import sigma.validation.SigmaValidationSettings -import sigma.{Coll, Header, PreHeader} -import sigmastate.ErgoTree -import sigmastate.eval._ -import sigmastate.interpreter.ContextExtension - +import sigma.{Coll, Colls, Header, PreHeader} import scala.collection.compat.immutable.ArraySeq // TODO refactor: unification is required between two hierarchies of tests @@ -47,7 +45,7 @@ object TestingHelpers { */ def cloneColl[A](c: Coll[A]): Coll[A] = (c match { case c: CollOverArray[_] => - new CollOverArray(c.toArray.clone(), SigmaDsl.Colls)(c.tItem) + new CollOverArray(c.toArray.clone(), Colls)(c.tItem) case ps: PairOfCols[_,_] => new PairOfCols(cloneColl(ps.ls), cloneColl(ps.rs)) }).asInstanceOf[Coll[A]] diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala deleted file mode 100644 index f754157558..0000000000 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala +++ /dev/null @@ -1,24 +0,0 @@ -package sigmastate.serialization - -import sigmastate.Values._ -import OpCodes._ -import sigma.ast.SBox - -class TaggedVariableSerializerSpecification extends SerializationSpecification { - - property("TaggedVariable: TaggedInt serializer round trip") { - forAll { ti: TaggedInt => - roundTripTest(ti) - } - } - - property("TaggedVariable: TaggedBox serializer round trip") { - forAll { tb: TaggedBox => - roundTripTest(tb) - } - } - - property("TaggedVariable deserialize from predefined bytes") { - predefinedBytesTest(TaggedBox(10), Array(TaggedVariableCode, 10, SBox.typeCode)) - } -} diff --git a/interpreter/shared/src/test/scala/sigmastate/utils/HelpersTests.scala b/interpreter/shared/src/test/scala/sigmastate/utils/HelpersTests.scala index 83a13e2e5a..b02c489b08 100644 --- a/interpreter/shared/src/test/scala/sigmastate/utils/HelpersTests.scala +++ b/interpreter/shared/src/test/scala/sigmastate/utils/HelpersTests.scala @@ -1,6 +1,6 @@ package sigmastate.utils -import sigmastate.serialization.generators.ObjectGenerators +import sigma.serialization.generators.ObjectGenerators import Helpers._ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec diff --git a/interpreter/shared/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala index 0f6b69b78f..e45bc00e70 100644 --- a/interpreter/shared/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala @@ -4,7 +4,8 @@ import org.scalacheck.{Arbitrary, Gen} import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import sigmastate.serialization.generators.ObjectGenerators +import sigma.serialization.generators.ObjectGenerators +import sigma.utils.SparseArrayContainer class SparseArrayContainerSpecification extends AnyPropSpec with ObjectGenerators diff --git a/interpreter/shared/src/test/scala/sigmastate/utxo/ProverSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/utxo/ProverSpecification.scala index c15b00deea..8b560c523d 100644 --- a/interpreter/shared/src/test/scala/sigmastate/utxo/ProverSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/utxo/ProverSpecification.scala @@ -2,11 +2,12 @@ package sigmastate.utxo import org.ergoplatform.ErgoLikeInterpreter import scorex.crypto.hash.Blake2b256 +import sigma.crypto.SecP256K1Group import sigma.data.{CAND, COR, CTHRESHOLD, SigmaBoolean, TrivialProp} +import sigma.exceptions.InterpreterException import sigmastate._ import sigmastate.crypto.DLogProtocol.FirstDLogProverMessage -import sigmastate.crypto.{FirstDHTupleProverMessage, SecP256K1Group} -import sigmastate.exceptions.InterpreterException +import sigmastate.crypto.FirstDHTupleProverMessage import sigmastate.helpers.{ErgoLikeTestProvingInterpreter, TestingCommons} import sigmastate.interpreter.{HintsBag, ProverInterpreter} diff --git a/interpreter/shared/src/test/scala/special/sigma/ContractsTestkit.scala b/interpreter/shared/src/test/scala/special/sigma/ContractsTestkit.scala index 2872e3e6ea..720223ee3a 100644 --- a/interpreter/shared/src/test/scala/special/sigma/ContractsTestkit.scala +++ b/interpreter/shared/src/test/scala/special/sigma/ContractsTestkit.scala @@ -1,11 +1,10 @@ package sigma import sigma.Extensions.ArrayOps +import sigma.ast.ErgoTree +import sigma.ast.syntax.TrueSigmaProp import sigma.data.{AvlTreeData, RType} -import sigmastate.ErgoTree -import sigmastate.Values import sigmastate.eval._ -import sigmastate.eval.Extensions._ import sigmastate.helpers.TestingHelpers._ import sigma.data._ @@ -63,7 +62,7 @@ trait ContractsTestkit { def newAliceBox(@nowarn id: Byte, value: Long): Box = { val ergoBox = testBox(value, - ErgoTree.fromProposition(Values.TrueSigmaProp), + ErgoTree.fromProposition(TrueSigmaProp), creationHeight = 0, additionalTokens = Seq(), additionalRegisters = Map()) new CBox(ergoBox) } diff --git a/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala b/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala index 8a98279273..d33f09dd80 100644 --- a/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala +++ b/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala @@ -10,17 +10,17 @@ import sigma.data._ import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.ModifierId -import sigmastate.Values.{ByteArrayConstant, ConcreteCollection, ConstantPlaceholder, FalseLeaf, IntConstant, LongConstant, SigmaPropConstant, TrueLeaf} +import sigma.ast._ import sigma.Extensions.ArrayOps -import sigmastate.eval.{CBox, CHeader, CPreHeader, CSigmaDslBuilder, SigmaDsl} +import sigmastate.eval.{CHeader, CPreHeader} import sigmastate.helpers.TestingCommons -import sigmastate.serialization.ErgoTreeSerializer -import sigmastate.serialization.generators.ObjectGenerators +import sigma.serialization.ErgoTreeSerializer +import sigma.serialization.generators.ObjectGenerators import sigmastate.utils.Helpers -import sigmastate.{ErgoTree, _} import sigma.ast.{SBoolean, SSigmaProp} import sigma.crypto.EcPointType -import sigmastate.ErgoTree.HeaderType +import ErgoTree.HeaderType +import sigma.eval.SigmaDsl import java.math.BigInteger import scala.reflect.ClassTag diff --git a/parsers/shared/src/main/scala/sigmastate/lang/SigmaParser.scala b/parsers/shared/src/main/scala/sigmastate/lang/SigmaParser.scala index 7ad72ecb30..3e7a5a313f 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/SigmaParser.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/SigmaParser.scala @@ -1,20 +1,18 @@ package sigmastate.lang import fastparse.internal.Logger -import sigmastate._ -import Values._ -import sigma.ast.{NoType, SInt, SLong, SType} +import sigma.ast._ import sigma.data.Nullable -import sigmastate.lang.Terms._ -import sigmastate.lang.syntax.Basic._ -import sigmastate.lang.syntax.{Core, Exprs} +import sigma.ast.syntax._ +import sigmastate.lang.parsers.{Basic, Core, Exprs} import scala.collection.mutable import scala.util.DynamicVariable /** Main facade to ErgoScript parser implementation. */ -object SigmaParser extends Exprs with Types with Core { - import fastparse._; import ScalaWhitespace._ +object SigmaParser extends Exprs with Types with Core { parser => + import fastparse._ + import ScalaWhitespace._ import builder._ private val currentInput = new DynamicVariable[String]("") @@ -31,7 +29,7 @@ object SigmaParser extends Exprs with Types with Core { mkVal(n, t.getOrElse(NoType), body) } case (index, pat,_,_) => - error(s"Only single name patterns supported but was $pat", Some(srcCtx(index))) + Basic.error(s"Only single name patterns supported but was $pat", Some(srcCtx(index))) } override def BlockDef[_:P] = P( Dcl ) @@ -48,7 +46,7 @@ object SigmaParser extends Exprs with Types with Core { mkConstant[SInt.type](-value, SInt) case LongConstant(value) => mkConstant[SLong.type](-value, SLong) - case _ => error(s"cannot prefix $arg with op $opName", arg.sourceContext) + case _ => Basic.error(s"cannot prefix $arg with op $opName", arg.sourceContext) } case "!" => mkLogicalNot(arg.asBoolValue) @@ -57,16 +55,16 @@ object SigmaParser extends Exprs with Types with Core { if (arg.tpe.isNumTypeOrNoType) mkNegation(arg.asNumValue) else - error(s"Numeric argument expected for '$opName' operation: $arg", arg.sourceContext) + Basic.error(s"Numeric argument expected for '$opName' operation: $arg", arg.sourceContext) case "~" => if (arg.tpe.isNumTypeOrNoType) mkBitInversion(arg.asNumValue) else - error(s"Numeric argument expected for '$opName' operation: $arg", arg.sourceContext) + Basic.error(s"Numeric argument expected for '$opName' operation: $arg", arg.sourceContext) case _ => - error(s"Unknown prefix operation $opName for $arg", arg.sourceContext) + Basic.error(s"Unknown prefix operation $opName for $arg", arg.sourceContext) } } @@ -87,18 +85,18 @@ object SigmaParser extends Exprs with Types with Core { if (l.tpe.isNumTypeOrNoType && r.tpe.isNumTypeOrNoType) mkBitOr(l.asNumValue, r.asNumValue) else - error(s"Numeric arguments expected for '$opName' operation: ($l, $r)", l.sourceContext) + Basic.error(s"Numeric arguments expected for '$opName' operation: ($l, $r)", l.sourceContext) case "&" => if (l.tpe.isNumTypeOrNoType && r.tpe.isNumTypeOrNoType) mkBitAnd(l.asNumValue, r.asNumValue) else - error(s"Numeric arguments expected for '$opName' operation: ($l, $r)", l.sourceContext) + Basic.error(s"Numeric arguments expected for '$opName' operation: ($l, $r)", l.sourceContext) case _ if parseAsMethods.contains(opName) => mkMethodCallLike(l, opName, IndexedSeq(r)) case "/" => mkDivide(l.asNumValue, r.asNumValue) case "%" => mkModulo(l.asNumValue, r.asNumValue) - case _ => error(s"Unknown binary operation $opName", l.sourceContext) + case _ => Basic.error(s"Unknown binary operation $opName", l.sourceContext) } } diff --git a/parsers/shared/src/main/scala/sigmastate/lang/Types.scala b/parsers/shared/src/main/scala/sigmastate/lang/Types.scala index b3b3f48ce9..06683f6e96 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/Types.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/Types.scala @@ -2,11 +2,8 @@ package sigmastate.lang import fastparse._ import ScalaWhitespace._ -import sigmastate._ -import Values._ -import sigmastate.lang.Terms.Ident -import sigmastate.lang.syntax.Core -import syntax.Basic.error +import sigmastate.lang.parsers.Core +import parsers.Basic.error import sigma.ast._ //noinspection ForwardReference diff --git a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Basic.scala b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Basic.scala similarity index 96% rename from parsers/shared/src/main/scala/sigmastate/lang/syntax/Basic.scala rename to parsers/shared/src/main/scala/sigmastate/lang/parsers/Basic.scala index 55bdd4e399..152de08780 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Basic.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Basic.scala @@ -1,11 +1,11 @@ -package sigmastate.lang.syntax +package sigmastate.lang.parsers import fastparse._ import NoWhitespace._ import fastparse.CharPredicates._ +import sigma.ast.SourceContext import sigma.data.Nullable -import sigmastate.lang.SourceContext -import sigmastate.exceptions.CompilerException +import sigma.exceptions.CompilerException /** Basic lexical parsers for ErgoScript. */ object Basic { diff --git a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Core.scala b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Core.scala similarity index 92% rename from parsers/shared/src/main/scala/sigmastate/lang/syntax/Core.scala rename to parsers/shared/src/main/scala/sigmastate/lang/parsers/Core.scala index 83c5e76065..a2d7781b87 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Core.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Core.scala @@ -1,12 +1,11 @@ -package sigmastate.lang.syntax +package sigmastate.lang.parsers -import sigma.ast.{NoType, SType} -import sigmastate._ -import sigmastate.Values._ -import sigmastate.lang.syntax +import sigma.ast.syntax.SValue +import sigma.ast._ +import sigmastate.lang.parsers /** Keywords and identifiers used in expressions. */ -trait Core extends syntax.Literals { +trait Core extends parsers.Literals { import fastparse._ import ScalaWhitespace._ diff --git a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Exprs.scala b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Exprs.scala similarity index 97% rename from parsers/shared/src/main/scala/sigmastate/lang/syntax/Exprs.scala rename to parsers/shared/src/main/scala/sigmastate/lang/parsers/Exprs.scala index edca50650a..fb31288d86 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Exprs.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Exprs.scala @@ -1,13 +1,12 @@ -package sigmastate.lang.syntax +package sigmastate.lang.parsers import fastparse._ import ScalaWhitespace._ import sigma.ast._ -import sigmastate.Values._ -import sigmastate.lang.Terms.{Ident, Val, ValueOps} +import sigma.ast.syntax.{SValue, ValueOps} import sigmastate.lang._ -import sigmastate.lang.SigmaPredef._ -import sigmastate.lang.syntax.Basic._ +import SigmaPredef._ +import sigmastate.lang.parsers.Basic._ import scala.annotation.tailrec import scala.collection.compat.immutable.ArraySeq @@ -76,7 +75,7 @@ trait Exprs extends Core with Types { } private def SuperPostfixSuffix[_:P] = P( (`=` ~/ Expr).? ) - private def ExprPrefix[_:P] = P( WL ~ CharPred("-+!~".contains(_)).! ~~ !syntax.Basic.OpChar ~ WS) + private def ExprPrefix[_:P] = P( WL ~ CharPred("-+!~".contains(_)).! ~~ !parsers.Basic.OpChar ~ WS) private def ExprSuffix[_:P] = P( (WL ~ "." ~/ (Index ~ Id.!).map{ case (i, s) => atSrcPos(i) { mkIdent(s, NoType)} } | WL ~ TypeArgs.map(items => STypeApply("", items.toIndexedSeq)) @@ -198,7 +197,7 @@ trait Exprs extends Core with Types { case STypeApply("", targs) => mkApplyTypes(acc, targs) case arg: SValue => acc match { case Ident(name, _) if name == ZKProofFunc.name => arg match { - case Terms.Block(_, body) => + case Block(_, body) => mkApply(mkIdent(ZKProofFunc.name, ZKProofFunc.declaration.tpe), Array(body)) case nonBlock => error(s"expected block parameter for ZKProof, got $nonBlock", nonBlock.sourceContext) diff --git a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Identifiers.scala b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Identifiers.scala similarity index 96% rename from parsers/shared/src/main/scala/sigmastate/lang/syntax/Identifiers.scala rename to parsers/shared/src/main/scala/sigmastate/lang/parsers/Identifiers.scala index 65acacc765..f8e3e4ccbd 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Identifiers.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Identifiers.scala @@ -1,9 +1,9 @@ -package sigmastate.lang.syntax +package sigmastate.lang.parsers import fastparse.CharPredicates.{isDigit, isLetter} import fastparse._ import NoWhitespace._ -import sigmastate.lang.syntax.Basic._ +import sigmastate.lang.parsers.Basic._ //noinspection ForwardReference /** Identifiers and keywords */ diff --git a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Literals.scala b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Literals.scala similarity index 96% rename from parsers/shared/src/main/scala/sigmastate/lang/syntax/Literals.scala rename to parsers/shared/src/main/scala/sigmastate/lang/parsers/Literals.scala index ad790d3599..6beff079e4 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Literals.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/parsers/Literals.scala @@ -1,15 +1,12 @@ -package sigmastate.lang.syntax +package sigmastate.lang.parsers +import fastparse.NoWhitespace._ import fastparse._ -import NoWhitespace._ -import Identifiers._ -import sigmastate._ -import Values._ -import sigma.ast.{SBoolean, SInt, SLong, SString, SType} - -import java.lang.Long.parseLong +import sigma.ast.syntax.BooleanConstant +import sigma.ast._ +import sigmastate.lang.parsers.Identifiers._ import java.lang.Integer.parseInt -import sigmastate.lang.{SigmaBuilder, SourceContext, StdSigmaBuilder} +import java.lang.Long.parseLong /** Parsers of literal expressions. */ trait Literals { l => diff --git a/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala b/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala index ee3d046753..c04f35ef71 100644 --- a/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala +++ b/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala @@ -1,21 +1,19 @@ package sigmastate.lang import org.scalatest.matchers.should.Matchers -import sigmastate.lang.Terms.{Ident, MethodCallLike} -import sigmastate.Values.{ConcreteCollection, LongConstant, SValue, Value} -import sigmastate._ - -import java.math.BigInteger +import sigma.{Coll, _} import sigma.ast.SCollection.SByteArray -import sigmastate.crypto.CryptoConstants -import sigmastate.interpreter.Interpreter.ScriptEnv -import sigma._ -import sigmastate.eval._ -import sigmastate.helpers.NegativeTesting -import sigma.Coll +import sigma.ast.syntax.{SValue, ValueOps} import sigma.ast._ -import sigma.data.{CAnyValue, ProveDHTuple, ProveDlog, SigmaBoolean} +import sigma.crypto.CryptoConstants +import sigma.data.{CAnyValue, CSigmaDslBuilder, ProveDHTuple, ProveDlog, SigmaBoolean} import sigma.util.Extensions.BigIntegerOps +import sigmastate.eval._ +import sigmastate.helpers.NegativeTesting +import sigmastate.interpreter.Interpreter.ScriptEnv +import sigma.ast.{Ident, MethodCallLike} + +import java.math.BigInteger trait LangTests extends Matchers with NegativeTesting { diff --git a/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala b/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala index a7854ed827..7213088a05 100644 --- a/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala +++ b/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala @@ -8,12 +8,12 @@ import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigma.ast.SCollection.{SByteArray, SLongArray} import sigma.ast._ -import sigmastate.Values._ +import sigma.ast.syntax.SValue import sigmastate._ -import sigmastate.lang.SigmaPredef.PredefinedFuncRegistry -import sigmastate.lang.Terms._ -import sigmastate.lang.syntax.ParserException -import sigmastate.serialization.OpCodes +import SigmaPredef.PredefinedFuncRegistry +import sigma.ast.syntax._ +import sigmastate.lang.parsers.ParserException +import sigma.serialization.OpCodes class SigmaParserTest extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers with LangTests { import StdSigmaBuilder._ diff --git a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala index 34a3b1cc6a..07cd094bf8 100644 --- a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala +++ b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala @@ -1,17 +1,16 @@ package sigmastate.lang.js import org.ergoplatform.ErgoAddressEncoder -import org.ergoplatform.sdk.js.Isos.isoValueToConstant import org.scalablytyped.runtime.StringDictionary +import sigma.ast +import sigma.ast.js.{ErgoTree, isoValueToConstant} import scala.scalajs.js import scala.scalajs.js.annotation.JSExportTopLevel -import org.ergoplatform.sdk.js.ErgoTree import sigma.js.Value -import sigmastate.ErgoTree.HeaderType -import sigmastate.Values +import sigma.ast.ErgoTree.HeaderType import sigmastate.eval.CompiletimeIRContext -import sigmastate.lang.Terms.ValueOps +import sigma.ast.syntax.ValueOps /** Wrapper exported to JS. */ @@ -38,9 +37,9 @@ class SigmaCompiler(_compiler: sigmastate.lang.SigmaCompiler) extends js.Object require(prop.tpe.isSigmaProp, s"Expected SigmaProp expression type bue got ${prop.tpe}: $prop") val tree = if (segregateConstants) { - sigmastate.ErgoTree.withSegregation(HeaderType @@ treeHeader, prop.asSigmaProp) + ast.ErgoTree.withSegregation(HeaderType @@ treeHeader, prop.asSigmaProp) } else { - sigmastate.ErgoTree.withoutSegregation(HeaderType @@ treeHeader, prop.asSigmaProp) + ast.ErgoTree.withoutSegregation(HeaderType @@ treeHeader, prop.asSigmaProp) } new ErgoTree(tree) } diff --git a/sc/jvm/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala b/sc/jvm/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala index bae67b3248..2b23d85846 100644 --- a/sc/jvm/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala +++ b/sc/jvm/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala @@ -3,17 +3,16 @@ package sigmastate import debox.cfor import org.scalameter.api.Bench import sigma.BenchmarkGens -import sigma.ast.SType -import sigma.crypto.Platform -import sigmastate.Values.{IntConstant, SValue} -import sigmastate.serialization.OpCodes.PlusCode +import sigma.ast.{ArithOp, EQ, IntConstant, SType} +import sigma.ast.syntax.SValue +import sigma.serialization.OpCodes.PlusCode object ErgoTreeBenchmarks extends Bench.LocalTime with BenchmarkGens { suite: Bench[Double] => override def maxSize: Int = 10000 /** Expected approximate results: - * ::Benchmark allocation of sigmastate.Values.ArithOp, EQ, IntConstant:: + * ::Benchmark allocation of sigma.ast.ArithOp, EQ, IntConstant:: * name: OpenJDK 64-Bit Server VM * osArch: x86_64 * osName: Mac OS X @@ -24,7 +23,7 @@ object ErgoTreeBenchmarks extends Bench.LocalTime with BenchmarkGens { suite: Be * Parameters(size -> 1000): 0.696851 ms * Parameters(size -> 10000): 5.687967 ms */ - performance of "allocation of sigmastate.Values" in { + performance of "allocation of sigma.ast" in { measure method "ArithOp, EQ, IntConstant" in { using(sizes) in { size => val arr = new Array[SValue](size) diff --git a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala index 28b2733c31..1375b48d99 100644 --- a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala +++ b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala @@ -34,7 +34,7 @@ object ReflectionGenerator { "sigma.", "sigma.", "special.wrappers.", - "sigmastate.Values.", + "sigma.ast.", "sigmastate.lang.Terms.", "sigmastate.interpreter.", "sigmastate.utxo.", diff --git a/sc/jvm/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala b/sc/jvm/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala index e81ace9575..54c0f652dc 100644 --- a/sc/jvm/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala +++ b/sc/jvm/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala @@ -1,20 +1,17 @@ package sigmastate.helpers import org.ergoplatform.settings.ErgoAlgos -import org.ergoplatform.{ErgoBox, Outputs} +import org.ergoplatform.ErgoBox import scorex.util.ModifierId import sigma.Extensions.ArrayOps import sigma.SigmaDslTesting import sigma.ast._ -import sigma.data.{AvlTreeData, AvlTreeFlags, CollType, Digest32Coll} -import sigmastate.ErgoTree.HeaderType -import sigmastate.Values._ -import sigmastate._ +import sigma.data.{AvlTreeData, AvlTreeFlags, CBox, CollType, Digest32Coll} +import ErgoTree.HeaderType import sigmastate.eval._ -import sigmastate.lang.Terms.MethodCall -import sigmastate.serialization.OpCodes +import sigma.ast.MethodCall +import sigma.serialization.OpCodes import sigmastate.utils.Helpers -import sigmastate.utxo.SelectField import java.math.BigInteger import scala.collection.mutable.ArrayBuffer diff --git a/sc/jvm/src/test/scala/sigmastate/utils/GenSerializers.scala b/sc/jvm/src/test/scala/sigmastate/utils/GenSerializers.scala index 75e39111ab..1aa3d81c33 100644 --- a/sc/jvm/src/test/scala/sigmastate/utils/GenSerializers.scala +++ b/sc/jvm/src/test/scala/sigmastate/utils/GenSerializers.scala @@ -3,8 +3,8 @@ package sigmastate.utils import sigma.util.Extensions.ByteOps import sigma.util.FileUtil import sigma.util.PrintExtensions._ -import sigmastate.lang.Terms.{MethodCall, PropertyCall} -import sigmastate.serialization.ValueSerializer._ +import sigma.ast.{MethodCall, PropertyCall} +import sigma.serialization.ValueSerializer._ /** Generate contents of ErgoTree serializer format specification. * To generate serialization formats, it is necessary that all branches of serializers diff --git a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala index 9ce000448d..faded6e28c 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala @@ -4,8 +4,9 @@ import sigmastate.lang.SigmaCompiler import sigmastate.eval.IRContext import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import sigma.ast.SType -import sigmastate.Values.{SigmaPropValue, Value} -import sigmastate.lang.Terms.ValueOps +import sigma.ast.syntax.SigmaPropValue +import sigma.ast.Value +import sigma.ast.syntax.ValueOps object ErgoScriptPredef { import sigmastate.interpreter.Interpreter._ diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala index 587fb8b76f..e3edffbc9c 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala @@ -1,16 +1,15 @@ package org.ergoplatform.dsl import org.ergoplatform.ErgoBox.{BoxId, NonMandatoryRegisterId, TokenId} -import sigmastate.interpreter.{CostedProverResult, ProverResult} -import sigma.data.RType +import sigma.interpreter.{CostedProverResult, ProverResult} +import sigma.data.{CSigmaDslBuilder, RType} import org.ergoplatform.{ErgoBox, ErgoLikeContext} import sigma.{AnyValue, Coll, SigmaDslBuilder, SigmaProp} -import sigmastate.ErgoTree -import sigmastate.eval.{CSigmaDslBuilder, IRContext} +import sigmastate.eval.IRContext import scala.util.Try import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} - +import sigma.ast.ErgoTree import scala.language.implicitConversions trait ContractSpec { diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala index b01914eed6..d4accabf3e 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala @@ -2,14 +2,14 @@ package org.ergoplatform.dsl import org.ergoplatform.ErgoBox import org.ergoplatform.ErgoBox.TokenId -import sigma.data.{AvlTreeData, RType, SigmaBoolean} +import sigma.data.{AvlTreeData, CSigmaDslBuilder, RType, SigmaBoolean} import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition} import org.ergoplatform.sdk.JavaHelpers.collRType -import sigmastate.eval.CSigmaDslBuilder import sigmastate.interpreter.Interpreter.ScriptEnv import sigma._ -import sigma.ast.SType +import sigma.ast.{SType, syntax} import sigma.ast.SType.AnyOps + import scala.reflect.ClassTag import scala.util.Try @@ -56,11 +56,11 @@ trait ContractSyntax { contract: SigmaContract => case _: Unit => UnitType case _: sigma.BigInt => BigIntRType case _: GroupElement => GroupElementRType - case _: ErgoBox => sigmastate.ErgoBoxRType // TODO remove this RType + case _: ErgoBox => syntax.ErgoBoxRType // TODO remove this RType case _: Box => BoxRType - case _: AvlTreeData => sigmastate.AvlTreeDataRType // TODO remove this RType + case _: AvlTreeData => syntax.AvlTreeDataRType // TODO remove this RType case _: AvlTree => AvlTreeRType - case _: SigmaBoolean => sigmastate.SigmaBooleanRType // TODO remove this RType + case _: SigmaBoolean => syntax.SigmaBooleanRType // TODO remove this RType case _: SigmaProp => SigmaPropRType case _: Context => ContextRType case _ => diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala index c1b0b40381..2c31304b70 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala @@ -1,10 +1,10 @@ package org.ergoplatform.dsl import sigma.Coll -import sigmastate.interpreter.CostedProverResult import sigmastate.eval.IRContext import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} import org.ergoplatform.ErgoBox.{BoxId, NonMandatoryRegisterId, TokenId} +import sigma.interpreter.CostedProverResult class ErgoContractSpec(implicit val IR: IRContext) extends ContractSpec { diff --git a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala index 521e1ca905..2ffc32ecce 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala @@ -2,22 +2,20 @@ package sigmastate.eval import org.ergoplatform._ import scalan.MutableLazy -import sigma.SigmaException +import sigma.{SigmaException, ast} import sigma.ast.TypeCodes.LastConstantCode +import sigma.ast.Value.Typed +import sigma.ast._ +import sigma.ast.syntax.{SValue, ValueOps} +import sigma.crypto.EcPointType import sigma.data.ExactIntegral.{ByteIsExactIntegral, IntIsExactIntegral, LongIsExactIntegral, ShortIsExactIntegral} import sigma.data.ExactOrdering.{ByteIsExactOrdering, IntIsExactOrdering, LongIsExactOrdering, ShortIsExactOrdering} +import sigma.data.{CSigmaDslBuilder, ExactIntegral, ExactNumeric, ExactOrdering, Lazy, Nullable} import sigma.util.Extensions.ByteOps -import sigma.data.{ExactIntegral, ExactNumeric, ExactOrdering, Lazy, Nullable} -import sigmastate.Values.Value.Typed -import sigmastate.Values._ import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.lang.{SourceContext, Terms} -import sigmastate.lang.Terms.{Ident, Select, Val, ValueOps} -import sigmastate.serialization.{OpCodes, ValueCodes} -import sigmastate.utxo._ -import sigma.ast._ -import sigma.crypto.EcPointType -import sigmastate.exceptions.GraphBuildingException +import sigma.ast.{Ident, Select, Val} +import sigma.exceptions.GraphBuildingException +import sigma.serialization.OpCodes import scala.collection.mutable.ArrayBuffer @@ -45,7 +43,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => import WOption._ /** Should be specified in the final cake */ - val builder: sigmastate.lang.SigmaBuilder + val builder: SigmaBuilder import builder._ @@ -313,8 +311,6 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => case _ => error(s"Don't know how to convert Elem $e to SType") } - import Liftables._ - /** Translates Elem to the corresponding Liftable instance. * @param eWT type descriptor */ @@ -341,7 +337,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => FuncIsLiftable(la, lb) }).asInstanceOf[Liftable[_,WT]] - import NumericOps._ + import sigma.data.NumericOps._ private lazy val elemToExactNumericMap = Map[Elem[_], ExactNumeric[_]]( (ByteElement, ByteIsExactIntegral), (ShortElement, ShortIsExactIntegral), @@ -486,7 +482,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => val resV = toRep(v)(e) resV } - case org.ergoplatform.Context => ctx + case sigma.ast.Context => ctx case Global => sigmaDslBuilder case Height => ctx.HEIGHT case Inputs => ctx.INPUTS @@ -498,10 +494,10 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => case Ident(n, _) => env.getOrElse(n, !!!(s"Variable $n not found in environment $env")) - case sigmastate.Upcast(Constant(value, _), toTpe: SNumericType) => + case ast.Upcast(Constant(value, _), toTpe: SNumericType) => eval(mkConstant(toTpe.upcast(value.asInstanceOf[AnyVal]), toTpe)) - case sigmastate.Downcast(Constant(value, _), toTpe: SNumericType) => + case ast.Downcast(Constant(value, _), toTpe: SNumericType) => eval(mkConstant(toTpe.downcast(value.asInstanceOf[AnyVal]), toTpe)) // Rule: col.size --> SizeOf(col) @@ -550,7 +546,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => else eval(mkUpcast(numValue, tRes)) - case Terms.Apply(col, Seq(index)) if col.tpe.isCollection => + case sigma.ast.Apply(col, Seq(index)) if col.tpe.isCollection => eval(mkByIndex(col.asCollection[SType], index.asValue[SInt.type], None)) case GetVar(id, optTpe) => @@ -560,7 +556,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => case ValUse(valId, _) => env.getOrElse(valId, !!!(s"ValUse $valId not found in environment $env")) - case Terms.Block(binds, res) => + case Block(binds, res) => var curEnv = env for (v @ Val(n, _, b) <- binds) { if (curEnv.contains(n)) @@ -593,37 +589,37 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => val vv = asRep[GroupElement](_vv) sigmaDslBuilder.proveDHTuple(gv, hv, uv, vv) - case sigmastate.Exponentiate(In(l), In(r)) => + case Exponentiate(In(l), In(r)) => val lV = asRep[GroupElement](l) val rV = asRep[BigInt](r) lV.exp(rV) - case sigmastate.MultiplyGroup(In(_l), In(_r)) => + case MultiplyGroup(In(_l), In(_r)) => val l = asRep[GroupElement](_l) val r = asRep[GroupElement](_r) l.multiply(r) - case Values.GroupGenerator => + case GroupGenerator => sigmaDslBuilder.groupGenerator - case sigmastate.ByteArrayToBigInt(In(arr)) => + case ByteArrayToBigInt(In(arr)) => val arrV = asRep[Coll[Byte]](arr) sigmaDslBuilder.byteArrayToBigInt(arrV) - case sigmastate.LongToByteArray(In(x)) => + case LongToByteArray(In(x)) => val xV = asRep[Long](x) sigmaDslBuilder.longToByteArray(xV) // opt.get - case utxo.OptionGet(In(opt: ROption[_]@unchecked)) => + case OptionGet(In(opt: ROption[_]@unchecked)) => opt.get // opt.isDefined - case utxo.OptionIsDefined(In(opt: ROption[_]@unchecked)) => + case OptionIsDefined(In(opt: ROption[_]@unchecked)) => opt.isDefined // opt.getOrElse(default) - case utxo.OptionGetOrElse(In(opt: ROption[a]@unchecked), In(default)) => + case OptionGetOrElse(In(opt: ROption[a]@unchecked), In(default)) => opt.getOrElse(asRep[a](default)) // tup._1 or tup._2 @@ -641,7 +637,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => } // (x, y) - case Values.Tuple(InSeq(Seq(x, y))) => + case Tuple(InSeq(Seq(x, y))) => Pair(x, y) // xs.exists(predicate) or xs.forall(predicate) @@ -707,7 +703,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => val pV = asRep[Any => Boolean](eval(p)) inputV.filter(pV) - case Terms.Apply(f, Seq(x)) if f.tpe.isFunc => + case sigma.ast.Apply(f, Seq(x)) if f.tpe.isFunc => val fV = asRep[Any => Coll[Any]](eval(f)) val xV = asRep[Any](eval(x)) Apply(fV, xV, mayInline = false) @@ -722,7 +718,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => val res = sigmaDslBuilder.sha256(inputV) res - case utxo.SizeOf(In(xs)) => + case ast.SizeOf(In(xs)) => xs.elem.asInstanceOf[Any] match { case _: CollElem[a,_] => val xsV = asRep[Coll[a]](xs) @@ -751,26 +747,26 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => val pV = asRep[SigmaProp](eval(p)) pV.propBytes - case utxo.ExtractId(In(box: Ref[Box]@unchecked)) => + case ExtractId(In(box: Ref[Box]@unchecked)) => box.id - case utxo.ExtractBytesWithNoRef(In(box: Ref[Box]@unchecked)) => + case ExtractBytesWithNoRef(In(box: Ref[Box]@unchecked)) => box.bytesWithoutRef - case utxo.ExtractAmount(In(box)) => + case ExtractAmount(In(box)) => val boxV = asRep[Box](box) boxV.value - case utxo.ExtractScriptBytes(In(box: Ref[Box]@unchecked)) => + case ExtractScriptBytes(In(box: Ref[Box]@unchecked)) => box.propositionBytes - case utxo.ExtractBytes(In(box: Ref[Box]@unchecked)) => + case ExtractBytes(In(box: Ref[Box]@unchecked)) => box.bytes - case utxo.ExtractCreationInfo(In(box: Ref[Box]@unchecked)) => + case ExtractCreationInfo(In(box: Ref[Box]@unchecked)) => box.creationInfo - case utxo.ExtractRegisterAs(In(box: Ref[Box]@unchecked), regId, optTpe) => + case ExtractRegisterAs(In(box: Ref[Box]@unchecked), regId, optTpe) => val elem = stypeToElem(optTpe.elemType).asInstanceOf[Elem[Any]] val i: Ref[Int] = regId.number.toInt box.getReg(i)(elem) @@ -888,14 +884,14 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => val y = eval(rel.right) binop.apply(x, asRep[t#WrappedType](y)) - case Terms.Lambda(_, Seq((n, argTpe)), _, Some(body)) => + case sigma.ast.Lambda(_, Seq((n, argTpe)), _, Some(body)) => val eArg = stypeToElem(argTpe).asInstanceOf[Elem[Any]] val f = fun(removeIsProven({ x: Ref[Any] => buildNode(ctx, env + (n -> x), body) }))(Lazy(eArg)) f - case Terms.Lambda(_, Seq((accN, accTpe), (n, tpe)), _, Some(body)) => + case sigma.ast.Lambda(_, Seq((accN, accTpe), (n, tpe)), _, Some(body)) => (stypeToElem(accTpe), stypeToElem(tpe)) match { case (eAcc: Elem[s], eA: Elem[a]) => val eArg = pairElement(eAcc, eA) val f = fun { x: Ref[(s, a)] => @@ -916,11 +912,11 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => val values = colBuilder.fromItems(vs: _*)(eAny) values - case sigmastate.Upcast(In(input), tpe) => + case ast.Upcast(In(input), tpe) => val elem = stypeToElem(tpe.asNumType) upcast(input)(elem) - case sigmastate.Downcast(In(input), tpe) => + case ast.Downcast(In(input), tpe) => val elem = stypeToElem(tpe.asNumType) downcast(input)(elem) @@ -938,7 +934,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => sigmaDslBuilder.decodePoint(bytes) // fallback rule for MethodCall, should be the last case in the list - case Terms.MethodCall(obj, method, args, _) => + case sigma.ast.MethodCall(obj, method, args, _) => val objV = eval(obj) val argsV = args.map(eval) (objV, method.objType) match { diff --git a/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala b/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala index 5a588633b9..b84098f2e7 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala @@ -1,6 +1,7 @@ package sigmastate.eval -import sigmastate.lang.TransformingSigmaBuilder +import sigma.ast.TransformingSigmaBuilder +import sigma.data.CSigmaDslBuilder import java.util.concurrent.locks.ReentrantLock import scala.util.Try diff --git a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala index f6b0b2fd2e..7a7d609549 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala @@ -1,17 +1,16 @@ package sigmastate.eval -import sigmastate.Values._ -import org.ergoplatform._ -import sigmastate._ -import sigmastate.lang.Terms.ValueOps -import sigmastate.serialization.OpCodes._ -import sigmastate.serialization.ConstantStore import sigma.ast._ +import org.ergoplatform._ +import sigma.ast.syntax.ValueOps +import sigma.serialization.OpCodes._ +import sigma.serialization.ConstantStore +import sigma.ast.syntax._ import sigma.data.{ProveDHTuple, ProveDlog} import scala.collection.mutable.ArrayBuffer -import sigmastate.serialization.ValueCodes.OpCode +import sigma.serialization.ValueCodes.OpCode /** Implementation of IR-graph to ErgoTree expression translation. * This, in a sense, is inverse to [[GraphBuilding]], however roundtrip identity is not @@ -158,7 +157,7 @@ trait TreeBuilding extends SigmaLibrary { IR: IRContext => def recurse[T <: SType](s: Sym) = buildValue(ctx, mainG, env, s, defId, constantsProcessing).asValue[T] object In { def unapply(s: Sym): Option[SValue] = Some(buildValue(ctx, mainG, env, s, defId, constantsProcessing)) } s match { - case _ if s == ctx => org.ergoplatform.Context + case _ if s == ctx => sigma.ast.Context case _ if env.contains(s) => val (id, tpe) = env(s) ValUse(id, tpe) // recursion base @@ -241,7 +240,7 @@ trait TreeBuilding extends SigmaLibrary { IR: IRContext => val col = recurse(colSym) mkByIndex(col, index.asIntValue, None) case CollM.length(col) => - utxo.SizeOf(recurse(col).asCollection[SType]) + sigma.ast.SizeOf(recurse(col).asCollection[SType]) case CollM.exists(colSym, pSym) => val Seq(col, p) = Seq(colSym, pSym).map(recurse) mkExists(col.asCollection[SType], p.asFunc) diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala index 5d390f5f66..f93e31703d 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala @@ -5,12 +5,12 @@ import org.ergoplatform._ import sigma.ast.NoType import sigma.data.Nullable import sigma.kiama.rewriting.CallbackRewriter -import sigmastate.Values._ -import sigmastate._ +import sigma.ast._ +import sigma.ast.syntax.SValue import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.lang.SigmaPredef.PredefinedFuncRegistry -import sigmastate.lang.Terms._ -import sigmastate.exceptions.{BinderException, InvalidArguments} +import SigmaPredef.PredefinedFuncRegistry +import sigma.ast.syntax._ +import sigma.exceptions.{BinderException, InvalidArguments} object SrcCtxCallbackRewriter extends CallbackRewriter { override def rewriting[T](oldTerm: T, newTerm: T): T = (oldTerm, newTerm) match { diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala index 865d58df51..f26dad5612 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala @@ -4,24 +4,23 @@ import fastparse.Parsed import fastparse.Parsed.Success import sigma.kiama.rewriting.Rewriter.{everywherebu, rewrite, rule} import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix -import org.ergoplatform.Global import scalan.GraphIRReflection -import sigmastate.Values.{SValue, Value} +import sigma.ast.{Exponentiate, MultiplyGroup, SCollectionMethods, SGlobalMethods, SGroupElementMethods, Value, Xor} import sigmastate.eval.IRContext import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.lang.SigmaPredef.PredefinedFuncRegistry -import sigmastate.lang.Terms.MethodCall -import sigmastate.lang.syntax.ParserException -import sigmastate.utxo._ +import sigma.ast.SigmaPredef.PredefinedFuncRegistry +import sigma.ast.MethodCall +import sigmastate.lang.parsers.ParserException import sigma.ast._ -import sigmastate.SCollectionMethods.{ExistsMethod, ForallMethod, MapMethod} -import sigmastate.{Exponentiate, InterpreterReflection, MultiplyGroup, SCollectionMethods, SGlobalMethods, SGroupElementMethods, Xor} +import sigma.ast.syntax.SValue +import SCollectionMethods.{ExistsMethod, ForallMethod, MapMethod} +import sigmastate.InterpreterReflection /** * @param networkPrefix network prefix to decode an ergo address from string (PK op) * @param builder used to create ErgoTree nodes * @param lowerMethodCalls if true, then MethodCall nodes are lowered to ErgoTree nodes - * when [[sigmastate.SMethod.irInfo.irBuilder]] is defined. For + * when [[sigma.ast.SMethod.irInfo.irBuilder]] is defined. For * example, in the `coll.map(x => x+1)` code, the `map` method * call can be lowered to MapCollection node. * The lowering if preferable, because it is more compact (1 byte diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala index 768eda4fc4..979beaa685 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala @@ -2,16 +2,15 @@ package sigmastate.lang import org.ergoplatform._ import sigma.ast.SCollection.{SBooleanArray, SByteArray} -import sigmastate.Values._ -import sigmastate._ import sigma.ast._ +import sigma.ast.syntax.SValue import sigma.data.{Nullable, SigmaBoolean} import sigma.util.Extensions.Ensuring -import sigmastate.lang.Terms._ import sigmastate.exceptions._ -import sigmastate.lang.SigmaPredef._ -import sigmastate.serialization.OpCodes -import sigmastate.utxo._ +import SigmaPredef._ +import sigma.ast.syntax._ +import sigma.exceptions.TyperException +import sigma.serialization.OpCodes import scala.collection.mutable.ArrayBuffer @@ -504,7 +503,6 @@ class SigmaTyper(val builder: SigmaBuilder, case Inputs => Inputs case Outputs => Outputs case LastBlockUtxoRootHash => LastBlockUtxoRootHash - case v: ContextVariable[_] => v case v: GetVar[_] => v case v: OptionGet[_] => v case v: EvaluatedValue[_] => v diff --git a/sc/shared/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala b/sc/shared/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala index c4660f3c43..ad0d316519 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala @@ -4,26 +4,25 @@ import org.ergoplatform.ErgoAddressEncoder.{MainnetNetworkPrefix, TestnetNetwork import org.scalatest.{Assertion, TryValues} import scorex.crypto.hash.Blake2b256 import scorex.util.encode.Base58 -import sigmastate.Values.{ByteArrayConstant, Constant, IntConstant} +import sigma.ast.{ByteArrayConstant, Constant, ErgoTree, IntConstant, SigmaAnd, UnparsedErgoTree} import sigmastate.crypto.DLogProtocol.DLogProverInput -import sigmastate.eval.InvalidType import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers._ -import sigmastate.interpreter.ContextExtension.VarBinding -import sigmastate.crypto.CryptoConstants.dlogGroup -import sigmastate.exceptions.CostLimitException +import sigma.interpreter.ContextExtension.VarBinding +import sigma.crypto.CryptoConstants.dlogGroup import sigmastate.interpreter.Interpreter.{ScriptEnv, ScriptNameProp} -import sigmastate.interpreter.{ContextExtension, CostedProverResult} -import sigmastate.lang.Terms.ValueOps -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.serialization.ValueSerializer +import sigma.ast.syntax.ValueOps +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer +import sigma.serialization.ValueSerializer import sigmastate.utils.Helpers._ -import sigmastate.{CompilerCrossVersionProps, ErgoTree, SigmaAnd, UnparsedErgoTree} +import sigmastate.CompilerCrossVersionProps import sigma.SigmaDslTesting -import sigmastate.ErgoTree.{ZeroHeader, setConstantSegregation} +import sigma.ast.ErgoTree.{ZeroHeader, setConstantSegregation} import sigma.ast.SType import sigma.data.ProveDlog +import sigma.exceptions.{CostLimitException, InvalidType} +import sigma.interpreter.{ContextExtension, CostedProverResult} import sigma.serialization.GroupElementSerializer import sigma.validation.ValidationException import sigma.validation.ValidationRules.CheckTypeCode diff --git a/sc/shared/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala index d49b460c7e..6849d4ee22 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala @@ -4,20 +4,18 @@ import org.ergoplatform.ErgoBox.TokenId import org.ergoplatform.settings.ErgoAlgos import scorex.util.encode.Base16 import scorex.util.{ModifierId, Random} +import sigma.Extensions._ +import sigma.SigmaDslTesting import sigma.ast.SCollection.SByteArray -import sigma.ast.{SInt, SPair, SSigmaProp, SType} -import sigmastate.Values._ -import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.serialization.SigmaSerializer -import sigmastate.eval._ -import sigmastate.eval.Extensions._ -import sigmastate._ import sigma.ast.SType._ +import sigma.ast.syntax.{ErgoBoxCandidateRType, TrueSigmaProp} +import sigma.ast._ +import sigma.data.{CSigmaProp, Digest32Coll, TrivialProp} +import sigma.eval.Extensions.{EvalCollOps, EvalIterableOps} +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.serialization.SigmaSerializer import sigmastate.helpers.TestingHelpers.copyTransaction import sigmastate.utils.Helpers -import sigma.SigmaDslTesting -import sigma.Extensions._ -import sigma.data.{CSigmaProp, Digest32Coll, TrivialProp} class ErgoLikeTransactionSpec extends SigmaDslTesting { diff --git a/sc/shared/src/test/scala/org/ergoplatform/ErgoTreePredefSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/ErgoTreePredefSpec.scala index 793825f72d..eb086e88c8 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/ErgoTreePredefSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/ErgoTreePredefSpec.scala @@ -8,19 +8,18 @@ import org.scalacheck.Gen import scorex.crypto.hash.Blake2b256 import scorex.util.Random import sigma.Colls -import sigma.ast.SByte +import sigma.ast._ +import sigma.ast.syntax.CollectionConstant import sigma.data.{AvlTreeData, Digest32Coll, ProveDlog, TrivialProp} import sigma.util.BenchmarkUtil.measure -import sigmastate.Values.{ByteArrayConstant, CollectionConstant, IntConstant, SigmaPropConstant} import sigmastate._ import sigmastate.crypto.DLogProtocol.DLogProverInput import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} -import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.lang.Terms.ValueOps -import sigmastate.serialization.ValueSerializer -import sigmastate.utxo.{ByIndex, ExtractCreationInfo, SelectField} +import sigma.ast.syntax.ValueOps +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.serialization.ValueSerializer import sigmastate.utils.Helpers._ import scala.util.Try diff --git a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala index 92ce39f5b5..8d7b54e1d4 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala @@ -3,8 +3,7 @@ package org.ergoplatform.dsl import sigmastate.interpreter.Interpreter.ScriptNameProp import scala.collection.mutable -import sigmastate.interpreter.{CostedProverResult, ProverResult} - +import sigma.interpreter.{CostedProverResult, ProverResult} import scala.collection.mutable.ArrayBuffer import org.ergoplatform.ErgoBox.{NonMandatoryRegisterId, TokenId} import sigma.data.{AvlTreeData, CAnyValue, CSigmaProp, Nullable} @@ -12,15 +11,14 @@ import sigma.data.{AvlTreeData, CAnyValue, CSigmaProp, Nullable} import scala.util.Try import org.ergoplatform.{ErgoBox, ErgoLikeContext} import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} -import sigma.ast.SType -import sigmastate.Values.EvaluatedValue +import sigma.ast.{ErgoTree, SType} +import sigma.ast.EvaluatedValue import sigmastate.eval.IRContext import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ -import sigmastate.lang.Terms.ValueOps +import sigma.ast.syntax.ValueOps import sigma.{AnyValue, Evaluation, SigmaProp} -import sigmastate.ErgoTree -import sigmastate.ErgoTree.ZeroHeader +import ErgoTree.ZeroHeader case class TestContractSpec(testSuite: CompilerTestingCommons)(implicit val IR: IRContext) extends ContractSpec { diff --git a/sc/shared/src/test/scala/org/ergoplatform/validation/RuleStatusSerializerSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/validation/RuleStatusSerializerSpec.scala index 03bcd2039c..da7d74e79b 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/validation/RuleStatusSerializerSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/validation/RuleStatusSerializerSpec.scala @@ -1,9 +1,8 @@ package org.ergoplatform.validation -import org.scalatest.Assertion import sigma.validation.{ReplacedRule, RuleStatus} import sigmastate.helpers.CompilerTestingCommons -import sigmastate.serialization.{SerializationSpecification, SigmaSerializer} +import sigma.serialization.{SerializationSpecification, SigmaSerializer} class RuleStatusSerializerSpec extends SerializationSpecification with CompilerTestingCommons { diff --git a/sc/shared/src/test/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializerSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializerSpec.scala index 9fd2de7075..ee1c1a339a 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializerSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializerSpec.scala @@ -1,11 +1,10 @@ package org.ergoplatform.validation import org.ergoplatform.validation.ValidationRules.currentSettings -import org.scalatest.Assertion import sigma.validation.{DisabledRule, SigmaValidationSettings} import sigma.validation.ValidationRules.FirstRuleId import sigmastate.helpers.CompilerTestingCommons -import sigmastate.serialization.SerializationSpecification +import sigma.serialization.SerializationSpecification class SigmaValidationSettingsSerializerSpec extends SerializationSpecification with CompilerTestingCommons { diff --git a/sc/shared/src/test/scala/sigma/DataValueComparerSpecification.scala b/sc/shared/src/test/scala/sigma/DataValueComparerSpecification.scala index 98035bee6d..b82a747069 100644 --- a/sc/shared/src/test/scala/sigma/DataValueComparerSpecification.scala +++ b/sc/shared/src/test/scala/sigma/DataValueComparerSpecification.scala @@ -1,14 +1,13 @@ package sigma import org.scalatest.BeforeAndAfterAll -import sigma.data.{CSigmaProp, RType, TrivialProp} +import sigma.data.{CSigmaProp, DataValueComparer, RType, TrivialProp} import sigma.util.BenchmarkUtil -import sigmastate.{DataValueComparer, JitCost} -import sigmastate.ErgoTree -import sigmastate.eval.{Profiler, SigmaDsl} +import sigmastate.eval.CProfiler import sigmastate.helpers.SigmaPPrint -import sigmastate.interpreter.{CostAccumulator, ErgoTreeEvaluator, EvalSettings, TracedCost} -import sigma.Coll +import sigmastate.interpreter.{CostAccumulator, CErgoTreeEvaluator} +import sigma.ast.{ErgoTree, JitCost} +import sigma.eval.{EvalSettings, SigmaDsl, TracedCost} import scala.util.{Success, Try} @@ -18,7 +17,7 @@ class DataValueComparerSpecification extends SigmaDslTesting implicit override val generatorDrivenConfig = PropertyCheckConfiguration(minSuccessful = 30) implicit override val evalSettings: EvalSettings = - ErgoTreeEvaluator.DefaultEvalSettings.copy( + CErgoTreeEvaluator.DefaultEvalSettings.copy( isMeasureOperationTime = true, isMeasureScriptTime = true, isLogEnabled = false, // don't commit the `true` value (CI log is too high) @@ -29,15 +28,15 @@ class DataValueComparerSpecification extends SigmaDslTesting val nWarmUpIterations = 100 - implicit val suiteProfiler = new Profiler + implicit val suiteProfiler = new CProfiler import TestData._ - def createEvaluator(settings: EvalSettings, profiler: Profiler): ErgoTreeEvaluator = { + def createEvaluator(settings: EvalSettings, profiler: CProfiler): CErgoTreeEvaluator = { val accumulator = new CostAccumulator( initialCost = JitCost(0), costLimit = Some(JitCost.fromBlockCost(settings.scriptCostLimitInEvaluator))) - val evaluator = new ErgoTreeEvaluator( + val evaluator = new CErgoTreeEvaluator( context = null, constants = ErgoTree.EmptyConstants, coster = accumulator, profiler, settings) @@ -51,7 +50,7 @@ class DataValueComparerSpecification extends SigmaDslTesting * @param x computation which produced first argument * @param y computation which produced second argument */ - def check(x: => Any, y: => Any, expected: Boolean)(implicit settings: EvalSettings, profiler: Profiler) = { + def check(x: => Any, y: => Any, expected: Boolean)(implicit settings: EvalSettings, profiler: CProfiler) = { val _x = x // force computation and obtain value val _y = y withClue(s"EQ.equalDataValues(${_x}, ${_y})") { @@ -96,7 +95,7 @@ class DataValueComparerSpecification extends SigmaDslTesting override protected def beforeAll(): Unit = { // this method warms up the code in DataValueComparer - val warmUpProfiler = new Profiler + val warmUpProfiler = new CProfiler warmUpBeforeAllTest(nTotalIters = nWarmUpIterations) { runBaseCases(warmUpProfiler)(evalSettings = evalSettings.copy(isLogEnabled = false)) } @@ -116,7 +115,7 @@ class DataValueComparerSpecification extends SigmaDslTesting * This method is used: * 1) to warm up DataValueComparer in the beforeAll method * 2) to profile DataValueComparer operations */ - def runBaseCases(profiler: Profiler)(implicit evalSettings: EvalSettings) = { + def runBaseCases(profiler: CProfiler)(implicit evalSettings: EvalSettings) = { implicit val suiteProfiler = profiler // hide suite's profiler and use explicitly passed ones.foreach { x => ones.foreach { y => diff --git a/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala b/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala index 3b9cf4a76e..4dd576f03a 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala @@ -13,24 +13,26 @@ import scorex.util.ModifierId import sigma.Extensions.{ArrayOps, CollOps} import sigma.ast.SCollection._ import sigma.ast._ +import sigma.ast.syntax._ import sigma.data.RType._ import sigma.data._ import sigma.util.Extensions.{BooleanOps, IntOps, LongOps} -import sigma.{VersionContext, data, _} -import sigmastate.ErgoTree.{HeaderType, ZeroHeader} -import sigmastate.Values.{IntConstant, _} +import sigma.{VersionContext, ast, data, _} +import ErgoTree.{HeaderType, ZeroHeader} +import sigma.eval.{CostDetails, EvalSettings, Profiler, SigmaDsl, TracedCost} import sigmastate._ -import sigmastate.eval.Extensions.{AvlTreeOps, ByteExt, IntExt, LongExt, ShortExt} -import sigmastate.eval.OrderingOps._ +import sigmastate.eval.Extensions.AvlTreeOps +import sigma.eval.Extensions.{ByteExt, IntExt, LongExt, ShortExt} +import OrderingOps._ import sigmastate.eval._ import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter._ -import sigmastate.lang.Terms.{Apply, MethodCall, PropertyCall} -import sigmastate.serialization.ValueCodes.OpCode +import sigma.ast.{Apply, MethodCall, PropertyCall} +import sigma.exceptions.InvalidType +import sigma.serialization.ValueCodes.OpCode import sigmastate.utils.Extensions._ import sigmastate.utils.Helpers import sigmastate.utils.Helpers._ -import sigmastate.utxo._ import java.math.BigInteger import scala.collection.compat.immutable.ArraySeq @@ -78,7 +80,7 @@ class SigmaDslSpecification extends SigmaDslTesting implicit override val generatorDrivenConfig = PropertyCheckConfiguration(minSuccessful = 30) - val evalSettingsInTests = ErgoTreeEvaluator.DefaultEvalSettings.copy( + val evalSettingsInTests = CErgoTreeEvaluator.DefaultEvalSettings.copy( isMeasureOperationTime = true, isMeasureScriptTime = true, isLogEnabled = false, // don't commit the `true` value (travis log is too high) @@ -89,7 +91,7 @@ class SigmaDslSpecification extends SigmaDslTesting */ costTracingEnabled = true, - profilerOpt = Some(ErgoTreeEvaluator.DefaultProfiler), + profilerOpt = Some(CErgoTreeEvaluator.DefaultProfiler), isTestRun = true ) @@ -172,7 +174,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FuncValue.AddToEnvironmentDesc_CostKind), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FuncValue.AddToEnvironmentDesc_CostKind), @@ -666,7 +668,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(LogicalNot), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -2490,14 +2492,14 @@ class SigmaDslSpecification extends SigmaDslTesting ) val collNeqCost2 = Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_Box"), PerItemCost(JitCost(15), JitCost(5), 1), 0) + ast.SeqCostItem(NamedDesc("EQ_COA_Box"), PerItemCost(JitCost(15), JitCost(5), 1), 0) ) implicit val evalSettings = suite.evalSettings.copy(isMeasureOperationTime = false) verifyNeq(Coll[Byte](), Coll(1.toByte), 1766, collNeqCost1, 1766)(cloneColl(_)) verifyNeq(Coll[Byte](0, 1), Coll(1.toByte, 1.toByte), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_Byte"), PerItemCost(JitCost(15), JitCost(2), 128), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_Byte"), PerItemCost(JitCost(15), JitCost(2), 128), 1)), 1768 )(cloneColl(_)) @@ -2505,7 +2507,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyNeq(Coll[Short](0), Coll(1.toShort), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_Short"), PerItemCost(JitCost(15), JitCost(2), 96), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_Short"), PerItemCost(JitCost(15), JitCost(2), 96), 1)), 1768 )(cloneColl(_)) @@ -2513,7 +2515,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyNeq(Coll[Int](0), Coll(1), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_Int"), PerItemCost(JitCost(15), JitCost(2), 64), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_Int"), PerItemCost(JitCost(15), JitCost(2), 64), 1)), 1768 )(cloneColl(_)) @@ -2521,7 +2523,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyNeq(Coll[Long](0), Coll(1.toLong), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_Long"), PerItemCost(JitCost(15), JitCost(2), 48), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_Long"), PerItemCost(JitCost(15), JitCost(2), 48), 1)), 1768 )(cloneColl(_)) @@ -2530,7 +2532,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyNeq(Coll[BigInt](0.toBigInt), Coll(1.toBigInt), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_BigInt"), PerItemCost(JitCost(15), JitCost(7), 5), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_BigInt"), PerItemCost(JitCost(15), JitCost(7), 5), 1)), 1768 )(cloneColl(_)) @@ -2539,7 +2541,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyNeq(Coll[GroupElement](ge1), Coll(ge2), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_GroupElement"), PerItemCost(JitCost(15), JitCost(5), 1), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_GroupElement"), PerItemCost(JitCost(15), JitCost(5), 1), 1)), 1768 )(cloneColl(_)) @@ -2548,7 +2550,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyNeq(Coll[AvlTree](t1), Coll(t2), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_AvlTree"), PerItemCost(JitCost(15), JitCost(5), 2), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_AvlTree"), PerItemCost(JitCost(15), JitCost(5), 2), 1)), 1768 )(cloneColl(_)) @@ -2569,7 +2571,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyNeq(Coll[Box](b1), Coll(b2), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_Box"), PerItemCost(JitCost(15), JitCost(5), 1), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_Box"), PerItemCost(JitCost(15), JitCost(5), 1), 1)), 1768 )(cloneColl(_), generateCases = false) } @@ -2579,7 +2581,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyNeq(Coll[PreHeader](preH1), Coll(preH2), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_PreHeader"), PerItemCost(JitCost(15), JitCost(3), 1), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_PreHeader"), PerItemCost(JitCost(15), JitCost(3), 1), 1)), 1768 )(cloneColl(_)) @@ -2588,7 +2590,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyNeq(Coll[Header](h1), Coll(h2), 1768, Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_Header"), PerItemCost(JitCost(15), JitCost(5), 1), 1)), + ast.SeqCostItem(NamedDesc("EQ_COA_Header"), PerItemCost(JitCost(15), JitCost(5), 1), 1)), 1768 )(cloneColl(_)) } @@ -2605,13 +2607,13 @@ class SigmaDslSpecification extends SigmaDslTesting val nestedNeq2 = Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) ) val nestedNeq3 = Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), - SeqCostItem(NamedDesc("EQ_COA_Int"), PerItemCost(JitCost(15), JitCost(2), 64), 1), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) + ast.SeqCostItem(NamedDesc("EQ_COA_Int"), PerItemCost(JitCost(15), JitCost(2), 64), 1), + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) ) verifyNeq(Coll[Coll[Int]](), Coll(Coll[Int]()), 1766, nestedNeq1, 1766)(cloneColl(_)) verifyNeq(Coll(Coll[Int]()), Coll(Coll[Int](1)), 1767, nestedNeq2, 1767)(cloneColl(_)) @@ -2627,8 +2629,8 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(NamedDesc("EQ_Tuple"), FixedCost(JitCost(4))), FixedCostItem(NamedDesc("EQ_Prim"), FixedCost(JitCost(3))), FixedCostItem(NamedDesc("EQ_BigInt"), FixedCost(JitCost(5))), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1), + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) ) val nestedNeq5 = Array( FixedCostItem(NamedDesc("MatchType"), FixedCost(JitCost(1))), @@ -2637,9 +2639,9 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(NamedDesc("EQ_Tuple"), FixedCost(JitCost(4))), FixedCostItem(NamedDesc("EQ_Prim"), FixedCost(JitCost(3))), FixedCostItem(NamedDesc("EQ_BigInt"), FixedCost(JitCost(5))), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1), + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1), + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) ) val nestedNeq6 = Array( FixedCostItem(NamedDesc("EQ_Tuple"), FixedCost(JitCost(4))), @@ -2655,9 +2657,9 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(NamedDesc("EQ_Tuple"), FixedCost(JitCost(4))), FixedCostItem(NamedDesc("EQ_Prim"), FixedCost(JitCost(3))), FixedCostItem(NamedDesc("EQ_BigInt"), FixedCost(JitCost(5))), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 2), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1), - SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 2), + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1), + ast.SeqCostItem(NamedDesc("EQ_Coll"), PerItemCost(JitCost(10), JitCost(2), 1), 1) ) verifyNeq(Coll(Coll((1, 10.toBigInt))), Coll(Coll((1, 11.toBigInt))), 1770, nestedNeq4, 1770)(cloneColl(_)) verifyNeq(Coll(Coll(Coll((1, 10.toBigInt)))), Coll(Coll(Coll((1, 11.toBigInt)))), 1771, nestedNeq5, 1771)(cloneColl(_)) @@ -3234,7 +3236,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -3245,12 +3247,12 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 456), - SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3), - SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3), - SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3), - SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3), - SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3) + ast.SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 456), + ast.SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3), + ast.SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3), + ast.SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3), + ast.SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3), + ast.SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 3) ) ) @@ -3281,7 +3283,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -3292,8 +3294,8 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), i), - SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 1) + ast.SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), i), + ast.SeqCostItem(NamedDesc("LookupAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 1) ) ) @@ -3487,7 +3489,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -3503,8 +3505,8 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails1 = TracedCost(testTraceBase) val costDetails2 = TracedCost( testTraceBase ++ Array( - SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 70), - SeqCostItem(NamedDesc("InsertIntoAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 1), + ast.SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 70), + ast.SeqCostItem(NamedDesc("InsertIntoAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 1), FixedCostItem(SAvlTreeMethods.updateDigestMethod, FixedCost(JitCost(40))) ) ) @@ -3625,7 +3627,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -3641,15 +3643,15 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails1 = TracedCost(testTraceBase) val costDetails2 = TracedCost( testTraceBase ++ Array( - SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 111), - SeqCostItem(NamedDesc("UpdateAvlTree"), PerItemCost(JitCost(120), JitCost(20), 1), 1), + ast.SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 111), + ast.SeqCostItem(NamedDesc("UpdateAvlTree"), PerItemCost(JitCost(120), JitCost(20), 1), 1), FixedCostItem(SAvlTreeMethods.updateDigestMethod, FixedCost(JitCost(40))) ) ) val costDetails3 = TracedCost( testTraceBase ++ Array( - SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 111), - SeqCostItem(NamedDesc("UpdateAvlTree"), PerItemCost(JitCost(120), JitCost(20), 1), 1) + ast.SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 111), + ast.SeqCostItem(NamedDesc("UpdateAvlTree"), PerItemCost(JitCost(120), JitCost(20), 1), 1) ) ) @@ -3754,7 +3756,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -3769,17 +3771,17 @@ class SigmaDslSpecification extends SigmaDslTesting ) val costDetails1 = TracedCost( testTraceBase ++ Array( - SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 436), - SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 3), - SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 3), + ast.SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 436), + ast.SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 3), + ast.SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 3), FixedCostItem(SAvlTreeMethods.digestMethod, FixedCost(JitCost(15))), FixedCostItem(SAvlTreeMethods.updateDigestMethod, FixedCost(JitCost(40))) ) ) val costDetails2 = TracedCost( testTraceBase ++ Array( - SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 140), - SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 1), + ast.SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 140), + ast.SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 1), FixedCostItem(SAvlTreeMethods.digestMethod, FixedCost(JitCost(15))), FixedCostItem(SAvlTreeMethods.updateDigestMethod, FixedCost(JitCost(40))) ) @@ -3787,8 +3789,8 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails3 = TracedCost(testTraceBase) val costDetails4 = TracedCost( testTraceBase ++ Array( - SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 140), - SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 1), + ast.SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 140), + ast.SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 1), FixedCostItem(SAvlTreeMethods.digestMethod, FixedCost(JitCost(15))) ) ) @@ -4082,7 +4084,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(CompanionDesc(ExtractRegisterAs), FixedCost(JitCost(50))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -4100,7 +4102,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(CompanionDesc(ExtractRegisterAs), FixedCost(JitCost(50))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -4155,14 +4157,14 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(CompanionDesc(ExtractRegisterAs), FixedCost(JitCost(50))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(CompanionDesc(OptionIsDefined), FixedCost(JitCost(10))), FixedCostItem(CompanionDesc(If), FixedCost(JitCost(10))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -4184,14 +4186,14 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(CompanionDesc(ExtractRegisterAs), FixedCost(JitCost(50))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(CompanionDesc(OptionIsDefined), FixedCost(JitCost(10))), FixedCostItem(CompanionDesc(If), FixedCost(JitCost(10))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -4216,14 +4218,14 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(CompanionDesc(ExtractRegisterAs), FixedCost(JitCost(50))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(CompanionDesc(OptionIsDefined), FixedCost(JitCost(10))), FixedCostItem(CompanionDesc(If), FixedCost(JitCost(10))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -4905,7 +4907,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(Inputs), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractAmount))) @@ -4919,7 +4921,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(Inputs), FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollectionMethods.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), 1), + ast.SeqCostItem(MethodDesc(SCollectionMethods.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractAmount) @@ -4961,9 +4963,9 @@ class SigmaDslSpecification extends SigmaDslTesting if (lowerMethodCallsInTests) Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(ExtractAmount), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -4974,9 +4976,9 @@ class SigmaDslSpecification extends SigmaDslTesting Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollectionMethods.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), 1), + ast.SeqCostItem(MethodDesc(SCollectionMethods.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(ExtractAmount), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5199,7 +5201,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), @@ -5360,7 +5362,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(Outputs), FixedCostItem(Constant), FixedCostItem(ByIndex), @@ -5371,7 +5373,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5395,7 +5397,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(Outputs), FixedCostItem(Constant), FixedCostItem(ByIndex), @@ -5406,7 +5408,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5428,7 +5430,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(Outputs), FixedCostItem(Constant), FixedCostItem(ByIndex), @@ -5529,7 +5531,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(Outputs), FixedCostItem(Constant), FixedCostItem(ByIndex), @@ -5540,7 +5542,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5567,7 +5569,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(Outputs), FixedCostItem(Constant), FixedCostItem(ByIndex), @@ -5578,7 +5580,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5602,7 +5604,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(Outputs), FixedCostItem(Constant), FixedCostItem(ByIndex), @@ -5613,7 +5615,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5635,7 +5637,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(Outputs), FixedCostItem(Constant), FixedCostItem(ByIndex), @@ -5758,7 +5760,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), @@ -5771,7 +5773,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5795,7 +5797,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), @@ -5808,7 +5810,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5829,7 +5831,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), @@ -5842,7 +5844,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5864,7 +5866,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), @@ -5986,7 +5988,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), @@ -5999,7 +6001,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -6026,7 +6028,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), @@ -6039,7 +6041,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -6063,7 +6065,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), @@ -6076,7 +6078,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(OptionIsDefined), FixedCostItem(If), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -6098,7 +6100,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), @@ -6223,7 +6225,7 @@ class SigmaDslSpecification extends SigmaDslTesting } property("xorOf equivalence") { - def costDetails(i: Int) = TracedCost(traceBase :+ SeqCostItem(CompanionDesc(XorOf), PerItemCost(JitCost(20), JitCost(5), 32), i)) + def costDetails(i: Int) = TracedCost(traceBase :+ ast.SeqCostItem(CompanionDesc(XorOf), PerItemCost(JitCost(20), JitCost(5), 32), i)) verifyCases( { def successNew[T](v: T, c: Int, newV: T, cd: CostDetails) = Expected( @@ -6472,7 +6474,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(CompanionDesc(Xor), PerItemCost(JitCost(10), JitCost(2), 128), i) + ast.SeqCostItem(CompanionDesc(Xor), PerItemCost(JitCost(10), JitCost(2), 128), i) ) ) else @@ -6489,7 +6491,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(CompanionDesc(Xor), PerItemCost(JitCost(10), JitCost(2), 128), i) + ast.SeqCostItem(CompanionDesc(Xor), PerItemCost(JitCost(10), JitCost(2), 128), i) ) ) } @@ -6619,13 +6621,13 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 0) + ast.SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 0) ) ) val costDetails2 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractAmount), @@ -6636,7 +6638,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails3 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 2), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractAmount), @@ -6679,7 +6681,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) + ast.SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) ) ) val costDetails2 = TracedCost( @@ -6689,7 +6691,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractScriptBytes), - SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 135) + ast.SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 135) ) ) val costDetails3 = TracedCost( @@ -6702,7 +6704,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractScriptBytes), - SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 147) + ast.SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 147) ) ) verifyCases( @@ -6741,7 +6743,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(ValUse), - SeqCostItem(MethodDesc(SCollectionMethods.ZipMethod), PerItemCost(JitCost(10), JitCost(1), 10), zipElements) + ast.SeqCostItem(MethodDesc(SCollectionMethods.ZipMethod), PerItemCost(JitCost(10), JitCost(1), 10), zipElements) ) ) @@ -6797,7 +6799,7 @@ class SigmaDslSpecification extends SigmaDslTesting def costDetails(indicesCount: Int) = TracedCost( traceBase ++ Array( FixedCostItem(PropertyCall), - SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), indicesCount) + ast.SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), indicesCount) ) ) verifyCases( @@ -6831,13 +6833,13 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails1 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 0) + ast.SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 0) ) ) val costDetails2 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractAmount), @@ -6848,7 +6850,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails3 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 2), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractAmount), @@ -6902,13 +6904,13 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails1 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 0) + ast.SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 0) ) ) val costDetails2 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractAmount), @@ -6919,7 +6921,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails3 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 2), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractAmount), @@ -6976,13 +6978,13 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails1 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 0) + ast.SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 0) ) ) val costDetails2 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -6994,7 +6996,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails3 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -7008,7 +7010,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails4 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(Exists), PerItemCost(JitCost(3), JitCost(1), 10), 2), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -7090,13 +7092,13 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails1 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 0) + ast.SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 0) ) ) val costDetails2 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -7108,7 +7110,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails3 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -7122,7 +7124,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails4 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 2), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -7211,7 +7213,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) + ast.SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) ) ) val costDetails1 = TracedCost( @@ -7219,8 +7221,8 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(MethodCall), FixedCostItem(FuncValue), FixedCostItem(NamedDesc("MatchSingleArgMethodCall"), FixedCost(JitCost(30))), - SeqCostItem(NamedDesc("CheckFlatmapBody"), PerItemCost(JitCost(20), JitCost(20), 1), 1), - SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) + ast.SeqCostItem(NamedDesc("CheckFlatmapBody"), PerItemCost(JitCost(20), JitCost(20), 1), 1), + ast.SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) ) ) val costDetails2 = TracedCost( @@ -7235,7 +7237,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), - SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 66) + ast.SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 66) ) ) val costDetails3 = TracedCost( @@ -7254,7 +7256,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), - SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 99) + ast.SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 99) ) ) val costDetails4 = TracedCost( @@ -7266,14 +7268,14 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(PropertyCall), FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), FixedCostItem(PropertyCall), - SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 33), + ast.SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 33), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), FixedCostItem(PropertyCall), - SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 33), - SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 66) + ast.SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 33), + ast.SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 66) ) ) @@ -7388,7 +7390,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -7402,7 +7404,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(MethodDesc(SCollectionMethods.PatchMethod), PerItemCost(JitCost(30), JitCost(2), 10), i) + ast.SeqCostItem(MethodDesc(SCollectionMethods.PatchMethod), PerItemCost(JitCost(30), JitCost(2), 10), i) ) ) @@ -7480,7 +7482,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -7491,7 +7493,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(MethodDesc(SCollectionMethods.UpdatedMethod), PerItemCost(JitCost(20), JitCost(1), 10), i) + ast.SeqCostItem(MethodDesc(SCollectionMethods.UpdatedMethod), PerItemCost(JitCost(20), JitCost(1), 10), i) ) ) verifyCases( @@ -7557,7 +7559,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -7568,7 +7570,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(MethodDesc(SCollectionMethods.UpdateManyMethod), PerItemCost(JitCost(20), JitCost(2), 10), i) + ast.SeqCostItem(MethodDesc(SCollectionMethods.UpdateManyMethod), PerItemCost(JitCost(20), JitCost(2), 10), i) ) ) verifyCases( @@ -7674,7 +7676,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 0) + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 0) ) ) val costDetails2 = TracedCost( @@ -7683,7 +7685,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(SelectField), @@ -7699,7 +7701,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 2), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(SelectField), @@ -7722,7 +7724,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 3), + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 3), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(SelectField), @@ -7821,7 +7823,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 0) + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 0) ) ) val costDetails2 = TracedCost( @@ -7830,9 +7832,9 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), TypeBasedCostItem(Upcast, SInt), @@ -7855,9 +7857,9 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), TypeBasedCostItem(Upcast, SInt), @@ -7878,9 +7880,9 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 2), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), TypeBasedCostItem(Upcast, SInt), @@ -7896,7 +7898,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), TypeBasedCostItem(ArithOp.Plus, SInt), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), TypeBasedCostItem(Upcast, SInt), @@ -7919,9 +7921,9 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 2), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), TypeBasedCostItem(Upcast, SInt), @@ -7937,7 +7939,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), TypeBasedCostItem(ArithOp.Plus, SInt), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), TypeBasedCostItem(Upcast, SInt), @@ -7958,9 +7960,9 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 3), + ast.SeqCostItem(CompanionDesc(Fold), PerItemCost(JitCost(3), JitCost(1), 10), 3), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), TypeBasedCostItem(Upcast, SInt), @@ -7976,7 +7978,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), TypeBasedCostItem(ArithOp.Plus, SInt), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), TypeBasedCostItem(Upcast, SInt), @@ -7990,7 +7992,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(If), FixedCostItem(ValUse), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(SelectField), TypeBasedCostItem(Upcast, SInt), @@ -8113,7 +8115,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -8126,7 +8128,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField) ) ++ Array.fill(i)(FixedCostItem(NamedDesc("EQ_Prim"), FixedCost(JitCost(3)))) - :+ SeqCostItem(MethodDesc(SCollectionMethods.IndexOfMethod), PerItemCost(JitCost(20), JitCost(10), 2), i) + :+ ast.SeqCostItem(MethodDesc(SCollectionMethods.IndexOfMethod), PerItemCost(JitCost(20), JitCost(10), 2), i) ) verifyCases( // (coll, (elem: Byte, from: Int)) @@ -8233,7 +8235,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -8393,13 +8395,13 @@ class SigmaDslSpecification extends SigmaDslTesting if (lowerMethodCallsInTests) Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), i) + ast.SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), i) ) else Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollectionMethods.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), i) + ast.SeqCostItem(MethodDesc(SCollectionMethods.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), i) ) ) ++ repeatPlusChunk(i) @@ -8447,13 +8449,13 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails1 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 0) + ast.SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 0) ) ) val costDetails2 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -8467,7 +8469,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails3 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -8481,7 +8483,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails4 = TracedCost( traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 2), + ast.SeqCostItem(CompanionDesc(MapCollection), PerItemCost(JitCost(20), JitCost(1), 10), 2), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -8549,7 +8551,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), i) + ast.SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), i) ) ++ gtChunk ) @@ -8603,7 +8605,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), i) + ast.SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), i) ) ++ repeatLeftBranch(i) ) @@ -8612,7 +8614,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 3) + ast.SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 3) ) ++ repeatLeftBranch(2) ++ rightBranch @@ -8621,7 +8623,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 5) + ast.SeqCostItem(CompanionDesc(Filter), PerItemCost(JitCost(20), JitCost(1), 10), 5) ) ++ leftBranch ++ rightBranch ++ @@ -8665,7 +8667,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(SelectField), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -8675,7 +8677,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(CompanionDesc(Slice), PerItemCost(JitCost(10), JitCost(2), 100), i) + ast.SeqCostItem(CompanionDesc(Slice), PerItemCost(JitCost(10), JitCost(2), 100), i) ) ) val samples = genSamples(collWithRangeGen, DefaultMinSuccessful) @@ -8767,7 +8769,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(CompanionDesc(Append), PerItemCost(JitCost(20), JitCost(2), 100), i) + ast.SeqCostItem(CompanionDesc(Append), PerItemCost(JitCost(20), JitCost(2), 100), i) ) ) if (lowerMethodCallsInTests) { @@ -9171,7 +9173,7 @@ class SigmaDslSpecification extends SigmaDslTesting property("blake2b256 benchmark: to estimate timeout") { val cases = (1 to 10).map { i => - val block = Colls.fromArray(Array.fill(ErgoTreeEvaluator.DataBlockSize * i)(0.toByte)) + val block = Colls.fromArray(Array.fill(CErgoTreeEvaluator.DataBlockSize * i)(0.toByte)) block } benchmarkCases(cases, @@ -9183,8 +9185,8 @@ class SigmaDslSpecification extends SigmaDslTesting } property("blake2b256, sha256 equivalence") { - def costDetailsBlake(i: Int) = TracedCost(traceBase :+ SeqCostItem(CompanionDesc(CalcBlake2b256), PerItemCost(JitCost(20), JitCost(7), 128), i)) - def costDetailsSha(i: Int) = TracedCost(traceBase :+ SeqCostItem(CompanionDesc(CalcSha256), PerItemCost(JitCost(80), JitCost(8), 64), i)) + def costDetailsBlake(i: Int) = TracedCost(traceBase :+ ast.SeqCostItem(CompanionDesc(CalcBlake2b256), PerItemCost(JitCost(20), JitCost(7), 128), i)) + def costDetailsSha(i: Int) = TracedCost(traceBase :+ ast.SeqCostItem(CompanionDesc(CalcSha256), PerItemCost(JitCost(80), JitCost(8), 64), i)) verifyCases( Seq( @@ -9255,7 +9257,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(Constant), TypeBasedCostItem(ArithOp.Minus, SInt), FixedCostItem(ValUse), - SeqCostItem(CompanionDesc(AtLeast), PerItemCost(JitCost(20), JitCost(3), 5), i) + ast.SeqCostItem(CompanionDesc(AtLeast), PerItemCost(JitCost(20), JitCost(3), 5), i) ) ) @@ -9319,11 +9321,11 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField) ) - val costDetails1 = TracedCost(testTraceBase :+ SeqCostItem(CompanionDesc(SigmaAnd), PerItemCost(JitCost(10), JitCost(2), 1), 2)) + val costDetails1 = TracedCost(testTraceBase :+ ast.SeqCostItem(CompanionDesc(SigmaAnd), PerItemCost(JitCost(10), JitCost(2), 1), 2)) val costDetails2 = TracedCost( testTraceBase ++ Array( FixedCostItem(BoolToSigmaProp), - SeqCostItem(CompanionDesc(SigmaAnd), PerItemCost(JitCost(10), JitCost(2), 1), 2) + ast.SeqCostItem(CompanionDesc(SigmaAnd), PerItemCost(JitCost(10), JitCost(2), 1), 2) ) ) @@ -9401,7 +9403,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField) ) - val costDetails1 = TracedCost(testTraceBase :+ SeqCostItem(CompanionDesc(SigmaOr), PerItemCost(JitCost(10), JitCost(2), 1), 2)) + val costDetails1 = TracedCost(testTraceBase :+ ast.SeqCostItem(CompanionDesc(SigmaOr), PerItemCost(JitCost(10), JitCost(2), 1), 2)) verifyCases( { def success[T](v: T, newCost: Int) = Expected(Success(v), newCost, costDetails1, newCost) @@ -9448,7 +9450,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails2 = TracedCost( testTraceBase ++ Array( FixedCostItem(BoolToSigmaProp), - SeqCostItem(CompanionDesc(SigmaOr), PerItemCost(JitCost(10), JitCost(2), 1), 2) + ast.SeqCostItem(CompanionDesc(SigmaOr), PerItemCost(JitCost(10), JitCost(2), 1), 2) ) ) verifyCases( @@ -9542,7 +9544,7 @@ class SigmaDslSpecification extends SigmaDslTesting } property("allOf equivalence") { - def costDetails(i: Int) = TracedCost(traceBase :+ SeqCostItem(CompanionDesc(AND), PerItemCost(JitCost(10), JitCost(5), 32), i)) + def costDetails(i: Int) = TracedCost(traceBase :+ ast.SeqCostItem(CompanionDesc(AND), PerItemCost(JitCost(10), JitCost(5), 32), i)) verifyCases( Seq( (Coll[Boolean]() -> Expected(Success(true), 1765, costDetails(0), 1765)), @@ -9563,7 +9565,7 @@ class SigmaDslSpecification extends SigmaDslTesting } property("anyOf equivalence") { - def costDetails(i: Int) = TracedCost(traceBase :+ SeqCostItem(CompanionDesc(OR), PerItemCost(JitCost(5), JitCost(5), 64), i)) + def costDetails(i: Int) = TracedCost(traceBase :+ ast.SeqCostItem(CompanionDesc(OR), PerItemCost(JitCost(5), JitCost(5), 64), i)) verifyCases( Seq( (Coll[Boolean]() -> Expected(Success(false), 1764, costDetails(0), 1764)), @@ -9659,7 +9661,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ConcreteCollection), FixedCostItem(Constant), FixedCostItem(BoolToSigmaProp), - SeqCostItem(CompanionDesc(SubstConstants), PerItemCost(JitCost(100), JitCost(100), 1), i) + ast.SeqCostItem(CompanionDesc(SubstConstants), PerItemCost(JitCost(100), JitCost(100), 1), i) ) ) verifyCases( @@ -9731,22 +9733,22 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(GetVar), FixedCostItem(OptionGet), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), - SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), + ast.SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(PropertyCall), FixedCostItem(SContextMethods.headersMethod, FixedCost(JitCost(15))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 1), + ast.SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 1), FixedCostItem(Constant), FixedCostItem(ValUse), FixedCostItem(SizeOf), FixedCostItem(Constant), TypeBasedCostItem(ArithOp.Minus, SInt), - SeqCostItem(CompanionDesc(Slice), PerItemCost(JitCost(10), JitCost(2), 100), 0), + ast.SeqCostItem(CompanionDesc(Slice), PerItemCost(JitCost(10), JitCost(2), 100), 0), FixedCostItem(FuncValue), - SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 0) + ast.SeqCostItem(CompanionDesc(ForAll), PerItemCost(JitCost(3), JitCost(1), 10), 0) ) ) @@ -10022,7 +10024,7 @@ class SigmaDslSpecification extends SigmaDslTesting } override protected def afterAll(): Unit = { - printDebug(ErgoTreeEvaluator.DefaultProfiler.generateReport) + printDebug(CErgoTreeEvaluator.DefaultProfiler.generateReport) printDebug("==========================================================") printDebug(Interpreter.verifySignatureProfiler.generateReport) printDebug("==========================================================") diff --git a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala index ed0f97ec24..5ac9b80889 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala @@ -3,9 +3,8 @@ package sigma import org.scalatest.BeforeAndAfterAll import scalan.{BaseCtxTests, BaseLiftableTests} import sigma.data.TrivialProp -import sigmastate.eval.Extensions._ +import sigma.eval.Extensions.toAnyValue import sigmastate.eval._ -import sigmastate.eval import scala.language.reflectiveCalls @@ -24,7 +23,7 @@ class SigmaDslStaginTests extends BaseCtxTests with ErgoScriptTestkit with BaseL import SigmaDslBuilder._ import SigmaProp._ - val dsl: SSigmaDslBuilder = eval.SigmaDsl + val dsl: SSigmaDslBuilder = sigma.eval.SigmaDsl type RSigmaDslBuilder = cake.SigmaDslBuilder type RContext = cake.Context type RBox = cake.Box @@ -34,8 +33,8 @@ class SigmaDslStaginTests extends BaseCtxTests with ErgoScriptTestkit with BaseL val ctx: SContext = newContext(10, boxA1, VersionContext.MaxSupportedScriptVersion, VersionContext.MaxSupportedScriptVersion) .withInputs(boxA2) .withVariables(Map(1 -> toAnyValue(30), 2 -> toAnyValue(40))) - val p1: SSigmaProp = eval.SigmaDsl.SigmaProp(TrivialProp(true)) - val p2: SSigmaProp = eval.SigmaDsl.SigmaProp(TrivialProp(false)) + val p1: SSigmaProp = sigma.eval.SigmaDsl.SigmaProp(TrivialProp(true)) + val p2: SSigmaProp = sigma.eval.SigmaDsl.SigmaProp(TrivialProp(false)) cake.check(dsl, { env: EnvRep[RSigmaDslBuilder] => for { dsl <- env; arg <- lifted(true) } yield dsl.sigmaProp(arg) }, dsl.sigmaProp(true)) diff --git a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala index afe1c1521c..46222d9fb1 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala @@ -13,31 +13,31 @@ import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import scalan.Platform.threadSleepOrNoOp import sigma.Extensions.ArrayOps -import sigma.data.{CollType, OptionType, PairType, ProveDlog, RType, SigmaLeaf} +import sigma.data.{CBox, CollType, OptionType, PairType, ProveDlog, RType, SigmaLeaf} import sigma.util.BenchmarkUtil import sigma.util.CollectionUtil._ import sigma.util.Extensions._ import sigma.util.StringUtil.StringUtilExtensions -import sigmastate.ErgoTree.ZeroHeader +import sigma.ast.ErgoTree.ZeroHeader import sigma.ast.SType.AnyOps -import sigmastate.Values.{ByteArrayConstant, Constant, ConstantNode, IntConstant, SValue} +import sigma.ast.syntax.{SValue, ValueOps} +import sigma.ast._ +import sigma.eval.{CostDetails, EvalSettings, SigmaDsl} import sigmastate.crypto.DLogProtocol.DLogProverInput import sigmastate.crypto.SigmaProtocolPrivateInput -import sigmastate.eval.Extensions.SigmaBooleanOps -import sigmastate.eval.{CompiletimeIRContext, CBox, CContext, IRContext, SigmaDsl} +import sigmastate.eval.{CContext, CompiletimeIRContext, IRContext} import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{CompilerTestingCommons, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaPPrint} import sigmastate.interpreter.Interpreter.{ScriptEnv, VerificationResult} import sigmastate.interpreter._ -import sigmastate.lang.Terms.{Apply, ValueOps} -import sigmastate.serialization.ValueSerializer -import sigmastate.serialization.generators.ObjectGenerators +import sigma.ast.Apply +import sigma.eval.Extensions.SigmaBooleanOps +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.serialization.ValueSerializer +import sigma.serialization.generators.ObjectGenerators import sigmastate.utils.Helpers._ -import sigmastate.utxo.{DeserializeContext, DeserializeRegister, GetVar, OptionGet} -import sigma.ast.{SOption, SSigmaProp, SType} import sigma.validation.ValidationRules.CheckSerializableTypeCode import sigma.validation.{SigmaValidationSettings, ValidationException} -import sigmastate.{ErgoTree, eval} import scala.collection.mutable import scala.reflect.ClassTag @@ -323,14 +323,14 @@ class SigmaDslTesting extends AnyPropSpec val prop = compile(env, code)(IR).asSigmaProp // Add additional oparations which are not yet implemented in ErgoScript compiler - val multisig = sigmastate.AtLeast( + val multisig = AtLeast( IntConstant(2), Array( pkAlice, DeserializeRegister(ErgoBox.R5, SSigmaProp), // deserialize pkBob DeserializeContext(2, SSigmaProp))) // deserialize pkCarol val header = ErgoTree.headerWithVersion(ZeroHeader, ergoTreeVersionInTests) - ErgoTree.withSegregation(header, sigmastate.SigmaOr(prop, multisig)) + ErgoTree.withSegregation(header, SigmaOr(prop, multisig)) } def ergoCtx(prover: FeatureProvingInterpreter, compiledTree: ErgoTree, expectedValue: B) = { @@ -352,8 +352,8 @@ class SigmaDslTesting extends AnyPropSpec ) // We add ctx as it's own variable with id = 1 - val ctxVar = eval.Extensions.toAnyValue[sigma.Context](ctx)(sigma.ContextRType) - val carolVar = eval.Extensions.toAnyValue[Coll[Byte]](pkCarolBytes.toColl)(RType[Coll[Byte]]) + val ctxVar = sigma.eval.Extensions.toAnyValue[sigma.Context](ctx)(sigma.ContextRType) + val carolVar = sigma.eval.Extensions.toAnyValue[Coll[Byte]](pkCarolBytes.toColl)(RType[Coll[Byte]]) val newCtx = ctx .withUpdatedVars(1 -> ctxVar, 2 -> carolVar) .copy( @@ -462,7 +462,7 @@ class SigmaDslTesting extends AnyPropSpec } /** A number of times the newF function in each test feature is repeated. - * In combination with [[sigmastate.eval.Profiler]] it allows to collect more accurate + * In combination with [[sigmastate.eval.CProfiler]] it allows to collect more accurate * timings for all operations. * @see SigmaDslSpecification */ def nBenchmarkIters: Int = 0 diff --git a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala index e53cec4c41..28f907c199 100644 --- a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala +++ b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala @@ -1,14 +1,14 @@ package sigmastate import scala.util.DynamicVariable -import sigmastate.lang.{CompilerResult, CompilerSettings, SigmaCompiler, TransformingSigmaBuilder} +import sigmastate.lang.{CompilerResult, CompilerSettings, SigmaCompiler} import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.Values.{SValue, SigmaPropValue, Value} +import sigma.ast.{ErgoTree, SType, TransformingSigmaBuilder, Value} import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix -import sigma.ast.SType -import sigmastate.serialization.ValueSerializer +import sigma.ast.syntax.{SValue, SigmaPropValue} +import sigma.serialization.ValueSerializer import sigmastate.eval.IRContext -import sigmastate.lang.Terms.ValueOps +import sigma.ast.syntax.ValueOps trait CompilerTestsBase extends TestsBase { protected val _lowerMethodCalls = new DynamicVariable[Boolean](true) diff --git a/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala b/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala index a5addae4f8..938de5d836 100644 --- a/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala @@ -1,31 +1,28 @@ -package sigmastate +package sigma import org.ergoplatform.settings.ErgoAlgos -import org.ergoplatform.validation.ValidationRules -import org.ergoplatform.{ErgoAddressEncoder, ErgoBox, ErgoLikeContext, Self} -import sigma.data.RType.asType -import sigma.data.{Nullable, RType, TrivialProp} -import sigma.{Evaluation, VersionContext} -import sigma.ast.SCollection.SByteArray -import sigmastate.Values._ +import org.ergoplatform.{ErgoAddressEncoder, ErgoBox, ErgoLikeContext} import sigma.VersionContext._ -import sigmastate.eval.{CBox, Profiler} -import sigmastate.exceptions.{CostLimitException, InterpreterException} -import sigmastate.helpers.{ErgoLikeContextTesting, SigmaPPrint} -import sigmastate.interpreter.{ErgoTreeEvaluator, EvalSettings} -import sigmastate.interpreter.Interpreter.ReductionResult -import sigmastate.lang.{CompilerSettings, SourceContext} -import sigmastate.lang.Terms._ -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.utils.Helpers.TryOps -import sigmastate.utxo._ -import sigma._ +import sigma.ast.SCollection.SByteArray import sigma.ast._ +import sigma.ast.syntax.{SValue, SigmaPropValue, TrueSigmaProp} +import sigma.data.RType.asType +import sigma.data.{CBox, Nullable, RType, TrivialProp} import sigma.validation.ValidationException import sigma.validation.ValidationRules.CheckTypeCode -import sigma.{ContractsTestkit, SigmaDslTesting} -import sigmastate.ErgoTree.HeaderType -import sigmastate.SCollectionMethods.checkValidFlatmap +import ErgoTree.HeaderType +import SCollectionMethods.checkValidFlatmap +import sigmastate.eval.CProfiler +import sigmastate.helpers.{ErgoLikeContextTesting, SigmaPPrint} +import sigmastate.interpreter.Interpreter.ReductionResult +import sigmastate.interpreter.CErgoTreeEvaluator +import sigma.ast.syntax._ +import sigma.eval.EvalSettings +import sigma.exceptions.{CostLimitException, InterpreterException} +import sigmastate.lang.CompilerSettings +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer +import sigmastate.Plus +import sigmastate.utils.Helpers.TryOps /** Regression tests with ErgoTree related test vectors. @@ -51,7 +48,6 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { Block(Seq(), null), ValNode("x", SInt, null), ApplyTypes(null, Seq()), - TaggedVariableNode(1, SByte), ValDef(1, null), ValUse(1, SInt), BlockValue(IndexedSeq(), null) @@ -614,7 +610,7 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { } property("checkValidFlatmap") { - implicit val E = ErgoTreeEvaluator.forProfiling(new Profiler, evalSettings) + implicit val E = CErgoTreeEvaluator.forProfiling(new CProfiler, evalSettings) def mkLambda(t: SType, mkBody: SValue => SValue) = { MethodCall( ValUse(1, SCollectionType(t)), @@ -692,19 +688,19 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { ) def createCtx: ErgoLikeContext = ErgoLikeContextTesting - .dummy(CBox(fakeSelf), VersionContext.current.activatedVersion) + .dummy(fakeSelf, VersionContext.current.activatedVersion) .withErgoTreeVersion(tree.version) VersionContext.withVersions(activatedVersion = 1, tree.version) { // v4.x behavior - val res = ErgoTreeEvaluator.evalToCrypto(createCtx, tree, evalSettings) + val res = CErgoTreeEvaluator.evalToCrypto(createCtx, tree, evalSettings) res shouldBe ReductionResult(TrivialProp(true), 3) } VersionContext.withVersions(activatedVersion = 2, tree.version) { // v5.0 behavior assertExceptionThrown( - ErgoTreeEvaluator.evalToCrypto(createCtx, tree, evalSettings), + CErgoTreeEvaluator.evalToCrypto(createCtx, tree, evalSettings), exceptionLike[ClassCastException]() ) } diff --git a/sc/shared/src/test/scala/sigmastate/FailingToProveSpec.scala b/sc/shared/src/test/scala/sigmastate/FailingToProveSpec.scala index 29e57bace7..e047a8d158 100644 --- a/sc/shared/src/test/scala/sigmastate/FailingToProveSpec.scala +++ b/sc/shared/src/test/scala/sigmastate/FailingToProveSpec.scala @@ -2,7 +2,7 @@ package sigmastate import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ import org.scalatest.TryValues._ import sigma.data.AvlTreeData import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} diff --git a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala index e660c505a6..b0206fa464 100644 --- a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala @@ -3,19 +3,21 @@ package sigmastate import org.ergoplatform.ErgoBox.AdditionalRegisters import org.ergoplatform._ import scorex.util.ModifierId -import sigmastate.ErgoTree.{DefaultHeader, HeaderType, ZeroHeader, setConstantSegregation, setVersionBits} import sigma.VersionContext.MaxSupportedScriptVersion +import sigma.ast.ErgoTree.{HeaderType, ZeroHeader, setConstantSegregation, setVersionBits} +import sigma.ast._ import sigma.{Box, SigmaDslTesting} -import sigmastate.Values._ -import sigma.ast.{SBoolean, SBox, SCollection, SType} import sigmastate.eval._ -import sigmastate.exceptions.InterpreterException import sigmastate.helpers.TestingHelpers.createBox import sigmastate.helpers.{ErgoLikeContextTesting, ErgoLikeTestInterpreter} -import sigmastate.interpreter.ErgoTreeEvaluator.DefaultEvalSettings -import sigmastate.interpreter.EvalSettings.EvaluationMode +import sigmastate.interpreter.CErgoTreeEvaluator.DefaultEvalSettings +import sigma.eval.EvalSettings.EvaluationMode import sigmastate.interpreter._ -import sigmastate.lang.Terms.ValueOps +import sigma.ast.syntax.ValueOps +import sigma.data.CBox +import sigma.eval.EvalSettings +import sigma.exceptions.InterpreterException +import sigma.interpreter.{CostedProverResult, ProverResult} import sigmastate.utils.Helpers._ /** Specification to verify that the interpreter behaves according to docs/aot-jit-switch.md. @@ -26,7 +28,7 @@ import sigmastate.utils.Helpers._ class ScriptVersionSwitchSpecification extends SigmaDslTesting { override implicit val generatorDrivenConfig: PropertyCheckConfiguration = PropertyCheckConfiguration(minSuccessful = 30) override implicit val evalSettings: EvalSettings = - ErgoTreeEvaluator.DefaultEvalSettings.copy( + CErgoTreeEvaluator.DefaultEvalSettings.copy( costTracingEnabled = true // should always be enabled in tests (and false by default) ) diff --git a/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala b/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala index 354583f7b7..bca2d0e638 100644 --- a/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala @@ -4,27 +4,26 @@ import org.ergoplatform._ import org.ergoplatform.validation.ValidationRules._ import org.scalatest.BeforeAndAfterAll import sigma.{Colls, SigmaTestingData} -import sigma.ast.{SBoolean, SCollection, SContext, SFunc, SGlobal, SInt} +import sigma.ast._ import sigma.ast.SPrimType.MaxPrimTypeCode import sigma.ast.TypeCodes.LastConstantCode import sigma.data.AvlTreeData import sigma.serialization.SerializerException import sigma.validation.ValidationRules.{CheckPrimitiveTypeCode, CheckSerializableTypeCode, CheckTypeCode, CheckTypeWithMethods, trySoftForkable} import sigma.validation.{ChangedRule, ReplacedRule, SigmaValidationSettings, ValidationException, ValidationRule} -import sigmastate.ErgoTree.{EmptyConstants, HeaderType, ZeroHeader, setSizeBit} -import sigmastate.Values.{ByteArrayConstant, IntConstant, NotReadyValueInt, ValueCompanion} -import sigmastate.exceptions.InterpreterException +import ErgoTree.{EmptyConstants, HeaderType, ZeroHeader, setSizeBit} import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{CompilerTestingCommons, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter} -import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} -import sigmastate.interpreter.{ContextExtension, ErgoTreeEvaluator, ProverResult} -import sigmastate.lang.Terms._ -import sigmastate.serialization.SigmaSerializer.startReader -import sigmastate.serialization.{DataSerializer, _} -import sigmastate.serialization.ValueCodes.OpCode +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.ast.syntax._ +import sigma.eval.ErgoTreeEvaluator +import sigma.eval.ErgoTreeEvaluator.DataEnv +import sigma.exceptions.InterpreterException +import sigma.serialization.SigmaSerializer.startReader +import sigma.serialization._ +import sigma.serialization.ValueCodes.OpCode import sigmastate.utils.Helpers._ -import sigmastate.utxo.DeserializeContext class SoftForkabilitySpecification extends SigmaTestingData with CompilerTestingCommons diff --git a/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala b/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala index 145af35401..fe5a678679 100644 --- a/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala @@ -2,19 +2,20 @@ package sigmastate import sigmastate.crypto.DLogProtocol.DLogProverInput import scorex.crypto.hash.Blake2b256 -import sigmastate.Values._ +import sigma.ast._ +import sigma.ast.syntax._ import sigmastate.interpreter._ import Interpreter._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ import org.ergoplatform._ import org.scalatest.BeforeAndAfterAll import scorex.util.encode.Base58 +import sigma.crypto.CryptoConstants import sigma.data.{AvlTreeData, CAND, ProveDlog, SigmaBoolean, TrivialProp} import sigma.util.Extensions.IntOps -import sigmastate.crypto.CryptoConstants import sigmastate.helpers.{CompilerTestingCommons, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter} import sigmastate.helpers.TestingHelpers._ -import sigmastate.serialization.ValueSerializer +import sigma.serialization.ValueSerializer import sigmastate.utils.Helpers._ import scala.util.Random diff --git a/sc/shared/src/test/scala/sigmastate/TypesSpecification.scala b/sc/shared/src/test/scala/sigmastate/TypesSpecification.scala index befafbe3de..9a4c5ce1b8 100644 --- a/sc/shared/src/test/scala/sigmastate/TypesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/TypesSpecification.scala @@ -2,10 +2,9 @@ package sigmastate import sigma.Environment import sigma.ast.SType.isValueOfType -import sigmastate.eval.CSigmaDslBuilder import sigma.SigmaTestingData import sigma.ast._ -import sigma.data.CSigmaProp +import sigma.data.{CSigmaDslBuilder, CSigmaProp} class TypesSpecification extends SigmaTestingData { diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala index 86a7e30533..abbed09992 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala @@ -2,20 +2,22 @@ package sigmastate.eval import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix import org.ergoplatform.validation.ValidationSpecification -import org.ergoplatform.{Context => _, _} +import org.ergoplatform._ import scalan.BaseCtxTests import sigma.VersionContext -import sigmastate.Values.{BigIntArrayConstant, EvaluatedValue, SValue, SigmaPropConstant, Value} +import sigma.ast.{BigIntArrayConstant, ErgoTree, EvaluatedValue, SigmaPropConstant, Value} import sigma.ast.SType +import sigma.ast.syntax.SValue import sigma.data.AvlTreeData import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting} import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.interpreter.{ContextExtension, ErgoTreeEvaluator} -import sigmastate.lang.Terms.ValueOps +import sigmastate.interpreter.CErgoTreeEvaluator +import sigma.ast.syntax.ValueOps +import sigma.interpreter.ContextExtension import sigmastate.lang.{CompilerResult, CompilerSettings, LangTests, SigmaCompiler} -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.{CompilerTestsBase, ErgoTree} +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer +import sigmastate.CompilerTestsBase import sigma.{ContractsTestkit, Context => DContext} import scala.annotation.unused @@ -168,11 +170,11 @@ trait ErgoScriptTestkit extends ContractsTestkit with LangTests } // check calc - val (res, _) = ErgoTreeEvaluator.eval( + val (res, _) = CErgoTreeEvaluator.eval( context = ectx, constants = ergoTree.constants, exp = ergoTree.toProposition(replaceConstants = false), - evalSettings = ErgoTreeEvaluator.DefaultEvalSettings + evalSettings = CErgoTreeEvaluator.DefaultEvalSettings ) checkExpected(res, expectedResult.calc, "Calc evaluation:\n value = %s,\n expectedResult.calc: %s\n") diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala index 6d80e20734..526012f212 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala @@ -1,15 +1,13 @@ package sigmastate.eval -import org.ergoplatform.{Height, Inputs, Outputs, Self} import sigmastate._ -import sigmastate.Values.{BlockValue, FuncValue, IntConstant, LongConstant, SigmaPropConstant, ValDef, ValUse} +import sigma.ast._ import sigmastate.helpers.ContextEnrichingTestProvingInterpreter import sigmastate.interpreter.Interpreter._ import scalan.BaseCtxTests -import sigma.ast.{SBox, SFunc, SInt, SLong, SSigmaProp, SType} +import sigma.ast.syntax.ValueOps import sigmastate.lang.LangTests -import sigmastate.lang.Terms.{Apply, ValueOps} -import sigmastate.utxo._ +import sigma.ast.Apply class ErgoTreeBuildingTest extends BaseCtxTests with LangTests with ExampleContracts with ErgoScriptTestkit { diff --git a/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala b/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala index dd6117b603..5fcbd0f220 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala @@ -1,18 +1,17 @@ package sigmastate.eval import org.ergoplatform.ErgoBox -import sigmastate.Values.{ConcreteCollection, IntArrayConstant, IntConstant, SigmaPropConstant, SigmaPropValue} +import sigma.ast.{AND, ConcreteCollection, CreateProveDlog, DecodePoint, EQ, ErgoTree, IntArrayConstant, IntConstant, SSigmaProp, SigmaPropConstant, SigmaPropIsProven, SubstConstants} import sigmastate.helpers.ContextEnrichingTestProvingInterpreter import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter._ import scalan.BaseCtxTests -import sigma.ast.SSigmaProp +import sigma.ast.syntax.SigmaPropValue import sigma.data.ProveDlog import sigmastate.lang.LangTests import sigma.util.BenchmarkUtil._ -import sigmastate._ import sigmastate.crypto.DLogProtocol.DLogProverInput -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer class EvaluationTest extends BaseCtxTests with LangTests with ExampleContracts with ErgoScriptTestkit { @@ -103,7 +102,7 @@ class EvaluationTest extends BaseCtxTests test("SubstConst") { def script(pk: ProveDlog): SigmaPropValue = - AND(EQ(IntConstant(1), IntConstant(1)), SigmaPropConstant(pk).isProven).toSigmaProp + AND(EQ(IntConstant(1), IntConstant(1)), SigmaPropIsProven(SigmaPropConstant(pk))).toSigmaProp val pk1 = DLogProverInput.random().publicImage val pk2 = DLogProverInput.random().publicImage diff --git a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala index 0be1c73a0a..a39609eeab 100644 --- a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala @@ -6,21 +6,22 @@ import org.scalacheck.Arbitrary.arbByte import org.scalacheck.Gen import sigma.util.BenchmarkUtil import scalan.TestContexts -import sigma.ast.{SOption, SType} +import sigma.ast.{Constant, CostItem, ErgoTree, JitCost, SOption, SType} import sigma.{Colls, Evaluation, TestUtils} import sigma.data.{RType, SigmaBoolean} import sigma.validation.ValidationException import sigma.validation.ValidationRules.CheckSerializableTypeCode -import sigmastate.Values.{Constant, SValue, SigmaPropValue} -import sigmastate.eval._ +import sigma.ast.syntax.{SValue, SigmaPropValue} +import sigma.eval.{CostDetails, EvalSettings, Extensions, GivenCost, TracedCost} import sigmastate.helpers.TestingHelpers._ -import sigmastate.interpreter.ContextExtension.VarBinding -import sigmastate.interpreter.ErgoTreeEvaluator.DefaultProfiler +import sigma.interpreter.ContextExtension.VarBinding +import sigmastate.interpreter.CErgoTreeEvaluator.DefaultProfiler import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.interpreter._ -import sigmastate.lang.{CompilerSettings, SigmaCompiler, Terms} -import sigmastate.serialization.SigmaSerializer -import sigmastate.{CompilerTestsBase, ErgoTree, JitCost} +import sigmastate.lang.{CompilerSettings, SigmaCompiler} +import sigma.serialization.SigmaSerializer +import sigmastate.CompilerTestsBase +import sigmastate.eval.{CContext, IRContext} import scala.language.implicitConversions import scala.reflect.ClassTag @@ -117,7 +118,7 @@ trait CompilerTestingCommons extends TestingCommons compiledTree } - def evalSettings = ErgoTreeEvaluator.DefaultEvalSettings + def evalSettings = CErgoTreeEvaluator.DefaultEvalSettings def printCostDetails(script: String, details: CostDetails) = { val traceLines = SigmaPPrint(details, height = 550, width = 150) @@ -140,13 +141,13 @@ trait CompilerTestingCommons extends TestingCommons val accumulator = new CostAccumulator( initialCost = JitCost(0), costLimit = Some(JitCost.fromBlockCost(evalSettings.scriptCostLimitInEvaluator))) - val evaluator = new ErgoTreeEvaluator( + val evaluator = new CErgoTreeEvaluator( context = sigmaCtx, constants = ErgoTree.EmptyConstants, coster = accumulator, evalSettings.profilerOpt.getOrElse(DefaultProfiler), evalSettings) val (res, actualTime) = BenchmarkUtil.measureTimeNano( - evaluator.evalWithCost[B](ErgoTreeEvaluator.EmptyDataEnv, expr)) + evaluator.evalWithCost[B](CErgoTreeEvaluator.EmptyDataEnv, expr)) val costDetails = if (evalSettings.costTracingEnabled) { val trace: Seq[CostItem] = evaluator.getCostTrace() val costDetails = TracedCost(trace, Some(actualTime)) @@ -164,7 +165,7 @@ trait CompilerTestingCommons extends TestingCommons } (res.value, costDetails) } - val Terms.Apply(funcVal, _) = expr.asInstanceOf[SValue] + val sigma.ast.Apply(funcVal, _) = expr.asInstanceOf[SValue] CompiledFunc(funcScript, bindings, funcVal, expr, f) } diff --git a/sc/shared/src/test/scala/sigmastate/helpers/SigmaPPrint.scala b/sc/shared/src/test/scala/sigmastate/helpers/SigmaPPrint.scala index eea742e49e..1b0f7b112d 100644 --- a/sc/shared/src/test/scala/sigmastate/helpers/SigmaPPrint.scala +++ b/sc/shared/src/test/scala/sigmastate/helpers/SigmaPPrint.scala @@ -10,20 +10,17 @@ import sigma.crypto.EcPointType import sigma.data.{AvlTreeData, AvlTreeFlags, CollType, PrimitiveType, TrivialProp} import sigma.serialization.GroupElementSerializer import sigma.{Coll, GroupElement} -import sigmastate.Values.{ConstantNode, FuncValue, ValueCompanion} +import sigma.ast.{ConstantNode, FuncValue, ValueCompanion} import sigmastate._ import sigmastate.crypto.GF2_192_Poly -import sigmastate.interpreter.{CompanionDesc, FixedCostItem, MethodDesc} -import sigmastate.lang.Terms.MethodCall -import sigmastate.utxo.SelectField - +import sigma.ast.MethodCall import java.math.BigInteger import scala.collection.compat.immutable.ArraySeq import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.reflect.ClassTag -/** Pretty-printer customized to print [[sigmastate.Values.Value]] instances +/** Pretty-printer customized to print [[sigma.ast.Value]] instances * into a valid Scala code (can be cut-and-pasted).*/ object SigmaPPrint extends PPrinter { override def showFieldNames = false diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala index 94d3467598..1f758370a0 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala @@ -1,18 +1,18 @@ package sigmastate.lang -import org.ergoplatform.{Height, Inputs, Outputs, Self} import org.ergoplatform.ErgoAddressEncoder._ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigma.ast.{NoType, SBoolean, SBox, SCollection, SFunc, SInt, SLong, STuple} -import sigmastate.Values._ +import sigma.ast._ +import sigma.ast.syntax.SValue import sigmastate._ import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.lang.SigmaPredef.PredefinedFuncRegistry -import sigmastate.lang.Terms._ -import sigmastate.exceptions.BinderException -import sigmastate.eval._ +import SigmaPredef.PredefinedFuncRegistry +import sigma.ast.syntax._ +import sigma.eval.SigmaDsl +import sigma.exceptions.BinderException class SigmaBinderTest extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers with LangTests { import StdSigmaBuilder._ diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala index 2d25adcbd3..88c75a90b6 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala @@ -3,17 +3,15 @@ package sigmastate.lang import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix import org.ergoplatform._ import scorex.util.encode.Base58 -import sigma.ast.{EmptySubst, SAvlTree, SBoolean, SBox, SByte, SCollection, SInt, SSigmaProp, SType} -import sigmastate.Values._ +import sigma.ast.{ByIndex, ExtractAmount, GetVar, _} +import sigma.ast.syntax._ import sigmastate._ -import sigmastate.exceptions.{GraphBuildingException, InvalidArguments, TyperException} import sigmastate.helpers.CompilerTestingCommons import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.lang.Terms.{Apply, MethodCall, ZKProofBlock} -import sigmastate.serialization.ValueSerializer -import sigmastate.serialization.generators.ObjectGenerators -import sigmastate.utxo.{ByIndex, ExtractAmount, GetVar} - +import sigma.ast.{Apply, MethodCall, ZKProofBlock} +import sigma.exceptions.{GraphBuildingException, InvalidArguments, TyperException} +import sigma.serialization.ValueSerializer +import sigma.serialization.generators.ObjectGenerators import scala.annotation.unused class SigmaCompilerTest extends CompilerTestingCommons with LangTests with ObjectGenerators { diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala index a81feda76b..99ad2ae908 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala @@ -7,20 +7,19 @@ import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigma.Colls import sigma.ast.SCollection._ -import sigmastate.Values._ -import sigmastate._ import sigma.ast._ +import sigma.ast.syntax.{SValue, SigmaPropValue, SigmaPropValueOps} +import sigma.crypto.CryptoConstants import sigma.data.ProveDlog -import sigmastate.crypto.CryptoConstants +import sigmastate._ import sigmastate.crypto.DLogProtocol.DLogProverInput -import sigmastate.exceptions.TyperException import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.lang.SigmaPredef._ -import sigmastate.lang.Terms._ -import sigmastate.lang.syntax.ParserException -import sigmastate.serialization.ErgoTreeSerializer -import sigmastate.serialization.generators.ObjectGenerators -import sigmastate.utxo.{Append, ExtractCreationInfo} +import SigmaPredef._ +import sigmastate.lang.parsers.ParserException +import sigma.serialization.ErgoTreeSerializer +import sigma.serialization.generators.ObjectGenerators +import sigma.ast.Select +import sigma.exceptions.TyperException class SigmaTyperTest extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers with LangTests with ObjectGenerators { @@ -640,7 +639,7 @@ class SigmaTyperTest extends AnyPropSpec property("substConst") { def script(pk: ProveDlog): SigmaPropValue = - AND(EQ(IntConstant(1), IntConstant(1)), SigmaPropConstant(pk).isProven).toSigmaProp + AND(EQ(IntConstant(1), IntConstant(1)), SigmaPropIsProven(SigmaPropConstant(pk))).toSigmaProp val pk1 = DLogProverInput.random().publicImage val pk2 = DLogProverInput.random().publicImage diff --git a/sc/shared/src/test/scala/sigmastate/serialization/DeserializationResilience.scala b/sc/shared/src/test/scala/sigmastate/serialization/DeserializationResilience.scala index 1d03555d9b..f4344fbf8d 100644 --- a/sc/shared/src/test/scala/sigmastate/serialization/DeserializationResilience.scala +++ b/sc/shared/src/test/scala/sigmastate/serialization/DeserializationResilience.scala @@ -1,29 +1,29 @@ -package sigmastate.serialization +package sigma.serialization -import org.ergoplatform.{ErgoBoxCandidate, Outputs} +import org.ergoplatform.ErgoBoxCandidate import org.scalacheck.Gen import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert} import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.serialization.{Reader, VLQByteBufferReader} -import sigma.ast.{SBoolean, SInt} +import sigma.ast.{SBoolean, SInt, SizeOf} import sigma.data.{AvlTreeData, AvlTreeFlags, CAND, SigmaBoolean} -import sigma.serialization.{DeserializeCallDepthExceeded, InvalidTypePrefix, ReaderPositionLimitExceeded, SerializerException} import sigma.util.{BenchmarkUtil, safeNewArray} import sigma.validation.ValidationException import sigma.validation.ValidationRules.CheckPositionLimit import sigma.{Colls, Environment} -import sigmastate.Values.{BlockValue, GetVarInt, IntConstant, SValue, SigmaPropValue, Tuple, ValDef, ValUse} +import sigma.ast._ +import sigma.ast.syntax._ import sigmastate._ import sigma.Extensions.ArrayOps -import sigmastate.eval.Extensions.{EvalIterableOps, SigmaBooleanOps} +import sigma.eval.Extensions.SigmaBooleanOps +import sigma.eval.SigmaDsl +import sigma.interpreter.{ContextExtension, CostedProverResult} +import sigma.eval.Extensions.EvalIterableOps import sigmastate.eval._ import sigmastate.helpers.{CompilerTestingCommons, ErgoLikeContextTesting, ErgoLikeTestInterpreter} -import sigmastate.interpreter.{ContextExtension, CostedProverResult} -import sigmastate.serialization.OpCodes._ +import sigma.serialization.OpCodes._ import sigmastate.utils.Helpers._ -import sigmastate.utils.SigmaByteReader -import sigmastate.utxo.SizeOf import java.nio.ByteBuffer import scala.collection.immutable.Seq @@ -420,7 +420,7 @@ class DeserializationResilience extends DeserializationResilienceTesting { val v = k avlProver.performOneOperation(Insert(ADKey @@@ k, ADValue @@@ v)) val proof = avlProver.generateProof() - val verifier = AvlTreeVerifier(tree, Colls.fromArray(proof)) + val verifier = CAvlTreeVerifier(tree, Colls.fromArray(proof)) verifier.performOneOperation(Insert(ADKey @@@ k, ADValue @@@ v)).isFailure shouldBe true // NOTE, even though performOneOperation fails, some AvlTree$ methods used in Interpreter // (remove_eval, update_eval, contains_eval) won't throw, while others will. diff --git a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala index d837dfb3f0..fff1d40c61 100644 --- a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala @@ -1,22 +1,20 @@ -package sigmastate.serialization +package sigma.serialization import org.ergoplatform.ErgoBox import org.ergoplatform.validation.ValidationRules.CheckDeserializedScriptIsSigmaProp import sigma.SigmaProp -import sigma.ast.SInt +import sigma.ast._ +import sigma.ast.syntax.SigmaPropValue import sigma.data.CBigInt -import sigma.serialization.{ReaderPositionLimitExceeded, SerializerException} import sigma.util.Extensions.SigmaPropOps import sigma.validation.ValidationException -import sigmastate.ErgoTree.EmptyConstants -import sigmastate.Values.{BigIntConstant, ByteConstant, ConstantPlaceholder, IntConstant, ShortConstant, SigmaPropValue} -import sigmastate.ErgoTree.HeaderType +import ErgoTree.EmptyConstants +import ErgoTree.HeaderType +import sigma.eval.Extensions.SigmaBooleanOps import sigmastate._ -import sigmastate.eval.Extensions.SigmaBooleanOps import sigmastate.eval.IRContext import sigmastate.helpers.CompilerTestingCommons -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.utxo.{DeserializeContext, DeserializeRegister} +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer import java.math.BigInteger diff --git a/sc/shared/src/test/scala/sigmastate/utils/GenInfoObjects.scala b/sc/shared/src/test/scala/sigmastate/utils/GenInfoObjects.scala index 9ebdce9f31..78962f20e3 100644 --- a/sc/shared/src/test/scala/sigmastate/utils/GenInfoObjects.scala +++ b/sc/shared/src/test/scala/sigmastate/utils/GenInfoObjects.scala @@ -1,6 +1,6 @@ package sigmastate.utils -import sigmastate.SMethod +import sigma.ast.SMethod import sigma.util.PrintExtensions._ import scala.util.Try import Helpers._ // required for Scala 2.11 diff --git a/sc/shared/src/test/scala/sigmastate/utils/SpecGen.scala b/sc/shared/src/test/scala/sigmastate/utils/SpecGen.scala index b1584e8b8d..4c56580c9b 100644 --- a/sc/shared/src/test/scala/sigmastate/utils/SpecGen.scala +++ b/sc/shared/src/test/scala/sigmastate/utils/SpecGen.scala @@ -1,21 +1,16 @@ package sigmastate.utils -import sigma.util.PrintExtensions.IterableExtensions -import sigmastate._ import sigma.Evaluation._ import sigma.ast.TypeCodes.LastConstantCode -import sigma.ast.{SBigInt, SBoolean, SCollection, SEmbeddable, SGlobal, SGroupElement, SNumericType, SOption, SPrimType, SString, SType, STypeCompanion} +import sigma.ast._ import sigma.serialization.CoreByteWriter.ArgInfo -import sigma.util.Extensions.ByteOps import sigma.util.CollectionUtil +import sigma.util.Extensions.ByteOps import sigma.util.PrintExtensions._ -import sigmastate.Values._ -import sigmastate.lang.SigmaPredef.{PredefinedFunc, PredefinedFuncRegistry} -import sigmastate.lang.StdSigmaBuilder -import sigmastate.lang.Terms.{MethodCall, PropertyCall} -import sigmastate.serialization.ValueCodes.OpCode -import sigmastate.serialization.{OpCodes, ValueCodes, ValueSerializer} -import sigmastate.utxo.{SelectField, SigmaPropIsProven} +import SigmaPredef.{PredefinedFunc, PredefinedFuncRegistry} +import sigma.ast.{MethodCall, PropertyCall} +import sigma.serialization.ValueCodes.OpCode +import sigma.serialization.ValueSerializer object SpecGenUtils { val types = SType.allPredefTypes.diff(Seq(SString)) @@ -32,7 +27,7 @@ trait SpecGen { description: String, args: Seq[ArgInfo], op: Either[PredefinedFunc, SMethod]) - def collectSerializers(): Seq[ValueSerializer[_ <: Values.Value[SType]]] = { + def collectSerializers(): Seq[ValueSerializer[_ <: Value[SType]]] = { ((LastConstantCode + 1) to 255).collect { case i if ValueSerializer.serializers(i.toByte) != null => val ser = ValueSerializer.serializers(i.toByte) @@ -257,7 +252,7 @@ object GenPrimOpsApp extends SpecGen { val methods = collectMethods() val ops = collectSerializableOperations() val noOps = Set( - TaggedVariable, ValUse, ConstantPlaceholder, TrueLeaf, FalseLeaf, + ValUse, ConstantPlaceholder, TrueLeaf, FalseLeaf, ConcreteCollection, ConcreteCollectionBooleanConstant, Tuple, SelectField, SigmaPropIsProven, ValDef, FunDef, BlockValue ) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala index 61236442e2..566bf5bd58 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala @@ -7,7 +7,7 @@ import scorex.crypto.authds.avltree.batch._ import scorex.crypto.authds.{ADKey, ADValue, SerializedAdProof} import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.ast.SCollection.SByteArray -import sigmastate.Values._ +import sigma.ast._ import sigmastate._ import sigmastate.eval.IRContext import sigmastate.eval._ @@ -15,11 +15,13 @@ import sigma.Extensions.ArrayOps import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.ScriptNameProp -import sigmastate.interpreter.ProverResult -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ import sigma.Coll import sigma.ast.SAvlTree +import sigma.ast.syntax.{GetVarByteArray, OptionValueOps} import sigma.data.{AvlTreeData, AvlTreeFlags, CSigmaProp, TrivialProp} +import sigma.eval.SigmaDsl +import sigma.interpreter.ProverResult import sigma.{AvlTree, Context} import sigmastate.eval.Extensions.AvlTreeOps diff --git a/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala index 1a236fa31a..346ad69e1a 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala @@ -5,20 +5,20 @@ import org.ergoplatform._ import sigma.Extensions.ArrayOps import sigma.ast.SCollection.SByteArray import sigma.ast.SType.AnyOps -import sigma.ast._ import sigma.data.{AvlTreeData, CAnyValue} import sigma.util.StringUtil._ -import sigmastate.Values._ +import sigma.ast._ +import sigma.ast.syntax._ +import sigma.crypto.CryptoConstants import sigmastate._ -import sigmastate.crypto.CryptoConstants -import sigmastate.eval.InvalidType import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} -import sigmastate.interpreter.ContextExtension.VarBinding -import sigmastate.interpreter.ErgoTreeEvaluator.DefaultEvalSettings -import sigmastate.interpreter.EvalSettings +import sigma.interpreter.ContextExtension.VarBinding +import sigmastate.interpreter.CErgoTreeEvaluator.DefaultEvalSettings import sigmastate.interpreter.Interpreter._ -import sigmastate.lang.Terms._ +import sigma.ast.Apply +import sigma.eval.EvalSettings +import sigma.exceptions.InvalidType import sigmastate.utils.Helpers._ import java.math.BigInteger diff --git a/sc/shared/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala index 484518a8bb..0de1a13f08 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala @@ -1,18 +1,19 @@ package sigmastate.utxo -import sigmastate.Values._ +import sigma.ast._ import sigmastate._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ import org.ergoplatform._ import sigma.ast.SCollection._ -import sigma.ast._ import sigma.data.AvlTreeData -import sigmastate.SCollectionMethods.{FlatMapMethod, IndexOfMethod, IndicesMethod, PatchMethod, UpdateManyMethod, UpdatedMethod} -import sigmastate.eval.Extensions.SigmaBooleanOps +import SCollectionMethods.{FlatMapMethod, IndexOfMethod, IndicesMethod, PatchMethod, UpdateManyMethod, UpdatedMethod} +import sigma.ast import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} -import sigmastate.serialization.OpCodes._ +import sigma.serialization.OpCodes._ +import sigma.ast.MethodCall +import sigma.eval.Extensions.SigmaBooleanOps import sigmastate.utils.Helpers._ class CollectionOperationsSpecification extends CompilerTestingCommons @@ -219,8 +220,8 @@ class CollectionOperationsSpecification extends CompilerTestingCommons FuncValue( Vector((1, SBox)), EQ( - utxo.ExtractRegisterAs[SLong.type](ValUse(1, SBox), reg1).get, - Plus(utxo.ExtractRegisterAs[SLong.type](Self, reg1).get, LongConstant(1))) + ast.ExtractRegisterAs[SLong.type](ValUse(1, SBox), reg1).get, + Plus(ast.ExtractRegisterAs[SLong.type](Self, reg1).get, LongConstant(1))) ) ).toSigmaProp prop shouldBe propExpected @@ -262,8 +263,8 @@ class CollectionOperationsSpecification extends CompilerTestingCommons FuncValue( Vector((1, SBox)), EQ( - utxo.ExtractRegisterAs[SLong.type](ValUse(1, SBox), reg1).getOrElse(LongConstant(0)), - Plus(utxo.ExtractRegisterAs[SLong.type](Self, reg1).get, LongConstant(1)) + ast.ExtractRegisterAs[SLong.type](ValUse(1, SBox), reg1).getOrElse(LongConstant(0)), + Plus(ast.ExtractRegisterAs[SLong.type](Self, reg1).get, LongConstant(1)) ) ) ).toSigmaProp diff --git a/sc/shared/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala index 984afbcd37..961bc08020 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala @@ -1,12 +1,11 @@ package sigmastate.utxo -import org.ergoplatform.Height import org.scalacheck.Gen import sigma.data.{AvlTreeData, CAND, COR, CTHRESHOLD} -import sigmastate.Values.IntConstant +import sigma.ast.{GT, Height, IntConstant, SigmaAnd, SigmaOr} import sigmastate._ import sigmastate.helpers._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ import scala.util.Random diff --git a/sc/shared/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala index 6c84a5f54f..fe3dac68b3 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala @@ -2,9 +2,9 @@ package sigmastate.utxo import scorex.util.encode.Base16 import scorex.crypto.hash.Blake2b256 -import sigmastate.Values._ +import sigma.ast._ +import sigma.ast.syntax._ import sigmastate._ -import sigmastate.lang.Terms._ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, CompilerTestingCommons} import sigma.Coll diff --git a/sc/shared/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala index c61aec900a..74c28c2ec9 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala @@ -1,10 +1,11 @@ package sigmastate.utxo +import sigma.ast.ErgoTree import sigma.data.CAND import sigmastate._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeTestProvingInterpreter} import sigmastate.interpreter._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ /** * Distributed signatures examples. diff --git a/sc/shared/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala index 8ce3ce6e1d..615a826649 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala @@ -6,21 +6,20 @@ import org.ergoplatform._ import org.scalatest.TryValues._ import scorex.crypto.hash.Blake2b256 import sigma.ast.SCollection.SByteArray -import sigmastate.Values._ -import sigmastate._ import sigma.ast._ +import sigmastate._ +import sigma.ast.syntax._ import sigma.data.{AvlTreeData, ProveDHTuple, ProveDlog, TrivialProp} import sigma.util.Extensions.EcpOps import sigma.validation.ValidationException import sigmastate.eval._ import sigmastate.interpreter.Interpreter._ -import sigmastate.eval.Extensions.SigmaBooleanOps import sigmastate.helpers._ import sigmastate.helpers.TestingHelpers._ -import sigmastate.interpreter.ContextExtension.VarBinding -import sigmastate.interpreter.{ContextExtension, CostedProverResult} -import sigmastate.lang.Terms._ -import sigmastate.serialization.{SerializationSpecification, ValueSerializer} +import sigma.interpreter.ContextExtension.VarBinding +import sigma.eval.Extensions.SigmaBooleanOps +import sigma.interpreter.{ContextExtension, CostedProverResult} +import sigma.serialization.{SerializationSpecification, ValueSerializer} import sigmastate.utils.Helpers._ class ErgoLikeInterpreterSpecification extends CompilerTestingCommons @@ -30,6 +29,15 @@ class ErgoLikeInterpreterSpecification extends CompilerTestingCommons implicit lazy val IR: TestingIRContext = new TestingIRContext private val reg1 = ErgoBox.nonMandatoryRegisters.head + def sum[T <: SNumericType](input: Value[SCollection[T]], varId: Int)(implicit tT: T) = + Fold(input, + Constant(tT.upcast(0.toByte), tT), + FuncValue(Array((varId, STuple(tT, tT))), + Plus( + SelectField(ValUse(varId, STuple(tT, tT)), 1).asNumValue, + SelectField(ValUse(varId, STuple(tT, tT)), 2).asNumValue)) + ) + property("scripts EQ/NEQ") { val prover1 = new ContextEnrichingTestProvingInterpreter val prover2 = new ContextEnrichingTestProvingInterpreter @@ -43,8 +51,8 @@ class ErgoLikeInterpreterSpecification extends CompilerTestingCommons .withErgoTreeVersion(ergoTreeVersionInTests) val e = compile(Map( - "h1" -> h1.treeWithSegregation(ergoTreeHeaderInTests).bytes, - "h2" -> h2.treeWithSegregation(ergoTreeHeaderInTests).bytes), + "h1" -> ErgoTree.withSegregation(ergoTreeHeaderInTests, h1).bytes, + "h2" -> ErgoTree.withSegregation(ergoTreeHeaderInTests, h2).bytes), "h1 == h1") val exp = TrueLeaf e shouldBe exp @@ -53,8 +61,8 @@ class ErgoLikeInterpreterSpecification extends CompilerTestingCommons res shouldBe TrivialProp.TrueProp val ergoTree = mkTestErgoTree( EQ( - ByteArrayConstant(h1.treeWithSegregation(ergoTreeHeaderInTests).bytes), - ByteArrayConstant(h2.treeWithSegregation(ergoTreeHeaderInTests).bytes) + ByteArrayConstant(ErgoTree.withSegregation(ergoTreeHeaderInTests, h1).bytes), + ByteArrayConstant(ErgoTree.withSegregation(ergoTreeHeaderInTests, h2).bytes) ).toSigmaProp ) val res2 = verifier.fullReduction(ergoTree, ctx).value @@ -248,7 +256,7 @@ class ErgoLikeInterpreterSpecification extends CompilerTestingCommons SigmaPropConstant(pubkey), BoolToSigmaProp( GT( - Fold.sum[SLong.type](MapCollection(Outputs, + sum[SLong.type](MapCollection(Outputs, FuncValue(Vector((1, SBox)), ExtractAmount(ValUse(1, SBox)))), 1), LongConstant(20)) ) @@ -743,7 +751,7 @@ class ErgoLikeInterpreterSpecification extends CompilerTestingCommons } property("non-const ProveDHT") { - import sigmastate.crypto.CryptoConstants.dlogGroup + import sigma.crypto.CryptoConstants.dlogGroup compile(Map("gA" -> dlogGroup.generator.toGroupElement), "proveDHTuple(gA, OUTPUTS(0).R4[GroupElement].get, gA, gA)" ).asInstanceOf[BlockValue].result shouldBe a [CreateProveDHTuple] diff --git a/sc/shared/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala b/sc/shared/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala index 8899b90584..0fdf6db97b 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala @@ -3,8 +3,8 @@ package sigmastate.utxo import org.ergoplatform._ import sigma.util.BenchmarkUtil import sigmastate.helpers.CompilerTestingCommons -import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.serialization.generators.ObjectGenerators +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.serialization.generators.ObjectGenerators import debox.{Buffer => DBuffer} import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec diff --git a/sc/shared/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala index 8809e22836..e84dc6211b 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala @@ -1,12 +1,12 @@ package sigmastate.utxo -import sigma.ast.SType +import sigma.ast.{GE, ModQ, SType} import sigma.data.CAnyValue -import sigmastate.Values._ +import sigma.ast._ +import sigma.ast.syntax.{GetVarInt, OptionValueOps} import sigmastate.helpers.CompilerTestingCommons import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.lang.Terms._ -import sigmastate.{GE, ModQ} +import sigma.ast.syntax._ /** * Specification for compile function diff --git a/sc/shared/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala index c239a38d30..2328b51989 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala @@ -1,13 +1,13 @@ package sigmastate.utxo -import sigma.ast.SSigmaProp +import sigma.ast._ +import sigma.ast.syntax._ import sigma.data.{AvlTreeData, CAND, COR, ProveDlog, TrivialProp} -import sigmastate.crypto.DLogProtocol.DLogProverInput -import sigmastate.Values.{ConcreteCollection, FalseLeaf, IntConstant, SigmaPropConstant, SigmaPropValue, TrueLeaf} +import sigma.eval.Extensions.SigmaBooleanOps +import sigma.exceptions.GraphBuildingException import sigmastate._ -import sigmastate.eval.Extensions.SigmaBooleanOps -import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTransactionTesting} -import sigmastate.exceptions.GraphBuildingException +import sigmastate.crypto.DLogProtocol.DLogProverInput +import sigmastate.helpers._ class ThresholdSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { @@ -116,7 +116,6 @@ class ThresholdSpecification extends CompilerTestingCommons } property("threshold reduce to crypto") { - import sigma.data.TrivialProp._ val prover = new ContextEnrichingTestProvingInterpreter val ctx = ErgoLikeContextTesting( currentHeight = 1, diff --git a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationSpecification.scala index 13ec9f2518..f063cf5aa0 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationSpecification.scala @@ -1,15 +1,12 @@ package sigmastate.utxo.blockchain -import java.io.{FileWriter, File} - +import sigma.ast.TrueLeaf +import sigma.ast.syntax.{GetVarBoolean, OptionValueOps} import sigmastate.CompilerCrossVersionProps -import sigmastate.Values.{TrueLeaf, GetVarBoolean} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestProvingInterpreter} -import sigmastate.interpreter.ContextExtension +import sigmastate.helpers.ErgoLikeTestProvingInterpreter +import sigma.interpreter.ContextExtension import sigmastate.utxo.blockchain.BlockchainSimulationTestingCommons._ -import scala.collection.concurrent.TrieMap - class BlockchainSimulationSpecification extends BlockchainSimulationTestingCommons with CompilerCrossVersionProps { diff --git a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala index 4e435a6d12..0dca8a4471 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala @@ -5,8 +5,7 @@ import org.ergoplatform._ import scorex.crypto.authds.{ADDigest, ADKey, ADValue} import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert, Remove} import scorex.crypto.hash.{Blake2b256, Digest32} -import sigmastate.{ErgoTree, Values} -import sigmastate.Values.LongConstant +import sigma.ast.{ErgoTree, LongConstant, TrueLeaf} import sigmastate.eval._ import sigmastate.helpers.{BlockchainState, CompilerTestingCommons, ErgoLikeContextTesting, ErgoLikeTestProvingInterpreter, ErgoTransactionValidator} import sigmastate.helpers.TestingHelpers._ @@ -17,9 +16,9 @@ import scala.util.{Random, Try} import scorex.util._ import sigma.Colls import sigma.data.{AvlTreeData, AvlTreeFlags} -import sigmastate.ErgoTree.ZeroHeader -import sigmastate.eval.Extensions.SigmaBooleanOps -import sigmastate.interpreter.ContextExtension +import ErgoTree.ZeroHeader +import sigma.eval.Extensions.SigmaBooleanOps +import sigma.interpreter.ContextExtension import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.utxo.blockchain.BlockchainSimulationTestingCommons.{FullBlock, ValidationState} @@ -159,7 +158,7 @@ object BlockchainSimulationTestingCommons extends CompilerTestingCommons { testBox(10, ErgoTree.fromProposition( ErgoTree.headerWithVersion(ZeroHeader, scriptVersion), - Values.TrueLeaf.toSigmaProp), + TrueLeaf.toSigmaProp), i, Seq(), Map(), txId)) createTransaction(boxes) }, diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala index 10dc4b7607..a428f6779d 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala @@ -1,19 +1,19 @@ package sigmastate.utxo.examples -import org.ergoplatform.{ErgoBox, Height, Outputs, Self} +import org.ergoplatform.ErgoBox import org.ergoplatform.ErgoBox.R4 import sigmastate.helpers.CompilerTestingCommons import org.ergoplatform.dsl.ContractSyntax.Token import org.ergoplatform.dsl.TestContractSpec import scorex.crypto.hash.Blake2b256 import sigma.ast.SCollection.SByteArray -import sigmastate._ import sigma.ast._ +import sigma.ast.syntax._ import sigma.data.{CSigmaProp, Digest32Coll, TrivialProp} -import sigmastate.Values.{BlockValue, ByteArrayConstant, LongConstant, ValDef, ValUse, Value} +import sigma.ast.{BlockValue, ByteArrayConstant, LongConstant, ValDef, ValUse, Value} import sigmastate.eval.Extensions._ -import sigmastate.lang.Terms.ValueOps -import sigmastate.utxo._ +import sigma.ast.syntax.ValueOps +import sigma.eval.Extensions.toAnyValue /** An example of an atomic ergo <=> asset exchange. * Let's assume that Alice is willing to buy 60 assets of type "token1" for 100 ergo coins, and Bob diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala index 1f8f8041d3..131aba22d0 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala @@ -1,16 +1,14 @@ package sigmastate.utxo.examples -import org.ergoplatform.Height import scorex.crypto.hash.Blake2b256 import scorex.utils.Random -import sigma.ast.{SBoolean, SByte, SCollection} import sigma.data.AvlTreeData -import sigmastate.Values._ +import sigma.ast._ +import sigma.ast.syntax.{CollectionConstant, GetVarByteArray, OptionValueOps} import sigmastate._ import sigmastate.interpreter.Interpreter._ import sigmastate.helpers._ -import sigmastate.lang.Terms._ -import sigmastate.utxo.SizeOf +import sigma.ast.syntax._ class AtomicSwapExampleSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { private implicit lazy val IR: TestingIRContext = new TestingIRContext diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala index 5ad4b63e81..12e6a236c8 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala @@ -3,15 +3,14 @@ package sigmastate.utxo.examples import org.ergoplatform._ import org.ergoplatform.settings.ErgoAlgos import sigma.Colls -import sigma.ast.{SBoolean, SBox, SInt, SLong, SOption} -import sigmastate.Values.{BlockValue, IntConstant, LongConstant, ValDef, ValUse} -import sigmastate.{ErgoTree, _} +import sigma.ast.syntax.OptionValueOps +import sigma.ast._ +import sigmastate._ import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting} -import sigmastate.interpreter.ContextExtension +import sigma.interpreter.ContextExtension import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} -import sigmastate.lang.Terms._ -import sigmastate.utxo._ +import sigma.ast.syntax._ import sigmastate.utxo.blockchain.BlockchainSimulationTestingCommons._ /** diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala index db6f9dfad5..9bcfd81ecf 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala @@ -3,12 +3,12 @@ package sigmastate.utxo.examples import org.ergoplatform.ErgoBox.{R4, R5, R6} import org.ergoplatform._ import sigma.data.AvlTreeData -import sigmastate.{CompilerCrossVersionProps, ErgoTree} -import sigmastate.Values.{IntConstant, LongConstant} +import sigmastate.CompilerCrossVersionProps +import sigma.ast.{ErgoTree, IntConstant, LongConstant} import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.ScriptNameProp -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ class ColdWalletAdvContractExampleSpecification extends CompilerTestingCommons diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala index c3efd21709..1948bc16d9 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala @@ -5,10 +5,10 @@ import org.ergoplatform._ import sigma.data.AvlTreeData import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ -import sigmastate.{CompilerCrossVersionProps, ErgoTree} -import sigmastate.Values.{IntConstant, LongConstant} +import sigmastate.CompilerCrossVersionProps +import sigma.ast.{ErgoTree, IntConstant, LongConstant} import sigmastate.interpreter.Interpreter.ScriptNameProp -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ class ColdWalletContractExampleSpecification extends CompilerTestingCommons diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala index 41720491dc..d197845e80 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala @@ -5,13 +5,13 @@ import org.scalatest.Assertion import org.scalatest.TryValues._ import scorex.crypto.hash.Blake2b256 import sigma.data.{AvlTreeData, ProveDlog} -import sigmastate.ErgoTree.ZeroHeader -import sigmastate.Values.{BooleanConstant, ByteArrayConstant} +import sigma.ast.ErgoTree.ZeroHeader +import sigma.ast.{BooleanConstant, ByteArrayConstant, ErgoTree} import sigmastate.crypto.DLogProtocol.DLogProverInput import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} -import sigmastate.lang.Terms._ -import sigmastate.{CompilerCrossVersionProps, ErgoTree} +import sigma.ast.syntax._ +import sigmastate.CompilerCrossVersionProps class CoopExampleSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala index 05ad14c969..9246cc1c8e 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala @@ -6,12 +6,13 @@ import org.ergoplatform.ErgoBox.{R4, R5} import sigma.data.{AvlTreeData, ProveDHTuple, ProveDlog} import sigma.util.Extensions.EcpOps import sigmastate.CompilerCrossVersionProps -import sigmastate.Values.GroupElementConstant -import sigmastate.crypto.{CryptoConstants, DiffieHellmanTupleProverInput} +import sigma.ast.GroupElementConstant +import sigma.crypto.CryptoConstants +import sigmastate.crypto.DiffieHellmanTupleProverInput import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ class DHTupleExampleSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala index ec5ddcdb57..4ec6922c38 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala @@ -3,12 +3,12 @@ package sigmastate.utxo.examples import sigmastate.interpreter.Interpreter._ import org.ergoplatform._ import sigma.data.AvlTreeData -import sigmastate.Values.ShortConstant +import sigma.ast.ShortConstant import sigmastate._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ -import sigmastate.interpreter.ContextExtension -import sigmastate.lang.Terms._ +import sigma.interpreter.ContextExtension +import sigma.ast.syntax._ class DemurrageExampleSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/DummyExamplesSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/DummyExamplesSpecification.scala index 754e3baa73..6b430888ac 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/DummyExamplesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/DummyExamplesSpecification.scala @@ -5,7 +5,7 @@ import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, StdContracts, Te import scorex.crypto.hash import sigmastate.helpers.CompilerTestingCommons import sigma.{Box, Context, Coll} -import sigmastate.eval.Extensions +import sigma.eval.Extensions class DummyExamplesSpecification extends CompilerTestingCommons { suite => implicit lazy val IR = new TestingIRContext diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/ExecuteFromExamplesSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/ExecuteFromExamplesSpecification.scala index 5ea4ef7a05..d8c533f17c 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/ExecuteFromExamplesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/ExecuteFromExamplesSpecification.scala @@ -4,7 +4,7 @@ import org.ergoplatform._ import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, StdContracts, TestContractSpec} import sigmastate.helpers.CompilerTestingCommons import sigma.Context -import sigmastate.eval.Extensions._ +import sigma.eval.Extensions.toAnyValue class ExecuteFromExamplesSpecification extends CompilerTestingCommons { suite => implicit lazy val IR = new TestingIRContext diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala index 6f36d29b74..8f4f3414a3 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala @@ -7,18 +7,16 @@ import scorex.crypto.hash import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.Colls import sigma.ast.SCollection.SByteArray -import sigmastate.Values._ -import sigmastate._ import sigma.ast._ +import sigmastate._ +import sigma.ast.syntax._ import sigma.data.{AvlTreeData, AvlTreeFlags} -import sigmastate.eval.Extensions.SigmaBooleanOps -import sigmastate.eval._ -import sigmastate.lang.Terms._ +import sigma.eval.Extensions.SigmaBooleanOps +import sigma.eval.SigmaDsl import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} -import sigmastate.serialization.ValueSerializer -import sigmastate.utxo._ +import sigma.serialization.ValueSerializer class FsmExampleSpecification extends CompilerTestingCommons diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala index 601b02fe96..c930135bc2 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala @@ -11,19 +11,20 @@ import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.Colls import sigma.ast.SByte import sigma.data.{AvlTreeData, AvlTreeFlags, Digest32Coll} -import sigmastate.Values._ +import sigma.ast._ import sigmastate._ -import sigmastate.crypto.CryptoConstants import sigma.Extensions.ArrayOps +import sigma.ast.syntax.{CollectionConstant, SigmaPropValue} +import sigma.crypto.CryptoConstants import sigmastate.eval._ import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestProvingInterpreter} import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.interpreter.Interpreter -import sigmastate.lang.Terms._ -import sigmastate.serialization.ErgoTreeSerializer -import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.utxo.ComplexityTableStat +import sigma.ast.syntax._ +import sigma.eval.SigmaDsl +import sigma.serialization.ErgoTreeSerializer +import sigma.serialization.ErgoTreeSerializer.DefaultSerializer import scala.util.Random @@ -552,10 +553,6 @@ class IcoExample extends CompilerTestingCommons printDebug("lookup proof size: " + lookupProof.length) } - property("ComplexityTableStat") { - printDebug(ComplexityTableStat.complexityTableString) - } - /** This is the last executed test suite, so this method is executed after all tests. * We output statistics of how PrecompiledScriptProcessor cache was used. */ override protected def afterAll(): Unit = { diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala index 1a41a656d9..ce4ed2114e 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala @@ -8,14 +8,15 @@ import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.Colls import sigma.data.{AvlTreeData, AvlTreeFlags, Digest32Coll, TrivialProp} import sigmastate.CompilerCrossVersionProps -import sigmastate.Values.{AvlTreeConstant, ByteArrayConstant, LongConstant, SigmaPropConstant} +import sigma.ast.{AvlTreeConstant, ByteArrayConstant, LongConstant, SigmaPropConstant} import sigma.Extensions.ArrayOps -import sigmastate.eval.{IRContext, SigmaDsl} +import sigmastate.eval.IRContext import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestProvingInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.ScriptNameProp -import sigmastate.serialization.ErgoTreeSerializer -import sigmastate.lang.Terms._ +import sigma.serialization.ErgoTreeSerializer +import sigma.ast.syntax._ +import sigma.eval.SigmaDsl import scala.util.Random diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala index ac6510cdd7..368fe3d8ea 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala @@ -7,16 +7,16 @@ import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.ast.{SAvlTree, SBoolean, SLong} import sigma.ast.SCollection.SByteArray import sigma.data.{AvlTreeData, AvlTreeFlags} -import sigmastate.Values._ +import sigma.ast._ import sigmastate._ import sigma.Extensions.ArrayOps +import sigma.ast.syntax.{GetVarByteArray, OptionValueOps} import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ +import sigma.eval.SigmaDsl import sigmastate.interpreter.Interpreter._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utxo._ -import sigmastate.eval._ +import sigma.serialization.ValueSerializer import scala.util.Random diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala index 878229982f..fc19a485ee 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala @@ -5,14 +5,16 @@ import org.ergoplatform.ErgoBox.{R4, R5} import scorex.crypto.hash.Blake2b256 import sigma.data.{AvlTreeData, ProveDHTuple, ProveDlog} import sigma.util.Extensions.EcpOps -import sigmastate.{CompilerCrossVersionProps, ErgoTree} -import sigmastate.Values.GroupElementConstant -import sigmastate.crypto.{CryptoConstants, DiffieHellmanTupleProverInput} +import sigmastate.CompilerCrossVersionProps +import sigma.ast.{ErgoTree, GroupElementConstant} +import sigma.ast.syntax.GroupElementConstant +import sigma.crypto.CryptoConstants +import sigmastate.crypto.DiffieHellmanTupleProverInput import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter._ -import sigmastate.lang.Terms._ -import sigmastate.eval._ +import sigma.ast.syntax._ +import sigma.eval.SigmaDsl class MixExampleSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala index 231cef6c02..9d0ffc880b 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala @@ -6,22 +6,19 @@ import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert, Lookup} import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.ast.SCollection.SByteArray -import sigmastate.Values._ -import sigmastate._ import sigma.ast._ +import sigmastate._ import sigmastate.eval._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import org.ergoplatform._ import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, StdContracts, TestContractSpec} -import sigmastate.crypto.CryptoConstants -import sigmastate.crypto.BigIntegers import sigma.Extensions.ArrayOps import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} -import sigmastate.utxo._ import sigma.Context -import sigma.crypto.CryptoFacade +import sigma.ast.syntax._ +import sigma.crypto.{BigIntegers, CryptoConstants, CryptoFacade} import sigma.data.{AvlTreeData, AvlTreeFlags} import sigmastate.utils.Helpers._ diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala index be2d852b46..c695b8e07d 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala @@ -5,12 +5,12 @@ import org.ergoplatform.ErgoBox.{R4, R5, R6, R7} import scorex.crypto.hash.Blake2b256 import scorex.utils.Random import sigma.data.{AvlTreeData, ProveDlog} -import sigmastate.Values.{ByteArrayConstant, ByteConstant, IntConstant, SigmaPropConstant} +import sigma.ast.{ByteArrayConstant, ByteConstant, ErgoTree, IntConstant, SigmaPropConstant} import sigmastate._ import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.interpreter.Interpreter._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ class RPSGameExampleSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala index 41d3b59039..5ac8599ce1 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala @@ -1,7 +1,7 @@ package sigmastate.utxo.examples import org.ergoplatform.dsl.{SigmaContractSyntax, ContractSpec, TestContractSpec, StdContracts} -import sigmastate.eval.Extensions +import sigma.eval.Extensions import sigmastate.helpers.CompilerTestingCommons import sigma.Context diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala index 5ce5163b33..4294dc5b4b 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala @@ -4,12 +4,12 @@ import org.ergoplatform.ErgoBox.{R4, R5} import org.ergoplatform._ import scorex.crypto.hash.Blake2b256 import sigma.data.AvlTreeData -import sigmastate.Values.{IntConstant, SigmaPropConstant} +import sigma.ast.{ErgoTree, IntConstant, SigmaPropConstant} import sigmastate._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.ScriptNameProp -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ class ReversibleTxExampleSpecification extends CompilerTestingCommons diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala index 401e8f87ae..a8c58bcc40 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala @@ -4,17 +4,15 @@ import org.ergoplatform._ import scorex.crypto.hash.Blake2b256 import scorex.util._ import sigma.Colls -import sigma.ast.{SBoolean, SByte, SInt, SLong} +import sigma.ast.syntax.{BooleanConstant, GetVarByteArray, OptionValueOps} +import sigma.ast._ import sigma.data.AvlTreeData -import sigmastate.Values._ import sigmastate._ -import sigmastate.eval._ -import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ -import sigmastate.interpreter.ContextExtension -import sigmastate.lang.Terms._ -import sigmastate.serialization.ValueSerializer -import sigmastate.utxo._ +import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} +import sigma.ast.syntax._ +import sigma.interpreter.ContextExtension +import sigma.serialization.ValueSerializer import sigmastate.utxo.blockchain.BlockchainSimulationTestingCommons._ /** diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala index a60cf35a7c..2657a49eb0 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala @@ -1,14 +1,14 @@ package sigmastate.utxo.examples import org.ergoplatform._ -import sigmastate.Values.IntConstant +import sigma.ast.{ErgoTree, IntConstant} import sigma.data.AvlTreeData import sigmastate._ -import sigmastate.exceptions.InterpreterException import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.ScriptNameProp -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ +import sigma.exceptions.InterpreterException class TimedPaymentExampleSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/TrustlessLETS.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/TrustlessLETS.scala index ecaa4c0a14..50348ce7ab 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/TrustlessLETS.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/TrustlessLETS.scala @@ -5,7 +5,7 @@ import scorex.crypto.hash.Blake2b256 import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, CompilerTestingCommons} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ class TrustlessLETS1 extends CompilerTestingCommons { private implicit lazy val IR: TestingIRContext = new TestingIRContext diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala index a98e6410e3..b3d6d4eff8 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala @@ -5,12 +5,12 @@ import org.ergoplatform.ErgoBox.{R4, R5, R6} import scorex.crypto.hash.Blake2b256 import scorex.utils.Random import sigma.data.{AvlTreeData, ProveDlog} -import sigmastate.Values.{ByteArrayConstant, ByteConstant, IntConstant, SigmaPropConstant} +import sigma.ast.{ByteArrayConstant, ByteConstant, IntConstant, SigmaPropConstant} import sigmastate._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter._ -import sigmastate.lang.Terms._ +import sigma.ast.syntax._ class XorGameExampleSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala index fc46b2ea1c..54e0a6c602 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala +++ b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala @@ -10,11 +10,12 @@ import scorex.util.ModifierId import scorex.util.encode.Base16 import sigma.Extensions.CollBytesOps import sigma.ast.SType +import sigma.ast.syntax.GroupElementConstant import sigma.data.Iso.{isoStringToArray, isoStringToColl} import sigma.data.{CBigInt, CGroupElement, Digest32Coll, Iso} import sigma.js.{AvlTree, GroupElement, Type, Value} import sigma.{Coll, Colls, Evaluation} -import sigmastate.Values.{Constant, GroupElementConstant} +import sigma.ast.{Constant, GroupElementConstant} import sigmastate.eval.{CHeader, CPreHeader} import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.Box import sigmastate.fleetSdkCommon.distEsmTypesCommonMod.HexString @@ -22,8 +23,8 @@ import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters import sigmastate.fleetSdkCommon.distEsmTypesTokenMod.TokenAmount import sigmastate.fleetSdkCommon.distEsmTypesTransactionsMod.{SignedTransaction, UnsignedTransaction} import sigmastate.fleetSdkCommon.{distEsmTypesBoxesMod => boxesMod, distEsmTypesCommonMod => commonMod, distEsmTypesContextExtensionMod => contextExtensionMod, distEsmTypesInputsMod => inputsMod, distEsmTypesProverResultMod => proverResultMod, distEsmTypesRegistersMod => registersMod, distEsmTypesTokenMod => tokenMod} -import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.serialization.{ErgoTreeSerializer, ValueSerializer} +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.serialization.{ErgoTreeSerializer, ValueSerializer} import sigma.data.Digest32CollRType import java.math.BigInteger import scala.collection.immutable.ListMap @@ -32,18 +33,6 @@ import scala.scalajs.js.Object /** Definitions of isomorphisms. */ object Isos { - /** Conversion between `Value` and `Constant[SType]`. */ - implicit val isoValueToConstant: Iso[Value, Constant[SType]] = new Iso[Value, Constant[SType]] { - override def to(x: Value): Constant[SType] = - Constant(x.runtimeData.asInstanceOf[SType#WrappedType], Evaluation.rtypeToSType(x.tpe.rtype)) - - override def from(x: Constant[SType]): Value = { - val rtype = Evaluation.stypeToRType(x.tpe) - val jsvalue = Value.fromRuntimeData(x.value, rtype) - new Value(jsvalue, new Type(rtype)) - } - } - val isoStringToGroupElement: Iso[String, sigma.GroupElement] = new Iso[String, sigma.GroupElement] { override def to(x: String): sigma.GroupElement = { val bytes = Base16.decode(x).get diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ProverBuilder.scala b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ProverBuilder.scala index 81aab56a3d..e0f4f8f190 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ProverBuilder.scala +++ b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ProverBuilder.scala @@ -7,7 +7,7 @@ import scala.scalajs.js import scala.scalajs.js.annotation.JSExportTopLevel import Isos._ import sigma.js.GroupElement -import sigmastate.eval.SigmaDsl +import sigma.eval.SigmaDsl /** Equivalent of [[sdk.ProverBuilder]] available from JS. * diff --git a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala index 32a49802fc..ddd0655dea 100644 --- a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala +++ b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala @@ -12,9 +12,9 @@ import sigma.ast.SType import sigma.data.Iso import sigma.js.AvlTree import sigma.{Coll, Colls, GroupElement} -import sigmastate.Values.Constant -import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.serialization.generators.ObjectGenerators +import sigma.ast.Constant +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.serialization.generators.ObjectGenerators import scala.scalajs.js diff --git a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/ValueSpec.scala b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/ValueSpec.scala index fffecbf9db..4599980006 100644 --- a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/ValueSpec.scala +++ b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/ValueSpec.scala @@ -4,15 +4,15 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import scorex.util.encode.Base16 -import sigma.ast.SType -import sigmastate.Values.{AvlTreeConstant, BigIntConstant, BooleanConstant, BoxConstant, ByteConstant, Constant, GroupElementConstant, IntConstant, LongConstant, ShortConstant, SigmaPropConstant, UnitConstant} -import sigmastate.crypto.CryptoConstants.dlogGroup +import sigma.ast.{DeserializationSigmaBuilder, SType} +import sigma.ast._ +import sigma.crypto.CryptoConstants.dlogGroup import sigma.crypto.CryptoFacade -import sigmastate.lang.DeserializationSigmaBuilder -import sigmastate.serialization.ConstantSerializer +import sigma.serialization.ConstantSerializer import sigmastate.utils.Helpers import sigma.SigmaTestingData import sigma.data.{CSigmaProp, ProveDlog} +import sigma.ast.js.isoValueToConstant import sigma.js.Value import java.math.BigInteger @@ -20,11 +20,11 @@ import java.math.BigInteger class ValueSpec extends AnyPropSpec with Matchers with SigmaTestingData with ScalaCheckPropertyChecks { def test[T <: SType](c: Constant[T], expectedHex: String) = { - val v = Isos.isoValueToConstant.from(c) + val v = isoValueToConstant.from(c) val S = ConstantSerializer(DeserializationSigmaBuilder) Base16.encode(S.toBytes(c)) shouldBe expectedHex v.toHex() shouldBe expectedHex - Isos.isoValueToConstant.to(Value.fromHex(expectedHex)) shouldBe c + isoValueToConstant.to(Value.fromHex(expectedHex)) shouldBe c } property("Boolean toHex()/fromHex()") { diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/AppkitProvingInterpreter.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/AppkitProvingInterpreter.scala index 9b09c487f3..c0dc075a9b 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/AppkitProvingInterpreter.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/AppkitProvingInterpreter.scala @@ -10,13 +10,13 @@ import org.ergoplatform.sdk.wallet.secrets.ExtendedSecretKey import org.ergoplatform.validation.ValidationRules import sigma.VersionContext import sigma.data.{AvlTreeData, ProveDlog, SigmaBoolean} +import sigma.interpreter.{ContextExtension, ProverResult} import sigma.util.Extensions.LongOps import sigmastate.crypto.DLogProtocol.DLogProverInput import sigmastate.crypto.{DiffieHellmanTupleProverInput, SigmaProtocolPrivateInput} import sigmastate.interpreter.Interpreter.{ReductionResult, estimateCryptoVerifyCost} import sigmastate.interpreter._ -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} import java.util import java.util.{Objects, List => JList} diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala index 7042791a93..d0ab8f5e5e 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala @@ -7,16 +7,13 @@ import io.circe.syntax.EncoderOps import org.ergoplatform.sdk.utils.SerializationUtils.{parseString, serializeString} import org.ergoplatform.sdk.utils.Zero import sigma.Evaluation -import sigma.ast.SType -import sigma.serialization.SerializerException +import sigma.ast.{DeserializationSigmaBuilder, SType, StdSigmaBuilder} +import sigma.serialization.{SerializerException, SigmaByteReader, SigmaByteWriter} import sigma.util.safeNewArray -import sigmastate.ErgoTree.{ZeroHeader, headerWithVersion, setConstantSegregation} -import sigmastate.Values._ -import sigmastate._ -import sigmastate.lang.{DeserializationSigmaBuilder, StdSigmaBuilder} -import sigmastate.serialization.{DataSerializer, _} -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} - +import sigma.ast.ErgoTree.{ZeroHeader, headerWithVersion, setConstantSegregation} +import sigma.ast._ +import sigma.ast.syntax.SigmaPropValue +import sigma.serialization._ import java.util.Objects import scala.collection.mutable import scala.language.implicitConversions @@ -146,7 +143,7 @@ case class ContractTemplate( * provided in the template. * @return `ErgoTree` generated by replacing the template parameters with the value provided in `paramValues`. */ - def applyTemplate(version: Option[Byte], paramValues: Map[String, Values.Constant[SType]]): ErgoTree = { + def applyTemplate(version: Option[Byte], paramValues: Map[String, Constant[SType]]): ErgoTree = { require(treeVersion.isDefined || version.isDefined, "ErgoTreeVersion must be provided to generate the ErgoTree.") val nConsts = constTypes.size val requiredParameterNames = diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/DataJsonEncoder.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/DataJsonEncoder.scala index fef67a2704..87e3402bcb 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/DataJsonEncoder.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/DataJsonEncoder.scala @@ -5,21 +5,22 @@ import io.circe._ import io.circe.syntax._ import org.ergoplatform.ErgoBox import org.ergoplatform.ErgoBox.{NonMandatoryRegisterId, Token} -import org.ergoplatform.settings.ErgoAlgos import sigma.data.{CAnyValue, RType} import scorex.util._ -import sigmastate.Values.{Constant, EvaluatedValue} +import sigma.ast.{Constant, EvaluatedValue} import sigmastate.lang.SigmaParser import sigmastate.eval._ import sigma._ import debox.cfor +import scorex.util.encode.Base16 import scala.collection.compat.immutable.ArraySeq import scala.collection.mutable import sigma.ast._ +import sigma.eval.SigmaDsl import sigma.serialization.SerializerException -import sigmastate.serialization.{DataSerializer, SigmaSerializer} -import sigmastate.serialization.ErgoTreeSerializer +import sigma.serialization.{DataSerializer, SigmaSerializer} +import sigma.serialization.ErgoTreeSerializer object DataJsonEncoder { def encode[T <: SType](v: T#WrappedType, tpe: T): Json = { @@ -32,7 +33,7 @@ object DataJsonEncoder { } private def encodeBytes: Encoder[Array[Byte]] = Encoder.instance((bytes: Array[Byte]) => { - ErgoAlgos.encode(bytes).asJson + Base16.encode(bytes).asJson }) def encodeAnyValue(v: AnyValue): Json = { @@ -152,7 +153,7 @@ object DataJsonEncoder { private def decodeBytes(json: Json): Array[Byte] = { val jsonStr = json.as[String] jsonStr match { - case Right(jsonStr) => ErgoAlgos.decode(jsonStr).get + case Right(jsonStr) => Base16.decode(jsonStr).get case Left(error) => throw new SerializerException(error.getMessage) } } diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ExtendedInputBox.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ExtendedInputBox.scala index 05cd83daea..81b1ba0085 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ExtendedInputBox.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ExtendedInputBox.scala @@ -2,7 +2,7 @@ package org.ergoplatform.sdk import org.ergoplatform.{ErgoBox, ErgoBoxCandidate, UnsignedInput} import scorex.util.ModifierId -import sigmastate.interpreter.ContextExtension +import sigma.interpreter.ContextExtension /** Input ErgoBox paired with context variables (aka ContextExtensions). * diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JavaHelpers.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JavaHelpers.scala index 31984fe028..ce139ef6c7 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JavaHelpers.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JavaHelpers.scala @@ -11,18 +11,17 @@ import org.ergoplatform.settings.ErgoAlgos import scorex.crypto.authds.ADKey import scorex.util.encode.Base16 import scorex.util.{ModifierId, bytesToId, idToBytes} -import sigma.ast.SType +import sigma.ast.{ErgoTree, SType} +import sigma.ast.syntax.SValue import sigma.crypto.{CryptoFacade, EcPointType} import sigma.data.ExactIntegral.LongIsExactIntegral -import sigma.data.{Digest32Coll, Iso, ProveDHTuple, ProveDlog, RType, SigmaBoolean, SigmaConstants} +import sigma.data.{CSigmaDslBuilder, Digest32Coll, Iso, ProveDHTuple, ProveDlog, RType, SigmaBoolean, SigmaConstants} import sigma.serialization.GroupElementSerializer import sigma.util.StringUtil.StringUtilExtensions import sigma.{AnyValue, AvlTree, Coll, Colls, Evaluation, GroupElement, Header} -import sigmastate.ErgoTree -import sigmastate.Values.{Constant, EvaluatedValue, SValue, SigmaPropConstant} +import sigma.ast.{Constant, EvaluatedValue, SigmaPropConstant} import sigmastate.crypto.DiffieHellmanTupleProverInput -import sigmastate.eval.CSigmaDslBuilder -import sigmastate.serialization.{ErgoTreeSerializer, SigmaSerializer, ValueSerializer} +import sigma.serialization.{ErgoTreeSerializer, SigmaSerializer, ValueSerializer} import sigmastate.utils.Helpers._ // required for Scala 2.11 import java.lang.{Boolean => JBoolean, Byte => JByte, Integer => JInt, Long => JLong, Short => JShort, String => JString} @@ -334,7 +333,7 @@ object JavaHelpers { def BoxRType: RType[sigma.Box] = sigma.BoxRType - def SigmaDsl: CSigmaDslBuilder = sigmastate.eval.SigmaDsl + def SigmaDsl: CSigmaDslBuilder = sigma.eval.SigmaDsl def collFrom(arr: Array[Byte]): Coll[Byte] = { Colls.fromArray(arr) diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala index ce8c6dce35..47ed6623d1 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala @@ -11,16 +11,16 @@ import scorex.crypto.authds.{ADDigest, ADKey} import scorex.crypto.hash.Digest32 import scorex.util.ModifierId import sigma.Extensions.ArrayOps -import sigma.ast.SType +import sigma.ast.{ErgoTree, SType} import sigma.data.{AvlTreeData, AvlTreeFlags, CBigInt, Digest32Coll, WrapperOf} import sigma.validation.SigmaValidationSettings import sigma.{AnyValue, Coll, Colls, Header, PreHeader, SigmaException} -import sigmastate.ErgoTree -import sigmastate.Values.EvaluatedValue -import sigmastate.eval.Extensions._ +import sigma.ast.EvaluatedValue +import sigma.eval.Extensions.EvalIterableOps +import sigma.eval.SigmaDsl import sigmastate.eval._ -import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.serialization.{ErgoTreeSerializer, ValueSerializer} +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.serialization.{ErgoTreeSerializer, ValueSerializer} import sigmastate.utils.Helpers._ // required for Scala 2.11 import java.math.BigInteger diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/OutBoxBuilder.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/OutBoxBuilder.scala index 89314fe97d..1046767fbf 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/OutBoxBuilder.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/OutBoxBuilder.scala @@ -4,10 +4,9 @@ import org.ergoplatform.ErgoBox.TokenId import org.ergoplatform.sdk.JavaHelpers.collRType import org.ergoplatform.{ErgoBox, ErgoBoxCandidate} import sigma.Colls -import sigma.ast.SType +import sigma.ast.{ErgoTree, SType} import sigma.data.{RType, SigmaConstants} -import sigmastate.ErgoTree -import sigmastate.Values.{Constant, EvaluatedValue} +import sigma.ast.{Constant, EvaluatedValue} import scala.collection.mutable.ArrayBuffer diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ReducingInterpreter.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ReducingInterpreter.scala index 148f25bc43..73c3cd0168 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ReducingInterpreter.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ReducingInterpreter.scala @@ -6,11 +6,11 @@ import org.ergoplatform.sdk.utils.ArithUtils import org.ergoplatform.sdk.wallet.protocol.context.{BlockchainStateContext, TransactionContext} import org.ergoplatform.validation.ValidationRules import org.ergoplatform.{ErgoLikeContext, ErgoLikeInterpreter} +import sigma.ast.ErgoTree import sigma.data.AvlTreeData +import sigma.exceptions.CostLimitException import sigma.util.Extensions.LongOps -import sigmastate.ErgoTree import sigmastate.eval.addCostChecked -import sigmastate.exceptions.CostLimitException import sigmastate.interpreter.Interpreter import sigmastate.interpreter.Interpreter.ScriptEnv diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/SigmaProver.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/SigmaProver.scala index 3d1b4f97b9..6dc08fbfee 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/SigmaProver.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/SigmaProver.scala @@ -3,7 +3,8 @@ package org.ergoplatform.sdk import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import org.ergoplatform._ import org.ergoplatform.sdk.wallet.protocol.context.BlockchainStateContext -import sigmastate.eval.{CSigmaDslBuilder, SigmaDsl} +import sigma.data.CSigmaDslBuilder +import sigma.eval.SigmaDsl import sigmastate.interpreter.HintsBag import sigmastate.utils.Helpers.TryOps import sigma.{BigInt, SigmaProp} diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/Transactions.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/Transactions.scala index 8848e73c42..a3a4510653 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/Transactions.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/Transactions.scala @@ -3,9 +3,7 @@ package org.ergoplatform.sdk import org.ergoplatform.sdk.JavaHelpers.StringExtensions import org.ergoplatform.{ErgoBox, ErgoLikeTransaction, UnsignedErgoLikeTransaction} import sigmastate.eval.Extensions.ArrayByteOps -import sigmastate.serialization.SigmaSerializer - -import java.util +import sigma.serialization.SigmaSerializer /** Represents a transaction data chat can be reduced to [[ReducedTransaction]]. * diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/SerializationUtils.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/SerializationUtils.scala index 1530e1876a..4291a750f4 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/SerializationUtils.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/SerializationUtils.scala @@ -1,7 +1,6 @@ package org.ergoplatform.sdk.utils -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} - +import sigma.serialization.{SigmaByteReader, SigmaByteWriter} import java.nio.charset.StandardCharsets object SerializationUtils { diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/Zero.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/Zero.scala index 4d083e9ff4..78dfe2dc94 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/Zero.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/Zero.scala @@ -6,12 +6,11 @@ import sigma.data.RType._ import scorex.crypto.authds.avltree.batch.BatchAVLProver import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.ModifierId -import sigmastate.ErgoTree -import sigmastate.crypto.CryptoConstants import sigmastate.eval._ import sigma._ -import sigmastate.ErgoTree.HeaderType - +import sigma.ast.ErgoTree +import ErgoTree.HeaderType +import sigma.crypto.CryptoConstants import java.math.BigInteger import scala.language.implicitConversions diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/DerivationPath.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/DerivationPath.scala index 601a45e537..ac2143694e 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/DerivationPath.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/DerivationPath.scala @@ -1,10 +1,7 @@ package org.ergoplatform.sdk.wallet.secrets import org.ergoplatform.sdk.wallet.Constants -import scorex.util.serialization.{Reader, Writer} -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} - +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} import scala.util.{Failure, Success, Try} /** diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/ExtendedPublicKey.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/ExtendedPublicKey.scala index 99179e73d0..43488974b9 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/ExtendedPublicKey.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/ExtendedPublicKey.scala @@ -1,13 +1,9 @@ package org.ergoplatform.sdk.wallet.secrets -import sigma.crypto.CryptoFacade +import sigma.crypto.{BigIntegers, CryptoConstants, CryptoFacade} import sigma.data.ProveDlog import sigmastate.crypto.DLogProtocol.DLogProverInput -import sigmastate.crypto.CryptoConstants -import sigmastate.crypto.BigIntegers -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} - +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} import scala.annotation.tailrec /** diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/ExtendedSecretKey.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/ExtendedSecretKey.scala index 9e871f7bfb..5493929ac5 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/ExtendedSecretKey.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/wallet/secrets/ExtendedSecretKey.scala @@ -1,13 +1,10 @@ package org.ergoplatform.sdk.wallet.secrets -import sigma.crypto.CryptoFacade +import sigma.crypto.{BigIntegers, CryptoConstants, CryptoFacade} import sigma.data.ProveDlog import java.math.BigInteger -import sigmastate.crypto.BigIntegers import sigmastate.crypto.DLogProtocol.DLogProverInput -import sigmastate.crypto.CryptoConstants -import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigma.serialization.{SigmaByteReader, SigmaByteWriter, SigmaSerializer} /** * Secret, its chain code and path in key tree. diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ContractTemplateSpecification.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ContractTemplateSpecification.scala index ef83bfd6d0..f81db87371 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ContractTemplateSpecification.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ContractTemplateSpecification.scala @@ -3,14 +3,15 @@ package org.ergoplatform.sdk import org.ergoplatform.sdk.generators.ObjectGenerators import org.scalatest.compatible.Assertion import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import sigmastate.Values._ +import sigma.ast._ import sigmastate._ import sigmastate.helpers.NegativeTesting -import sigmastate.serialization.{SerializationSpecification, SigmaSerializer} +import sigma.serialization.{SerializationSpecification, SigmaSerializer} import sigma.ContractsTestkit +import sigma.ast.syntax.SigmaPropValue import sigma.ast.{SByte, SInt, SType} import sigma.data.CBigInt -import sigmastate.ErgoTree.setConstantSegregation +import ErgoTree.setConstantSegregation import java.math.BigInteger diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/DataJsonEncoderSpecification.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/DataJsonEncoderSpecification.scala index 0b35fd2462..c3f7b43af4 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/DataJsonEncoderSpecification.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/DataJsonEncoderSpecification.scala @@ -12,9 +12,9 @@ import sigma.crypto.EcPointType import sigma.serialization.SerializerException import sigma.util.Extensions.{BigIntegerOps, EcpOps, SigmaBooleanOps} import sigma.Extensions.ArrayOps -import sigmastate.eval._ +import sigma.eval.SigmaDsl import sigma.{AvlTree, Box, Colls, Evaluation} -import sigmastate.serialization.SerializationSpecification +import sigma.serialization.SerializationSpecification import scala.annotation.nowarn import scala.reflect.ClassTag diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala index a272f00cd4..98f61331bb 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala @@ -5,8 +5,7 @@ import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigma.{Coll, CollGens} import org.ergoplatform.sdk.Extensions.{CollBuilderOps, CollOps, GenIterableOps, PairCollOps} -import sigma.data.RType -import sigmastate.eval.CSigmaDslBuilder +import sigma.data.{CSigmaDslBuilder, RType} class ExtensionsSpec extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers with CollGens { def Coll[T](items: T*)(implicit cT: RType[T]) = diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/JsonSerializationSpec.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/JsonSerializationSpec.scala index 5fe0cb8dee..93adef9f81 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/JsonSerializationSpec.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/JsonSerializationSpec.scala @@ -10,14 +10,12 @@ import org.scalacheck.Arbitrary.arbitrary import scorex.crypto.authds.{ADDigest, ADKey} import scorex.util.ModifierId import scorex.util.encode.Base16 -import sigma.ast.SType import sigma.data.{AvlTreeData, Digest32Coll, ProveDlog} import sigma.{Coll, Header, PreHeader} -import sigmastate.ErgoTree -import sigmastate.Values.{ByteArrayConstant, ByteConstant, EvaluatedValue, IntConstant, LongArrayConstant, SigmaPropConstant} -import sigmastate.crypto.CryptoConstants -import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.serialization.SerializationSpecification +import sigma.ast._ +import sigma.crypto.CryptoConstants +import sigma.interpreter.{ContextExtension, ProverResult} +import sigma.serialization.SerializationSpecification import sigmastate.utils.Helpers.DecoderResultOps // required for Scala 2.11 class JsonSerializationSpec extends SerializationSpecification with JsonCodecs { diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/generators/ObjectGenerators.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/generators/ObjectGenerators.scala index 6fb22792b6..1c6d2efc5d 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/generators/ObjectGenerators.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/generators/ObjectGenerators.scala @@ -3,10 +3,9 @@ package org.ergoplatform.sdk.generators import org.ergoplatform.sdk.{ContractTemplate, Parameter} import org.ergoplatform.validation.ValidationSpecification import org.scalacheck.Gen -import sigma.ast.SType +import sigma.ast.{ErgoTree, SType} import sigmastate.TestsBase -import sigmastate.ErgoTree -import sigmastate.serialization.generators.{ConcreteCollectionGenerators, TypeGenerators, ObjectGenerators => InterpreterObjectGenerators} +import sigma.serialization.generators.{ConcreteCollectionGenerators, TypeGenerators, ObjectGenerators => InterpreterObjectGenerators} import scala.util.Random diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/wallet/utils/Generators.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/wallet/utils/Generators.scala index 83765c012a..56b2ea02d1 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/wallet/utils/Generators.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/wallet/utils/Generators.scala @@ -2,22 +2,19 @@ package org.ergoplatform.sdk.wallet.utils import org.ergoplatform.ErgoBox.{BoxId, NonMandatoryRegisterId, Token} import org.ergoplatform.sdk.wallet.Constants -import org.ergoplatform.sdk.wallet.secrets.ExtendedPublicKey -import org.ergoplatform.sdk.wallet.secrets.{DerivationPath, ExtendedSecretKey, Index, SecretKey} +import org.ergoplatform.sdk.wallet.secrets._ import org.ergoplatform.sdk.wallet.settings.EncryptionSettings +import org.ergoplatform._ import org.scalacheck.Arbitrary.arbByte import org.scalacheck.{Arbitrary, Gen} import scorex.crypto.authds.ADKey -import sigmastate.Values.{ByteArrayConstant, CollectionConstant, EvaluatedValue, FalseLeaf, TrueLeaf} -import sigma.ast.{SByte, SType} import scorex.util._ -import org.ergoplatform.{ErgoBox, ErgoBoxCandidate, ErgoTreePredef, UnsignedErgoLikeTransaction, UnsignedInput} import sigma.Extensions.ArrayOps -import scorex.util.{ModifierId, bytesToId} +import sigma.ast._ +import sigma.ast.syntax.CollectionConstant import sigma.crypto.CryptoFacade import sigma.data.{Digest32Coll, ProveDlog} -import sigmastate.ErgoTree -import sigmastate.eval.Extensions.{EvalIterableOps, SigmaBooleanOps} +import sigma.eval.Extensions.EvalIterableOps import sigmastate.helpers.TestingHelpers._ trait Generators {