diff --git a/build.sbt b/build.sbt index fedb83ec0a..821f27969f 100644 --- a/build.sbt +++ b/build.sbt @@ -118,6 +118,13 @@ libraryDependencies ++= Seq( "org.spire-math" %% "debox" % "0.8.0" ) ++ testingDependencies +val circeVersion = "0.10.0" + +libraryDependencies ++= Seq( + "io.circe" %% "circe-core", + "io.circe" %% "circe-generic", + "io.circe" %% "circe-parser" +).map(_ % circeVersion) scalacOptions ++= Seq("-feature", "-deprecation") @@ -201,7 +208,7 @@ lazy val sigma = (project in file(".")) .settings(commonSettings: _*) def runErgoTask(task: String, sigmastateVersion: String, log: Logger): Unit = { - val ergoBranch = "ergobox-opt" + val ergoBranch = "ergolikectx-json" val sbtEnvVars = Seq("BUILD_ENV" -> "test", "SIGMASTATE_VERSION" -> sigmastateVersion) log.info(s"Testing current build in Ergo (branch $ergoBranch):") diff --git a/sigma-impl/src/main/scala/special/sigma/Extensions.scala b/sigma-impl/src/main/scala/special/sigma/Extensions.scala index 20465ccb54..e07c0127ce 100644 --- a/sigma-impl/src/main/scala/special/sigma/Extensions.scala +++ b/sigma-impl/src/main/scala/special/sigma/Extensions.scala @@ -16,10 +16,15 @@ class DslSyntaxExtensions(dsl: SigmaDslBuilder) { object Extensions { - def showECPoint(p: ECPoint) = { - val rawX = p.getRawXCoord.toString.substring(0, 6) - val rawY = p.getRawYCoord.toString.substring(0, 6) - s"ECPoint($rawX,$rawY,...)" + def showECPoint(p: ECPoint): String = { + if (p.isInfinity) { + "INF" + } + else { + val rawX = p.getRawXCoord.toString.substring(0, 6) + val rawY = p.getRawYCoord.toString.substring(0, 6) + s"ECPoint($rawX,$rawY,...)" + } } implicit class GroupElementOps(val source: GroupElement) extends AnyVal { diff --git a/src/main/scala/org/ergoplatform/ErgoBox.scala b/src/main/scala/org/ergoplatform/ErgoBox.scala index d41a01c092..0ab065f61c 100644 --- a/src/main/scala/org/ergoplatform/ErgoBox.scala +++ b/src/main/scala/org/ergoplatform/ErgoBox.scala @@ -2,20 +2,20 @@ package org.ergoplatform import com.google.common.primitives.Shorts import org.ergoplatform.ErgoBox.{NonMandatoryRegisterId, TokenId} +import org.ergoplatform.settings.ErgoAlgos import scorex.crypto.authds.ADKey -import scorex.util.encode.Base16 -import scorex.crypto.hash.{Digest32, Blake2b256} +import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util._ -import sigmastate.Values._ +import sigmastate.SCollection.SByteArray import sigmastate.SType.AnyOps +import sigmastate.Values._ import sigmastate._ +import sigmastate.eval.Extensions._ +import sigmastate.eval._ import sigmastate.serialization.SigmaSerializer -import sigmastate.SCollection.SByteArray -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter, Helpers} +import sigmastate.utils.{Helpers, SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.ExtractCreationInfo import special.collection._ -import sigmastate.eval._ -import sigmastate.eval.Extensions._ import scala.runtime.ScalaRunTime @@ -84,8 +84,8 @@ class ErgoBox( def toCandidate: ErgoBoxCandidate = new ErgoBoxCandidate(value, ergoTree, creationHeight, additionalTokens, additionalRegisters) - override def toString: Idn = s"ErgoBox(${Base16.encode(id)},$value,$ergoTree," + - s"tokens: (${additionalTokens.map(t => Base16.encode(t._1) + ":" + t._2)}), $transactionId, " + + override def toString: String = s"ErgoBox(${ErgoAlgos.encode(id)},$value,$ergoTree," + + s"tokens: (${additionalTokens.map(t => ErgoAlgos.encode(t._1) + ":" + t._2)}), $transactionId, " + s"$index, $additionalRegisters, $creationHeight)" } @@ -100,7 +100,7 @@ object ErgoBox { val size: Short = 32 } - val MaxBoxSize: Int = ErgoConstants.MaxBoxSize.value + val MaxBoxSize: Int = SigmaConstants.MaxBoxSize.value val STokenType = STuple(SByteArray, SLong) val STokensRegType = SCollection(STokenType) @@ -134,9 +134,9 @@ object ErgoBox { val TokensRegId: MandatoryRegisterId = R2 val ReferenceRegId: MandatoryRegisterId = R3 - val MaxTokens: Int = ErgoConstants.MaxTokens.value + val MaxTokens: Int = SigmaConstants.MaxTokens.value - val maxRegisters: Int = ErgoConstants.MaxRegisters.value + val maxRegisters: Int = SigmaConstants.MaxRegisters.value /** @hotspot don't beautify the code in this companion */ private val _mandatoryRegisters: Array[MandatoryRegisterId] = Array(R0, R1, R2, R3) @@ -197,5 +197,4 @@ object ErgoBox { ergoBoxCandidate.toBox(transactionId, index.toShort) } } - } diff --git a/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala b/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala index 9d83860f47..332c2ac533 100644 --- a/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala +++ b/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala @@ -3,8 +3,8 @@ package org.ergoplatform import java.util import org.ergoplatform.ErgoBox._ +import org.ergoplatform.settings.ErgoAlgos import scorex.crypto.hash.Digest32 -import scorex.util.encode.Base16 import scorex.util.ModifierId import sigmastate.Values._ import sigmastate._ @@ -75,7 +75,7 @@ class ErgoBoxCandidate(val value: Long, ScalaRunTime._hashCode((value, ergoTree, additionalTokens, additionalRegisters, creationHeight)) override def toString: Idn = s"ErgoBoxCandidate($value, $ergoTree," + - s"tokens: (${additionalTokens.map(t => Base16.encode(t._1) + ":" + t._2).toArray.mkString(", ")}), " + + s"tokens: (${additionalTokens.map(t => ErgoAlgos.encode(t._1) + ":" + t._2).toArray.mkString(", ")}), " + s"$additionalRegisters, creationHeight: $creationHeight)" } diff --git a/src/main/scala/org/ergoplatform/ErgoLikeContext.scala b/src/main/scala/org/ergoplatform/ErgoLikeContext.scala index 84a0e9b53e..bacbfa7312 100644 --- a/src/main/scala/org/ergoplatform/ErgoLikeContext.scala +++ b/src/main/scala/org/ergoplatform/ErgoLikeContext.scala @@ -1,202 +1,194 @@ package org.ergoplatform -import org.ergoplatform.ErgoLikeContext.Height -import scalan.RType +import java.util + +import org.ergoplatform.validation.SigmaValidationSettings +import sigmastate.SType._ import sigmastate.Values._ import sigmastate._ -import sigmastate.eval._ import sigmastate.eval.Extensions._ +import sigmastate.eval._ import sigmastate.interpreter.{ContextExtension, InterpreterContext} import sigmastate.serialization.OpCodes import sigmastate.serialization.OpCodes.OpCode import special.collection.Coll import special.sigma -import special.sigma.{AnyValue, Box, PreHeader, Header} -import SType._ -import RType._ -import org.ergoplatform.ErgoConstants.ScriptCostLimit -import org.ergoplatform.validation.{ValidationRules, SigmaValidationSettings} +import special.sigma.{AnyValue, Header, PreHeader} import spire.syntax.all.cfor -import scala.util.Try - -case class BlockchainState(currentHeight: Height, lastBlockUtxoRoot: AvlTreeData) /** - * TODO currentHeight and minerPubkey should be calculated from PreHeader * TODO lastBlockUtxoRoot should be calculated from headers if it is nonEmpty * - * @param self - box that contains the script we're evaluating - * @param currentHeight - height of a block with the current `spendingTransaction` - * @param lastBlockUtxoRoot - state root before current block application - * @param minerPubkey - public key of a miner of the block with the current `spendingTransaction` - * @param headers - fixed number of last block headers in descending order (first header is the newest one) - * @param preHeader - fields of block header with the current `spendingTransaction`, that can be predicted - * by a miner before it's formation - * @param dataBoxes - boxes, that corresponds to id's of `spendingTransaction.dataInputs` - * @param boxesToSpend - boxes, that corresponds to id's of `spendingTransaction.inputs` + * @param selfIndex - index of the box in `boxesToSpend` that contains the script we're evaluating + * @param lastBlockUtxoRoot - state root before current block application + * @param headers - fixed number of last block headers in descending order (first header is the newest one) + * @param preHeader - fields of block header with the current `spendingTransaction`, that can be predicted + * by a miner before it's formation + * @param dataBoxes - boxes, that corresponds to id's of `spendingTransaction.dataInputs` + * @param boxesToSpend - boxes, that corresponds to id's of `spendingTransaction.inputs` * @param spendingTransaction - transaction that contains `self` box - * @param extension - prover-defined key-value pairs, that may be used inside a script + * @param extension - prover-defined key-value pairs, that may be used inside a script * @param validationSettings validataion parameters passed to Interpreter.verify to detect soft-fork conditions - * @param costLimit hard limit on accumulated execution cost, if exceeded lead to CostLimitException to be thrown - * @param initCost initial value of execution cost already accumulated before Interpreter.verify is called + * @param costLimit hard limit on accumulated execution cost, if exceeded lead to CostLimitException to be thrown + * @param initCost initial value of execution cost already accumulated before Interpreter.verify is called */ -class ErgoLikeContext(val currentHeight: Height, - val lastBlockUtxoRoot: AvlTreeData, - val minerPubkey: Array[Byte], +class ErgoLikeContext(val lastBlockUtxoRoot: AvlTreeData, val headers: Coll[Header], val preHeader: PreHeader, val dataBoxes: IndexedSeq[ErgoBox], val boxesToSpend: IndexedSeq[ErgoBox], val spendingTransaction: ErgoLikeTransactionTemplate[_ <: UnsignedInput], - val self: ErgoBox, + val selfIndex: Int, val extension: ContextExtension, val validationSettings: SigmaValidationSettings, val costLimit: Long, val initCost: Long ) extends InterpreterContext { - assert(self == null || boxesToSpend.exists(box => box.id == self.id), s"Self box if defined should be among boxesToSpend") - assert(preHeader == null || preHeader.height == currentHeight, "Incorrect preHeader height") - assert(preHeader == null || java.util.Arrays.equals(minerPubkey, preHeader.minerPk.getEncoded.toArray), "Incorrect preHeader minerPubkey") + /* NOHF PROOF: + Added: assert(preHeader != null) + Motivation: to fail early, rather then on evaluation on `CONTEXT.preHeader` access + Safety: According to ergo design PreHeader should always exist. + Examined ergo code: all that leads to ErgoLikeContext creation. + Fixed some cases in ergo where PreHeader might be null. + */ + assert(preHeader != null, "preHeader cannot be null") + /* NOHF PROOF: + Added: assert(spendingTransaction != null) + Motivation: to fail early + Safety: According to ergo design spendingTransaction should always exist. + Examined ergo code: all that leads to ErgoLikeContext creation. + */ + assert(spendingTransaction != null, "spendingTransaction cannot be null") + /* NOHF PROOF: + Added: assert that box with `selfIndex` exist in boxesToSpend + Motivation: to fail early, rather than when going into evaluation + Safety: ergo itself uses index to identify the box + Examined ergo code: all that leads to ErgoLikeContext creation. + */ + assert(boxesToSpend.isDefinedAt(selfIndex), s"Self box if defined should be among boxesToSpend") assert(headers.toArray.headOption.forall(h => java.util.Arrays.equals(h.stateRoot.digest.toArray, lastBlockUtxoRoot.digest)), "Incorrect lastBlockUtxoRoot") cfor(0)(_ < headers.length, _ + 1) { i => if (i > 0) assert(headers(i - 1).parentId == headers(i).id, s"Incorrect chain: ${headers(i - 1).parentId},${headers(i).id}") } - assert(preHeader == null || headers.toArray.headOption.forall(_.id == preHeader.parentId), s"preHeader.parentId should be id of the best header") + assert(headers.toArray.headOption.forall(_.id == preHeader.parentId), s"preHeader.parentId should be id of the best header") + /* NOHF PROOF: + Added: assert that dataBoxes corresponds to spendingTransaction.dataInputs + Motivation: to fail early, rather than when going into evaluation + Safety: dataBoxes and spendingTransaction are supplied separately in ergo. No checks in ergo. + Examined ergo code: all that leads to ErgoLikeContext creation. + */ + assert(spendingTransaction.dataInputs.length == dataBoxes.length && + spendingTransaction.dataInputs.forall(dataInput => dataBoxes.exists(b => util.Arrays.equals(b.id, dataInput.boxId))), + "dataBoxes do not correspond to spendingTransaction.dataInputs") + + // TODO assert boxesToSpend correspond to spendingTransaction.inputs + + /* NOHF PROOF: + Changed: make `self` a property returning box from `boxesToSpend`. + Motivation: avoid DRY and avoid user error when trying to get the box from `boxesToSpend` supplying wrong index. + Safety: index of the box and not the box itself are used internally in ergo. + Examined ergo code: all that leads to ErgoLikeContext creation. + */ + val self: ErgoBox = boxesToSpend(selfIndex) override def withCostLimit(newCostLimit: Long): ErgoLikeContext = new ErgoLikeContext( - currentHeight, lastBlockUtxoRoot, minerPubkey, headers, preHeader, - dataBoxes, boxesToSpend, spendingTransaction, self, extension, validationSettings, newCostLimit, initCost) + lastBlockUtxoRoot, headers, preHeader, + dataBoxes, boxesToSpend, spendingTransaction, selfIndex, extension, validationSettings, newCostLimit, initCost) override def withInitCost(newCost: Long): ErgoLikeContext = new ErgoLikeContext( - currentHeight, lastBlockUtxoRoot, minerPubkey, headers, preHeader, - dataBoxes, boxesToSpend, spendingTransaction, self, extension, validationSettings, costLimit, newCost) + lastBlockUtxoRoot, headers, preHeader, + dataBoxes, boxesToSpend, spendingTransaction, selfIndex, extension, validationSettings, costLimit, newCost) override def withValidationSettings(newVs: SigmaValidationSettings): ErgoLikeContext = new ErgoLikeContext( - currentHeight, lastBlockUtxoRoot, minerPubkey, headers, preHeader, - dataBoxes, boxesToSpend, spendingTransaction, self, extension, newVs, costLimit, initCost) + lastBlockUtxoRoot, headers, preHeader, + dataBoxes, boxesToSpend, spendingTransaction, selfIndex, extension, newVs, costLimit, initCost) override def withExtension(newExtension: ContextExtension): ErgoLikeContext = new ErgoLikeContext( - currentHeight, lastBlockUtxoRoot, minerPubkey, headers, preHeader, - dataBoxes, boxesToSpend, spendingTransaction, self, newExtension, validationSettings, costLimit, initCost) + lastBlockUtxoRoot, headers, preHeader, + dataBoxes, boxesToSpend, spendingTransaction, selfIndex, newExtension, validationSettings, costLimit, initCost) def withTransaction(newSpendingTransaction: ErgoLikeTransactionTemplate[_ <: UnsignedInput]): ErgoLikeContext = new ErgoLikeContext( - currentHeight, lastBlockUtxoRoot, minerPubkey, headers, preHeader, - dataBoxes, boxesToSpend, newSpendingTransaction, self, extension, validationSettings, costLimit, initCost) + lastBlockUtxoRoot, headers, preHeader, + dataBoxes, boxesToSpend, newSpendingTransaction, selfIndex, extension, validationSettings, costLimit, initCost) - import ErgoLikeContext._ - import Evaluation._ override def toSigmaContext(IR: Evaluation, isCost: Boolean, extensions: Map[Byte, AnyValue] = Map()): sigma.Context = { implicit val IRForBox: Evaluation = IR + import Evaluation._ + + def contextVars(m: Map[Byte, AnyValue])(implicit IR: Evaluation): Coll[AnyValue] = { + val maxKey = if (m.keys.isEmpty) 0 else m.keys.max + val res = new Array[AnyValue](maxKey + 1) + for ((id, v) <- m) { + res(id) = v + } + IR.sigmaDslBuilderValue.Colls.fromArray(res) + } + val dataInputs = this.dataBoxes.toArray.map(_.toTestBox(isCost)).toColl val inputs = boxesToSpend.toArray.map(_.toTestBox(isCost)).toColl - val outputs = if (spendingTransaction == null) - noOutputs.toColl - else - spendingTransaction.outputs.toArray.map(_.toTestBox(isCost)).toColl + /* NOHF PROOF: + Changed: removed check for spendingTransaction == null + Motivation: spendingTransaction cannot be null + Safety: in ergo spendingTransaction cannot be null + Examined ergo code: all that leads to ErgoLikeContext creation. + */ + val outputs = spendingTransaction.outputs.toArray.map(_.toTestBox(isCost)).toColl val varMap = extension.values.mapValues { case v: EvaluatedValue[_] => val tVal = stypeToRType[SType](v.tpe) toAnyValue(v.value.asWrappedType)(tVal) } val vars = contextVars(varMap ++ extensions) val avlTree = CAvlTree(lastBlockUtxoRoot) - new CostingDataContext( - dataInputs, headers, preHeader, inputs, outputs, currentHeight, self.toTestBox(isCost), avlTree, - minerPubkey.toColl, - vars, - isCost) + CostingDataContext( + dataInputs, headers, preHeader, inputs, outputs, preHeader.height, boxesToSpend(selfIndex).toTestBox(isCost), avlTree, + preHeader.minerPk.getEncoded, vars, isCost) } -} - -object ErgoLikeContext { - type Height = Int - val dummyPubkey: Array[Byte] = Array.fill(32)(0: Byte) + override def equals(other: Any): Boolean = other match { + case that: ErgoLikeContext => + (that canEqual this) && + lastBlockUtxoRoot == that.lastBlockUtxoRoot && + headers == that.headers && + preHeader == that.preHeader && + dataBoxes == that.dataBoxes && + boxesToSpend == that.boxesToSpend && + spendingTransaction == that.spendingTransaction && + selfIndex == that.selfIndex && + extension == that.extension && + validationSettings == that.validationSettings && + costLimit == that.costLimit && + initCost == that.initCost + case _ => false + } - val noBoxes = IndexedSeq.empty[ErgoBox] - val noHeaders = CostingSigmaDslBuilder.Colls.emptyColl[Header] - val dummyPreHeader: PreHeader = null + def canEqual(other: Any): Boolean = other.isInstanceOf[ErgoLikeContext] - /** Maximimum number of headers in `headers` collection of the context. */ - val MaxHeaders = ErgoConstants.MaxHeaders.value - - def apply(currentHeight: Height, - lastBlockUtxoRoot: AvlTreeData, - minerPubkey: Array[Byte], - boxesToSpend: IndexedSeq[ErgoBox], - spendingTransaction: ErgoLikeTransactionTemplate[_ <: UnsignedInput], - self: ErgoBox, - extension: ContextExtension = ContextExtension.empty, - vs: SigmaValidationSettings = ValidationRules.currentSettings) = - new ErgoLikeContext(currentHeight, lastBlockUtxoRoot, minerPubkey, - noHeaders, - dummyPreHeader, - noBoxes, - boxesToSpend, spendingTransaction, self, extension, vs, ScriptCostLimit.value, 0L) - - def apply(currentHeight: Height, - lastBlockUtxoRoot: AvlTreeData, - minerPubkey: Array[Byte], - dataBoxes: IndexedSeq[ErgoBox], - boxesToSpend: IndexedSeq[ErgoBox], - spendingTransaction: ErgoLikeTransactionTemplate[_ <: UnsignedInput], - self: ErgoBox) = - new ErgoLikeContext(currentHeight, lastBlockUtxoRoot, minerPubkey, - noHeaders, - dummyPreHeader, - dataBoxes, boxesToSpend, spendingTransaction, self, ContextExtension.empty, ValidationRules.currentSettings, ScriptCostLimit.value, 0L) - - - def dummy(selfDesc: ErgoBox) = ErgoLikeContext(currentHeight = 0, - lastBlockUtxoRoot = AvlTreeData.dummy, dummyPubkey, boxesToSpend = IndexedSeq(selfDesc), - spendingTransaction = null, self = selfDesc) - - def fromTransaction(tx: ErgoLikeTransaction, - blockchainState: BlockchainState, - boxesReader: ErgoBoxReader, - inputIndex: Int): Try[ErgoLikeContext] = Try { - - val boxes = tx.inputs.map(_.boxId).map(id => boxesReader.byId(id).get) - - val proverExtension = tx.inputs(inputIndex).spendingProof.extension - - ErgoLikeContext(blockchainState.currentHeight, - blockchainState.lastBlockUtxoRoot, - dummyPubkey, - boxes, - tx, - boxes(inputIndex), - proverExtension) + override def hashCode(): Int = { + val state = Array(lastBlockUtxoRoot, headers, preHeader, dataBoxes, boxesToSpend, spendingTransaction, selfIndex, extension, validationSettings, costLimit, initCost) + var hashCode = 0 + cfor(0)(_ < state.length, _ + 1) { i => + hashCode = 31 * hashCode + state(i).hashCode + } + hashCode } - val noInputs: Array[Box] = Array[Box]() - val noOutputs: Array[Box] = Array[Box]() + override def toString = s"ErgoLikeContext(lastBlockUtxoRoot=$lastBlockUtxoRoot, headers=$headers, preHeader=$preHeader, dataBoxes=$dataBoxes, boxesToSpend=$boxesToSpend, spendingTransaction=$spendingTransaction, selfIndex=$selfIndex, extension=$extension, validationSettings=$validationSettings, costLimit=$costLimit, initCost=$initCost)" +} - import special.sigma._ +object ErgoLikeContext { - def contextVars(m: Map[Byte, AnyValue])(implicit IR: Evaluation): Coll[AnyValue] = { - val maxKey = if (m.keys.isEmpty) 0 else m.keys.max - val res = new Array[AnyValue](maxKey + 1) - for ((id, v) <- m) { - assert(res(id) == null, s"register $id is defined more then once") - res(id) = v - } - IR.sigmaDslBuilderValue.Colls.fromArray(res) - } + type Height = Int - implicit class ErgoBoxOps(val ebox: ErgoBox) extends AnyVal { - def toTestBox(isCost: Boolean): Box = { - if (ebox == null) return null - new CostingBox(isCost, ebox) - } - } + /** Maximimum number of headers in `headers` collection of the context. */ + val MaxHeaders = SigmaConstants.MaxHeaders.value } /** When interpreted evaluates to a ByteArrayConstant built from Context.minerPubkey */ @@ -237,7 +229,7 @@ case object LastBlockUtxoRootHash extends NotReadyValueAvlTree with ValueCompani } -/** When interpreted evaluates to a BoxConstant built from Context.self */ +/** When interpreted evaluates to a BoxConstant built from context.boxesToSpend(context.selfIndex) */ case object Self extends NotReadyValueBox with ValueCompanion { override def companion = this override def opCode: OpCode = OpCodes.SelfCode diff --git a/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala b/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala index 91d5c5622d..7deda754c0 100644 --- a/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala +++ b/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala @@ -13,7 +13,7 @@ class ErgoLikeInterpreter(implicit val IR: IRContext) extends Interpreter { override def substDeserialize(context: CTX, updateContext: CTX => Unit, node: SValue): Option[SValue] = node match { case d: DeserializeRegister[_] => - context.self.get(d.reg).flatMap { v => + context.boxesToSpend(context.selfIndex).get(d.reg).flatMap { v => v match { case eba: EvaluatedValue[SByteArray]@unchecked => val (ctx1, outVal) = deserializeMeasured(context, eba.value.toArray) diff --git a/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala b/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala index 2c1bb71edf..4b1f9aee38 100644 --- a/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala +++ b/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala @@ -1,21 +1,20 @@ package org.ergoplatform -import java.util - import org.ergoplatform.ErgoBox.TokenId import scorex.crypto.authds.ADKey import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util._ +import sigmastate.SType._ +import sigmastate.eval.Extensions._ +import sigmastate.eval._ import sigmastate.interpreter.ProverResult import sigmastate.serialization.SigmaSerializer import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import special.collection.ExtensionMethods._ -import sigmastate.eval.Extensions._ import spire.syntax.all.cfor + import scala.collection.mutable import scala.util.Try -import sigmastate.SType._ -import sigmastate.eval._ trait ErgoBoxReader { def byId(boxId: ADKey): Try[ErgoBox] @@ -50,6 +49,8 @@ trait ErgoLikeTransactionTemplate[IT <: UnsignedInput] { lazy val messageToSign: Array[Byte] = ErgoLikeTransaction.bytesToSign(this) lazy val inputIds: IndexedSeq[ADKey] = inputs.map(_.boxId) + + override def toString = s"ErgoLikeTransactionTemplate(dataInputs=$dataInputs, inputs=$inputs, outputCandidates=$outputCandidates)" } @@ -68,6 +69,13 @@ class UnsignedErgoLikeTransaction(override val inputs: IndexedSeq[UnsignedInput] val ins = inputs.zip(proofs).map { case (ui, proof) => Input(ui.boxId, proof) } new ErgoLikeTransaction(ins, dataInputs, outputCandidates) } + + override def equals(obj: Any): Boolean = obj match { + case tx: UnsignedErgoLikeTransaction => this.id == tx.id + case _ => false + } + + override def hashCode(): Int = id.hashCode() } object UnsignedErgoLikeTransaction { @@ -189,5 +197,4 @@ object ErgoLikeTransaction { // TODO unify serialization approach in Ergo/sigma with BytesSerializable val serializer: SigmaSerializer[ErgoLikeTransaction, ErgoLikeTransaction] = ErgoLikeTransactionSerializer - } diff --git a/src/main/scala/org/ergoplatform/Input.scala b/src/main/scala/org/ergoplatform/Input.scala index 6d76934855..d8bd8c6d1d 100644 --- a/src/main/scala/org/ergoplatform/Input.scala +++ b/src/main/scala/org/ergoplatform/Input.scala @@ -3,18 +3,27 @@ package org.ergoplatform import java.util import org.ergoplatform.ErgoBox.BoxId +import org.ergoplatform.settings.ErgoAlgos import scorex.crypto.authds.ADKey -import scorex.util.encode.Base16 import sigmastate.interpreter.{ContextExtension, ProverResult} import sigmastate.serialization.SigmaSerializer -import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} +import sigmastate.utils.{Helpers, SigmaByteReader, SigmaByteWriter} /** * Inputs, that are used to enrich script context, but won't be spent by the transaction * * @param boxId - id of a box to add into context (should be in UTXO) */ -case class DataInput(boxId: BoxId) +case class DataInput(boxId: BoxId) { + override def toString: String = s"DataInput(${ErgoAlgos.encode(boxId)})" + + override def equals(obj: Any): Boolean = obj match { + case x: DataInput => util.Arrays.equals(boxId, x.boxId) + case _ => false + } + + override def hashCode(): Int = Helpers.deepHashCode(boxId) +} /** * Inputs of formed, but unsigned transaction @@ -34,6 +43,8 @@ class UnsignedInput(val boxId: BoxId, val extension: ContextExtension) { case _ => false } + override def hashCode(): Int = Helpers.deepHashCode(boxId) + /** * Input, that should be signed by prover and verified by verifier. * Contains all the input data except of signature itself. @@ -49,7 +60,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(${Base16.encode(boxId)},$spendingProof)" + override def toString: String = s"Input(${ErgoAlgos.encode(boxId)},$spendingProof)" } object Input { diff --git a/src/main/scala/org/ergoplatform/JsonCodecs.scala b/src/main/scala/org/ergoplatform/JsonCodecs.scala new file mode 100644 index 0000000000..10dd58bff8 --- /dev/null +++ b/src/main/scala/org/ergoplatform/JsonCodecs.scala @@ -0,0 +1,417 @@ +package org.ergoplatform + +import java.math.BigInteger + +import cats.syntax.either._ +import io.circe._ +import io.circe.syntax._ +import org.ergoplatform.ErgoBox.{BoxId, NonMandatoryRegisterId, TokenId} +import org.ergoplatform.settings.ErgoAlgos +import org.ergoplatform.validation.{SigmaValidationSettings, SigmaValidationSettingsSerializer} +import scorex.crypto.authds.{ADDigest, ADKey} +import scorex.crypto.hash.Digest32 +import scorex.util.ModifierId +import sigmastate.Values.{ErgoTree, EvaluatedValue} +import sigmastate.eval.Extensions._ +import sigmastate.eval.{CGroupElement, CPreHeader, WrapperOf, _} +import sigmastate.interpreter.{ContextExtension, ProverResult} +import sigmastate.lang.exceptions.SigmaException +import sigmastate.serialization.{ErgoTreeSerializer, ValueSerializer} +import sigmastate.{AvlTreeData, AvlTreeFlags, SType} +import special.collection.Coll +import special.sigma.{Header, PreHeader} + +import scala.util.Try + +trait JsonCodecs { + + def fromTry[T](tryResult: Try[T])(implicit cursor: ACursor): Either[DecodingFailure, T] = { + tryResult.fold(e => Left(DecodingFailure(e.toString, cursor.history)), Right.apply) + } + + def fromOption[T](maybeResult: Option[T])(implicit cursor: ACursor): Either[DecodingFailure, T] = { + maybeResult.fold[Either[DecodingFailure, T]](Left(DecodingFailure("No value found", cursor.history)))(Right.apply) + } + + def fromThrows[T](throwsBlock: => T)(implicit cursor: ACursor): Either[DecodingFailure, T] = { + Either.catchNonFatal(throwsBlock).leftMap(e => DecodingFailure(e.toString, cursor.history)) + } + + private def bytesDecoder[T](transform: Array[Byte] => T): Decoder[T] = { implicit cursor => + for { + str <- cursor.as[String] + bytes <- fromTry(ErgoAlgos.decode(str)) + } yield transform(bytes) + } + + implicit val sigmaBigIntEncoder: Encoder[special.sigma.BigInt] = { bigInt => + JsonNumber.fromDecimalStringUnsafe(bigInt.asInstanceOf[WrapperOf[BigInteger]].wrappedValue.toString).asJson + } + + implicit val sigmaBigIntDecoder: Decoder[special.sigma.BigInt] = { implicit cursor => + for { + jsonNumber <- cursor.as[JsonNumber] + bigInt <- fromOption(jsonNumber.toBigInt) + } yield CBigInt(bigInt.bigInteger) + } + + implicit val arrayBytesEncoder: Encoder[Array[Byte]] = ErgoAlgos.encode(_).asJson + implicit val arrayBytesDecoder: Decoder[Array[Byte]] = bytesDecoder(x => x) + + implicit val collBytesEncoder: Encoder[Coll[Byte]] = ErgoAlgos.encode(_).asJson + implicit val collBytesDecoder: Decoder[Coll[Byte]] = bytesDecoder(Colls.fromArray(_)) + + implicit val adKeyEncoder: Encoder[ADKey] = _.array.asJson + implicit val adKeyDecoder: Decoder[ADKey] = bytesDecoder(ADKey @@ _) + + implicit val adDigestEncoder: Encoder[ADDigest] = _.array.asJson + implicit val adDigestDecoder: Decoder[ADDigest] = bytesDecoder(ADDigest @@ _) + + implicit val digest32Encoder: Encoder[Digest32] = _.array.asJson + implicit val digest32Decoder: Decoder[Digest32] = bytesDecoder(Digest32 @@ _) + + implicit val assetEncoder: Encoder[(TokenId, Long)] = { asset => + Json.obj( + "tokenId" -> asset._1.asJson, + "amount" -> asset._2.asJson + ) + } + + implicit val assetDecoder: Decoder[(TokenId, Long)] = { cursor => + for { + tokenId <- cursor.downField("tokenId").as[TokenId] + amount <- cursor.downField("amount").as[Long] + } yield (tokenId, amount) + } + + implicit val modifierIdEncoder: Encoder[ModifierId] = _.asInstanceOf[String].asJson + implicit val modifierIdDecoder: Decoder[ModifierId] = ModifierId @@ _.as[String] + + implicit val registerIdEncoder: KeyEncoder[NonMandatoryRegisterId] = { regId => + s"R${regId.number}" + } + + implicit val registerIdDecoder: KeyDecoder[NonMandatoryRegisterId] = { key => + ErgoBox.registerByName.get(key).collect { + case nonMandatoryId: NonMandatoryRegisterId => nonMandatoryId + } + } + + implicit val headerEncoder: Encoder[Header] = { h: Header => + Map( + "id" -> h.id.asJson, + "version" -> h.version.asJson, + "parentId" -> h.parentId.asJson, + "adProofsRoot" -> h.ADProofsRoot.asJson, + "stateRoot" -> SigmaDsl.toAvlTreeData(h.stateRoot).asJson, + "transactionsRoot" -> h.transactionsRoot.asJson, + "timestamp" -> h.timestamp.asJson, + "nBits" -> h.nBits.asJson, + "height" -> h.height.asJson, + "extensionRoot" -> h.extensionRoot.asJson, + "minerPk" -> h.minerPk.getEncoded.asJson, + "powOnetimePk" -> h.powOnetimePk.getEncoded.asJson, + "powNonce" -> h.powNonce.asJson, + "powDistance" -> h.powDistance.asJson, + "votes" -> h.votes.asJson + ).asJson + } + + implicit val headerDecoder: Decoder[Header] = { cursor => + for { + id <- cursor.downField("id").as[Coll[Byte]] + version <- cursor.downField("version").as[Byte] + parentId <- cursor.downField("parentId").as[Coll[Byte]] + adProofsRoot <- cursor.downField("adProofsRoot").as[Coll[Byte]] + stateRoot <- cursor.downField("stateRoot").as[AvlTreeData] + transactionsRoot <- cursor.downField("transactionsRoot").as[Coll[Byte]] + timestamp <- cursor.downField("timestamp").as[Long] + nBits <- cursor.downField("nBits").as[Long] + height <- cursor.downField("height").as[Int] + extensionRoot <- cursor.downField("extensionRoot").as[Coll[Byte]] + minerPk <- cursor.downField("minerPk").as[Coll[Byte]] + powOnetimePk <- cursor.downField("powOnetimePk").as[Coll[Byte]] + powNonce <- cursor.downField("powNonce").as[Coll[Byte]] + powDistance <- cursor.downField("powDistance").as[special.sigma.BigInt] + votes <- cursor.downField("votes").as[Coll[Byte]] + } yield new CHeader(id, version, parentId, adProofsRoot, stateRoot, transactionsRoot, timestamp, nBits, + height, extensionRoot, SigmaDsl.decodePoint(minerPk), SigmaDsl.decodePoint(powOnetimePk), powNonce, powDistance, votes) + } + + implicit val preHeaderEncoder: Encoder[PreHeader] = { v: PreHeader => + Map( + "version" -> v.version.asJson, + "parentId" -> v.parentId.asJson, + "timestamp" -> v.timestamp.asJson, + "nBits" -> v.nBits.asJson, + "height" -> v.height.asJson, + "minerPk" -> v.minerPk.getEncoded.asJson, + "votes" -> v.votes.asJson + ).asJson + } + + implicit val preHeaderDecoder: Decoder[PreHeader] = { cursor => + for { + version <- cursor.downField("version").as[Byte] + parentId <- cursor.downField("parentId").as[Coll[Byte]] + timestamp <- cursor.downField("timestamp").as[Long] + nBits <- cursor.downField("nBits").as[Long] + height <- cursor.downField("height").as[Int] + minerPk <- cursor.downField("minerPk").as[Coll[Byte]] + votes <- cursor.downField("votes").as[Coll[Byte]] + } yield CPreHeader(version, parentId, timestamp, nBits, height, SigmaDsl.decodePoint(minerPk), votes) + } + + implicit val evaluatedValueEncoder: Encoder[EvaluatedValue[_ <: SType]] = { value => + ValueSerializer.serialize(value).asJson + } + + implicit val evaluatedValueDecoder: Decoder[EvaluatedValue[_ <: SType]] = { + decodeEvaluatedValue(_.asInstanceOf[EvaluatedValue[SType]]) + } + + def decodeEvaluatedValue[T](transform: EvaluatedValue[SType] => T): Decoder[T] = { implicit cursor: ACursor => + cursor.as[Array[Byte]] flatMap { bytes => + fromThrows(transform(ValueSerializer.deserialize(bytes).asInstanceOf[EvaluatedValue[SType]])) + } + } + + implicit val dataInputEncoder: Encoder[DataInput] = { input => + Json.obj( + "boxId" -> input.boxId.asJson, + ) + } + + implicit val dataInputDecoder: Decoder[DataInput] = { cursor => + for { + boxId <- cursor.downField("boxId").as[ADKey] + } yield DataInput(boxId) + } + + implicit val inputEncoder: Encoder[Input] = { input => + Json.obj( + "boxId" -> input.boxId.asJson, + "spendingProof" -> input.spendingProof.asJson + ) + } + + + implicit val inputDecoder: Decoder[Input] = { cursor => + for { + boxId <- cursor.downField("boxId").as[ADKey] + proof <- cursor.downField("spendingProof").as[ProverResult] + } yield Input(boxId, proof) + } + + implicit val unsignedInputEncoder: Encoder[UnsignedInput] = { input => + Json.obj( + "boxId" -> input.boxId.asJson, + "extension" -> input.extension.asJson + ) + } + + implicit val unsignedInputDecoder: Decoder[UnsignedInput] = { cursor => + for { + boxId <- cursor.downField("boxId").as[ADKey] + extension <- cursor.downField("extension").as[ContextExtension] + } yield new UnsignedInput(boxId, extension) + } + + implicit val contextExtensionEncoder: Encoder[ContextExtension] = { extension => + extension.values.map { case (key, value) => + key -> evaluatedValueEncoder(value) + }.asJson + } + + implicit val contextExtensionDecoder: Decoder[ContextExtension] = { cursor => + for { + values <- cursor.as[Map[Byte, EvaluatedValue[SType]]] + } yield ContextExtension(values) + } + + implicit val proverResultEncoder: Encoder[ProverResult] = { v => + Json.obj( + "proofBytes" -> v.proof.asJson, + "extension" -> v.extension.asJson + ) + } + + implicit val proverResultDecoder: Decoder[ProverResult] = { cursor => + for { + proofBytes <- cursor.downField("proofBytes").as[Array[Byte]] + extMap <- cursor.downField("extension").as[Map[Byte, EvaluatedValue[SType]]] + } yield ProverResult(proofBytes, ContextExtension(extMap)) + } + + + implicit val avlTreeDataEncoder: Encoder[AvlTreeData] = { v => + Json.obj( + "digest" -> v.digest.asJson, + "treeFlags" -> v.treeFlags.serializeToByte.asJson, + "keyLength" -> v.keyLength.asJson, + "valueLength" -> v.valueLengthOpt.asJson + ) + } + + implicit val avlTreeDataDecoder: Decoder[AvlTreeData] = { cursor => + for { + digest <- cursor.downField("digest").as[ADDigest] + treeFlagsByte <- cursor.downField("treeFlags").as[Byte] + keyLength <- cursor.downField("keyLength").as[Int] + valueLength <- cursor.downField("valueLength").as[Option[Int]] + } yield new AvlTreeData(digest, AvlTreeFlags(treeFlagsByte), keyLength, valueLength) + } + + implicit val ergoTreeEncoder: Encoder[ErgoTree] = { value => + ErgoTreeSerializer.DefaultSerializer.serializeErgoTree(value).asJson + } + + def decodeErgoTree[T](transform: ErgoTree => T): Decoder[T] = { implicit cursor: ACursor => + cursor.as[Array[Byte]] flatMap { bytes => + fromThrows(transform(ErgoTreeSerializer.DefaultSerializer.deserializeErgoTree(bytes))) + } + } + + implicit val ergoTreeDecoder: Decoder[ErgoTree] = { + decodeErgoTree(_.asInstanceOf[ErgoTree]) + } + + implicit def registersEncoder[T <: EvaluatedValue[_ <: SType]]: Encoder[Map[NonMandatoryRegisterId, T]] = { m => + Json.obj( + m.toSeq + .sortBy(_._1.number) + .map { case (k, v) => registerIdEncoder(k) -> evaluatedValueEncoder(v) }: _*) + } + + implicit val ergoBoxEncoder: Encoder[ErgoBox] = { box => + Json.obj( + "boxId" -> box.id.asJson, + "value" -> box.value.asJson, + "ergoTree" -> ErgoTreeSerializer.DefaultSerializer.serializeErgoTree(box.ergoTree).asJson, + "assets" -> box.additionalTokens.toArray.toSeq.asJson, + "creationHeight" -> box.creationHeight.asJson, + "additionalRegisters" -> box.additionalRegisters.asJson, + "transactionId" -> box.transactionId.asJson, + "index" -> box.index.asJson + ) + } + + implicit val ergoBoxDecoder: Decoder[ErgoBox] = { cursor => + for { + value <- cursor.downField("value").as[Long] + ergoTreeBytes <- cursor.downField("ergoTree").as[Array[Byte]] + additionalTokens <- cursor.downField("assets").as(Decoder.decodeSeq(assetDecoder)) + creationHeight <- cursor.downField("creationHeight").as[Int] + additionalRegisters <- cursor.downField("additionalRegisters").as[Map[NonMandatoryRegisterId, EvaluatedValue[SType]]] + transactionId <- cursor.downField("transactionId").as[ModifierId] + index <- cursor.downField("index").as[Short] + } yield new ErgoBox( + value = value, + ergoTree = ErgoTreeSerializer.DefaultSerializer.deserializeErgoTree(ergoTreeBytes), + additionalTokens = additionalTokens.toColl, + additionalRegisters = additionalRegisters, + transactionId = transactionId, + index = index, + creationHeight = creationHeight + ) + } + + implicit val ergoLikeTransactionEncoder: Encoder[ErgoLikeTransaction] = { tx => + Json.obj( + "id" -> tx.id.asJson, + "inputs" -> tx.inputs.asJson, + "dataInputs" -> tx.dataInputs.asJson, + "outputs" -> tx.outputs.asJson + ) + } + + implicit val unsignedErgoLikeTransactionEncoder: Encoder[UnsignedErgoLikeTransaction] = { tx => + Json.obj( + "id" -> tx.id.asJson, + "inputs" -> tx.inputs.asJson, + "dataInputs" -> tx.dataInputs.asJson, + "outputs" -> tx.outputs.asJson + ) + } + + implicit def ergoLikeTransactionTemplateEncoder[T <: UnsignedInput]: Encoder[ErgoLikeTransactionTemplate[T]] = { + case transaction: ErgoLikeTransaction => ergoLikeTransactionEncoder(transaction) + case transaction: UnsignedErgoLikeTransaction => unsignedErgoLikeTransactionEncoder(transaction) + case t => throw new SigmaException(s"Don't know how to encode transaction $t") + } + + implicit val transactionOutputsDecoder: Decoder[(ErgoBoxCandidate, Option[BoxId])] = { cursor => + for { + maybeId <- cursor.downField("boxId").as[Option[BoxId]] + value <- cursor.downField("value").as[Long] + creationHeight <- cursor.downField("creationHeight").as[Int] + ergoTree <- cursor.downField("ergoTree").as[ErgoTree] + assets <- cursor.downField("assets").as[Seq[(ErgoBox.TokenId, Long)]] // TODO optimize: encode directly into Coll avoiding allocation of Tuple2 for each element + registers <- cursor.downField("additionalRegisters").as[Map[NonMandatoryRegisterId, EvaluatedValue[SType]]] + } yield (new ErgoBoxCandidate(value, ergoTree, creationHeight, assets.toColl, registers), maybeId) + } + + implicit val ergoLikeTransactionDecoder: Decoder[ErgoLikeTransaction] = { implicit cursor => + for { + inputs <- cursor.downField("inputs").as[IndexedSeq[Input]] + dataInputs <- cursor.downField("dataInputs").as[IndexedSeq[DataInput]] + outputsWithIndex <- cursor.downField("outputs").as[IndexedSeq[(ErgoBoxCandidate, Option[BoxId])]] + } yield new ErgoLikeTransaction(inputs, dataInputs, outputsWithIndex.map(_._1)) + } + + implicit val unsignedErgoLikeTransactionDecoder: Decoder[UnsignedErgoLikeTransaction] = { implicit cursor => + for { + inputs <- cursor.downField("inputs").as[IndexedSeq[UnsignedInput]] + dataInputs <- cursor.downField("dataInputs").as[IndexedSeq[DataInput]] + outputsWithIndex <- cursor.downField("outputs").as[IndexedSeq[(ErgoBoxCandidate, Option[BoxId])]] + } yield new UnsignedErgoLikeTransaction(inputs, dataInputs, outputsWithIndex.map(_._1)) + } + + implicit val ergoLikeTransactionTemplateDecoder: Decoder[ErgoLikeTransactionTemplate[_ <: UnsignedInput]] = { + ergoLikeTransactionDecoder.asInstanceOf[Decoder[ErgoLikeTransactionTemplate[_ <: UnsignedInput]]] or + unsignedErgoLikeTransactionDecoder.asInstanceOf[Decoder[ErgoLikeTransactionTemplate[_ <: UnsignedInput]]] + } + + implicit val sigmaValidationSettingsEncoder: Encoder[SigmaValidationSettings] = { v => + SigmaValidationSettingsSerializer.toBytes(v).asJson + } + + implicit val sigmaValidationSettingsDecoder: Decoder[SigmaValidationSettings] = { implicit cursor: ACursor => + cursor.as[Array[Byte]] flatMap { bytes => + fromThrows(SigmaValidationSettingsSerializer.fromBytes(bytes)) + } + } + + implicit val ergoLikeContextEncoder: Encoder[ErgoLikeContext] = { ctx => + Json.obj( + "lastBlockUtxoRoot" -> ctx.lastBlockUtxoRoot.asJson, + "headers" -> ctx.headers.toArray.toSeq.asJson, + "preHeader" -> ctx.preHeader.asJson, + "dataBoxes" -> ctx.dataBoxes.asJson, + "boxesToSpend" -> ctx.boxesToSpend.asJson, + "spendingTransaction" -> ctx.spendingTransaction.asJson, + "selfIndex" -> ctx.selfIndex.asJson, + "extension" -> ctx.extension.asJson, + "validationSettings" -> ctx.validationSettings.asJson, + "costLimit" -> ctx.costLimit.asJson, + "initCost" -> ctx.initCost.asJson + ) + } + + implicit val ergoLikeContextDecoder: Decoder[ErgoLikeContext] = { cursor => + for { + lastBlockUtxoRoot <- cursor.downField("lastBlockUtxoRoot").as[AvlTreeData] + headers <- cursor.downField("headers").as[Seq[Header]] + preHeader <- cursor.downField("preHeader").as[PreHeader] + dataBoxes <- cursor.downField("dataBoxes").as[IndexedSeq[ErgoBox]] + boxesToSpend <- cursor.downField("boxesToSpend").as[IndexedSeq[ErgoBox]] + spendingTransaction <- cursor.downField("spendingTransaction").as(ergoLikeTransactionTemplateDecoder) + selfIndex <- cursor.downField("selfIndex").as[Int] + extension <- cursor.downField("extension").as[ContextExtension] + validationSettings <- cursor.downField("validationSettings").as[SigmaValidationSettings] + costLimit <- cursor.downField("costLimit").as[Long] + initCost <- cursor.downField("initCost").as[Long] + } yield new ErgoLikeContext(lastBlockUtxoRoot, Colls.fromArray(headers.toArray), preHeader, + dataBoxes, boxesToSpend, spendingTransaction, selfIndex, extension, validationSettings, costLimit, initCost) + } +} diff --git a/src/main/scala/org/ergoplatform/ErgoConstants.scala b/src/main/scala/org/ergoplatform/SigmaConstants.scala similarity index 88% rename from src/main/scala/org/ergoplatform/ErgoConstants.scala rename to src/main/scala/org/ergoplatform/SigmaConstants.scala index aff3c56ce9..5f3c86adc5 100644 --- a/src/main/scala/org/ergoplatform/ErgoConstants.scala +++ b/src/main/scala/org/ergoplatform/SigmaConstants.scala @@ -14,7 +14,7 @@ case class SizeConstant[T: Numeric](value: T, id: Short, description: String) * but due to versioned execution, all versions of the values should be * available simultaneously. */ -object ErgoConstants { +object SigmaConstants { object MaxBoxSize extends SizeConstant[Int](4 * 1024, 1, "Box size should not be greater than provided value") { @@ -68,6 +68,14 @@ object ErgoConstants { "Maximum allowed loop level in a cost function") { } + object VotesArraySize extends SizeConstant[Int](3, 14, + "Size of of Header.votes array") { + } + + object AutolykosPowSolutionNonceArraySize extends SizeConstant[Int](8, 15, + "size of nonce array from Autolykos POW solution in Header.powNonce array") { + } + val ConstTable: Seq[SizeConstant[_]] = { val rows = Seq( MaxBoxSize, @@ -82,7 +90,9 @@ object ErgoConstants { MaxHeaders, MaxChildrenCountForAtLeastOp, ScriptCostLimit, - MaxLoopLevelInCostFunction + MaxLoopLevelInCostFunction, + VotesArraySize, + AutolykosPowSolutionNonceArraySize ) require(rows.length == rows.distinctBy(_.id).length, s"Duplicate constant id in $rows") rows diff --git a/src/main/scala/org/ergoplatform/settings/ErgoAlgos.scala b/src/main/scala/org/ergoplatform/settings/ErgoAlgos.scala new file mode 100644 index 0000000000..624e713654 --- /dev/null +++ b/src/main/scala/org/ergoplatform/settings/ErgoAlgos.scala @@ -0,0 +1,24 @@ +package org.ergoplatform.settings + +import scorex.crypto.hash.Blake2b256 +import scorex.util._ +import special.collection.Coll + +import scala.util.Try + +trait ErgoAlgos extends ScorexEncoding { + + type HF = Blake2b256.type + + val hash: HF = Blake2b256 + + @inline def encode(bytes: Array[Byte]): String = encoder.encode(bytes) + + @inline def encode(bytes: Coll[Byte]): String = encoder.encode(bytes.toArray) + + @inline def decode(str: String): Try[Array[Byte]] = encoder.decode(str) + + @inline def decodeUnsafe(str: String): Array[Byte] = decode(str).get +} + +object ErgoAlgos extends ErgoAlgos diff --git a/src/main/scala/org/ergoplatform/validation/SigmaValidationSettings.scala b/src/main/scala/org/ergoplatform/validation/SigmaValidationSettings.scala index bb9a3508cd..e74e41c8c1 100644 --- a/src/main/scala/org/ergoplatform/validation/SigmaValidationSettings.scala +++ b/src/main/scala/org/ergoplatform/validation/SigmaValidationSettings.scala @@ -37,6 +37,7 @@ package org.ergoplatform.validation * when isSoftFork returns true), for example when a new opCode is added in the * newer version of the protocol, and this fact can be recognized by the old * code. + * * @see SoftForkWhenCodeAdded */ abstract class SigmaValidationSettings extends Iterable[(Short, (ValidationRule, RuleStatus))] { diff --git a/src/main/scala/org/ergoplatform/validation/ValidationRules.scala b/src/main/scala/org/ergoplatform/validation/ValidationRules.scala index 3378d87194..deb793a81e 100644 --- a/src/main/scala/org/ergoplatform/validation/ValidationRules.scala +++ b/src/main/scala/org/ergoplatform/validation/ValidationRules.scala @@ -3,18 +3,18 @@ package org.ergoplatform.validation import java.nio.ByteBuffer import java.util -import org.ergoplatform.ErgoConstants.MaxLoopLevelInCostFunction +import org.ergoplatform.SigmaConstants.MaxLoopLevelInCostFunction import scorex.util.ByteArrayBuilder import scorex.util.serialization.{VLQByteBufferReader, VLQByteBufferWriter} import sigma.util.Extensions.toUByte +import sigmastate.Values.{ErgoTree, IntValue, SValue, Value} +import sigmastate._ import sigmastate.eval.IRContext -import sigmastate.serialization.OpCodes.{OpCodeExtra, OpCode} -import sigmastate.Values.{Value, ErgoTree, SValue, IntValue} -import sigmastate.serialization.{ValueSerializer, OpCodes} -import sigmastate.utxo.DeserializeContext import sigmastate.lang.exceptions._ +import sigmastate.serialization.OpCodes.{OpCode, OpCodeExtra} import sigmastate.serialization.TypeSerializer.embeddableIdToType -import sigmastate._ +import sigmastate.serialization.{OpCodes, ValueSerializer} +import sigmastate.utxo.DeserializeContext import scala.collection.mutable diff --git a/src/main/scala/sigmastate/AvlTreeData.scala b/src/main/scala/sigmastate/AvlTreeData.scala index ac89c070f2..87adf2fb2a 100644 --- a/src/main/scala/sigmastate/AvlTreeData.scala +++ b/src/main/scala/sigmastate/AvlTreeData.scala @@ -1,7 +1,8 @@ package sigmastate import java.util -import java.util.{Objects, Arrays} +import java.util.{Arrays, Objects} + import scorex.crypto.authds.ADDigest import sigmastate.interpreter.CryptoConstants import sigmastate.serialization.SigmaSerializer @@ -97,5 +98,4 @@ object AvlTreeData { AvlTreeData(ADDigest @@ digest, tf, keyLength, valueLengthOpt) } } - } diff --git a/src/main/scala/sigmastate/eval/CostingDataContext.scala b/src/main/scala/sigmastate/eval/CostingDataContext.scala index 4e5641af19..ab7156a562 100644 --- a/src/main/scala/sigmastate/eval/CostingDataContext.scala +++ b/src/main/scala/sigmastate/eval/CostingDataContext.scala @@ -4,27 +4,28 @@ import java.math.BigInteger import java.util import org.bouncycastle.math.ec.ECPoint -import org.ergoplatform.ErgoBox +import org.ergoplatform.{ErgoBox, SigmaConstants} import org.ergoplatform.validation.ValidationRules import scorex.crypto.authds.avltree.batch._ -import scorex.crypto.authds.{ADDigest, ADKey, SerializedAdProof, ADValue} +import scorex.crypto.authds.{ADDigest, ADKey, ADValue, SerializedAdProof} import sigmastate.SCollection.SByteArray import sigmastate.{TrivialProp, _} -import sigmastate.Values.{Constant, EvaluatedValue, SValue, ConstantNode, Value, ErgoTree, SigmaBoolean} +import sigmastate.Values.{Constant, ConstantNode, ErgoTree, EvaluatedValue, SValue, SigmaBoolean, Value} import sigmastate.interpreter.CryptoConstants.EcPointType import sigmastate.interpreter.{CryptoConstants, Interpreter} -import special.collection.{Size, CSizeOption, SizeColl, CCostedBuilder, CollType, SizeOption, CostedBuilder, Coll} +import special.collection.{CCostedBuilder, CSizeOption, Coll, CollType, CostedBuilder, Size, SizeColl, SizeOption} import special.sigma.{Box, _} import sigmastate.eval.Extensions._ import spire.syntax.all.cfor -import scala.util.{Success, Failure} + +import scala.util.{Failure, Success} import scalan.RType -import scorex.crypto.hash.{Digest32, Sha256, Blake2b256} +import scorex.crypto.hash.{Blake2b256, Digest32, Sha256} import sigmastate.basics.DLogProtocol.ProveDlog import sigmastate.basics.ProveDHTuple import sigmastate.lang.Terms.OperationId import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.serialization.{SigmaSerializer, GroupElementSerializer} +import sigmastate.serialization.{GroupElementSerializer, SigmaSerializer} import special.Types.TupleType import scala.reflect.ClassTag @@ -429,6 +430,11 @@ case class CHeader( ) extends Header { } +object CHeader { + val VotesSize: Int = SigmaConstants.VotesArraySize.value + val NonceSize: Int = SigmaConstants.AutolykosPowSolutionNonceArraySize.value +} + class CCostModel extends CostModel { private def costOf(opName: String, opType: SFunc): Int = { val operId = OperationId(opName, opType) diff --git a/src/main/scala/sigmastate/eval/CostingRules.scala b/src/main/scala/sigmastate/eval/CostingRules.scala index a38d8176b8..3df3c9f14f 100644 --- a/src/main/scala/sigmastate/eval/CostingRules.scala +++ b/src/main/scala/sigmastate/eval/CostingRules.scala @@ -1,7 +1,7 @@ package sigmastate.eval -import org.ergoplatform.ErgoConstants.{MaxBoxSize, MaxBoxSizeWithoutRefs, MaxPropositionBytes} -import org.ergoplatform.{ErgoLikeContext, ErgoConstants} +import org.ergoplatform.SigmaConstants.{MaxBoxSize, MaxBoxSizeWithoutRefs, MaxPropositionBytes} +import org.ergoplatform.{ErgoLikeContext, SigmaConstants} import scalan.{SigmaLibrary, MutableLazy} import sigmastate._ import sigmastate.interpreter.CryptoConstants @@ -166,7 +166,7 @@ trait CostingRules extends SigmaLibrary { IR: RuntimeCosting => val HeadersInfo = new KnownCollInfo(ErgoLikeContext.MaxHeaders, costedBuilder.mkSizePrim(Sized.SizeHeader.dataSize, element[Header])) - val TokensInfo = new KnownCollInfo(ErgoConstants.MaxTokens.value, + val TokensInfo = new KnownCollInfo(SigmaConstants.MaxTokens.value, mkSizePair(HashInfo.size, SizeLong)) diff --git a/src/main/scala/sigmastate/eval/Extensions.scala b/src/main/scala/sigmastate/eval/Extensions.scala index 4f343bbc79..627312cd3c 100644 --- a/src/main/scala/sigmastate/eval/Extensions.scala +++ b/src/main/scala/sigmastate/eval/Extensions.scala @@ -9,6 +9,7 @@ import sigmastate.lang.DefaultSigmaBuilder import special.collection.Coll import special.sigma._ import SType.AnyOps +import org.ergoplatform.ErgoBox import spire.syntax.all._ object Extensions { @@ -58,4 +59,17 @@ object Extensions { } def toAnyValue[A:RType](x: A) = new TestValue(x, RType[A].asInstanceOf[RType[Any]]) + + implicit class ErgoBoxOps(val ebox: ErgoBox) extends AnyVal { + def toTestBox(isCost: Boolean): Box = { + /* NOHF PROOF: + Changed: removed check for ebox == null + Motivation: box cannot be null + Safety: used in ErgoLikeContext where boxes cannot be null + Examined ergo code: all that leads to ErgoLikeContext creation. + */ + CostingBox(isCost, ebox) + } + } + } diff --git a/src/main/scala/sigmastate/eval/RuntimeCosting.scala b/src/main/scala/sigmastate/eval/RuntimeCosting.scala index 88f064bf1f..2d87f8d821 100644 --- a/src/main/scala/sigmastate/eval/RuntimeCosting.scala +++ b/src/main/scala/sigmastate/eval/RuntimeCosting.scala @@ -17,7 +17,7 @@ import sigmastate.utxo.CostTable.Cost import sigmastate.utxo._ import scalan.compilation.GraphVizConfig import SType._ -import org.ergoplatform.ErgoConstants._ +import org.ergoplatform.SigmaConstants._ import scalan.RType._ import scorex.crypto.hash.{Sha256, Blake2b256} import sigmastate.interpreter.Interpreter.ScriptEnv diff --git a/src/main/scala/sigmastate/eval/Sized.scala b/src/main/scala/sigmastate/eval/Sized.scala index c752747b15..5c006383d6 100644 --- a/src/main/scala/sigmastate/eval/Sized.scala +++ b/src/main/scala/sigmastate/eval/Sized.scala @@ -6,7 +6,7 @@ import scalan.RType._ import sigmastate._ import special.sigma._ import SType.AnyOps -import org.ergoplatform.ErgoConstants.{MaxBoxSize, MaxTokens} +import org.ergoplatform.SigmaConstants.{MaxBoxSize, MaxTokens} import sigmastate.interpreter.CryptoConstants /** Type-class to give types a capability to build a Size structure. */ diff --git a/src/main/scala/sigmastate/interpreter/CryptoFunctions.scala b/src/main/scala/sigmastate/interpreter/CryptoFunctions.scala index 0aa16f2480..008048605c 100644 --- a/src/main/scala/sigmastate/interpreter/CryptoFunctions.scala +++ b/src/main/scala/sigmastate/interpreter/CryptoFunctions.scala @@ -1,6 +1,5 @@ package sigmastate.interpreter -import org.bouncycastle.math.ec.ECPoint import scorex.crypto.hash.Blake2b256 object CryptoFunctions { @@ -10,10 +9,4 @@ object CryptoFunctions { Blake2b256.hash(input).take(soundnessBytes) } - def showECPoint(p: ECPoint): String = { - val rawX = p.getRawXCoord.toString.substring(0, 6) - val rawY = p.getRawYCoord.toString.substring(0, 6) - s"ECPoint($rawX,$rawY,...)" - } - } diff --git a/src/main/scala/sigmastate/interpreter/InterpreterContext.scala b/src/main/scala/sigmastate/interpreter/InterpreterContext.scala index 1cee748e6c..ea2470c0e7 100644 --- a/src/main/scala/sigmastate/interpreter/InterpreterContext.scala +++ b/src/main/scala/sigmastate/interpreter/InterpreterContext.scala @@ -37,7 +37,6 @@ object ContextExtension { ContextExtension(ext) } } - } diff --git a/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala b/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala index 557d2083a4..99b2f94903 100644 --- a/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala +++ b/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala @@ -6,8 +6,8 @@ import gf2t.{GF2_192, GF2_192_Poly} import org.bitbucket.inkytonik.kiama.attribution.AttributionCore import org.bitbucket.inkytonik.kiama.rewriting.Rewriter.{everywherebu, everywheretd, rule} import org.bitbucket.inkytonik.kiama.rewriting.Strategy +import org.ergoplatform.settings.ErgoAlgos import scalan.util.CollectionUtil._ -import scorex.util.encode.Base16 import sigmastate.Values._ import sigmastate._ import sigmastate.basics.DLogProtocol._ @@ -34,7 +34,7 @@ class ProverResult(val proof: Array[Byte], val extension: ContextExtension) { case _ => false } - override def toString: Idn = s"ProverResult(${Base16.encode(proof)},$extension)" + override def toString: Idn = s"ProverResult(${ErgoAlgos.encode(proof)},$extension)" } object ProverResult { @@ -58,7 +58,6 @@ object ProverResult { ProverResult(proofBytes, ce) } } - } case class CostedProverResult(override val proof: Array[Byte], diff --git a/src/main/scala/sigmastate/serialization/GroupElementSerializer.scala b/src/main/scala/sigmastate/serialization/GroupElementSerializer.scala index cb8adb79aa..4305e899c5 100644 --- a/src/main/scala/sigmastate/serialization/GroupElementSerializer.scala +++ b/src/main/scala/sigmastate/serialization/GroupElementSerializer.scala @@ -43,4 +43,6 @@ object GroupElementSerializer extends SigmaSerializer[EcPointType, EcPointType] } } + def parse(bytes: Array[Byte]): EcPointType = parse(SigmaSerializer.startReader(bytes)) + } diff --git a/src/main/scala/sigmastate/serialization/SigmaSerializer.scala b/src/main/scala/sigmastate/serialization/SigmaSerializer.scala index 38dfe22c0d..e9b306be84 100644 --- a/src/main/scala/sigmastate/serialization/SigmaSerializer.scala +++ b/src/main/scala/sigmastate/serialization/SigmaSerializer.scala @@ -2,7 +2,7 @@ package sigmastate.serialization import java.nio.ByteBuffer -import org.ergoplatform.ErgoConstants +import org.ergoplatform.SigmaConstants import org.ergoplatform.validation.SigmaValidationSettings import scorex.util.ByteArrayBuilder import sigmastate.lang.exceptions.SerializerException @@ -14,8 +14,8 @@ object SigmaSerializer { type Position = Int type Consumed = Int - val MaxPropositionSize: Int = ErgoConstants.MaxPropositionBytes.value - val MaxTreeDepth: Int = ErgoConstants.MaxTreeDepth.value + val MaxPropositionSize: Int = SigmaConstants.MaxPropositionBytes.value + val MaxTreeDepth: Int = SigmaConstants.MaxTreeDepth.value /** Helper function to be use in serializers. * Starting position is marked and then used to compute number of consumed bytes. @@ -84,6 +84,10 @@ trait SigmaSerializer[TFamily, T <: TFamily] extends Serializer[TFamily, T, Sigm serialize(obj, w) w.toBytes } + + final def fromBytes(bytes: Array[Byte]): TFamily = { + parse(SigmaSerializer.startReader(bytes)) + } } trait SigmaSerializerCompanion[TFamily] { diff --git a/src/main/scala/sigmastate/trees.scala b/src/main/scala/sigmastate/trees.scala index 6d7407f5b3..cbf2405069 100644 --- a/src/main/scala/sigmastate/trees.scala +++ b/src/main/scala/sigmastate/trees.scala @@ -1,6 +1,6 @@ package sigmastate -import org.ergoplatform.ErgoConstants +import org.ergoplatform.SigmaConstants import org.ergoplatform.validation.SigmaValidationSettings import scorex.crypto.hash.{Sha256, Blake2b256, CryptographicHash32} import sigmastate.Operations._ @@ -269,7 +269,7 @@ case class AtLeast(bound: Value[SInt.type], input: Value[SCollection[SSigmaProp. object AtLeast extends ValueCompanion { override def opCode: OpCode = AtLeastCode - val MaxChildrenCount: Int = ErgoConstants.MaxChildrenCountForAtLeastOp.value + val MaxChildrenCount: Int = SigmaConstants.MaxChildrenCountForAtLeastOp.value def apply(bound: Value[SInt.type], children: Seq[SigmaPropValue]): AtLeast = AtLeast(bound, ConcreteCollection(children.toIndexedSeq)) diff --git a/src/main/scala/sigmastate/types.scala b/src/main/scala/sigmastate/types.scala index 8a35f39011..b2d8f8af22 100644 --- a/src/main/scala/sigmastate/types.scala +++ b/src/main/scala/sigmastate/types.scala @@ -646,7 +646,7 @@ case object SBigInt extends SPrimType with SEmbeddable with SNumericType with SM val RelationOpType = SFunc(Vector(SBigInt, SBigInt), SBoolean) /** The maximum size of BigInteger value in byte array representation. */ - val MaxSizeInBytes: Long = ErgoConstants.MaxBigIntSizeInBytes.value + val MaxSizeInBytes: Long = SigmaConstants.MaxBigIntSizeInBytes.value override def dataSize(v: SType#WrappedType): Long = MaxSizeInBytes @@ -748,7 +748,7 @@ case object SSigmaProp extends SProduct with SPrimType with SEmbeddable with SLo override def mkConstant(v: SigmaProp): Value[SSigmaProp.type] = SigmaPropConstant(v) /** The maximum size of SigmaProp value in serialized byte array representation. */ - val MaxSizeInBytes: Long = ErgoConstants.MaxSigmaPropSizeInBytes.value + val MaxSizeInBytes: Long = SigmaConstants.MaxSigmaPropSizeInBytes.value override def dataSize(v: SType#WrappedType): Long = MaxSizeInBytes @@ -1265,7 +1265,7 @@ object STuple extends STypeCompanion { def methods: Seq[SMethod] = sys.error(s"Shouldn't be called.") def apply(items: SType*): STuple = STuple(items.toIndexedSeq) - val MaxTupleLength: Int = ErgoConstants.MaxTupleLength.value + val MaxTupleLength: Int = SigmaConstants.MaxTupleLength.value private val componentNames = Array.tabulate(MaxTupleLength){ i => s"_${i + 1}" } def componentNameByIndex(i: Int): String = try componentNames(i) diff --git a/src/main/scala/sigmastate/utxo/CostTable.scala b/src/main/scala/sigmastate/utxo/CostTable.scala index 2eb8ac5e75..35857c29fc 100644 --- a/src/main/scala/sigmastate/utxo/CostTable.scala +++ b/src/main/scala/sigmastate/utxo/CostTable.scala @@ -1,6 +1,6 @@ package sigmastate.utxo -import org.ergoplatform.ErgoConstants +import org.ergoplatform.SigmaConstants import sigmastate.{Downcast, Upcast} import sigmastate.lang.SigmaParser import sigmastate.lang.Terms.OperationId @@ -305,7 +305,7 @@ object CostTable { } //Maximum cost of a script - val ScriptLimit = ErgoConstants.ScriptCostLimit.value + val ScriptLimit = SigmaConstants.ScriptCostLimit.value //Maximum number of expressions in initial(non-reduced script) val MaxExpressions = 300 diff --git a/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala b/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala index 3b77da522e..9ca011b09a 100644 --- a/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala +++ b/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala @@ -5,17 +5,17 @@ import org.ergoplatform.ErgoBox.R4 import org.ergoplatform.mining.emission.EmissionRules import org.ergoplatform.settings.MonetarySettings import org.scalacheck.Gen -import scorex.crypto.hash.{Digest32, Blake2b256} +import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.Random -import sigmastate.Values.{SigmaPropConstant, CollectionConstant, ByteArrayConstant, IntConstant, ErgoTree} +import sigmastate.Values.{ByteArrayConstant, CollectionConstant, ErgoTree, IntConstant, SigmaPropConstant} import sigmastate._ -import sigmastate.basics.DLogProtocol.{ProveDlog, DLogProverInput} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons, ErgoLikeTestInterpreter} +import sigmastate.basics.DLogProtocol.{DLogProverInput, ProveDlog} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} -import sigmastate.interpreter.{ProverResult, ContextExtension} +import sigmastate.interpreter.{ContextExtension, ProverResult} import sigmastate.lang.Terms.ValueOps import sigmastate.serialization.ValueSerializer -import sigmastate.utxo.{CostTable, ExtractCreationInfo, ByIndex, SelectField} +import sigmastate.utxo.{ByIndex, CostTable, ExtractCreationInfo, SelectField} import scalan.util.BenchmarkUtil._ import ErgoScriptPredef._ @@ -48,7 +48,7 @@ class ErgoScriptPredefSpec extends SigmaTestingCommons { val spendingTransaction = ErgoLikeTransaction(inputs, IndexedSeq(minerBox)) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = nextHeight, lastBlockUtxoRoot = AvlTreeData.dummy, minerPubkey = pk, @@ -106,10 +106,10 @@ class ErgoScriptPredefSpec extends SigmaTestingCommons { val newFoundersBox = ErgoBox(remainingAmount, newProp, 0, Seq(), Map(R4 -> outputR4Val)) val collectedBox = ErgoBox(inputBoxes.head.value - remainingAmount, TrueProp, 0) val spendingTransaction = ErgoLikeTransaction(inputs, IndexedSeq(newFoundersBox, collectedBox)) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = height, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = inputBoxes, spendingTransaction, self = inputBoxes.head) @@ -127,17 +127,17 @@ class ErgoScriptPredefSpec extends SigmaTestingCommons { val inputs = inputBoxes.map(b => Input(b.id, emptyProverResult)) val spendingTransaction = ErgoLikeTransaction(inputs, IndexedSeq(ErgoBox(inputBoxes.head.value, TrueProp, 0))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = inputBoxes.head.creationHeight + settings.minerRewardDelay, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = inputBoxes, spendingTransaction, self = inputBoxes.head) - val prevBlockCtx = ErgoLikeContext( + val prevBlockCtx = ErgoLikeContextTesting( currentHeight = inputBoxes.head.creationHeight + settings.minerRewardDelay - 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = inputBoxes, spendingTransaction, self = inputBoxes.head) @@ -216,10 +216,10 @@ class ErgoScriptPredefSpec extends SigmaTestingCommons { val amount = inputBoxes.map(_.value).sum val spendingTransaction = ErgoLikeTransaction(inputs, IndexedSeq(ErgoBox(amount, pubkey.toSigmaProp, 0))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = inputBoxes, spendingTransaction, self = inputBoxes.head).withCostLimit(CostTable.ScriptLimit * 10) @@ -293,7 +293,7 @@ class ErgoScriptPredefSpec extends SigmaTestingCommons { val spendingTransaction = ErgoLikeTransaction(inputs, IndexedSeq(newEmissionBox, minerBox)) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = nextHeight, lastBlockUtxoRoot = AvlTreeData.dummy, minerPubkey = pkBytes, diff --git a/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala b/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala new file mode 100644 index 0000000000..48f6fec54f --- /dev/null +++ b/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala @@ -0,0 +1,145 @@ +package org.ergoplatform + +import io.circe._ +import io.circe.syntax._ +import org.ergoplatform.ErgoBox.{NonMandatoryRegisterId, R4, R5, R6, R7, R8} +import org.ergoplatform.validation.ValidationRules +import scorex.crypto.authds.{ADDigest, ADKey} +import scorex.crypto.hash.Digest32 +import scorex.util.ModifierId +import scorex.util.encode.Base16 +import sigmastate.{AvlTreeData, SType} +import sigmastate.Values.{ByteArrayConstant, ByteConstant, ErgoTree, EvaluatedValue, IntConstant, LongArrayConstant, SigmaPropConstant} +import sigmastate.basics.DLogProtocol.ProveDlog +import sigmastate.helpers.SigmaTestingCommons +import sigmastate.interpreter.{ContextExtension, CryptoConstants, ProverResult} +import sigmastate.serialization.SerializationSpecification +import special.collection.Coll +import special.sigma.{Header, PreHeader} + +class JsonSerializationSpec extends SigmaTestingCommons with SerializationSpecification with JsonCodecs { + + def jsonRoundTrip[T](v: T)(implicit encoder: Encoder[T], decoder: Decoder[T]): Unit = { + val json = v.asJson + withClue(s"\n for JSON: ${json.spaces2}") { json.as[T].toTry.get shouldEqual v } + } + + property("ErgoLikeContext should be encoded into JSON and decoded back correctly") { + forAll(ergoLikeContextGen) { v: ErgoLikeContext => jsonRoundTrip(v) } + } + + property("sigma.BigInt should be encoded into JSON and decoded back correctly") { + forAll { v: special.sigma.BigInt => jsonRoundTrip(v) } + } + + property("byte array should be encoded into JSON and decoded back correctly") { + forAll(byteArrayGen(0, 1000)) { v: Array[Byte] => jsonRoundTrip(v) } + } + + property("byte coll should be encoded into JSON and decoded back correctly") { + forAll(byteCollGen(0, 1000)) { v: Coll[Byte] => jsonRoundTrip(v) } + } + + property("ADKey should be encoded into JSON and decoded back correctly") { + forAll(boxIdGen) { v: ADKey => jsonRoundTrip(v) } + } + + property("ADDigest should be encoded into JSON and decoded back correctly") { + forAll(aDDigestGen) { v: ADDigest => jsonRoundTrip(v) } + } + + property("Digest32 should be encoded into JSON and decoded back correctly") { + forAll(digest32Gen) { v: Digest32 => jsonRoundTrip(v) } + } + + property("ModifierId should be encoded into JSON and decoded back correctly") { + forAll(modifierIdGen) { v: ModifierId => jsonRoundTrip(v) } + } + + property("Header should be encoded into JSON and decoded back correctly") { + forAll(headerGen) { v: Header => jsonRoundTrip(v) } + } + + property("PreHeader should be encoded into JSON and decoded back correctly") { + forAll(preHeaderGen) { v: PreHeader => jsonRoundTrip(v) } + } + + property("EvaluatedValue[SType] should be encoded into JSON and decoded back correctly") { + forAll(evaluatedValueGen) { v: EvaluatedValue[SType] => jsonRoundTrip(v) } + } + + property("DataInput should be encoded into JSON and decoded back correctly") { + forAll(dataInputGen) { v: DataInput => jsonRoundTrip(v) } + } + + property("Input should be encoded into JSON and decoded back correctly") { + forAll(inputGen) { v: Input => jsonRoundTrip(v) } + } + + property("UnsignedInput should be encoded into JSON and decoded back correctly") { + forAll(unsignedInputGen) { v: UnsignedInput => jsonRoundTrip(v) } + } + + property("ContextExtension should be encoded into JSON and decoded back correctly") { + forAll(contextExtensionGen) { v: ContextExtension => jsonRoundTrip(v) } + } + + property("ProverResult should be encoded into JSON and decoded back correctly") { + forAll(serializedProverResultGen) { v: ProverResult => jsonRoundTrip(v) } + } + + property("AvlTreeData should be encoded into JSON and decoded back correctly") { + forAll(avlTreeDataGen) { v: AvlTreeData => jsonRoundTrip(v) } + } + + property("ErgoTree should be encoded into JSON and decoded back correctly") { + forAll(ergoTreeGen) { v: ErgoTree => jsonRoundTrip(v) } + } + + property("ErgoBox should be encoded into JSON and decoded back correctly") { + forAll(ergoBoxGen) { v: ErgoBox => jsonRoundTrip(v) } + } + + property("ErgoLikeTransaction should be encoded into JSON and decoded back correctly") { + forAll(ergoLikeTransactionGen) { v: ErgoLikeTransaction => jsonRoundTrip(v) } + } + + property("UnsignedErgoLikeTransaction should be encoded into JSON and decoded back correctly") { + forAll(unsignedErgoLikeTransactionGen) { v: UnsignedErgoLikeTransaction => jsonRoundTrip(v) } + } + + property("ErgoLikeTransactionTemplate should be encoded into JSON and decoded back correctly") { + forAll(ergoLikeTransactionTemplateGen) { v: ErgoLikeTransactionTemplate[_ <: UnsignedInput] => + v.asJson.as(ergoLikeTransactionTemplateDecoder).toTry.get shouldEqual v + } + } + + property("SigmaValidationSettingsEncoder should be encoded into JSON and decoded back correctly") { + jsonRoundTrip(ValidationRules.currentSettings) + } + + property("ErgoBox.additionalRegisters should be encoded into JSON in certain order") { + val minerPkHex = "0326df75ea615c18acc6bb4b517ac82795872f388d5d180aac90eaa84de750b942" + val minerPk = Base16.decode(minerPkHex).map { point => + ProveDlog( + CryptoConstants.dlogGroup.curve.decodePoint(point).asInstanceOf[CryptoConstants.EcPointType] + ) + }.get + val regs = Map( + R7 -> LongArrayConstant(Array(1L, 2L, 1234123L)), + R4 -> ByteConstant(1), + R6 -> IntConstant(10), + R5 -> SigmaPropConstant(minerPk), + R8 -> ByteArrayConstant(Base16.decode("123456123456123456123456123456123456123456123456123456123456123456").get), + ) + // registers should be ordered by their number in Json + regs.asJson.spaces2 shouldEqual + """{ + | "R4" : "0201", + | "R5" : "08cd0326df75ea615c18acc6bb4b517ac82795872f388d5d180aac90eaa84de750b942", + | "R6" : "0414", + | "R7" : "1103020496d39601", + | "R8" : "0e21123456123456123456123456123456123456123456123456123456123456123456" + |}""".stripMargin + } +} diff --git a/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala b/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala index 4141f54901..7041058a58 100644 --- a/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala +++ b/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala @@ -3,25 +3,24 @@ package org.ergoplatform.dsl import sigmastate.interpreter.Interpreter.ScriptNameProp import scala.collection.mutable -import sigmastate.interpreter.{ProverResult, ContextExtension, CostedProverResult} +import sigmastate.interpreter.{ContextExtension, CostedProverResult, ProverResult} import scala.collection.mutable.ArrayBuffer import org.ergoplatform.ErgoBox.NonMandatoryRegisterId -import org.ergoplatform.ErgoConstants.ScriptCostLimit -import org.ergoplatform.ErgoLikeContext.{dummyPreHeader, noHeaders} +import org.ergoplatform.SigmaConstants.ScriptCostLimit import scalan.Nullable import scorex.crypto.hash.Digest32 import scala.util.Try -import org.ergoplatform.{ErgoLikeContext, ErgoBox} -import org.ergoplatform.dsl.ContractSyntax.{Token, TokenId, ErgoScript, Proposition} +import org.ergoplatform.{ErgoBox, ErgoLikeContext} +import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token, TokenId} import org.ergoplatform.validation.ValidationRules import sigmastate.{AvlTreeData, SType} import sigmastate.Values.{ErgoTree, EvaluatedValue} -import sigmastate.eval.{IRContext, CSigmaProp, Evaluation} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons, ErgoLikeTestInterpreter} +import sigmastate.eval.{CSigmaProp, Evaluation, IRContext} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.lang.Terms.ValueOps -import special.sigma.{AnyValue, TestValue, SigmaProp} +import special.sigma.{AnyValue, SigmaProp, TestValue} case class TestContractSpec(testSuite: SigmaTestingCommons)(implicit val IR: IRContext) extends ContractSpec { @@ -78,21 +77,16 @@ case class TestContractSpec(testSuite: SigmaTestingCommons)(implicit val IR: IRC case class TestInputBox(tx: TransactionCandidate, utxoBox: OutBox) extends InputBox { private [dsl] def toErgoContext: ErgoLikeContext = { - val propSpec = utxoBox.propSpec - val ctx = new ErgoLikeContext( + val boxesToSpend = tx.inputs.map(_.utxoBox.ergoBox).toIndexedSeq + val dataBoxes = tx.dataInputs.map(_.utxoBox.ergoBox).toIndexedSeq + val ctx = ErgoLikeContextTesting( currentHeight = tx.block.height, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, - headers = noHeaders, - preHeader = dummyPreHeader, - dataBoxes = tx.dataInputs.map(_.utxoBox.ergoBox).toIndexedSeq, - boxesToSpend = tx.inputs.map(_.utxoBox.ergoBox).toIndexedSeq, - spendingTransaction = testSuite.createTransaction(tx.outputs.map(_.ergoBox).toIndexedSeq), - self = utxoBox.ergoBox, - extension = ContextExtension.empty, - validationSettings = ValidationRules.currentSettings, - costLimit = ScriptCostLimit.value, - initCost = 0L) + minerPubkey = ErgoLikeContextTesting.dummyPubkey, + dataBoxes = dataBoxes, + boxesToSpend = boxesToSpend, + spendingTransaction = testSuite.createTransaction(dataBoxes, tx.outputs.map(_.ergoBox).toIndexedSeq), + selfIndex = boxesToSpend.indexOf(utxoBox.ergoBox) ) ctx } def runDsl(extensions: Map[Byte, AnyValue] = Map()): SigmaProp = { diff --git a/src/test/scala/sigmastate/CalcSha256Specification.scala b/src/test/scala/sigmastate/CalcSha256Specification.scala index 39f1fea9ef..ee120a71fd 100644 --- a/src/test/scala/sigmastate/CalcSha256Specification.scala +++ b/src/test/scala/sigmastate/CalcSha256Specification.scala @@ -3,8 +3,8 @@ package sigmastate import org.ergoplatform.ErgoLikeContext import org.scalatest.prop.TableFor2 import scorex.util.encode.Base16 -import sigmastate.Values.{CollectionConstant, ByteArrayConstant} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons} +import sigmastate.Values.{ByteArrayConstant, CollectionConstant} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, SigmaTestingCommons} class CalcSha256Specification extends SigmaTestingCommons { implicit lazy val IR = new TestingIRContext @@ -30,7 +30,7 @@ class CalcSha256Specification extends SigmaTestingCommons { property("CalcSha256: Should pass standard tests.") { val int = new ContextEnrichingTestProvingInterpreter() - val ctx = ErgoLikeContext.dummy(fakeSelf) + val ctx = ErgoLikeContextTesting.dummy(fakeSelf) forAll(objects) { (in, result) => val expectedResult = decodeString(result) val calcSha256 = EQ(CalcSha256(stringToByteConstant(in)), expectedResult) diff --git a/src/test/scala/sigmastate/CostingSpecification.scala b/src/test/scala/sigmastate/CostingSpecification.scala index a053be663a..0b2667c28b 100644 --- a/src/test/scala/sigmastate/CostingSpecification.scala +++ b/src/test/scala/sigmastate/CostingSpecification.scala @@ -1,9 +1,9 @@ package sigmastate -import org.ergoplatform.ErgoConstants.ScriptCostLimit +import org.ergoplatform.SigmaConstants.ScriptCostLimit import org.ergoplatform.ErgoScriptPredef.TrueProp import org.ergoplatform.validation.ValidationRules -import org.ergoplatform.{ErgoBox, ErgoLikeContext} +import org.ergoplatform.{ErgoBox, ErgoLikeContext, ErgoLikeTransaction} import scorex.crypto.authds.avltree.batch.Lookup import scorex.crypto.authds.{ADDigest, ADKey} import scorex.crypto.hash.Blake2b256 @@ -60,16 +60,14 @@ class CostingSpecification extends SigmaTestingData { ErgoBox.R6 -> AvlTreeConstant(avlTree))) lazy val outBoxA = ErgoBox(10, pkA, 0) lazy val outBoxB = ErgoBox(20, pkB, 0) - lazy val tx = createTransaction(IndexedSeq(outBoxA, outBoxB)) + lazy val tx = createTransaction(IndexedSeq(dataBox), IndexedSeq(outBoxA, outBoxB)) lazy val context = new ErgoLikeContext( - currentHeight = preHeader.height, lastBlockUtxoRoot = header2.stateRoot.asInstanceOf[CAvlTree].treeData, - minerPubkey = preHeader.minerPk.getEncoded.toArray, headers = headers, preHeader = preHeader, dataBoxes = IndexedSeq(dataBox), boxesToSpend = IndexedSeq(selfBox), - spendingTransaction = tx, self = selfBox, extension, ValidationRules.currentSettings, ScriptCostLimit.value, CostTable.interpreterInitCost) + spendingTransaction = tx, selfIndex = 0, extension, ValidationRules.currentSettings, ScriptCostLimit.value, CostTable.interpreterInitCost) def cost(script: String)(expCost: Int): Unit = { val ergoTree = compiler.compile(env, script) diff --git a/src/test/scala/sigmastate/FailingToProveSpec.scala b/src/test/scala/sigmastate/FailingToProveSpec.scala index 2dc1ecfb6d..475e52f020 100644 --- a/src/test/scala/sigmastate/FailingToProveSpec.scala +++ b/src/test/scala/sigmastate/FailingToProveSpec.scala @@ -1,7 +1,7 @@ package sigmastate import org.ergoplatform.{ErgoBox, ErgoLikeContext, ErgoLikeInterpreter, ErgoLikeTransaction} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.lang.Terms._ import org.scalatest.TryValues._ import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} @@ -36,13 +36,13 @@ class FailingToProveSpec extends SigmaTestingCommons { val o1 = ErgoBox(101L, TrueProp, 5001) val o2 = ErgoBox(99L, TrueProp, 5001) val tx = createTransaction(IndexedSeq(o1, o2)) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 5001, lastBlockUtxoRoot = AvlTreeData.dummy, boxesToSpend = IndexedSeq(selfBox), spendingTransaction = tx, self = selfBox, - minerPubkey = ErgoLikeContext.dummyPubkey) + minerPubkey = ErgoLikeContextTesting.dummyPubkey) val proof = interpreter.prove(emptyEnv + (ScriptNameProp -> "prove"), compiledScript, ctx, fakeMessage).success.value.proof verifier.verify(emptyEnv + (ScriptNameProp -> "verify"), compiledScript, ctx, proof, fakeMessage) should be a 'success } @@ -70,13 +70,13 @@ class FailingToProveSpec extends SigmaTestingCommons { val o2 = ErgoBox(98L, TrueProp, 5001) val o3 = ErgoBox(100L, TrueProp, 5001) val tx = createTransaction(IndexedSeq(o1, o2, o3)) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 5001, lastBlockUtxoRoot = AvlTreeData.dummy, boxesToSpend = IndexedSeq(selfBox), spendingTransaction = tx, self = selfBox, - minerPubkey = ErgoLikeContext.dummyPubkey) + minerPubkey = ErgoLikeContextTesting.dummyPubkey) val proof = interpreter.prove(emptyEnv + (ScriptNameProp -> "prove"), compiledScript, ctx, fakeMessage).success.value.proof verifier.verify(emptyEnv + (ScriptNameProp -> "verify"), compiledScript, ctx, proof, fakeMessage) should be a 'success } diff --git a/src/test/scala/sigmastate/SoftForkabilitySpecification.scala b/src/test/scala/sigmastate/SoftForkabilitySpecification.scala index e857645e46..7aab722500 100644 --- a/src/test/scala/sigmastate/SoftForkabilitySpecification.scala +++ b/src/test/scala/sigmastate/SoftForkabilitySpecification.scala @@ -7,7 +7,7 @@ import sigmastate.SPrimType.MaxPrimTypeCode import sigmastate.Values.ErgoTree.EmptyConstants import sigmastate.Values.{ByteArrayConstant, ErgoTree, IntConstant, NotReadyValueInt, Tuple, UnparsedErgoTree, ValueCompanion} import sigmastate.eval.Colls -import sigmastate.helpers.{ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter} +import sigmastate.helpers.{ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter} import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.interpreter.{ContextExtension, ProverResult} import sigmastate.lang.Terms._ @@ -38,8 +38,8 @@ class SoftForkabilitySpecification extends SigmaTestingData { val blockHeight = 110 def createContext(h: Int, tx: ErgoLikeTransaction, vs: SigmaValidationSettings) = - ErgoLikeContext(h, - AvlTreeData.dummy, ErgoLikeContext.dummyPubkey, IndexedSeq(fakeSelf), + ErgoLikeContextTesting(h, + AvlTreeData.dummy, ErgoLikeContextTesting.dummyPubkey, IndexedSeq(fakeSelf), tx, fakeSelf, vs = vs) def proveTx(name: String, tx: ErgoLikeTransaction, vs: SigmaValidationSettings): ProverResult = { diff --git a/src/test/scala/sigmastate/TestingInterpreterSpecification.scala b/src/test/scala/sigmastate/TestingInterpreterSpecification.scala index bc9354dc10..046ebc1de9 100644 --- a/src/test/scala/sigmastate/TestingInterpreterSpecification.scala +++ b/src/test/scala/sigmastate/TestingInterpreterSpecification.scala @@ -1,6 +1,6 @@ package sigmastate -import sigmastate.basics.DLogProtocol.{ProveDlog, DLogProverInput} +import sigmastate.basics.DLogProtocol.{DLogProverInput, ProveDlog} import scorex.crypto.hash.Blake2b256 import sigmastate.Values._ import sigmastate.interpreter._ @@ -9,7 +9,7 @@ import Interpreter._ import sigmastate.lang.Terms._ import org.ergoplatform._ import scorex.util.encode.Base58 -import sigmastate.helpers.{ErgoLikeTestProvingInterpreter, SigmaTestingCommons, ErgoLikeTestInterpreter} +import sigmastate.helpers.{ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter, SigmaTestingCommons} import sigmastate.serialization.ValueSerializer import TrivialProp._ @@ -23,8 +23,8 @@ class TestingInterpreterSpecification extends SigmaTestingCommons { implicit val soundness = CryptoConstants.soundnessBits def testingContext(h: Int) = - ErgoLikeContext(h, - AvlTreeData.dummy, ErgoLikeContext.dummyPubkey, IndexedSeq(fakeSelf), + ErgoLikeContextTesting(h, + AvlTreeData.dummy, ErgoLikeContextTesting.dummyPubkey, IndexedSeq(fakeSelf), ErgoLikeTransaction(IndexedSeq.empty, IndexedSeq.empty), fakeSelf) diff --git a/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala index 2c7f7d10d5..46c200903f 100644 --- a/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala +++ b/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala @@ -11,6 +11,7 @@ import sigmastate.utxo.CostTable import scalan.BaseCtxTests import sigmastate.lang.{LangTests, SigmaCompiler} import sigmastate.helpers.ContextEnrichingTestProvingInterpreter +import sigmastate.helpers.ErgoLikeContextTesting import sigmastate.interpreter.ContextExtension import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.serialization.ErgoTreeSerializer @@ -37,10 +38,10 @@ trait ErgoScriptTestkit extends ContractsTestkit with LangTests def newErgoContext(height: Int, boxToSpend: ErgoBox, extension: Map[Byte, EvaluatedValue[SType]] = Map()): ErgoLikeContext = { val tx1 = new ErgoLikeTransaction(IndexedSeq(), IndexedSeq(), IndexedSeq(boxToSpend)) - val ergoCtx = ErgoLikeContext( + val ergoCtx = ErgoLikeContextTesting( currentHeight = height, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(boxToSpend), spendingTransaction = tx1, self = boxToSpend, @@ -78,10 +79,10 @@ trait ErgoScriptTestkit extends ContractsTestkit with LangTests lazy val tx1Output1 = ErgoBox(minToRaise, projectPubKey, 0) lazy val tx1Output2 = ErgoBox(1, projectPubKey, 0) lazy val tx1 = new ErgoLikeTransaction(IndexedSeq(), IndexedSeq(), IndexedSeq(tx1Output1, tx1Output2)) - lazy val ergoCtx = ErgoLikeContext( + lazy val ergoCtx = ErgoLikeContextTesting( currentHeight = timeout - 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(boxToSpend), spendingTransaction = tx1, self = boxToSpend, diff --git a/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala b/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala new file mode 100644 index 0000000000..dcdafbf166 --- /dev/null +++ b/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala @@ -0,0 +1,87 @@ +package sigmastate.helpers + +import org.ergoplatform.SigmaConstants.ScriptCostLimit +import org.ergoplatform.ErgoLikeContext.Height +import org.ergoplatform.{ErgoBox, ErgoBoxReader, ErgoLikeContext, ErgoLikeTransaction, ErgoLikeTransactionTemplate, UnsignedInput} +import org.ergoplatform.validation.{SigmaValidationSettings, ValidationRules} +import sigmastate.AvlTreeData +import sigmastate.eval._ +import sigmastate.interpreter.{ContextExtension, CryptoConstants} +import sigmastate.serialization.{GroupElementSerializer, SigmaSerializer} +import special.collection.Coll +import special.sigma.{Box, Header, PreHeader} + +import scala.util.Try + +object ErgoLikeContextTesting { + /* NO HF PROOF: + Changed: val dummyPubkey from `Array[Byte] = Array.fill(32)(0: Byte)` to `GroupElementSerializer.toBytes(CryptoConstants.dlogGroup.generator)` + Motivation: to avoid exception on deserialization(wrong size, needs to be 33 bytes) and later in GroupElement.toString (infinity was not handled) and to provide more practical value in tests. + Safety: + Used only in tests and not used in ergo. + Examined ergo code: all (with IDE's "find usages" action). +*/ + val dummyPubkey: Array[Byte] = GroupElementSerializer.toBytes(CryptoConstants.dlogGroup.generator) + + val noBoxes: IndexedSeq[ErgoBox] = IndexedSeq.empty[ErgoBox] + val noHeaders: Coll[Header] = CostingSigmaDslBuilder.Colls.emptyColl[Header] + + def dummyPreHeader(currentHeight: Height, minerPk: Array[Byte]): PreHeader = CPreHeader(0, + parentId = Colls.emptyColl[Byte], + timestamp = 3, + nBits = 0, + height = currentHeight, + minerPk = GroupElementSerializer.parse(SigmaSerializer.startReader(minerPk)), + votes = Colls.emptyColl[Byte] + ) + + def apply(currentHeight: Height, + lastBlockUtxoRoot: AvlTreeData, + minerPubkey: Array[Byte], + boxesToSpend: IndexedSeq[ErgoBox], + spendingTransaction: ErgoLikeTransactionTemplate[_ <: UnsignedInput], + self: ErgoBox, + extension: ContextExtension = ContextExtension.empty, + vs: SigmaValidationSettings = ValidationRules.currentSettings) = + new ErgoLikeContext(lastBlockUtxoRoot, noHeaders, dummyPreHeader(currentHeight, minerPubkey), noBoxes, + boxesToSpend, spendingTransaction, boxesToSpend.indexOf(self), extension, vs, ScriptCostLimit.value, 0L) + + def apply(currentHeight: Height, + lastBlockUtxoRoot: AvlTreeData, + minerPubkey: Array[Byte], + dataBoxes: IndexedSeq[ErgoBox], + boxesToSpend: IndexedSeq[ErgoBox], + spendingTransaction: ErgoLikeTransactionTemplate[_ <: UnsignedInput], + selfIndex: Int) = + new ErgoLikeContext(lastBlockUtxoRoot, noHeaders, dummyPreHeader(currentHeight, minerPubkey), + dataBoxes, boxesToSpend, spendingTransaction, selfIndex, ContextExtension.empty, ValidationRules.currentSettings, ScriptCostLimit.value, 0L) + + + def dummy(selfDesc: ErgoBox) = ErgoLikeContextTesting(currentHeight = 0, + lastBlockUtxoRoot = AvlTreeData.dummy, dummyPubkey, boxesToSpend = IndexedSeq(selfDesc), + spendingTransaction = ErgoLikeTransaction(IndexedSeq(), IndexedSeq()), self = selfDesc) + + def fromTransaction(tx: ErgoLikeTransaction, + blockchainState: BlockchainState, + boxesReader: ErgoBoxReader, + inputIndex: Int): Try[ErgoLikeContext] = Try { + + val boxes = tx.inputs.map(_.boxId).map(id => boxesReader.byId(id).get) + + val proverExtension = tx.inputs(inputIndex).spendingProof.extension + + ErgoLikeContextTesting(blockchainState.currentHeight, + blockchainState.lastBlockUtxoRoot, + dummyPubkey, + boxes, + tx, + boxes(inputIndex), + proverExtension) + } + + val noInputs: Array[Box] = Array[Box]() + val noOutputs: Array[Box] = Array[Box]() +} + +case class BlockchainState(currentHeight: Height, lastBlockUtxoRoot: AvlTreeData) + diff --git a/src/test/scala/sigmastate/helpers/ErgoLikeTransactionTesting.scala b/src/test/scala/sigmastate/helpers/ErgoLikeTransactionTesting.scala new file mode 100644 index 0000000000..2672f0841b --- /dev/null +++ b/src/test/scala/sigmastate/helpers/ErgoLikeTransactionTesting.scala @@ -0,0 +1,8 @@ +package sigmastate.helpers + +import org.ergoplatform.ErgoLikeTransaction + +object ErgoLikeTransactionTesting { + + val dummy = ErgoLikeTransaction(IndexedSeq(), IndexedSeq()) +} diff --git a/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala b/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala index 6f3782b8d6..1d1717ff6b 100644 --- a/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala +++ b/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala @@ -36,7 +36,7 @@ class ErgoTransactionValidator(implicit IR: IRContext) { val proverExtension = tx.inputs(idx).spendingProof.extension val context = - ErgoLikeContext(blockchainState.currentHeight, blockchainState.lastBlockUtxoRoot, minerPubkey, boxes, + ErgoLikeContextTesting(blockchainState.currentHeight, blockchainState.lastBlockUtxoRoot, minerPubkey, boxes, tx, box, proverExtension) val verificationResult = verifier.verify( emptyEnv + (ScriptNameProp -> s"height_${blockchainState.currentHeight }_verify"), diff --git a/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala b/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala index 862b15ae91..5d93c51210 100644 --- a/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala +++ b/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala @@ -2,29 +2,34 @@ package sigmastate.helpers import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix import org.ergoplatform.ErgoBox.NonMandatoryRegisterId +import org.ergoplatform.SigmaConstants.ScriptCostLimit +import org.ergoplatform.ErgoLikeContext.Height import org.ergoplatform.ErgoScriptPredef.TrueProp import org.ergoplatform._ -import org.ergoplatform.validation.ValidationSpecification +import org.ergoplatform.validation.{SigmaValidationSettings, ValidationRules, ValidationSpecification} import org.scalacheck.Arbitrary.arbByte import org.scalacheck.Gen -import org.scalatest.prop.{PropertyChecks, GeneratorDrivenPropertyChecks} -import org.scalatest.{PropSpec, Assertion, Matchers} -import scalan.{TestUtils, TestContexts, RType} -import scorex.crypto.hash.{Digest32, Blake2b256} +import org.scalatest.prop.{GeneratorDrivenPropertyChecks, PropertyChecks} +import org.scalatest.{Assertion, Matchers, PropSpec} +import scalan.{RType, TestContexts, TestUtils} +import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.serialization.{VLQByteStringReader, VLQByteStringWriter} import sigma.types.IsPrimView -import sigmastate.Values.{Constant, EvaluatedValue, SValue, Value, ErgoTree, GroupElementConstant} -import sigmastate.interpreter.Interpreter.{ScriptNameProp, ScriptEnv} -import sigmastate.interpreter.{CryptoConstants, Interpreter} -import sigmastate.lang.{TransformingSigmaBuilder, SigmaCompiler} -import sigmastate.serialization.{ValueSerializer, SigmaSerializer} -import sigmastate.{SGroupElement, SType} -import sigmastate.eval.{CompiletimeCosting, IRContext, Evaluation, _} +import sigmastate.Values.{Constant, ErgoTree, EvaluatedValue, GroupElementConstant, SValue, Value} +import sigmastate.interpreter.Interpreter.{ScriptEnv, ScriptNameProp} +import sigmastate.interpreter.{ContextExtension, CryptoConstants, Interpreter} +import sigmastate.lang.{SigmaCompiler, TransformingSigmaBuilder} +import sigmastate.serialization.{GroupElementSerializer, SigmaSerializer, ValueSerializer} +import sigmastate.{AvlTreeData, SGroupElement, SType} +import sigmastate.eval.{CompiletimeCosting, Evaluation, IRContext, _} import sigmastate.interpreter.CryptoConstants.EcPointType +import special.collection.Coll import special.sigma +import special.sigma.{Box, Header, PreHeader} import scala.annotation.tailrec import scala.language.implicitConversions +import scala.util.Try trait SigmaTestingCommons extends PropSpec with PropertyChecks @@ -33,7 +38,7 @@ trait SigmaTestingCommons extends PropSpec val fakeSelf: ErgoBox = createBox(0, TrueProp) - val fakeContext: ErgoLikeContext = ErgoLikeContext.dummy(fakeSelf) + val fakeContext: ErgoLikeContext = ErgoLikeContextTesting.dummy(fakeSelf) //fake message, in a real-life a message is to be derived from a spending transaction val fakeMessage = Blake2b256("Hello World") @@ -83,6 +88,10 @@ trait SigmaTestingCommons extends PropSpec def createTransaction(box: ErgoBoxCandidate): ErgoLikeTransaction = createTransaction(IndexedSeq(box)) + def createTransaction(dataInputs: IndexedSeq[ErgoBox], + outputCandidates: IndexedSeq[ErgoBoxCandidate]): ErgoLikeTransaction = + new ErgoLikeTransaction(IndexedSeq(), dataInputs.map(b => DataInput(b.id)), outputCandidates) + class TestingIRContext extends TestContext with IRContext with CompiletimeCosting { override def onCostingResult[T](env: ScriptEnv, tree: SValue, res: RCostingResultEx[T]): Unit = { env.get(ScriptNameProp) match { @@ -155,7 +164,7 @@ trait SigmaTestingCommons extends PropSpec implicit val cA = tA.classTag val x = fromPrimView(in) val context = - ErgoLikeContext.dummy(createBox(0, TrueProp)) + ErgoLikeContextTesting.dummy(createBox(0, TrueProp)) .withBindings(1.toByte -> Constant[SType](x.asInstanceOf[SType#WrappedType], tpeA)).withBindings(bindings: _*) val calcCtx = context.toSigmaContext(IR, isCost = false) val (res, _) = valueFun(calcCtx) @@ -171,7 +180,7 @@ trait SigmaTestingCommons extends PropSpec catch { case e: Throwable => if (!assertion(e)) - fail(s"exception check failed on $e (root cause: ${rootCause(e)})") + fail(s"exception check failed on $e (root cause: ${rootCause(e)}) \n trace:\n${e.getStackTrace.mkString("\n")}}") } } diff --git a/src/test/scala/sigmastate/serialization/DeserializationResilience.scala b/src/test/scala/sigmastate/serialization/DeserializationResilience.scala index 9a96af0403..4ba603dfc7 100644 --- a/src/test/scala/sigmastate/serialization/DeserializationResilience.scala +++ b/src/test/scala/sigmastate/serialization/DeserializationResilience.scala @@ -11,7 +11,7 @@ import sigmastate.Values.{BlockValue, ErgoTree, GetVarInt, IntConstant, SValue, import sigmastate._ import sigmastate.eval.Extensions._ import sigmastate.eval._ -import sigmastate.helpers.{ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.interpreter.{ContextExtension, CostedProverResult, CryptoConstants} import sigmastate.lang.Terms._ @@ -263,7 +263,7 @@ class DeserializationResilience extends SerializationSpecification with SigmaTes assertExceptionThrown({ val verifier = new ErgoLikeTestInterpreter val pr = CostedProverResult(Array[Byte](), ContextExtension(Map()), 0L) - val ctx = ErgoLikeContext.dummy(fakeSelf) + val ctx = ErgoLikeContextTesting.dummy(fakeSelf) val (res, calcTime) = BenchmarkUtil.measureTime { verifier.verify(emptyEnv + (ScriptNameProp -> "verify"), ErgoTree(ErgoTree.DefaultHeader, IndexedSeq(), recursiveScript), ctx, pr, fakeMessage) diff --git a/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala b/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala index cabade8e82..2fdcb553f6 100644 --- a/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala +++ b/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala @@ -2,14 +2,14 @@ package sigmastate.serialization import java.util -import org.ergoplatform.ErgoLikeContext +import org.ergoplatform.{ErgoLikeContext, ErgoLikeTransaction} import org.scalacheck.{Arbitrary, Gen} import org.scalatest.Assertion -import sigmastate.Values.{Value, SigmaPropConstant, SigmaBoolean, SigmaPropValue} +import sigmastate.Values.{SigmaBoolean, SigmaPropConstant, SigmaPropValue, Value} import sigmastate._ import sigmastate.basics.DLogProtocol.ProveDlog import sigmastate.basics.ProveDHTuple -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTransactionTesting, SigmaTestingCommons} import sigmastate.serialization.generators.ObjectGenerators import sigmastate.utxo.Transformer @@ -72,12 +72,12 @@ class SigSerializerSpecification extends SigmaTestingCommons with ObjectGenerato val expr = sb.toSigmaProp val challenge = Array.fill(32)(Random.nextInt(100).toByte) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) // get sigma conjectures out of transformers diff --git a/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala b/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala index 08561784f6..9943bf0486 100644 --- a/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala +++ b/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala @@ -1,27 +1,28 @@ package sigmastate.serialization.generators import org.ergoplatform.ErgoBox._ -import org.ergoplatform.ErgoConstants.MaxPropositionBytes +import org.ergoplatform.SigmaConstants.MaxPropositionBytes import org.ergoplatform.ErgoScriptPredef.{FalseProp, TrueProp} import org.ergoplatform.validation._ import org.ergoplatform._ -import org.scalacheck.Arbitrary.{arbOption, arbAnyVal, arbShort, arbitrary, arbUnit, arbString, arbInt, arbLong, arbBool, arbByte} +import org.scalacheck.Arbitrary.{arbAnyVal, arbBool, arbByte, arbInt, arbLong, arbOption, arbShort, arbString, arbUnit, arbitrary} import org.scalacheck.{Arbitrary, Gen} import scorex.crypto.authds.{ADDigest, ADKey} import scorex.crypto.hash.Digest32 -import scorex.util.encode.{Base64, Base58} -import scorex.util.{bytesToId, ModifierId} -import sigmastate.Values.{ShortConstant, LongConstant, StringConstant, BoxConstant, FuncValue, FalseLeaf, EvaluatedValue, TrueLeaf, TaggedAvlTree, TaggedLong, BigIntConstant, BlockValue, AvlTreeConstant, GetVarInt, SigmaPropConstant, CollectionConstant, ConstantPlaceholder, Value, SigmaPropValue, Tuple, IntConstant, ErgoTree, SigmaBoolean, TaggedBox, ByteConstant, TaggedInt, ValDef, GroupElementConstant, ValUse, TaggedVariable} +import scorex.util.encode.{Base58, Base64} +import scorex.util.{ModifierId, bytesToId} +import sigmastate.Values.{AvlTreeConstant, BigIntConstant, BlockValue, BoxConstant, ByteConstant, CollectionConstant, ConstantPlaceholder, ErgoTree, EvaluatedValue, FalseLeaf, FuncValue, GetVarInt, GroupElementConstant, IntConstant, LongConstant, ShortConstant, SigmaBoolean, SigmaPropConstant, SigmaPropValue, StringConstant, TaggedAvlTree, TaggedBox, TaggedInt, TaggedLong, TaggedVariable, TrueLeaf, Tuple, ValDef, ValUse, Value} import sigmastate.basics.DLogProtocol.ProveDlog import sigmastate.basics.ProveDHTuple import sigmastate.eval.Extensions._ import sigmastate.eval.{CostingBox, SigmaDsl, _} import sigmastate.interpreter.CryptoConstants.EcPointType -import sigmastate.interpreter.{ProverResult, ContextExtension, CryptoConstants} -import sigmastate.lang.TransformingSigmaBuilder.{mkModulo, mkExtractCreationInfo, mkExtractScriptBytes, mkFilter, mkPlus, mkTaggedVariable, mkSlice, mkFold, mkAtLeast, mkExtractBytesWithNoRef, mkExists, mkByteArrayToBigInt, mkForAll, mkDivide, mkSigmaOr, mkSigmaAnd, mkGT, mkGE, mkMapCollection, mkDeserializeRegister, mkExtractBytes, mkBoolToSigmaProp, mkNEQ, mkExtractAmount, mkMultiply, mkByteArrayToLong, mkConstant, mkExtractId, mkTuple, mkMax, mkLT, mkLE, mkDowncast, mkSizeOf, mkCollectionConstant, mkMin, mkDeserializeContext, mkEQ, mkAppend, mkMinus} +import sigmastate.interpreter.{ContextExtension, CryptoConstants, ProverResult} +import sigmastate.lang.TransformingSigmaBuilder.{mkAppend, mkAtLeast, mkBoolToSigmaProp, mkByteArrayToBigInt, mkByteArrayToLong, mkCollectionConstant, mkConstant, mkDeserializeContext, mkDeserializeRegister, mkDivide, mkDowncast, mkEQ, mkExists, mkExtractAmount, mkExtractBytes, mkExtractBytesWithNoRef, mkExtractCreationInfo, mkExtractId, mkExtractScriptBytes, mkFilter, mkFold, mkForAll, mkGE, mkGT, mkLE, mkLT, mkMapCollection, mkMax, mkMin, mkMinus, mkModulo, mkMultiply, mkNEQ, mkPlus, mkSigmaAnd, mkSigmaOr, mkSizeOf, mkSlice, mkTaggedVariable, mkTuple} import sigmastate._ -import sigmastate.utxo.{ExtractBytesWithNoRef, OptionGet, ExtractRegisterAs, Append, ExtractScriptBytes, ExtractCreationInfo, GetVar, ExtractId, MapCollection, ExtractAmount, ForAll, ByIndex, OptionGetOrElse, OptionIsDefined, DeserializeContext, Exists, DeserializeRegister, Transformer, Fold, Slice, SizeOf, Filter, ExtractBytes} -import special.sigma.{AvlTree, SigmaProp} +import sigmastate.utxo.{Append, ByIndex, DeserializeContext, DeserializeRegister, Exists, ExtractAmount, ExtractBytes, ExtractBytesWithNoRef, ExtractCreationInfo, ExtractId, ExtractRegisterAs, ExtractScriptBytes, Filter, Fold, ForAll, GetVar, MapCollection, OptionGet, OptionGetOrElse, OptionIsDefined, SizeOf, Slice, Transformer} +import special.collection.Coll +import special.sigma._ import scala.collection.JavaConverters._ import scala.collection.mutable.ListBuffer @@ -110,6 +111,8 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with ints <- Gen.listOfN(length, arbInt.arbitrary) } yield mkCollectionConstant[SInt.type](ints.toArray, SInt) + val heightGen: Gen[Int] = Gen.chooseNum(0, 1000000) + val groupElementGen: Gen[EcPointType] = for { _ <- Gen.const(1) } yield CryptoConstants.dlogGroup.createRandomElement() @@ -163,15 +166,17 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with val taggedAvlTreeGen: Gen[TaggedAvlTree] = arbByte.arbitrary.map { v => TaggedAvlTree(v).asInstanceOf[TaggedAvlTree] } + val evaluatedValueGen: Gen[EvaluatedValue[SType]] = + Gen.oneOf(booleanConstGen.asInstanceOf[Gen[EvaluatedValue[SType]]], byteArrayConstGen, longConstGen) + def additionalRegistersGen(cnt: Byte): Seq[Gen[(NonMandatoryRegisterId, EvaluatedValue[SType])]] = { - (0 until cnt) + util.Random.shuffle((0 until cnt).toList) .map(_ + ErgoBox.startingNonMandatoryIndex) .map(rI => ErgoBox.registerByIndex(rI).asInstanceOf[NonMandatoryRegisterId]) .map { r => for { - arr <- byteArrayConstGen - v <- Gen.oneOf(TrueLeaf, FalseLeaf, arr) - } yield r -> v.asInstanceOf[EvaluatedValue[SType]] + v <- evaluatedValueGen + } yield r -> v } } @@ -224,11 +229,9 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with .map(_ + 1) .map { varId => for { - arr <- byteArrayConstGen - longConst <- longConstGen - v <- Gen.oneOf(TrueLeaf, FalseLeaf, arr, longConst) + v <- evaluatedValueGen } - yield varId.toByte -> v.asInstanceOf[EvaluatedValue[SType]] + yield varId.toByte -> v } def avlTreeFlagsGen: Gen[AvlTreeFlags] = for { @@ -237,8 +240,10 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with remove <- arbBool.arbitrary } yield AvlTreeFlags(insert, update, remove) + val aDDigestGen: Gen[ADDigest] = Gen.listOfN(AvlTreeData.DigestSize, arbByte.arbitrary).map(ADDigest @@ _.toArray) + def avlTreeDataGen: Gen[AvlTreeData] = for { - digest <- Gen.listOfN(AvlTreeData.DigestSize, arbByte.arbitrary).map(_.toArray) + digest <- aDDigestGen flags <- avlTreeFlagsGen keyLength <- unsignedIntGen vl <- arbOption[Int](Arbitrary(unsignedIntGen)).arbitrary @@ -289,6 +294,9 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with lazy val modifierIdGen: Gen[ModifierId] = Gen.listOfN(32, arbByte.arbitrary) .map(id => bytesToId(id.toArray)) + lazy val modifierIdBytesGen: Gen[Coll[Byte]] = Gen.listOfN(32, arbByte.arbitrary) + .map(id => bytesToId(id.toArray).toBytes.toColl) + val ergoBoxGen: Gen[ErgoBox] = for { tId <- modifierIdGen boxId <- unsignedShortGen @@ -297,11 +305,15 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with candidate <- ergoBoxCandidateGen(tokens) } yield candidate.toBox(tId, boxId) + val additionalRegistersGen: Gen[Map[NonMandatoryRegisterId, EvaluatedValue[SType]]] = for { + regNum <- Gen.chooseNum[Byte](0, ErgoBox.nonMandatoryRegistersCount) + regs <- Gen.sequence(additionalRegistersGen(regNum)) + } yield regs.asScala.toMap + def ergoBoxCandidateGen(availableTokens: Seq[Digest32]): Gen[ErgoBoxCandidate] = for { l <- arbLong.arbitrary b <- ergoTreeGen.filter(t => t.bytes.length < MaxPropositionBytes.value) - regNum <- Gen.chooseNum[Byte](0, ErgoBox.nonMandatoryRegistersCount) - ar <- Gen.sequence(additionalRegistersGen(regNum)) + ar <- additionalRegistersGen tokensCount <- Gen.chooseNum[Int](0, 20) tokens <- if(availableTokens.nonEmpty) { Gen.listOfN(tokensCount, Gen.oneOf(availableTokens)) @@ -309,27 +321,29 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with Gen.oneOf(Seq(List[Digest32]())) } tokenAmounts <- Gen.listOfN(tokensCount, Gen.oneOf(1, 500, 20000, 10000000, Long.MaxValue)) - creationHeight <- Gen.chooseNum(0, 100000) - } yield new ErgoBoxCandidate(l, b, creationHeight, tokens.toColl.zip(tokenAmounts.toColl), ar.asScala.toMap) + creationHeight <- heightGen + } yield new ErgoBoxCandidate(l, b, creationHeight, tokens.toColl.zip(tokenAmounts.toColl), ar) val boxConstantGen: Gen[BoxConstant] = ergoBoxGen.map { v => BoxConstant(CostingBox(false, v)) } - val tokenIdGen: Gen[Digest32] = for { + val digest32Gen: Gen[Digest32] = for { bytes <- Gen.listOfN(TokenId.size, arbByte.arbitrary).map(_.toArray) } yield Digest32 @@ bytes + val tokenIdGen: Gen[Digest32] = digest32Gen + val tokensGen: Gen[Seq[Digest32]] = for { count <- Gen.chooseNum(10, 50) tokens <- Gen.listOfN(count, tokenIdGen) } yield tokens + val digest32CollGen: Gen[Digest32Coll] = digest32Gen.map(Digest32Coll @@ _.toColl) + val ergoTransactionGen: Gen[ErgoLikeTransaction] = for { - inputs <- Gen.nonEmptyListOf(inputGen) - tokens <- tokensGen - dataInputs <- Gen.listOf(dataInputGen) - outputsCount <- Gen.chooseNum(50, 200) - outputCandidates <- Gen.listOfN(outputsCount, ergoBoxCandidateGen(tokens)) - } yield new ErgoLikeTransaction(inputs.toIndexedSeq, dataInputs.toIndexedSeq, outputCandidates.toIndexedSeq) + inputBoxIds <- Gen.nonEmptyListOf(boxIdGen) + dataInputBoxIds <- Gen.listOf(boxIdGen) + tx <- ergoLikeTransactionGen(inputBoxIds, dataInputBoxIds) + } yield tx // distinct list of elements from a given generator // with a maximum number of elements to discard @@ -352,11 +366,23 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with } } - val byteArrayGen: Gen[Array[Byte]] = for { - length <- Gen.chooseNum(1, 10) + def byteArrayGen(length: Int): Gen[Array[Byte]] = for { + bytes <- Gen.listOfN(length, arbByte.arbitrary) + } yield bytes.toArray + + def byteArrayGen(minLength: Int, maxLength: Int): Gen[Array[Byte]] = for { + length <- Gen.chooseNum(minLength, maxLength) bytes <- Gen.listOfN(length, arbByte.arbitrary) } yield bytes.toArray + def byteCollGen(length: Int): Gen[Coll[Byte]] = byteArrayGen(length).map(_.toColl) + + def byteCollGen(minLength: Int, maxLength: Int): Gen[Coll[Byte]] = byteArrayGen(minLength, maxLength).map(_.toColl) + + val minerVotesGen: Gen[Coll[Byte]] = byteCollGen(CHeader.VotesSize) + + val nonceBytesGen: Gen[Coll[Byte]] = byteCollGen(CHeader.NonceSize) + import ValidationRules._ val numRules = currentSettings.size @@ -368,7 +394,7 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with val statusGen: Gen[RuleStatus] = Gen.oneOf( Gen.oneOf(EnabledRule, DisabledRule), replacedRuleIdGen.map(id => ReplacedRule(id)), - byteArrayGen.map(xs => ChangedRule(xs)) + byteArrayGen(1, 10).map(xs => ChangedRule(xs)) ) val mapCollectionGen: Gen[MapCollection[SInt.type, SInt.type]] = for { @@ -625,4 +651,115 @@ trait ObjectGenerators extends TypeGenerators with ValidationSpecification with treeBuilder <- Gen.oneOf(Seq[SigmaPropValue => ErgoTree](ErgoTree.withSegregation, ErgoTree.withoutSegregation)) } yield treeBuilder(prop) + + val headerGen: Gen[Header] = for { + stateRoot <- avlTreeGen + parentId <- modifierIdBytesGen + header <- headerGen(stateRoot, parentId) + } yield header + + def headerGen(stateRoot: AvlTree, parentId: Coll[Byte]): Gen[Header] = for { + id <- modifierIdBytesGen + version <- arbByte.arbitrary + adProofsRoot <- digest32CollGen + transactionRoot <- digest32CollGen + timestamp <- arbLong.arbitrary + nBits <- arbLong.arbitrary + height <- heightGen + extensionRoot <- digest32CollGen + minerPk <- groupElementGen + powOnetimePk <- groupElementGen + powNonce <- nonceBytesGen + powDistance <- arbBigInt.arbitrary + votes <- minerVotesGen + } yield CHeader(id, version, parentId, adProofsRoot, stateRoot, transactionRoot, timestamp, nBits, + height, extensionRoot, minerPk, powOnetimePk, powNonce, powDistance, votes) + + def headersGen(stateRoot: AvlTree): Gen[Seq[Header]] = for { + size <- Gen.chooseNum(0, 10) + } yield if (size == 0) Seq() else + (0 to size) + .foldLeft(List[Header](headerGen(stateRoot, modifierIdBytesGen.sample.get).sample.get)) { (h, _) => + h :+ headerGen(stateRoot, h.last.id).sample.get + }.reverse + + val preHeaderGen: Gen[PreHeader] = for { + parentId <- modifierIdBytesGen + preHeader <- preHeaderGen(parentId) + } yield preHeader + + def preHeaderGen(parentId: Coll[Byte]): Gen[PreHeader] = for { + version <- arbByte.arbitrary + timestamp <- arbLong.arbitrary + nBits <- arbLong.arbitrary + height <- heightGen + minerPk <- groupElementGen + votes <- minerVotesGen + } yield CPreHeader(version, parentId, timestamp, nBits, height, minerPk, votes) + + val ergoLikeTransactionGen: Gen[ErgoLikeTransaction] = for { + inputBoxesIds <- Gen.nonEmptyListOf(boxIdGen) + dataInputBoxIds <- Gen.listOf(boxIdGen) + tx <- ergoLikeTransactionGen(inputBoxesIds, dataInputBoxIds) + } yield tx + + def ergoLikeTransactionGen(inputBoxesIds: Seq[BoxId], dataInputBoxIds: Seq[BoxId]): Gen[ErgoLikeTransaction] = for { + tokens <- tokensGen + outputsCount <- Gen.chooseNum(50, 200) + outputCandidates <- Gen.listOfN(outputsCount, ergoBoxCandidateGen(tokens)) + proofs <- Gen.listOfN(inputBoxesIds.length, serializedProverResultGen) + } yield new ErgoLikeTransaction( + inputs = inputBoxesIds.zip(proofs).map(t => Input(t._1, t._2)).toIndexedSeq, + dataInputs = dataInputBoxIds.map(DataInput).toIndexedSeq, + outputCandidates = outputCandidates.toIndexedSeq + ) + + val unsignedErgoLikeTransactionGen: Gen[UnsignedErgoLikeTransaction] = for { + inputBoxesIds <- Gen.nonEmptyListOf(boxIdGen) + dataInputBoxIds <- Gen.listOf(boxIdGen) + tx <- unsignedErgoLikeTransactionGen(inputBoxesIds, dataInputBoxIds) + } yield tx + + def unsignedErgoLikeTransactionGen(inputBoxesIds: Seq[BoxId], dataInputBoxIds: Seq[BoxId]): Gen[UnsignedErgoLikeTransaction] = for { + tokens <- tokensGen + outputsCount <- Gen.chooseNum(50, 200) + outputCandidates <- Gen.listOfN(outputsCount, ergoBoxCandidateGen(tokens)) + contextExtensions <- Gen.listOfN(inputBoxesIds.length, contextExtensionGen) + } yield new UnsignedErgoLikeTransaction( + inputs = inputBoxesIds.zip(contextExtensions).map(t => new UnsignedInput(t._1, t._2)).toIndexedSeq, + dataInputs = dataInputBoxIds.map(DataInput).toIndexedSeq, + outputCandidates = outputCandidates.toIndexedSeq + ) + + val ergoLikeTransactionTemplateGen: Gen[ErgoLikeTransactionTemplate[_ <: UnsignedInput]] = + Gen.oneOf(unsignedErgoLikeTransactionGen, ergoLikeTransactionGen) + + val ergoLikeContextGen: Gen[ErgoLikeContext] = for { + stateRoot <- avlTreeGen + headers <- headersGen(stateRoot) + preHeader <- preHeaderGen(headers.headOption.map(_.id).getOrElse(modifierIdBytesGen.sample.get)) + dataBoxes <- Gen.listOf(ergoBoxGen) + boxesToSpend <- Gen.nonEmptyListOf(ergoBoxGen) + extension <- contextExtensionGen + costLimit <- arbLong.arbitrary + initCost <- arbLong.arbitrary + avlTreeFlags <- avlTreeFlagsGen + spendingTransaction <- Gen.oneOf( + unsignedErgoLikeTransactionGen(boxesToSpend.map(_.id), dataBoxes.map(_.id)), + ergoLikeTransactionGen(boxesToSpend.map(_.id), dataBoxes.map(_.id)) + ) + } yield new ErgoLikeContext( + lastBlockUtxoRoot = AvlTreeData(ADDigest @@ stateRoot.digest.toArray, avlTreeFlags, unsignedIntGen.sample.get), + headers = headers.toColl, + preHeader = preHeader, + dataBoxes = dataBoxes.toIndexedSeq, + boxesToSpend = boxesToSpend.toIndexedSeq, + spendingTransaction = spendingTransaction, + selfIndex = 0, + extension = extension, + validationSettings = ValidationRules.currentSettings, + costLimit = costLimit, + initCost = initCost + ) + } diff --git a/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala b/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala index f70f972259..eefa1df334 100644 --- a/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala +++ b/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala @@ -3,21 +3,21 @@ package sigmastate.utxo import com.google.common.primitives.Longs import org.ergoplatform.ErgoScriptPredef.TrueProp import org.ergoplatform._ -import org.ergoplatform.dsl.{SigmaContractSyntax, ContractSpec, TestContractSpec} +import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, TestContractSpec} import scorex.crypto.authds.avltree.batch._ import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import sigmastate.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ -import sigmastate.eval.{IRContext, CSigmaProp} +import sigmastate.eval.{CSigmaProp, IRContext} import sigmastate.eval._ import sigmastate.eval.Extensions._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.lang.Terms._ import special.collection.Coll -import special.sigma.{Context, AvlTree} +import special.sigma.{AvlTree, Context} class AVLTreeScriptsSpecification extends SigmaTestingCommons { suite => @@ -217,10 +217,10 @@ class AVLTreeScriptsSpecification extends SigmaTestingCommons { suite => val s = ErgoBox(20, TrueProp, 0, Seq(), Map(reg1 -> AvlTreeConstant(SigmaDsl.avlTree(treeData)))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(s), spendingTransaction, self = s) @@ -251,10 +251,10 @@ class AVLTreeScriptsSpecification extends SigmaTestingCommons { suite => val recipientProposition = new ContextEnrichingTestProvingInterpreter().dlogSecrets.head.publicImage val selfBox = ErgoBox(20, TrueProp, 0, Seq(), Map(reg1 -> AvlTreeConstant(SigmaDsl.avlTree(treeData)))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(selfBox), createTransaction(ErgoBox(1, recipientProposition, 0)), self = selfBox) @@ -321,10 +321,10 @@ class AVLTreeScriptsSpecification extends SigmaTestingCommons { suite => val s = ErgoBox(20, TrueProp, 0, Seq(), Map(reg1 -> AvlTreeConstant(treeData), reg2 -> ByteArrayConstant(key))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(s), spendingTransaction, self = s) val pr = prover.prove(prop, ctx, fakeMessage).get @@ -373,10 +373,10 @@ class AVLTreeScriptsSpecification extends SigmaTestingCommons { suite => val s = ErgoBox(20, TrueProp, 0, Seq(), Map(reg1 -> AvlTreeConstant(treeData))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(s), spendingTransaction, self = s) val pr = prover.prove(env + (ScriptNameProp -> "prove"), prop, ctx, fakeMessage).get diff --git a/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala b/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala index 78e5ba71a7..4a4da55565 100644 --- a/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala +++ b/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala @@ -1,15 +1,15 @@ package sigmastate.utxo import java.math.BigInteger + import org.ergoplatform.ErgoBox.{R6, R8} -import org.ergoplatform.ErgoLikeContext.dummyPubkey import org.ergoplatform._ import scalan.RType import sigmastate.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ import sigmastate.eval.Extensions._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons, ErgoLikeTestInterpreter} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter._ import sigmastate.lang.Terms._ import special.sigma.InvalidType @@ -77,8 +77,8 @@ class BasicOpsSpecification extends SigmaTestingCommons { reg2 -> IntConstant(10))) val tx = createTransaction(newBox1) - val ctx = ErgoLikeContext(currentHeight = 0, - lastBlockUtxoRoot = AvlTreeData.dummy, dummyPubkey, boxesToSpend = IndexedSeq(boxToSpend), + val ctx = ErgoLikeContextTesting(currentHeight = 0, + lastBlockUtxoRoot = AvlTreeData.dummy, ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(boxToSpend), spendingTransaction = tx, self = boxToSpend) val pr = prover.prove(env + (ScriptNameProp -> s"${name}_prove"), prop, ctx, fakeMessage).fold(t => throw t, identity) diff --git a/src/test/scala/sigmastate/utxo/BlockchainSimulationSpecification.scala b/src/test/scala/sigmastate/utxo/BlockchainSimulationSpecification.scala index 6da37d6189..71f0a06e52 100644 --- a/src/test/scala/sigmastate/utxo/BlockchainSimulationSpecification.scala +++ b/src/test/scala/sigmastate/utxo/BlockchainSimulationSpecification.scala @@ -11,7 +11,7 @@ import scorex.crypto.authds.{ADDigest, ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util._ import sigmastate.Values.{IntConstant, LongConstant} -import sigmastate.helpers.{ErgoLikeTestProvingInterpreter, ErgoTransactionValidator, SigmaTestingCommons} +import sigmastate.helpers.{BlockchainState, ErgoLikeContextTesting, ErgoLikeTestProvingInterpreter, ErgoTransactionValidator, SigmaTestingCommons} import sigmastate.interpreter.ContextExtension import sigmastate.eval._ import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} @@ -36,9 +36,9 @@ class BlockchainSimulationSpecification extends SigmaTestingCommons { new ErgoBoxCandidate(10, minerPubKey, height, Colls.emptyColl[(TokenId, Long)], Map(heightReg -> IntConstant(height + windowSize))) val unsignedInput = new UnsignedInput(box.id) val tx = UnsignedErgoLikeTransaction(IndexedSeq(unsignedInput), IndexedSeq(newBoxCandidate)) - val context = ErgoLikeContext(height + 1, + val context = ErgoLikeContextTesting(height + 1, state.state.lastBlockUtxoRoot, - ErgoLikeContext.dummyPubkey, + ErgoLikeContextTesting.dummyPubkey, IndexedSeq(box), tx, box, @@ -215,7 +215,7 @@ object BlockchainSimulationSpecification { val boxes = (1 to 30).map(_ => ErgoBox(10, GE(Height, IntConstant(i)).toSigmaProp, 0, Seq(), Map(heightReg -> IntConstant(i)), txId)) ergoplatform.ErgoLikeTransaction(IndexedSeq(), boxes) }, - ErgoLikeContext.dummyPubkey + ErgoLikeContextTesting.dummyPubkey ) def initialState(block: Block = initBlock)(implicit IR: IRContext): ValidationState = { diff --git a/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala b/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala index 7b6c266ac6..2b419441b3 100644 --- a/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala +++ b/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala @@ -4,7 +4,7 @@ import org.ergoplatform import org.ergoplatform.ErgoScriptPredef.TrueProp import sigmastate.Values._ import sigmastate._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.lang.Terms._ import org.ergoplatform._ import sigmastate.SCollection._ @@ -19,10 +19,10 @@ class CollectionOperationsSpecification extends SigmaTestingCommons { outputs: IndexedSeq[ErgoBox]): ErgoLikeContext = { val (selfBox, toSpend) = if (boxesToSpend.isEmpty) (fakeSelf, IndexedSeq(fakeSelf)) else (boxesToSpend(0), boxesToSpend) - ergoplatform.ErgoLikeContext( + ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = toSpend, spendingTransaction = createTransaction(outputs), self = selfBox) @@ -97,10 +97,10 @@ class CollectionOperationsSpecification extends SigmaTestingCommons { val spendingTransaction = createTransaction(newBoxes) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), spendingTransaction, self = fakeSelf) @@ -129,10 +129,10 @@ class CollectionOperationsSpecification extends SigmaTestingCommons { val spendingTransaction = createTransaction(newBoxes) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), spendingTransaction, self = fakeSelf) @@ -159,10 +159,10 @@ class CollectionOperationsSpecification extends SigmaTestingCommons { val spendingTransaction = createTransaction(newBoxes) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), spendingTransaction, self = fakeSelf) @@ -199,10 +199,10 @@ class CollectionOperationsSpecification extends SigmaTestingCommons { val s = ErgoBox(20, TrueProp, 0, Seq(), Map(reg1 -> LongConstant(5))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(s), spendingTransaction, self = s) @@ -242,10 +242,10 @@ class CollectionOperationsSpecification extends SigmaTestingCommons { val s = ErgoBox(20, TrueProp, 0, Seq(), Map(reg1 -> LongConstant(5))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(s), spendingTransaction, self = s) @@ -273,10 +273,10 @@ class CollectionOperationsSpecification extends SigmaTestingCommons { val s = ErgoBox(21, pubkey, 0) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(s), spendingTransaction, self = s) diff --git a/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala b/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala index c9259858e8..e11bcb6969 100644 --- a/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala +++ b/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala @@ -1,11 +1,11 @@ package sigmastate.utxo -import org.ergoplatform.{ErgoLikeContext, Height} +import org.ergoplatform.{ErgoLikeContext, ErgoLikeTransaction, Height} import org.scalacheck.Gen import sigmastate.Values.IntConstant import sigmastate._ import sigmastate.lang.Terms._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTransactionTesting, SigmaTestingCommons} import scala.util.Random @@ -36,12 +36,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(pubkeyA, pubkeyB) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx, fakeMessage).get @@ -69,12 +69,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(pubkeyA, pubkeyB, pubkeyC) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx, fakeMessage).get @@ -103,12 +103,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(SigmaOr(pubkeyA, pubkeyB), pubkeyC) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx, fakeMessage).get @@ -138,12 +138,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(pubkeyA1, pubkeyA2, pubkeyA3, pubkeyA4) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx, fakeMessage).get @@ -169,12 +169,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(SigmaAnd(pubkeyA, pubkeyB), SigmaAnd(pubkeyC, pubkeyD)) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) proverA.prove(compiledProp, ctx, fakeMessage).isFailure shouldBe true @@ -210,12 +210,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(SigmaAnd(pubkeyA, pubkeyB), SigmaOr(pubkeyC, pubkeyD)) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) proverA.prove(compiledProp, ctx, fakeMessage).isFailure shouldBe true @@ -247,12 +247,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaAnd(pubkeyA, pubkeyB) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) proverA.prove(compiledProp, ctx, fakeMessage).isFailure shouldBe true @@ -280,12 +280,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(SigmaAnd(pubkeyA, pubkeyB), pubkeyC) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) proverA.prove(compiledProp, ctx, fakeMessage).isFailure shouldBe true @@ -320,12 +320,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaAnd(SigmaOr(pubkeyA, pubkeyB), SigmaOr(pubkeyC, pubkeyD)) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) proverA.prove(compiledProp, ctx, fakeMessage).isFailure shouldBe true @@ -361,12 +361,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaAnd(SigmaAnd(pubkeyA, pubkeyB), SigmaOr(pubkeyC, pubkeyD)) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) proverA.prove(compiledProp, ctx, fakeMessage).isFailure shouldBe true @@ -405,12 +405,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(SigmaOr(pubkeyA, pubkeyB), SigmaOr(pubkeyC, pubkeyD)) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx, fakeMessage).get @@ -443,12 +443,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(GT(Height, IntConstant(500)).toSigmaProp, SigmaOr(pubkeyA, pubkeyB)) compiledProp shouldBe prop - val ctx1 = ErgoLikeContext( + val ctx1 = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx1, fakeMessage).get verifier.verify(compiledProp, ctx1, prA, fakeMessage).get._1 shouldBe true @@ -456,12 +456,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { verifier.verify(compiledProp, ctx1, prB, fakeMessage).get._1 shouldBe true proverC.prove(compiledProp, ctx1, fakeMessage).isFailure shouldBe true - val ctx2 = ErgoLikeContext( + val ctx2 = ErgoLikeContextTesting( currentHeight = 501, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prC = proverC.prove(compiledProp, ctx2, fakeMessage).get verifier.verify(compiledProp, ctx2, prC, fakeMessage).get._1 shouldBe true @@ -485,12 +485,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(SigmaOr(pubkeyA, pubkeyB), SigmaAnd(pubkeyC, GT(Height, IntConstant(500)).toSigmaProp)) compiledProp shouldBe prop - val ctx1 = ErgoLikeContext( + val ctx1 = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx1, fakeMessage).get @@ -500,12 +500,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { proverC.prove(compiledProp, ctx1, fakeMessage).isFailure shouldBe true - val ctx2 = ErgoLikeContext( + val ctx2 = ErgoLikeContextTesting( currentHeight = 501, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA2 = proverA.prove(compiledProp, ctx2, fakeMessage).get @@ -533,12 +533,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { val prop = SigmaOr(SigmaOr(pubkeyA, pubkeyB), SigmaAnd(pubkeyC, GT(Height, IntConstant(500)).toSigmaProp)) compiledProp shouldBe prop - val ctx1 = ErgoLikeContext( + val ctx1 = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx1, fakeMessage).get @@ -548,12 +548,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { proverC.prove(compiledProp, ctx1, fakeMessage).isFailure shouldBe true - val ctx2 = ErgoLikeContext( + val ctx2 = ErgoLikeContextTesting( currentHeight = 501, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA2 = proverA.prove(compiledProp, ctx2, fakeMessage).get @@ -583,12 +583,12 @@ class ComplexSigSpecification extends SigmaTestingCommons { kNumKeysCombinations.map(combs => CAND(combs.map(_.publicImage))) ) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) // any prover alone (no added secrets) should fail diff --git a/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala b/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala index 4143faac81..a719c43ade 100644 --- a/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala +++ b/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala @@ -6,7 +6,7 @@ import scorex.crypto.hash.Blake2b256 import sigmastate.Values._ import sigmastate._ import sigmastate.lang.Terms._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons, ErgoLikeTestInterpreter} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import special.collection.Coll @@ -31,7 +31,7 @@ class ContextEnrichingSpecification extends SigmaTestingCommons { ) compiledScript shouldBe prop - val ctx = ErgoLikeContext.dummy(fakeSelf) + val ctx = ErgoLikeContextTesting.dummy(fakeSelf) val pr = prover.prove(compiledScript, ctx, fakeMessage).get val ctxv = ctx.withExtension(pr.extension) @@ -63,7 +63,7 @@ class ContextEnrichingSpecification extends SigmaTestingCommons { ) compiledScript shouldBe prop - val ctx = ErgoLikeContext.dummy(fakeSelf) + val ctx = ErgoLikeContextTesting.dummy(fakeSelf) val pr = prover.prove(compiledScript, ctx, fakeMessage).get val ctxv = ctx.withExtension(pr.extension) @@ -93,7 +93,7 @@ class ContextEnrichingSpecification extends SigmaTestingCommons { val prop = EQ(Xor(GetVarByteArray(k1).get, GetVarByteArray(k2).get), ByteArrayConstant(r)).toSigmaProp compiledScript shouldBe prop - val ctx = ErgoLikeContext.dummy(fakeSelf) + val ctx = ErgoLikeContextTesting.dummy(fakeSelf) val pr = prover.prove(prop, ctx, fakeMessage).get val ctxv = ctx.withExtension(pr.extension) @@ -124,7 +124,7 @@ class ContextEnrichingSpecification extends SigmaTestingCommons { val prop = EQ(CalcBlake2b256(GetVarByteArray(1).get), ByteArrayConstant(Blake2b256(preimage.toArray))).toSigmaProp compiledScript shouldBe prop - val ctx = ErgoLikeContext.dummy(fakeSelf) + val ctx = ErgoLikeContextTesting.dummy(fakeSelf) val pr = prover.prove(prop, ctx, fakeMessage).get val ctxv = ctx.withExtension(pr.extension) @@ -152,7 +152,7 @@ class ContextEnrichingSpecification extends SigmaTestingCommons { ByteArrayConstant(Blake2b256(preimage2.append(preimage1).toArray))).toSigmaProp compiledScript shouldBe prop - val ctx = ErgoLikeContext.dummy(fakeSelf) + val ctx = ErgoLikeContextTesting.dummy(fakeSelf) val pr = prover.prove(prop, ctx, fakeMessage).get val ctxv = ctx.withExtension(pr.extension) diff --git a/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala b/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala index 3788ed3d66..1244348741 100644 --- a/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala +++ b/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala @@ -14,10 +14,10 @@ import sigmastate.eval._ import sigmastate.interpreter.Interpreter._ import sigmastate.basics.DLogProtocol.ProveDlog import sigmastate.basics.ProveDHTuple -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons, ErgoLikeTestInterpreter} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTransactionTesting, SigmaTestingCommons} import sigmastate.lang.Terms._ import sigmastate.lang.exceptions.InterpreterException -import sigmastate.serialization.{ValueSerializer, SerializationSpecification} +import sigmastate.serialization.{SerializationSpecification, ValueSerializer} class ErgoLikeInterpreterSpecification extends SigmaTestingCommons with SerializationSpecification { @@ -34,7 +34,7 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val h1 = SigmaPropConstant(prover1.dlogSecrets.head.publicImage) val h2 = SigmaPropConstant(prover2.dlogSecrets.head.publicImage) - val ctx = ErgoLikeContext.dummy(fakeSelf) + val ctx = ErgoLikeContextTesting.dummy(fakeSelf) val e = compile(Map("h1" -> h1.treeWithSegregation.bytes, "h2" -> h2.treeWithSegregation.bytes), "h1 == h1") val exp = TrueLeaf @@ -69,12 +69,12 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons compiledProp2 shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val pr = prover.prove(prop, ctx, fakeMessage).get @@ -99,12 +99,12 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val prop = SigmaOr(pubkeyA, pubdhB) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx, fakeMessage).get @@ -126,12 +126,12 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val prop = SigmaAnd(pubkeyA, pubdhA) compiledProp shouldBe prop - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val prA = proverA.prove(compiledProp, ctx, fakeMessage).get @@ -181,10 +181,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons compiledProp } - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = height, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), spendingTransaction, self = fakeSelf) @@ -244,10 +244,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val spendingTransaction = createTransaction(newBoxes) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), spendingTransaction, self = fakeSelf) @@ -274,10 +274,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val spendingTransaction = createTransaction(newBoxes) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), spendingTransaction, self = fakeSelf) @@ -310,10 +310,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val recipientProposition = SigmaPropConstant(new ContextEnrichingTestProvingInterpreter().dlogSecrets.head.publicImage) val selfBox = ErgoBox(20, ErgoScriptPredef.TrueProp, 0, Seq(), Map()) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(selfBox), createTransaction(ErgoBox(1, recipientProposition, 0)), self = selfBox) @@ -354,10 +354,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons Map(regPubkey1 -> GroupElementConstant(pubkey1.value), regPubkey2 -> GroupElementConstant(pubkey2.value))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(s1), spendingTransaction, self = s1) @@ -369,10 +369,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons //make sure that wrong case couldn't be proved val s2 = ErgoBox(20, ErgoScriptPredef.TrueProp, 0, Seq(), Map(regPubkey1 -> GroupElementConstant(pubkey1.value))) - val wrongCtx = ErgoLikeContext( + val wrongCtx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(s2), spendingTransaction, self = s2) @@ -404,10 +404,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val recipientProposition = new ContextEnrichingTestProvingInterpreter().dlogSecrets.head.publicImage val selfBox = ErgoBox(20, TrueProp, 0, Seq(), Map()) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(selfBox), createTransaction(ErgoBox(1, recipientProposition, 0)), self = selfBox) @@ -457,10 +457,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val s = ErgoBox(10, prop, 0, Seq(), Map()) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(brother, s), spendingTransaction, self = s) @@ -468,10 +468,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val pr = prover.prove(emptyEnv + (ScriptNameProp -> "prove_prop"), prop, ctx, fakeMessage).fold(t => throw t, x => x) verifier.verify(emptyEnv + (ScriptNameProp -> "verify_prop"), prop, ctx, pr, fakeMessage).fold(t => throw t, x => x)._1 shouldBe true - val wrongCtx = ErgoLikeContext( + val wrongCtx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(brotherWithWrongId, s), spendingTransaction, self = s) @@ -537,10 +537,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val s = ErgoBox(10, prop, 0, Seq(), Map()) - val ctx1 = ErgoLikeContext( + val ctx1 = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(friend, s), spendingTransaction, self = s) @@ -548,10 +548,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val pr1 = prover.prove(prop, ctx1, fakeMessage).success.value verifier.verify(prop, ctx1, pr1, fakeMessage).success.value._1 shouldBe true - val ctx2 = ErgoLikeContext( + val ctx2 = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(s, friend), spendingTransaction, self = s) @@ -562,10 +562,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val pr3 = prover.prove(prop, ctx2, fakeMessage).success.value verifier.verify(prop, ctx2, pr3, fakeMessage).success.value._1 shouldBe true - val wrongCtx1 = ErgoLikeContext( + val wrongCtx1 = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(friendWithWrongId, s), spendingTransaction, self = s) @@ -612,10 +612,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons val spendingTransaction = createTransaction(output) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(input0, input1, input2, input3), spendingTransaction, self = input3) @@ -637,10 +637,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons // expect SBoolean in the register val prop = DeserializeRegister(R4, SBoolean).toSigmaProp - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(box), createTransaction(IndexedSeq(ErgoBox(10, TrueProp, 0))), self = box) @@ -662,10 +662,10 @@ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons ).toSigmaProp val box = ErgoBox(20, ErgoScriptPredef.TrueProp, 0, Seq(), Map()) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(box), createTransaction(IndexedSeq(ErgoBox(10, TrueProp, 0))), self = box) diff --git a/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala b/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala index 9ba01a676a..c68f1dc03a 100644 --- a/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala +++ b/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala @@ -1,10 +1,10 @@ package sigmastate.utxo -import org.ergoplatform.ErgoLikeContext +import org.ergoplatform.{ErgoLikeContext, ErgoLikeTransaction} import sigmastate.basics.DLogProtocol.{DLogProverInput, ProveDlog} import sigmastate.Values.{ConcreteCollection, FalseLeaf, IntConstant, SigmaPropConstant, SigmaPropValue, TrueLeaf} import sigmastate._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTransactionTesting, SigmaTestingCommons} import sigmastate.lang.Terms._ import sigmastate.lang.exceptions.CosterException @@ -34,12 +34,12 @@ class ThresholdSpecification extends SigmaTestingCommons { val proverAC = proverA.withSecrets(Seq(skC)) val proverBC = proverB.withSecrets(Seq(skC)) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val env = Map("pubkeyA" -> pubkeyA, "pubkeyB" -> pubkeyB, "pubkeyC" -> pubkeyC) @@ -113,12 +113,12 @@ class ThresholdSpecification extends SigmaTestingCommons { property("threshold reduce to crypto") { import TrivialProp._ val prover = new ContextEnrichingTestProvingInterpreter - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) case class TestCase(numTrue: Int, vector: Seq[SigmaPropValue], dlogOnlyVector: DlogOnlyVector) @@ -283,12 +283,12 @@ class ThresholdSpecification extends SigmaTestingCommons { val goodProvers = Seq(goodProver1, goodProver2, goodProver3, goodProver4) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val verifier = new ErgoLikeTestInterpreter @@ -330,12 +330,12 @@ class ThresholdSpecification extends SigmaTestingCommons { for (i <- secrets.indices) { provers = provers ++ provers.map(p => (p._1 + 1, p._2.withSecrets(secrets(i)))) } - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val verifier = new ErgoLikeTestInterpreter diff --git a/src/test/scala/sigmastate/utxo/benchmarks/CrowdFundingKernelContract.scala b/src/test/scala/sigmastate/utxo/benchmarks/CrowdFundingKernelContract.scala index bb52ae09f2..c15933dd47 100644 --- a/src/test/scala/sigmastate/utxo/benchmarks/CrowdFundingKernelContract.scala +++ b/src/test/scala/sigmastate/utxo/benchmarks/CrowdFundingKernelContract.scala @@ -54,9 +54,9 @@ class CrowdFundingKernelContract( } def prove(ctx: ErgoLikeContext, message: Array[Byte]): Array[Byte] = { - val c1 = ctx.currentHeight >= timeout //&& isProven(backerPubKey, fakeMessage) + val c1 = ctx.preHeader.height >= timeout //&& isProven(backerPubKey, fakeMessage) val c2 = Array( - ctx.currentHeight < timeout, + ctx.preHeader.height < timeout, ctx.spendingTransaction.outputs.exists(out => { out.value >= minToRaise && util.Arrays.equals(out.propositionBytes, projectPubKey.toSigmaProp.treeWithSegregation.bytes) diff --git a/src/test/scala/sigmastate/utxo/benchmarks/CrowdfundingBenchmark.scala b/src/test/scala/sigmastate/utxo/benchmarks/CrowdfundingBenchmark.scala index bc2bf4dd57..c24a80983a 100644 --- a/src/test/scala/sigmastate/utxo/benchmarks/CrowdfundingBenchmark.scala +++ b/src/test/scala/sigmastate/utxo/benchmarks/CrowdfundingBenchmark.scala @@ -1,10 +1,10 @@ package sigmastate.utxo.benchmarks -import org.ergoplatform.{ErgoLikeContext, ErgoLikeTransaction, ErgoBox, ErgoScriptPredef} +import org.ergoplatform.{ErgoBox, ErgoLikeContext, ErgoLikeTransaction, ErgoScriptPredef} import sigmastate.Values._ import sigmastate._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, SigmaTestingCommons} import scalan.util.BenchmarkUtil._ class CrowdfundingBenchmark extends SigmaTestingCommons { @@ -16,10 +16,10 @@ class CrowdfundingBenchmark extends SigmaTestingCommons { val tx1Output2 = ErgoBox(1, contract.projectPubKey, 0) //normally this transaction would invalid, but we're not checking it in this test val tx = createTransaction(IndexedSeq(tx1Output1, tx1Output2)) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = contract.timeout - 1, // HEIGHT < timeout, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(), spendingTransaction = tx, self = outputToSpend) diff --git a/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala b/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala index 676cfb8f3f..769781e081 100644 --- a/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala +++ b/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala @@ -3,19 +3,19 @@ package sigmastate.utxo.blockchain import org.ergoplatform.ErgoBox.TokenId import org.ergoplatform._ import scorex.crypto.authds.{ADDigest, ADKey, ADValue} -import scorex.crypto.authds.avltree.batch.{Remove, BatchAVLProver, Insert} -import scorex.crypto.hash.{Digest32, Blake2b256} -import sigmastate.{GE, AvlTreeData, AvlTreeFlags, Values} -import sigmastate.Values.{LongConstant, ErgoTree} +import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert, Remove} +import scorex.crypto.hash.{Blake2b256, Digest32} +import sigmastate.{AvlTreeData, AvlTreeFlags, GE, Values} +import sigmastate.Values.{ErgoTree, LongConstant} import sigmastate.eval._ -import sigmastate.helpers.{ErgoLikeTestProvingInterpreter, SigmaTestingCommons, ErgoTransactionValidator} +import sigmastate.helpers.{BlockchainState, ErgoLikeContextTesting, ErgoLikeTestProvingInterpreter, ErgoTransactionValidator, SigmaTestingCommons} import scala.collection.mutable import scala.util.{Random, Try} import scorex.util._ import sigmastate.interpreter.ContextExtension import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} -import sigmastate.utxo.blockchain.BlockchainSimulationTestingCommons.{ValidationState, FullBlock} +import sigmastate.utxo.blockchain.BlockchainSimulationTestingCommons.{FullBlock, ValidationState} import scala.annotation.tailrec @@ -51,7 +51,7 @@ trait BlockchainSimulationTestingCommons extends SigmaTestingCommons { new ErgoBoxCandidate(10, prop, height, Colls.emptyColl[(TokenId, Long)], Map()) val unsignedInput = new UnsignedInput(box.id) val tx = UnsignedErgoLikeTransaction(IndexedSeq(unsignedInput), IndexedSeq(newBoxCandidate)) - val context = ErgoLikeContext(height + 1, + val context = ErgoLikeContextTesting(height + 1, state.state.lastBlockUtxoRoot, minerPubkey, IndexedSeq(box), @@ -150,7 +150,7 @@ object BlockchainSimulationTestingCommons extends SigmaTestingCommons { val boxes = (1 to 50).map(_ => ErgoBox(10, Values.TrueLeaf.toSigmaProp, i, Seq(), Map(), txId)) createTransaction(boxes) }, - ErgoLikeContext.dummyPubkey + ErgoLikeContextTesting.dummyPubkey ) def initialState(block: FullBlock = initBlock)(implicit IR: IRContext): ValidationState = { diff --git a/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala index fb8f846b3a..3952bef3a1 100644 --- a/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala @@ -1,12 +1,12 @@ package sigmastate.utxo.examples -import org.ergoplatform.{ErgoLikeContext, Height} +import org.ergoplatform.{ErgoLikeContext, ErgoLikeTransaction, Height} import scorex.crypto.hash.Blake2b256 import scorex.utils.Random import sigmastate.Values._ import sigmastate._ import interpreter.Interpreter._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTransactionTesting, SigmaTestingCommons} import sigmastate.lang.Terms._ import sigmastate.utxo.SizeOf @@ -97,12 +97,12 @@ class AtomicSwapExampleSpecification extends SigmaTestingCommons { //Preliminary checks: //B can't spend coins of A in chain1 (generate a valid proof) - val ctxf1 = ErgoLikeContext( + val ctxf1 = ErgoLikeContextTesting( currentHeight = height1 + 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) proverB.prove(env, prop1, ctxf1, fakeMessage).isSuccess shouldBe false @@ -110,22 +110,22 @@ class AtomicSwapExampleSpecification extends SigmaTestingCommons { proverA.prove(env, prop1, ctxf1, fakeMessage).isSuccess shouldBe false //B cant't withdraw his coins in chain2 (generate a valid proof) - val ctxf2 = ErgoLikeContext( + val ctxf2 = ErgoLikeContextTesting( currentHeight = height2 + 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, - boxesToSpend = IndexedSeq(fakeSelf), spendingTransaction = null, self = fakeSelf) + minerPubkey = ErgoLikeContextTesting.dummyPubkey, + boxesToSpend = IndexedSeq(fakeSelf), spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) proverB.prove(env, prop2, ctxf2, fakeMessage).isSuccess shouldBe false //Successful run below: //A spends coins of B in chain2 - val ctx1 = ErgoLikeContext( + val ctx1 = ErgoLikeContextTesting( currentHeight = height2 + 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val pr = proverA.prove(env, prop2, ctx1, fakeMessage).get verifier.verify(env, prop2, ctx1, pr, fakeMessage).get._1 shouldBe true @@ -135,12 +135,12 @@ class AtomicSwapExampleSpecification extends SigmaTestingCommons { val proverB2 = proverB.withContextExtender(1, t.asInstanceOf[CollectionConstant[SByte.type]]) //B spends coins of A in chain1 with knowledge of x - val ctx2 = ErgoLikeContext( + val ctx2 = ErgoLikeContextTesting( currentHeight = height1 + 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fakeSelf), - spendingTransaction = null, + spendingTransaction = ErgoLikeTransactionTesting.dummy, self = fakeSelf) val pr2 = proverB2.prove(env, prop1, ctx2, fakeMessage).get verifier.verify(env, prop1, ctx2, pr2, fakeMessage).get._1 shouldBe true diff --git a/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala b/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala index dc0543e29b..d684ff908a 100644 --- a/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala @@ -3,7 +3,7 @@ package sigmastate.utxo.examples import org.ergoplatform._ import scorex.util.ScorexLogging import sigmastate.Values.IntConstant -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, SigmaTestingCommons} import sigmastate.interpreter.ContextExtension import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.lang.Terms._ @@ -145,7 +145,7 @@ class CoinEmissionSpecification extends SigmaTestingCommons with ScorexLogging { ) } - val context = ErgoLikeContext(height, + val context = ErgoLikeContextTesting(height, state.state.lastBlockUtxoRoot, minerPubkey, IndexedSeq(emissionBox), diff --git a/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala index a3955d476c..1933f73c0d 100644 --- a/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala @@ -4,7 +4,7 @@ import org.ergoplatform.ErgoBox.{R4, R5, R6} import org.ergoplatform._ import sigmastate.AvlTreeData import sigmastate.Values.{IntConstant, LongConstant} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.lang.Terms._ @@ -127,10 +127,10 @@ class ColdWalletAdvContractExampleSpecification extends SigmaTestingCommons { //normally this transaction would be invalid, but we're not checking it in this test val firstWithdrawTx1Key = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(firstChangeOutput1Key, firstWithdrawOutput1Key)) - val firstWithdrawContext1Key = ErgoLikeContext( + val firstWithdrawContext1Key = ErgoLikeContextTesting( currentHeight = firstWithdrawHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(depositOutput), spendingTransaction = firstWithdrawTx1Key, self = depositOutput @@ -163,10 +163,10 @@ class ColdWalletAdvContractExampleSpecification extends SigmaTestingCommons { //normally this transaction would be invalid, but we're not checking it in this test val firstWithdrawTx2Key = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(firstChangeOutput2Key, firstWithdrawOutput2Key)) - val firstWithdrawContext2Key = ErgoLikeContext( + val firstWithdrawContext2Key = ErgoLikeContextTesting( currentHeight = firstWithdrawHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(depositOutput), spendingTransaction = firstWithdrawTx2Key, self = depositOutput diff --git a/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala index d0bfa03882..64b0bf4b1c 100644 --- a/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala @@ -2,7 +2,7 @@ package sigmastate.utxo.examples import org.ergoplatform.ErgoBox.{R4, R5} import org.ergoplatform._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.AvlTreeData import sigmastate.Values.{IntConstant, LongConstant} import sigmastate.interpreter.Interpreter.ScriptNameProp @@ -93,10 +93,10 @@ class ColdWalletContractExampleSpecification extends SigmaTestingCommons { val withdrawTxAliceAndBob = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(withdrawOutputAliceAndBob)) - val withdrawContextAliceandBob = ErgoLikeContext( + val withdrawContextAliceandBob = ErgoLikeContextTesting( currentHeight = firstWithdrawHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(depositOutput), spendingTransaction = withdrawTxAliceAndBob, self = depositOutput @@ -123,10 +123,10 @@ class ColdWalletContractExampleSpecification extends SigmaTestingCommons { //normally this transaction would be invalid, but we're not checking it in this test val firstWithdrawTx = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(firstChangeOutput, firstWithdrawOutput)) - val firstWithdrawContext = ErgoLikeContext( + val firstWithdrawContext = ErgoLikeContextTesting( currentHeight = firstWithdrawHeight, // 51 lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(depositOutput), spendingTransaction = firstWithdrawTx, self = depositOutput @@ -152,10 +152,10 @@ class ColdWalletContractExampleSpecification extends SigmaTestingCommons { // normally this transaction would be invalid, but we're not checking it in this test val withdrawTxInvalid = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(changeOutputInvalid, withdrawOutputInvalid)) - val withdrawContextInvalid = ErgoLikeContext( + val withdrawContextInvalid = ErgoLikeContextTesting( currentHeight = firstWithdrawHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(depositOutput), spendingTransaction = withdrawTxInvalid, self = depositOutput @@ -186,10 +186,10 @@ class ColdWalletContractExampleSpecification extends SigmaTestingCommons { //normally this transaction would be invalid, but we're not checking it in this test val secondWithdrawTx = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(secondChangeOutput, secondWithdrawOutput)) - val secondWithdrawContext = ErgoLikeContext( + val secondWithdrawContext = ErgoLikeContextTesting( currentHeight = secondWithdrawHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(firstChangeOutput), spendingTransaction = secondWithdrawTx, self = firstChangeOutput diff --git a/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala index cbf578a0ef..b058028605 100644 --- a/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala @@ -6,7 +6,7 @@ import org.scalatest.TryValues._ import sigmastate.basics.DLogProtocol.ProveDlog import scorex.crypto.hash.Blake2b256 import sigmastate.Values.{ByteArrayConstant, SigmaPropValue, Value} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.lang.Terms._ import sigmastate.{AvlTreeData, SBoolean} @@ -20,10 +20,10 @@ class CoopExampleSpecification extends SigmaTestingCommons { def mkCtx(height: Int, tx: ErgoLikeTransaction, self: ErgoBox): ErgoLikeContext = { - ErgoLikeContext( + ErgoLikeContextTesting( currentHeight = height, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(self), spendingTransaction = tx, self = self) diff --git a/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala index fa551e6a20..3a44b051bf 100644 --- a/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala @@ -9,7 +9,7 @@ import sigmastate.AvlTreeData import sigmastate.Values.GroupElementConstant import sigmastate.basics.DLogProtocol.ProveDlog import sigmastate.basics.{DiffieHellmanTupleProverInput, ProveDHTuple} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.CryptoConstants import sigmastate.interpreter.Interpreter._ import sigmastate.lang.Terms._ @@ -79,10 +79,10 @@ class DHTupleExampleSpecification extends SigmaTestingCommons { val tx = createTransaction(IndexedSeq(outBox)) - val context = ErgoLikeContext( + val context = ErgoLikeContextTesting( currentHeight = 70, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(inBox), spendingTransaction = tx, self = inBox diff --git a/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala index 65877b7013..65befc4e8b 100644 --- a/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala @@ -4,7 +4,7 @@ import sigmastate.interpreter.Interpreter._ import org.ergoplatform._ import sigmastate.Values.ShortConstant import sigmastate._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.ContextExtension import sigmastate.lang.Terms._ @@ -84,10 +84,10 @@ class DemurrageExampleSpecification extends SigmaTestingCommons { val tx1 = createTransaction(createBox(outValue, prop, currentHeight1)) val selfBox = createBox(inValue, prop, inHeight) - val ctx1 = ErgoLikeContext( + val ctx1 = ErgoLikeContextTesting( currentHeight1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(selfBox), spendingTransaction = tx1, self = selfBox, @@ -104,10 +104,10 @@ class DemurrageExampleSpecification extends SigmaTestingCommons { //case 2: demurrage time has come val currentHeight2 = inHeight + demurragePeriod val tx2 = createTransaction(createBox(outValue, prop, currentHeight2)) - val ctx2 = ErgoLikeContext( + val ctx2 = ErgoLikeContextTesting( currentHeight2, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(selfBox), spendingTransaction = tx2, self = selfBox, @@ -120,15 +120,15 @@ class DemurrageExampleSpecification extends SigmaTestingCommons { //miner can spend "demurrageCoeff * demurragePeriod" tokens val b = createBox(outValue, prop, currentHeight2) val tx3 = createTransaction(b) - val ctx3 = ErgoLikeContext( + val ctx3 = ErgoLikeContextTesting( currentHeight = currentHeight2, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(b, selfBox), spendingTransaction = tx3, self = selfBox) - assert(ctx3.spendingTransaction.outputs.head.propositionBytes sameElements ctx3.self.propositionBytes) + assert(ctx3.spendingTransaction.outputs.head.propositionBytes sameElements ctx3.boxesToSpend(ctx3.selfIndex).propositionBytes) val mProverRes1 = minerProver.prove(prop, ctx3, fakeMessage).get val _ctx3: ErgoLikeContext = ctx3.withExtension(mProverRes1.extension) @@ -137,10 +137,10 @@ class DemurrageExampleSpecification extends SigmaTestingCommons { //miner can't spend more val b2 = createBox(outValue - 1, prop, currentHeight2) val tx4 = createTransaction(b2) - val ctx4 = ErgoLikeContext( + val ctx4 = ErgoLikeContextTesting( currentHeight = currentHeight2, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(b2, selfBox), spendingTransaction = tx4, self = selfBox, @@ -152,10 +152,10 @@ class DemurrageExampleSpecification extends SigmaTestingCommons { //miner can spend less val tx5 = createTransaction(createBox(outValue + 1, prop, currentHeight2)) - val ctx5 = ErgoLikeContext( + val ctx5 = ErgoLikeContextTesting( currentHeight = currentHeight2, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(selfBox), spendingTransaction = tx5, self = selfBox, @@ -169,10 +169,10 @@ class DemurrageExampleSpecification extends SigmaTestingCommons { val b3 = createBox(iv, ErgoScriptPredef.FalseProp, currentHeight2) val tx6 = createTransaction(b3) val selfBox6 = createBox(iv, prop, inHeight) - val ctx6 = ErgoLikeContext( + val ctx6 = ErgoLikeContextTesting( currentHeight = currentHeight2, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(b3, selfBox6), spendingTransaction = tx6, self = selfBox6, diff --git a/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala index 112f114600..213cad5606 100644 --- a/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala @@ -1,16 +1,16 @@ package sigmastate.utxo.examples import org.ergoplatform._ -import scorex.crypto.authds.avltree.batch.{Lookup, BatchAVLProver, Insert} +import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert, Lookup} import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash -import scorex.crypto.hash.{Digest32, Blake2b256} +import scorex.crypto.hash.{Blake2b256, Digest32} import sigmastate.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ import sigmastate.eval._ import sigmastate.lang.Terms._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons, ErgoLikeTestInterpreter} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.serialization.ValueSerializer import sigmastate.utxo._ @@ -143,10 +143,10 @@ class FsmExampleSpecification extends SigmaTestingCommons { avlProver.performOneOperation(Lookup(ADKey @@ (transition12 ++ script1Hash))) val transition12Proof = avlProver.generateProof() - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fsmBox1), createTransaction(fsmBox2), self = fsmBox1) @@ -163,10 +163,10 @@ class FsmExampleSpecification extends SigmaTestingCommons { avlProver.performOneOperation(Lookup(ADKey @@ (transition21 ++ script2Hash))) val transition21Proof = avlProver.generateProof() - val ctx2 = ErgoLikeContext( + val ctx2 = ErgoLikeContextTesting( currentHeight = 51, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fsmBox2), createTransaction(fsmBox1), self = fsmBox2) @@ -191,10 +191,10 @@ class FsmExampleSpecification extends SigmaTestingCommons { avlProver.performOneOperation(Lookup(ADKey @@ (transition13 ++ script1Hash))) val transition13Proof = avlProver.generateProof() - val ctx3 = ErgoLikeContext( + val ctx3 = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fsmBox1), createTransaction(fsmBox3), self = fsmBox1) @@ -218,10 +218,10 @@ class FsmExampleSpecification extends SigmaTestingCommons { avlProver.performOneOperation(Lookup(ADKey @@ (transition23 ++ script3Hash))) val transition23Proof = avlProver.generateProof() - val ctx23 = ErgoLikeContext( + val ctx23 = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fsmBox2), createTransaction(fsmBox3), self = fsmBox2) @@ -240,10 +240,10 @@ class FsmExampleSpecification extends SigmaTestingCommons { avlProver.performOneOperation(Lookup(ADKey @@ (transition30 ++ script4Hash))) val transition30Proof = avlProver.generateProof() - val ctx30 = ErgoLikeContext( + val ctx30 = ErgoLikeContextTesting( currentHeight = 52, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fsmBox3), createTransaction(freeBox), self = fsmBox3) @@ -256,10 +256,10 @@ class FsmExampleSpecification extends SigmaTestingCommons { (new ErgoLikeTestInterpreter).verify(fsmScript, ctx30, spendingProof30, fakeMessage).get._1 shouldBe true //it is impossible to leave FSM at state2 - val ctx20 = ErgoLikeContext( + val ctx20 = ErgoLikeContextTesting( currentHeight = 52, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fsmBox2), createTransaction(freeBox), self = fsmBox2) diff --git a/src/test/scala/sigmastate/utxo/examples/IcoExample.scala b/src/test/scala/sigmastate/utxo/examples/IcoExample.scala index e5992e6a68..7089cb0f3c 100644 --- a/src/test/scala/sigmastate/utxo/examples/IcoExample.scala +++ b/src/test/scala/sigmastate/utxo/examples/IcoExample.scala @@ -10,6 +10,7 @@ import scorex.crypto.hash.{Digest32, Blake2b256} import sigmastate.Values.{AvlTreeConstant, IntArrayConstant, CollectionConstant, ByteArrayConstant, SigmaPropValue} import sigmastate._ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestProvingInterpreter, SigmaTestingCommons} +import sigmastate.helpers.ErgoLikeContextTesting import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.lang.Terms._ import sigmastate.serialization.ErgoTreeSerializer @@ -406,10 +407,10 @@ class IcoExample extends SigmaTestingCommons { suite => val fundingTx = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(projectBoxAfter, feeBox)) - val fundingContext = ErgoLikeContext( + val fundingContext = ErgoLikeContextTesting( currentHeight = 1000, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = inputBoxes, spendingTransaction = fundingTx, self = projectBoxBefore) @@ -443,10 +444,10 @@ class IcoExample extends SigmaTestingCommons { suite => val issuanceTx = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(projectBoxAfterClosing, ergoWithdrawalBox, feeBox)) - val issuanceContext = ErgoLikeContext( + val issuanceContext = ErgoLikeContextTesting( currentHeight = 1000, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(projectBoxBeforeClosing), spendingTransaction = issuanceTx, self = projectBoxBeforeClosing) @@ -515,10 +516,10 @@ class IcoExample extends SigmaTestingCommons { suite => val outputs = IndexedSeq(projectBoxAfter) ++ withdrawBoxes ++ IndexedSeq(feeBox) val fundingTx = ErgoLikeTransaction(IndexedSeq(), outputs) - val fundingContext = ErgoLikeContext( + val fundingContext = ErgoLikeContextTesting( currentHeight = 1000, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(projectBoxBefore), spendingTransaction = fundingTx, self = projectBoxBefore) diff --git a/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala b/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala index 9da3ba7d2d..3268eabad7 100644 --- a/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala @@ -6,9 +6,9 @@ import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert, Lookup} import scorex.crypto.hash.{Blake2b256, Digest32} import sigmastate.{AvlTreeData, AvlTreeFlags, TrivialProp} -import sigmastate.Values.{ByteArrayConstant, AvlTreeConstant, SigmaPropConstant, LongConstant} +import sigmastate.Values.{AvlTreeConstant, ByteArrayConstant, LongConstant, SigmaPropConstant} import sigmastate.eval.{IRContext, SigmaDsl} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestProvingInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestProvingInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.serialization.ErgoTreeSerializer import sigmastate.lang.Terms._ @@ -302,10 +302,10 @@ class LetsSpecification extends SigmaTestingCommons { val issuanceTx = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(projectBoxAfter, userBox, feeBox)) - val fundingContext = ErgoLikeContext( + val fundingContext = ErgoLikeContextTesting( currentHeight = 1000, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(projectBoxBefore), spendingTransaction = issuanceTx, self = projectBoxBefore) @@ -349,14 +349,14 @@ class LetsSpecification extends SigmaTestingCommons { val issuanceTx = new ErgoLikeTransaction(IndexedSeq(), IndexedSeq(directoryDataInput), IndexedSeq(userBoxAfter0, userBoxAfter1)) - val exchangeContext = ErgoLikeContext( + val exchangeContext = ErgoLikeContextTesting( currentHeight = 1000, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, dataBoxes = IndexedSeq(directoryBox), boxesToSpend = IndexedSeq(userBoxBefore0, userBoxBefore1), spendingTransaction = issuanceTx, - self = userBoxBefore0) + selfIndex = 0) val managementProver = new ContextEnrichingTestProvingInterpreter() .withContextExtender(1, ByteArrayConstant(proof)) diff --git a/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala index 8fad6e8025..b705017af3 100644 --- a/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala @@ -3,11 +3,11 @@ package sigmastate.utxo.examples import org.ergoplatform._ import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert, Lookup} import scorex.crypto.authds.{ADKey, ADValue} -import scorex.crypto.hash.{Digest32, Blake2b256} +import scorex.crypto.hash.{Blake2b256, Digest32} import sigmastate.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.lang.Terms._ import sigmastate.interpreter.Interpreter._ import sigmastate.serialization.ValueSerializer @@ -48,10 +48,10 @@ class MASTExampleSpecification extends SigmaTestingCommons { val input1 = ErgoBox(20, prop, 0) val tx = UnsignedErgoLikeTransaction(IndexedSeq(input1).map(i => new UnsignedInput(i.id)), IndexedSeq(ErgoBox(1, ErgoScriptPredef.TrueProp, 0))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(input1), tx, self = input1) @@ -102,10 +102,10 @@ class MASTExampleSpecification extends SigmaTestingCommons { val recipientProposition = new ContextEnrichingTestProvingInterpreter().dlogSecrets.head.publicImage val selfBox = ErgoBox(20, ErgoScriptPredef.TrueProp, 0, Seq(), Map(reg1 -> AvlTreeConstant(treeData))) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(selfBox), createTransaction(ErgoBox(1, recipientProposition, 0)), self = selfBox) diff --git a/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala index f3c0998420..98098e43c9 100644 --- a/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala @@ -9,7 +9,7 @@ import sigmastate.AvlTreeData import sigmastate.Values.GroupElementConstant import sigmastate.basics.DLogProtocol.ProveDlog import sigmastate.basics.{DiffieHellmanTupleProverInput, ProveDHTuple} -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.CryptoConstants import sigmastate.interpreter.Interpreter._ import sigmastate.lang.Terms._ @@ -156,10 +156,10 @@ class MixExampleSpecification extends SigmaTestingCommons { // normally this transaction would be invalid, but we're not checking it in this test val fullMixTx = createTransaction(IndexedSeq(fullMixOutput0, fullMixOutput1)) - val fullMixContext = ErgoLikeContext( + val fullMixContext = ErgoLikeContextTesting( currentHeight = fullMixCreationHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(halfMixOutput), spendingTransaction = fullMixTx, self = halfMixOutput @@ -211,10 +211,10 @@ class MixExampleSpecification extends SigmaTestingCommons { (fullMixOutput1, fullMixOutput0) } - val aliceSpendContext = ErgoLikeContext( + val aliceSpendContext = ErgoLikeContextTesting( currentHeight = spendHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(aliceAnonBox), spendingTransaction = spendingTx, self = aliceAnonBox @@ -233,10 +233,10 @@ class MixExampleSpecification extends SigmaTestingCommons { //// Bob spending his output ////////////////////////////////////////////// - val bobSpendContext = ErgoLikeContext( + val bobSpendContext = ErgoLikeContextTesting( currentHeight = spendHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(bobAnonBox), spendingTransaction = spendingTx, self = bobAnonBox diff --git a/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala b/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala index 161ca518b7..6e5f297808 100644 --- a/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala @@ -6,16 +6,16 @@ import com.google.common.primitives.Longs import org.ergoplatform.ErgoBox.RegisterId import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert, Lookup} import scorex.crypto.authds.{ADKey, ADValue} -import scorex.crypto.hash.{Digest32, Blake2b256} +import scorex.crypto.hash.{Blake2b256, Digest32} import sigmastate.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ import sigmastate.eval._ import sigmastate.lang.Terms._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons, ErgoLikeTestInterpreter} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.CryptoConstants import org.ergoplatform._ -import org.ergoplatform.dsl.{SigmaContractSyntax, ContractSpec, TestContractSpec, StdContracts} +import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, StdContracts, TestContractSpec} import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.utxo._ import special.sigma.Context @@ -172,10 +172,10 @@ class OracleExamplesSpecification extends SigmaTestingCommons { suite => val propBob = withinTimeframe(sinceHeight, timeout, bobPubKey.isProven)(propAlong).toSigmaProp val sBob = ErgoBox(10, propBob, 0, Seq(), Map(), boxIndex = 4) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = treeData, - ErgoLikeContext.dummyPubkey, + ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(sAlice, sBob), spendingTransaction, self = sAlice) @@ -249,10 +249,10 @@ class OracleExamplesSpecification extends SigmaTestingCommons { suite => val newBoxes = IndexedSeq(newBox1) val spendingTransaction = createTransaction(newBoxes) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 50, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(sOracle, sAlice, sBob), spendingTransaction, self = sOracle) diff --git a/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala index b80fb1f36b..be1b72a08d 100644 --- a/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala @@ -8,7 +8,7 @@ import scorex.utils.Random import sigmastate.Values.{ByteArrayConstant, ByteConstant, IntConstant, SigmaBoolean, SigmaPropConstant} import sigmastate._ import sigmastate.basics.DLogProtocol.ProveDlog -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter._ import sigmastate.lang.Terms._ import sigmastate.utxo._ @@ -155,10 +155,10 @@ class RPSGameExampleSpecification extends SigmaTestingCommons { //normally this transaction would invalid (why?), but we're not checking it in this test val fullGameTx = createTransaction(IndexedSeq(fullGameOutput0, fullGameOutput1)) - val fullGameContext = ErgoLikeContext( + val fullGameContext = ErgoLikeContextTesting( currentHeight = fullGameCreationHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(halfGameOutput), spendingTransaction = fullGameTx, self = halfGameOutput // what is the use of self? @@ -191,19 +191,19 @@ class RPSGameExampleSpecification extends SigmaTestingCommons { val aliceProver = alice.withContextExtender(0, ByteArrayConstant(s)).withContextExtender(1, ByteConstant(a)) val bobProver = bob.withContextExtender(0, ByteArrayConstant(s)).withContextExtender(1, ByteConstant(a)) - val winContext0 = ErgoLikeContext( + val winContext0 = ErgoLikeContextTesting( currentHeight = gameOverHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fullGameOutput0, fullGameOutput1), spendingTransaction = gameOverTx, self = fullGameOutput0 ) - val winContext1 = ErgoLikeContext( + val winContext1 = ErgoLikeContextTesting( currentHeight = gameOverHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fullGameOutput0, fullGameOutput1), spendingTransaction = gameOverTx, self = fullGameOutput1 @@ -216,10 +216,10 @@ class RPSGameExampleSpecification extends SigmaTestingCommons { // Possibility 1.1: draw ///////////////////////////////////////////////////////// - val drawContextAlice = ErgoLikeContext( + val drawContextAlice = ErgoLikeContextTesting( currentHeight = gameOverHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fullGameOutput0), spendingTransaction = gameOverTx, self = fullGameOutput0 @@ -228,10 +228,10 @@ class RPSGameExampleSpecification extends SigmaTestingCommons { val proofAliceDraw = aliceProver.prove(fullGameEnv, fullGameScript, drawContextAlice, fakeMessage).get verifier.verify(fullGameEnv, fullGameScript, drawContextAlice, proofAliceDraw, fakeMessage).get._1 shouldBe true - val drawContextBob = ErgoLikeContext( + val drawContextBob = ErgoLikeContextTesting( currentHeight = gameOverHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fullGameOutput1), spendingTransaction = gameOverTx, self = fullGameOutput1 @@ -277,18 +277,18 @@ class RPSGameExampleSpecification extends SigmaTestingCommons { //normally this transaction would invalid (why?), but we're not checking it in this test val defaultWinTx = createTransaction(defaultWinOutput) - val defaultWinContext0 = ErgoLikeContext( + val defaultWinContext0 = ErgoLikeContextTesting( currentHeight = defaultWinHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fullGameOutput0, fullGameOutput1), spendingTransaction = defaultWinTx, self = fullGameOutput0 // what is the use of self? ) - val defaultWinContext1 = ErgoLikeContext( + val defaultWinContext1 = ErgoLikeContextTesting( currentHeight = defaultWinHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fullGameOutput0, fullGameOutput1), spendingTransaction = defaultWinTx, self = fullGameOutput1 // what is the use of self? diff --git a/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala index 564389d24e..ca736e18dc 100644 --- a/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala @@ -5,7 +5,7 @@ import org.ergoplatform._ import scorex.crypto.hash.Blake2b256 import sigmastate.Values.{IntConstant, SigmaPropConstant} import sigmastate._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.lang.Terms._ @@ -143,10 +143,10 @@ class ReversibleTxExampleSpecification extends SigmaTestingCommons { //normally this transaction would be invalid (why?), but we're not checking it in this test val withdrawTx = createTransaction(reversibleWithdrawOutput) - val withdrawContext = ErgoLikeContext( + val withdrawContext = ErgoLikeContextTesting( currentHeight = withdrawHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(depositOutput), spendingTransaction = withdrawTx, self = depositOutput @@ -172,10 +172,10 @@ class ReversibleTxExampleSpecification extends SigmaTestingCommons { //normally this transaction would be invalid (why?), but we're not checking it in this test val bobSpendTx = createTransaction(bobSpendOutput) - val bobSpendContext = ErgoLikeContext( + val bobSpendContext = ErgoLikeContextTesting( currentHeight = bobSpendHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(reversibleWithdrawOutput), spendingTransaction = bobSpendTx, self = reversibleWithdrawOutput @@ -199,10 +199,10 @@ class ReversibleTxExampleSpecification extends SigmaTestingCommons { //normally this transaction would be invalid (why?), but we're not checking it in this test val carolSpendTx = createTransaction(carolSpendOutput) - val carolSpendContext = ErgoLikeContext( + val carolSpendContext = ErgoLikeContextTesting( currentHeight = carolSpendHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(reversibleWithdrawOutput), spendingTransaction = carolSpendTx, self = reversibleWithdrawOutput diff --git a/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala b/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala index 0cde3cd427..7d6bd0615c 100644 --- a/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala +++ b/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala @@ -3,10 +3,10 @@ package sigmastate.utxo.examples import org.ergoplatform._ import scorex.crypto.hash.Blake2b256 import scorex.util._ -import sigmastate.Values.{LongConstant, FalseLeaf, TrueLeaf, GetVarByteArray, Value, ByteArrayConstant, IntConstant, BooleanConstant, ByteConstant} +import sigmastate.Values.{BooleanConstant, ByteArrayConstant, ByteConstant, FalseLeaf, GetVarByteArray, IntConstant, LongConstant, TrueLeaf, Value} import sigmastate._ import sigmastate.eval._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, SigmaTestingCommons, ErgoLikeTestInterpreter} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.ContextExtension import sigmastate.lang.Terms._ import sigmastate.serialization.ValueSerializer @@ -55,10 +55,10 @@ class Rule110Specification extends SigmaTestingCommons { val output = ErgoBox(1, prop, 0, Seq(), Map(reg1 -> ByteArrayConstant(Array[Byte](1, 1, 1, 1, 1, 0)))) val tx = UnsignedErgoLikeTransaction(IndexedSeq(new UnsignedInput(input.id)), IndexedSeq(output)) - val ctx = ErgoLikeContext( + val ctx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(input), tx, self = input).withCostLimit(maxCost) @@ -217,10 +217,10 @@ class Rule110Specification extends SigmaTestingCommons { val nProver = new ContextEnrichingTestProvingInterpreter() .withContextExtender(scriptId, ByteArrayConstant(normalCaseBytes)) - val nCtx = ErgoLikeContext( + val nCtx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(nIn0, nIn1, nIn2), nTx, self = nIn0) @@ -239,10 +239,10 @@ class Rule110Specification extends SigmaTestingCommons { val rProver = new ContextEnrichingTestProvingInterpreter() .withContextExtender(scriptId, ByteArrayConstant(rightmostBytes)) - val rCtx = ErgoLikeContext( + val rCtx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(rIn0, rIn1), rTx, self = rIn0) @@ -261,10 +261,10 @@ class Rule110Specification extends SigmaTestingCommons { val lnProver = new ContextEnrichingTestProvingInterpreter() .withContextExtender(scriptId, ByteArrayConstant(nLeftmostBytes)) - val lnCtx = ErgoLikeContext( + val lnCtx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(lnIn0, lnIn1), lnTx, self = lnIn0) @@ -282,10 +282,10 @@ class Rule110Specification extends SigmaTestingCommons { val lProver = new ContextEnrichingTestProvingInterpreter() .withContextExtender(scriptId, ByteArrayConstant(leftmostBytes)) - val lCtx = ErgoLikeContext( + val lCtx = ErgoLikeContextTesting( currentHeight = 1, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(lIn0), lTx, self = lIn0) @@ -405,7 +405,7 @@ class Rule110Specification extends SigmaTestingCommons { val initBlock = FullBlock( IndexedSeq(createTransaction(coins)), - ErgoLikeContext.dummyPubkey + ErgoLikeContextTesting.dummyPubkey ) val genesisState = ValidationState.initialState(initBlock) @@ -438,27 +438,27 @@ class Rule110Specification extends SigmaTestingCommons { IndexedSeq(c, left.toCandidate, center.toCandidate, right.toCandidate) ) - val contextLeft = ErgoLikeContext(row, + val contextLeft = ErgoLikeContextTesting(row, state.state.lastBlockUtxoRoot, - ErgoLikeContext.dummyPubkey, + ErgoLikeContextTesting.dummyPubkey, IndexedSeq(left, center, right), ut, left, ContextExtension.empty) val proverResultLeft = prover.prove(left.ergoTree, contextLeft, ut.messageToSign).get - val contextCenter = ErgoLikeContext(row, + val contextCenter = ErgoLikeContextTesting(row, state.state.lastBlockUtxoRoot, - ErgoLikeContext.dummyPubkey, + ErgoLikeContextTesting.dummyPubkey, IndexedSeq(left, center, right), ut, center, ContextExtension.empty) val proverResultCenter = prover.prove(center.ergoTree, contextCenter, ut.messageToSign).get - val contextRight = ErgoLikeContext(row, + val contextRight = ErgoLikeContextTesting(row, state.state.lastBlockUtxoRoot, - ErgoLikeContext.dummyPubkey, + ErgoLikeContextTesting.dummyPubkey, IndexedSeq(left, center, right), ut, right, @@ -468,7 +468,7 @@ class Rule110Specification extends SigmaTestingCommons { } } - val firstRowBlock = FullBlock(generateTransactionsForRow(genesisState, 1), ErgoLikeContext.dummyPubkey) + val firstRowBlock = FullBlock(generateTransactionsForRow(genesisState, 1), ErgoLikeContextTesting.dummyPubkey) val t0 = System.currentTimeMillis() val firstRowState = genesisState.applyBlock(firstRowBlock, 10000000).get diff --git a/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala index 3ceafee273..5b9b1300ac 100644 --- a/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala @@ -4,7 +4,7 @@ import org.ergoplatform.ErgoBox.{R4, R5} import org.ergoplatform._ import sigmastate.Values.{ByteArrayConstant, ByteConstant, IntConstant} import sigmastate._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.lang.Terms._ import sigmastate.lang.exceptions.InterpreterException @@ -58,10 +58,10 @@ class TimedPaymentExampleSpecification extends SigmaTestingCommons { //normally this transaction would be invalid, but we're not checking it in this test val withdrawTx = createTransaction(IndexedSeq(timedWithdrawOutput)) - val withdrawContext = ErgoLikeContext( + val withdrawContext = ErgoLikeContextTesting( currentHeight = 109, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(depositOutput), spendingTransaction = withdrawTx, self = depositOutput @@ -75,10 +75,10 @@ class TimedPaymentExampleSpecification extends SigmaTestingCommons { verifier.verify(env, script, withdrawContext, proofWithdraw, fakeMessage).get._1 shouldBe true - val withdrawContextBad = ErgoLikeContext( + val withdrawContextBad = ErgoLikeContextTesting( currentHeight = 111, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(depositOutput), spendingTransaction = withdrawTx, self = depositOutput diff --git a/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala b/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala index 05f1fca36a..606d64f17a 100644 --- a/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala +++ b/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala @@ -8,7 +8,7 @@ import scorex.utils.Random import sigmastate.Values.{ByteArrayConstant, ByteConstant, IntConstant, SigmaPropConstant} import sigmastate._ import sigmastate.basics.DLogProtocol.ProveDlog -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter, SigmaTestingCommons} +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaTestingCommons} import sigmastate.interpreter.Interpreter._ import sigmastate.lang.Terms._ import sigmastate.utxo._ @@ -144,10 +144,10 @@ class XorGameExampleSpecification extends SigmaTestingCommons { //normally this transaction would invalid (why?), but we're not checking it in this test val abortHalfGameTx = createTransaction(abortHalfGameOutput) - val abortHalfGameContext = ErgoLikeContext( + val abortHalfGameContext = ErgoLikeContextTesting( currentHeight = abortHalfGameHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(halfGameOutput), spendingTransaction = abortHalfGameTx, self = halfGameOutput // what is the use of self? @@ -180,10 +180,10 @@ class XorGameExampleSpecification extends SigmaTestingCommons { //normally this transaction would invalid (why?), but we're not checking it in this test val fullGameTx = createTransaction(fullGameOutput) - val fullGameContext = ErgoLikeContext( + val fullGameContext = ErgoLikeContextTesting( currentHeight = fullGameCreationHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(halfGameOutput), spendingTransaction = fullGameTx, self = halfGameOutput // what is the use of self? @@ -230,10 +230,10 @@ class XorGameExampleSpecification extends SigmaTestingCommons { //normally this transaction would invalid (why?), but we're not checking it in this test val gameOverTx = createTransaction(gameOverOutput) - val gameOverContext = ErgoLikeContext( + val gameOverContext = ErgoLikeContextTesting( currentHeight = gameOverHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fullGameOutput), spendingTransaction = gameOverTx, self = fullGameOutput // what is the use of self? @@ -257,10 +257,10 @@ class XorGameExampleSpecification extends SigmaTestingCommons { //normally this transaction would invalid (why?), but we're not checking it in this test val defaultWinTx = createTransaction(defaultWinOutput) - val defaultWinContext = ErgoLikeContext( + val defaultWinContext = ErgoLikeContextTesting( currentHeight = defaultWinHeight, lastBlockUtxoRoot = AvlTreeData.dummy, - minerPubkey = ErgoLikeContext.dummyPubkey, + minerPubkey = ErgoLikeContextTesting.dummyPubkey, boxesToSpend = IndexedSeq(fullGameOutput), spendingTransaction = defaultWinTx, self = fullGameOutput // what is the use of self? diff --git a/src/test/scala/special/sigma/SigmaDslTest.scala b/src/test/scala/special/sigma/SigmaDslTest.scala index 15599989ed..2f0b7b0fc3 100644 --- a/src/test/scala/special/sigma/SigmaDslTest.scala +++ b/src/test/scala/special/sigma/SigmaDslTest.scala @@ -2,7 +2,6 @@ package special.sigma import java.math.BigInteger -import org.ergoplatform.ErgoLikeContext.dummyPubkey import org.ergoplatform.ErgoScriptPredef.TrueProp import org.ergoplatform.dsl.{SigmaContractSyntax, TestContractSpec} import org.ergoplatform._ @@ -426,7 +425,7 @@ class SigmaDslTest extends PropSpec byteArrayToBigInt(x) } forAll { x: Array[Byte] => - whenever(x.length <= ErgoConstants.MaxBigIntSizeInBytes.value) { + whenever(x.length <= SigmaConstants.MaxBigIntSizeInBytes.value) { eq(Builder.DefaultCollBuilder.fromArray(x)) } } diff --git a/src/test/scala/special/sigma/SigmaTestingData.scala b/src/test/scala/special/sigma/SigmaTestingData.scala index e5b9bb6f1e..6eab01e559 100644 --- a/src/test/scala/special/sigma/SigmaTestingData.scala +++ b/src/test/scala/special/sigma/SigmaTestingData.scala @@ -1,6 +1,6 @@ package special.sigma -import org.ergoplatform.ErgoConstants.ScriptCostLimit +import org.ergoplatform.SigmaConstants.ScriptCostLimit import org.ergoplatform.validation.ValidationRules import sigmastate.interpreter.ContextExtension import org.scalacheck.Gen.containerOfN @@ -10,8 +10,8 @@ import org.scalacheck.{Arbitrary, Gen} import sigmastate.helpers.SigmaTestingCommons import sigmastate.eval._ import sigmastate.eval.Extensions._ -import org.ergoplatform.{ErgoLikeContext, ErgoLikeTransaction, ErgoBox} -import scorex.crypto.hash.{Digest32, Blake2b256} +import org.ergoplatform.{DataInput, ErgoBox, ErgoLikeContext, ErgoLikeTransaction} +import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.crypto.authds.{ADKey, ADValue} trait SigmaTestingData extends SigmaTestingCommons with SigmaTypeGens { @@ -91,12 +91,10 @@ trait SigmaTestingData extends SigmaTestingCommons with SigmaTypeGens { votes = Colls.emptyColl[Byte] ) val ergoCtx = new ErgoLikeContext( - currentHeight = preHeader.height, lastBlockUtxoRoot = header2.stateRoot.asInstanceOf[CAvlTree].treeData, - preHeader.minerPk.getEncoded.toArray, boxesToSpend = IndexedSeq(inBox), - spendingTransaction = ErgoLikeTransaction(IndexedSeq(), IndexedSeq(outBox)), - self = inBox, headers = headers, preHeader = preHeader, dataBoxes = IndexedSeq(dataBox), + spendingTransaction = new ErgoLikeTransaction(IndexedSeq(), IndexedSeq(DataInput(dataBox.id)), IndexedSeq(outBox)), + selfIndex = 0, headers = headers, preHeader = preHeader, dataBoxes = IndexedSeq(dataBox), extension = ContextExtension.empty, validationSettings = ValidationRules.currentSettings, costLimit = ScriptCostLimit.value, initCost = 0L)