diff --git a/graph-ir/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala b/graph-ir/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala index 4b69cfe957..e5e7f333e6 100644 --- a/graph-ir/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala +++ b/graph-ir/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala @@ -90,7 +90,7 @@ class WOptionCls extends EntityObject("WOption") { case class WOptionAdapter[A](source: Ref[WOption[A]]) extends Node with WOption[A] with Def[WOption[A]] { - implicit lazy val eA = source.elem.typeArgs("A")._1.asInstanceOf[Elem[A]] + implicit lazy val eA: Elem[A] = source.elem.typeArgs("A")._1.asInstanceOf[Elem[A]] val resultType: Elem[WOption[A]] = element[WOption[A]] override def transform(t: Transformer) = WOptionAdapter[A](t(source)) diff --git a/graph-ir/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala b/graph-ir/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala index dfbd0f3111..66bbf9ed81 100644 --- a/graph-ir/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala +++ b/graph-ir/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala @@ -67,7 +67,7 @@ class WRTypeCls extends EntityObject("WRType") { case class WRTypeAdapter[A](source: Ref[WRType[A]]) extends Node with WRType[A] with Def[WRType[A]] { - implicit lazy val eA = source.elem.typeArgs("A")._1.asInstanceOf[Elem[A]] + implicit lazy val eA: Elem[A] = source.elem.typeArgs("A")._1.asInstanceOf[Elem[A]] val resultType: Elem[WRType[A]] = element[WRType[A]] override def transform(t: Transformer) = WRTypeAdapter[A](t(source)) diff --git a/interpreter/shared/src/main/scala/sigmastate/SigSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/SigSerializer.scala index 07ff33c5bc..f003586d85 100644 --- a/interpreter/shared/src/main/scala/sigmastate/SigSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/SigSerializer.scala @@ -5,13 +5,14 @@ import scorex.util.encode.Base16 import sigmastate.Values.SigmaBoolean import sigmastate.basics.DLogProtocol.{ProveDlog, SecondDLogProverMessage} import sigmastate.basics.VerifierMessage.Challenge -import sigmastate.basics.{SecondDiffieHellmanTupleProverMessage, ProveDHTuple, CryptoConstants} +import sigmastate.basics.{CryptoConstants, ProveDHTuple, SecondDHTupleProverMessage} import sigmastate.interpreter.ErgoTreeEvaluator.{fixedCostOp, perItemCostOp} import sigmastate.interpreter.{ErgoTreeEvaluator, NamedDesc, OperationCostInfo} import sigmastate.serialization.SigmaSerializer import sigmastate.util.safeNewArray import sigmastate.utils.{Helpers, SigmaByteReader, SigmaByteWriter} import debox.cfor +import sigmastate.eval.Extensions.ArrayOps import sigmastate.exceptions.SerializerException /** Contains implementation of signature (aka proof) serialization. @@ -61,7 +62,7 @@ class SigSerializer { w: SigmaByteWriter, writeChallenge: Boolean): Unit = { if (writeChallenge) { - w.putBytes(node.challenge) + w.putBytes(node.challenge.toArray) } node match { case dl: UncheckedSchnorr => @@ -184,7 +185,7 @@ class SigSerializer { // Verifier Step 2: Let e_0 be the challenge in the node here (e_0 is called "challenge" in the code) val challenge = if (challengeOpt == null) { Challenge @@ readBytesChecked(r, hashSize, - hex => warn(s"Invalid challenge in: $hex")) + hex => warn(s"Invalid challenge in: $hex")).toColl } else { challengeOpt } @@ -203,7 +204,7 @@ class SigSerializer { fixedCostOp(ParseChallenge_ProveDHT) { val z_bytes = readBytesChecked(r, order, hex => warn(s"Invalid z bytes for $dh: $hex")) val z = BigIntegers.fromUnsignedByteArray(z_bytes) - UncheckedDiffieHellmanTuple(dh, None, challenge, SecondDiffieHellmanTupleProverMessage(z)) + UncheckedDiffieHellmanTuple(dh, None, challenge, SecondDHTupleProverMessage(z)) } case and: CAND => @@ -223,18 +224,18 @@ class SigSerializer { // Read all the children but the last and compute the XOR of all the challenges including e_0 val nChildren = or.children.length val children = safeNewArray[UncheckedSigmaTree](nChildren) - val xorBuf = challenge.clone() + val xorBuf = challenge.toArray.clone() val iLastChild = nChildren - 1 cfor(0)(_ < iLastChild, _ + 1) { i => val parsedChild = parseAndComputeChallenges(or.children(i), r, null) children(i) = parsedChild - Helpers.xorU(xorBuf, parsedChild.challenge) // xor it into buffer + Helpers.xorU(xorBuf, parsedChild.challenge.toArray) // xor it into buffer } val lastChild = or.children(iLastChild) // use the computed XOR for last child's challenge children(iLastChild) = parseAndComputeChallenges( - lastChild, r, challengeOpt = Challenge @@ xorBuf) + lastChild, r, challengeOpt = Challenge @@ xorBuf.toColl) COrUncheckedNode(challenge, children) @@ -248,13 +249,13 @@ class SigSerializer { val polynomial = perItemCostOp(ParsePolynomial, nCoefs) { () => val coeffBytes = readBytesChecked(r, hashSize * nCoefs, hex => warn(s"Invalid coeffBytes for $th: $hex")) - GF2_192_Poly.fromByteArray(challenge, coeffBytes) + GF2_192_Poly.fromByteArray(challenge.toArray, coeffBytes) } val children = safeNewArray[UncheckedSigmaTree](nChildren) cfor(0)(_ < nChildren, _ + 1) { i => val c = perItemCostOp(EvaluatePolynomial, nCoefs) { () => - Challenge @@ polynomial.evaluate((i + 1).toByte).toByteArray + Challenge @@ polynomial.evaluate((i + 1).toByte).toByteArray.toColl } children(i) = parseAndComputeChallenges(th.children(i), r, c) } diff --git a/interpreter/shared/src/main/scala/sigmastate/UncheckedTree.scala b/interpreter/shared/src/main/scala/sigmastate/UncheckedTree.scala index 365a1f85a7..99e26be99e 100644 --- a/interpreter/shared/src/main/scala/sigmastate/UncheckedTree.scala +++ b/interpreter/shared/src/main/scala/sigmastate/UncheckedTree.scala @@ -1,10 +1,9 @@ package sigmastate -import java.util.Arrays import sigmastate.basics.DLogProtocol.{FirstDLogProverMessage, ProveDlog, SecondDLogProverMessage} import sigmastate.basics.VerifierMessage.Challenge import sigmastate.Values.SigmaBoolean -import sigmastate.basics.{FirstDiffieHellmanTupleProverMessage, ProveDHTuple, SecondDiffieHellmanTupleProverMessage} +import sigmastate.basics.{FirstDHTupleProverMessage, ProveDHTuple, SecondDHTupleProverMessage} import sigmastate.crypto.GF2_192_Poly sealed trait UncheckedTree extends ProofTree @@ -12,114 +11,48 @@ sealed trait UncheckedTree extends ProofTree case object NoProof extends UncheckedTree sealed trait UncheckedSigmaTree extends UncheckedTree { - val challenge: Array[Byte] + val challenge: Challenge } -trait UncheckedConjecture extends UncheckedSigmaTree with ProofTreeConjecture { - - override def equals(obj: Any): Boolean = (this eq obj.asInstanceOf[AnyRef]) || (obj match { - case x: UncheckedConjecture => - Arrays.equals(challenge, x.challenge) && children == x.children - case _ => false - }) - - override def hashCode(): Int = - 31 * Arrays.hashCode(challenge) + children.hashCode() -} +trait UncheckedConjecture extends UncheckedSigmaTree with ProofTreeConjecture trait UncheckedLeaf[SP <: SigmaBoolean] extends UncheckedSigmaTree with ProofTreeLeaf { val proposition: SigmaBoolean } -case class UncheckedSchnorr(override val proposition: ProveDlog, - override val commitmentOpt: Option[FirstDLogProverMessage], - override val challenge: Challenge, - secondMessage: SecondDLogProverMessage) - extends UncheckedLeaf[ProveDlog] { +case class UncheckedSchnorr( + override val proposition: ProveDlog, + override val commitmentOpt: Option[FirstDLogProverMessage], + override val challenge: Challenge, + secondMessage: SecondDLogProverMessage +) extends UncheckedLeaf[ProveDlog] - override def equals(obj: Any): Boolean = (this eq obj.asInstanceOf[AnyRef]) || (obj match { - case x: UncheckedSchnorr => - // NOTE, proposition is not compared because it is included into challenge - // like `challenge = hash(prop ++ msg)` - commitmentOpt == x.commitmentOpt && - Arrays.equals(challenge, x.challenge) && - secondMessage == x.secondMessage - case _ => false - }) - - override def hashCode(): Int = { - var h = commitmentOpt.hashCode() - h = 31 * h + Arrays.hashCode(challenge) - h = 31 * h + secondMessage.hashCode() - h - } -} - - -case class UncheckedDiffieHellmanTuple(override val proposition: ProveDHTuple, - override val commitmentOpt: Option[FirstDiffieHellmanTupleProverMessage], - override val challenge: Challenge, - secondMessage: SecondDiffieHellmanTupleProverMessage) - extends UncheckedLeaf[ProveDHTuple] { - - override def equals(obj: Any): Boolean = (this eq obj.asInstanceOf[AnyRef]) || (obj match { - case x: UncheckedDiffieHellmanTuple => - // NOTE, proposition is not compared because it is included into challenge - // like `challenge = hash(prop ++ msg)` - commitmentOpt == x.commitmentOpt && - Arrays.equals(challenge, x.challenge) && - secondMessage == x.secondMessage - case _ => false - }) - - override def hashCode(): Int = { - var h = commitmentOpt.hashCode() - h = 31 * h + Arrays.hashCode(challenge) - h = 31 * h + secondMessage.hashCode() - h - } -} - -case class CAndUncheckedNode(override val challenge: Challenge, - override val children: Seq[UncheckedSigmaTree]) - extends UncheckedConjecture { +case class UncheckedDiffieHellmanTuple( + override val proposition: ProveDHTuple, + override val commitmentOpt: Option[FirstDHTupleProverMessage], + override val challenge: Challenge, + secondMessage: SecondDHTupleProverMessage +) extends UncheckedLeaf[ProveDHTuple] +case class CAndUncheckedNode( + override val challenge: Challenge, + override val children: Seq[UncheckedSigmaTree]) extends UncheckedConjecture { override val conjectureType = ConjectureType.AndConjecture } - -case class COrUncheckedNode(override val challenge: Challenge, - override val children: Seq[UncheckedSigmaTree]) extends UncheckedConjecture { - +case class COrUncheckedNode( + override val challenge: Challenge, + override val children: Seq[UncheckedSigmaTree]) extends UncheckedConjecture { override val conjectureType = ConjectureType.OrConjecture - } -case class CThresholdUncheckedNode(override val challenge: Challenge, - override val children: Seq[UncheckedSigmaTree], - k: Integer, - polynomialOpt: Option[GF2_192_Poly]) extends UncheckedConjecture { +case class CThresholdUncheckedNode( + override val challenge: Challenge, + override val children: Seq[UncheckedSigmaTree], + k: Integer, + polynomialOpt: Option[GF2_192_Poly]) extends UncheckedConjecture { require(children.length <= 255) // Our polynomial arithmetic can take only byte inputs require(k >= 0 && k <= children.length) override val conjectureType = ConjectureType.ThresholdConjecture - - override def canEqual(other: Any) = other.isInstanceOf[CThresholdUncheckedNode] - - override def equals(other: Any) = (this eq other.asInstanceOf[AnyRef]) || (other match { - case other: CThresholdUncheckedNode => - Arrays.equals(challenge, other.challenge) && - children == other.children && - k == other.k && - polynomialOpt == other.polynomialOpt - case _ => false - }) - - override def hashCode(): Int = { - var h = Arrays.hashCode(challenge) - h = 31 * h + children.hashCode - h = 31 * h + k.hashCode() - h = 31 * h + polynomialOpt.hashCode() - h - } } diff --git a/interpreter/shared/src/main/scala/sigmastate/UnprovenTree.scala b/interpreter/shared/src/main/scala/sigmastate/UnprovenTree.scala index 3e6d802835..e6c3b0e3ef 100644 --- a/interpreter/shared/src/main/scala/sigmastate/UnprovenTree.scala +++ b/interpreter/shared/src/main/scala/sigmastate/UnprovenTree.scala @@ -4,7 +4,7 @@ import java.math.BigInteger import sigmastate.Values.{ErgoTree, SigmaBoolean, SigmaPropConstant} import sigmastate.basics.DLogProtocol.{FirstDLogProverMessage, ProveDlog} import sigmastate.basics.VerifierMessage.Challenge -import sigmastate.basics.{FirstDiffieHellmanTupleProverMessage, FirstProverMessage, ProveDHTuple} +import sigmastate.basics.{FirstDHTupleProverMessage, FirstProverMessage, ProveDHTuple} import sigmastate.interpreter.{ErgoTreeEvaluator, NamedDesc, OperationCostInfo} import sigmastate.interpreter.ErgoTreeEvaluator.fixedCostOp import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer @@ -61,7 +61,7 @@ sealed trait UnprovenTree extends ProofTree { /** * Challenge used by the prover. */ - val challengeOpt: Option[Array[Byte]] + val challengeOpt: Option[Challenge] def withChallenge(challenge: Challenge): UnprovenTree @@ -146,7 +146,7 @@ case class UnprovenSchnorr(override val proposition: ProveDlog, } case class UnprovenDiffieHellmanTuple(override val proposition: ProveDHTuple, - override val commitmentOpt: Option[FirstDiffieHellmanTupleProverMessage], + override val commitmentOpt: Option[FirstDHTupleProverMessage], randomnessOpt: Option[BigInteger], override val challengeOpt: Option[Challenge] = None, override val simulated: Boolean, diff --git a/interpreter/shared/src/main/scala/sigmastate/basics/DLogProtocol.scala b/interpreter/shared/src/main/scala/sigmastate/basics/DLogProtocol.scala index 5d378a5b1f..9b801d7ad1 100644 --- a/interpreter/shared/src/main/scala/sigmastate/basics/DLogProtocol.scala +++ b/interpreter/shared/src/main/scala/sigmastate/basics/DLogProtocol.scala @@ -78,7 +78,7 @@ object DLogProtocol { } - object DLogInteractiveProver { + object DLogInteractiveProver extends SigmaProtocolProver { import CryptoConstants.secureRandom def firstMessage(): (BigInteger, FirstDLogProverMessage) = { @@ -91,12 +91,7 @@ object DLogProtocol { } def secondMessage(privateInput: DLogProverInput, rnd: BigInteger, challenge: Challenge): SecondDLogProverMessage = { - import CryptoConstants.dlogGroup - - val q: BigInteger = dlogGroup.order - val e: BigInteger = new BigInteger(1, challenge) - val ew: BigInteger = e.multiply(privateInput.w).mod(q) - val z: BigInteger = rnd.add(ew).mod(q) + val z = responseToChallenge(privateInput, rnd, challenge) SecondDLogProverMessage(z) } @@ -108,7 +103,7 @@ object DLogProtocol { val z = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, secureRandom) //COMPUTE a = g^z*h^(-e) (where -e here means -e mod q) - val e: BigInteger = new BigInteger(1, challenge) + val e: BigInteger = new BigInteger(1, challenge.toArray) val minusE = dlogGroup.order.subtract(e) val hToE = dlogGroup.exponentiate(publicInput.value, minusE) val gToZ = dlogGroup.exponentiate(dlogGroup.generator, z) @@ -136,7 +131,7 @@ object DLogProtocol { dlogGroup.multiplyGroupElements( dlogGroup.exponentiate(g, secondMessage.z.underlying()), - dlogGroup.inverseOf(dlogGroup.exponentiate(h, new BigInteger(1, challenge)))) + dlogGroup.inverseOf(dlogGroup.exponentiate(h, new BigInteger(1, challenge.toArray)))) } } diff --git a/interpreter/shared/src/main/scala/sigmastate/basics/DiffieHellmanTupleProtocol.scala b/interpreter/shared/src/main/scala/sigmastate/basics/DiffieHellmanTupleProtocol.scala index c3ac730bd4..509be25a67 100644 --- a/interpreter/shared/src/main/scala/sigmastate/basics/DiffieHellmanTupleProtocol.scala +++ b/interpreter/shared/src/main/scala/sigmastate/basics/DiffieHellmanTupleProtocol.scala @@ -15,8 +15,8 @@ import scala.collection.mutable trait DiffieHellmanTupleProtocol extends SigmaProtocol[DiffieHellmanTupleProtocol] { - override type A = FirstDiffieHellmanTupleProverMessage - override type Z = SecondDiffieHellmanTupleProverMessage + override type A = FirstDHTupleProverMessage + override type Z = SecondDHTupleProverMessage } case class DiffieHellmanTupleProverInput(w: BigInteger, commonInput: ProveDHTuple) @@ -42,8 +42,12 @@ object DiffieHellmanTupleProverInput { } } -//a = g^r, b = h^r -case class FirstDiffieHellmanTupleProverMessage(a: CryptoConstants.EcPointType, b: CryptoConstants.EcPointType) +/** First message of Diffie Hellman tuple sigma protocol. + * @param a commitment to secret randomness `a = g^r`, where `g` is default generator of the group + * @param b commitment to secret randomness `b = h^r`, where `h` is another random generator of the group + * @see createRandomGenerator in [[sigmastate.basics.CryptoConstants.dlogGroup]] + */ +case class FirstDHTupleProverMessage(a: EcPointType, b: EcPointType) extends FirstProverMessage { override type SP = DiffieHellmanTupleProtocol @@ -53,11 +57,15 @@ case class FirstDiffieHellmanTupleProverMessage(a: CryptoConstants.EcPointType, } } -//z = r + ew mod q -case class SecondDiffieHellmanTupleProverMessage(z: BigInteger) extends SecondProverMessage { - +/** Represents a response for challenge in Diffie Hellman tuple sigma protocol. + * @param z responce to the challenge computed as `(r + ew) mod q`, where + * `r` is the prover's randomness, + * `e` challenge from the verifier (also computed by the prover in non-interactive case), + * `w` is the prover's secret. + * `q` is the group order + */ +case class SecondDHTupleProverMessage(z: BigInteger) extends SecondProverMessage { override type SP = DiffieHellmanTupleProtocol - } /** Construct a new SigmaProp value representing public key of Diffie Hellman signature protocol. @@ -84,38 +92,47 @@ object ProveDHTupleProp { } } -object DiffieHellmanTupleInteractiveProver { +object DiffieHellmanTupleInteractiveProver extends SigmaProtocolProver { import CryptoConstants.dlogGroup - def firstMessage(publicInput: ProveDHTuple): (BigInteger, FirstDiffieHellmanTupleProverMessage) = { + /** Create a commitment to randomness r and a first message of sigma protocol. */ + def firstMessage(publicInput: ProveDHTuple): (BigInteger, FirstDHTupleProverMessage) = { val qMinusOne = dlogGroup.order.subtract(BigInteger.ONE) val r = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, dlogGroup.secureRandom) val a = dlogGroup.exponentiate(publicInput.g, r) val b = dlogGroup.exponentiate(publicInput.h, r) - r -> FirstDiffieHellmanTupleProverMessage(a, b) + r -> FirstDHTupleProverMessage(a, b) } + /** Creates second message of sigma protocol, which is a response for the challenge from the verifier. + * + * @param privateInput private input of the prover (secret) + * @param rnd random number generated by the prover (secret random number used to + * compute commitment) + * @param challenge challenge from the verifier (also computed by the prover in non-interactive case) + * @return second message from the prover + */ def secondMessage(privateInput: DiffieHellmanTupleProverInput, rnd: BigInteger, - challenge: Challenge): SecondDiffieHellmanTupleProverMessage = { - val q: BigInteger = dlogGroup.order - val e: BigInteger = new BigInteger(1, challenge) - val ew: BigInteger = e.multiply(privateInput.w).mod(q) - val z: BigInteger = rnd.add(ew).mod(q) - SecondDiffieHellmanTupleProverMessage(z) + challenge: Challenge): SecondDHTupleProverMessage = { + val z = responseToChallenge(privateInput, rnd, challenge) + SecondDHTupleProverMessage(z) } - def simulate(publicInput: ProveDHTuple, challenge: Challenge): - (FirstDiffieHellmanTupleProverMessage, SecondDiffieHellmanTupleProverMessage) = { + /** Simulates messages of the sigma protocol which are indistinquishable from generated + * by the real prover. */ + def simulate(publicInput: ProveDHTuple, challenge: Challenge): (FirstDHTupleProverMessage, SecondDHTupleProverMessage) = { val qMinusOne = dlogGroup.order.subtract(BigInteger.ONE) - //SAMPLE a random z <- Zq + //SAMPLE a random z <- Zq, this will be the simulated response to the challenge val z = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, dlogGroup.secureRandom) // COMPUTE a = g^z*u^(-e) and b = h^z*v^{-e} (where -e here means -e mod q) - val e: BigInteger = new BigInteger(1, challenge) + // in real prover we compute commitments from random number and them compute response to the challenge, + // but here we do in opposite direction, use random response and compute commitments from it + val e: BigInteger = new BigInteger(1, challenge.toArray) val minusE = dlogGroup.order.subtract(e) val hToZ = dlogGroup.exponentiate(publicInput.h, z) val gToZ = dlogGroup.exponentiate(publicInput.g, z) @@ -123,7 +140,7 @@ object DiffieHellmanTupleInteractiveProver { val vToMinusE = dlogGroup.exponentiate(publicInput.v, minusE) val a = dlogGroup.multiplyGroupElements(gToZ, uToMinusE) val b = dlogGroup.multiplyGroupElements(hToZ, vToMinusE) - FirstDiffieHellmanTupleProverMessage(a, b) -> SecondDiffieHellmanTupleProverMessage(z) + FirstDHTupleProverMessage(a, b) -> SecondDHTupleProverMessage(z) } /** @@ -134,14 +151,14 @@ object DiffieHellmanTupleInteractiveProver { * * g^z = a*u^e, h^z = b*v^e => a = g^z/u^e, b = h^z/v^e * - * @param proposition - * @param challenge - * @param secondMessage + * @param proposition proposition "I know DH tuple" + * @param challenge challenge from verifier + * @param secondMessage prover's response to the challenge * @return */ def computeCommitment(proposition: ProveDHTuple, challenge: Challenge, - secondMessage: SecondDiffieHellmanTupleProverMessage): (EcPointType, EcPointType) = { + secondMessage: SecondDHTupleProverMessage): (EcPointType, EcPointType) = { val g = proposition.g val h = proposition.h @@ -150,7 +167,7 @@ object DiffieHellmanTupleInteractiveProver { val z = secondMessage.z - val e = new BigInteger(1, challenge) + val e = new BigInteger(1, challenge.toArray) val gToZ = dlogGroup.exponentiate(g, z) val hToZ = dlogGroup.exponentiate(h, z) diff --git a/interpreter/shared/src/main/scala/sigmastate/basics/SigmaProtocolFunctions.scala b/interpreter/shared/src/main/scala/sigmastate/basics/SigmaProtocolFunctions.scala index c080a761c8..2350c3f1d2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/basics/SigmaProtocolFunctions.scala +++ b/interpreter/shared/src/main/scala/sigmastate/basics/SigmaProtocolFunctions.scala @@ -1,8 +1,14 @@ package sigmastate.basics import sigmastate.SigmaLeaf +import sigmastate.basics.CryptoConstants.dlogGroup +import sigmastate.basics.DLogProtocol.{DLogProverInput, ProveDlog} +import sigmastate.basics.VerifierMessage.Challenge +import special.collection.Coll import supertagged.TaggedType +import java.math.BigInteger + /* Abstracting Sigma protocols Functionality to get: @@ -26,7 +32,7 @@ trait VerifierMessage extends TranscriptMessage object VerifierMessage { /** A challenge from the verifier (message `e` of `SigmaProtocol`)*/ - object Challenge extends TaggedType[Array[Byte]] + object Challenge extends TaggedType[Coll[Byte]] type Challenge = Challenge.Type } @@ -52,7 +58,34 @@ trait SigmaProtocol[SP <: SigmaProtocol[SP]] { trait SigmaProtocolPrivateInput[CI <: SigmaLeaf] { + /** Public image generated from the secret. + * Represents proof of knowledge proposition. + */ def publicImage: CI + + /** Secret random number known to the prover. */ + def w: BigInteger +} + +trait SigmaProtocolProver { + /** Computes response for the challenge in non-interactive sigma protocol. + * + * @param privateInput private input of the prover (secret) + * @param rnd random number generated by the prover (secret random number used to + * compute commitment) + * @param challenge challenge from the verifier (also computed by the prover in non-interactive case) + * @return response computed by the prover + */ + protected def responseToChallenge( + privateInput: SigmaProtocolPrivateInput[_ <: SigmaLeaf], + rnd: BigInteger, + challenge: Challenge): BigInteger = { + val q: BigInteger = dlogGroup.order + val e: BigInteger = new BigInteger(1, challenge.toArray) + val ew: BigInteger = e.multiply(privateInput.w).mod(q) + val z: BigInteger = rnd.add(ew).mod(q) + z + } } diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/BigIntegers.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/BigIntegers.scala index 7bab41df79..43bded8e09 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/BigIntegers.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/BigIntegers.scala @@ -65,7 +65,7 @@ object BigIntegers { if (min.bitLength > max.bitLength / 2) return createRandomInRange(ZERO, max.subtract(min), random).add(min) - for ( i <- 0 until MAX_ITERATIONS ) { + for ( _ <- 0 until MAX_ITERATIONS ) { val x = createRandomBigInteger(max.bitLength, random) if (x.compareTo(min) >= 0 && x.compareTo(max) <= 0) return x } diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala index dc0617ea29..344305a157 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala @@ -32,7 +32,6 @@ package sigmastate.crypto import debox.cfor import java.util -import java.util.Arrays class GF2_192_Poly { final private var c: Array[GF2_192] = null // must be not null and of length at least 1 diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala b/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala index 2f0e7f3e0c..74e187b809 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala @@ -169,12 +169,6 @@ class Profiler { /** Timings of method calls */ private val mcStat = new StatCollection[Int, Long]() - /** Update time measurement stats for a given method. */ - @inline private final def addMcTime(typeId: Byte, methodId: Byte, time: Long) = { - val key = typeId << 8 | methodId - mcStat.addPoint(key, time) - } - /** Wrapper class which implements special equality between CostItem instances, * suitable for collecting of the statistics. */ class CostItemKey(val costItem: CostItem) { diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala index 1559fcc775..d30a862f98 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala @@ -383,7 +383,7 @@ trait Interpreter { * (and, if applicable, the associated data). Reject otherwise. */ val expectedChallenge = CryptoFunctions.hashFn(bytes) - util.Arrays.equals(newRoot.challenge, expectedChallenge) + util.Arrays.equals(newRoot.challenge.toArray, expectedChallenge) } /** @@ -405,7 +405,7 @@ trait Interpreter { implicit val E = ErgoTreeEvaluator.getCurrentEvaluator fixedCostOp(ComputeCommitments_DHT) { val (a, b) = DiffieHellmanTupleInteractiveProver.computeCommitment(dh.proposition, dh.challenge, dh.secondMessage) - dh.copy(commitmentOpt = Some(FirstDiffieHellmanTupleProverMessage(a, b))) + dh.copy(commitmentOpt = Some(FirstDHTupleProverMessage(a, b))) } case _: UncheckedSigmaTree => ??? diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala index 7f315ce700..9fd3486367 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala @@ -11,8 +11,10 @@ import sigmastate.basics.DLogProtocol._ import sigmastate.basics.VerifierMessage.Challenge import sigmastate.basics._ import sigmastate.crypto.{GF2_192, GF2_192_Poly} +import sigmastate.eval.Extensions.ArrayOps import sigmastate.exceptions.InterpreterException import sigmastate.utils.Helpers +import special.collection.Coll import java.math.BigInteger import scala.util.Try @@ -91,7 +93,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { // Prover Step 8: compute the challenge for the root of the tree as the Fiat-Shamir hash of propBytes // and the message being signed. - val rootChallenge = Challenge @@ CryptoFunctions.hashFn(Helpers.concatArrays(propBytes, message)) + val rootChallenge = Challenge @@ CryptoFunctions.hashFn(Helpers.concatArrays(propBytes, message)).toColl val step8 = step6.withChallenge(rootChallenge) // Prover Step 9: complete the proof by computing challenges at real nodes and additionally responses at real leaves @@ -287,7 +289,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { // take challenge from previously done proof stored in the hints bag, // or generate random challenge for simulated child val newChallenge = hintsBag.proofs.find(_.position == c.position).map(_.challenge).getOrElse( - Challenge @@ secureRandomBytes(CryptoFunctions.soundnessBytes) + Challenge @@ secureRandomBytes(CryptoFunctions.soundnessBytes).toColl ) c.withChallenge(newChallenge) } @@ -314,8 +316,10 @@ trait ProverInterpreter extends Interpreter with ProverUtils { // the other children and e_0. assert(or.challengeOpt.isDefined) val unprovenChildren = or.children.cast[UnprovenTree] - val t = unprovenChildren.tail.map(_.withChallenge(Challenge @@ secureRandomBytes(CryptoFunctions.soundnessBytes))) - val toXor: Seq[Array[Byte]] = or.challengeOpt.get +: t.map(_.challengeOpt.get) + val t = unprovenChildren.tail.map( + _.withChallenge(Challenge @@ secureRandomBytes(CryptoFunctions.soundnessBytes).toColl) + ) + val toXor: Seq[Coll[Byte]] = or.challengeOpt.get +: t.map(_.challengeOpt.get) val xoredChallenge = Challenge @@ Helpers.xor(toXor: _*) val h = unprovenChildren.head.withChallenge(xoredChallenge) or.copy(children = h +: t) @@ -329,11 +333,11 @@ trait ProverInterpreter extends Interpreter with ProverUtils { assert(t.challengeOpt.isDefined) val n = t.children.length val unprovenChildren = t.children.cast[UnprovenTree] - val q = GF2_192_Poly.fromByteArray(t.challengeOpt.get, secureRandomBytes(CryptoFunctions.soundnessBytes * (n - t.k))) + val q = GF2_192_Poly.fromByteArray(t.challengeOpt.get.toArray, secureRandomBytes(CryptoFunctions.soundnessBytes * (n - t.k))) val newChildren = unprovenChildren.foldLeft((Seq[UnprovenTree](), 1)) { case ((childSeq, childIndex), child) => - (childSeq :+ child.withChallenge(Challenge @@ q.evaluate(childIndex.toByte).toByteArray), childIndex + 1) + (childSeq :+ child.withChallenge(Challenge @@ q.evaluate(childIndex.toByte).toByteArray.toColl), childIndex + 1) }._1 t.withPolynomial(q).copy(children = newChildren) @@ -395,7 +399,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { // Step 6 (real leaf -- compute the commitment a or take it from the hints bag) hintsBag.commitments.find(_.position == dhu.position).map { cmtHint => - dhu.copy(commitmentOpt = Some(cmtHint.commitment.asInstanceOf[FirstDiffieHellmanTupleProverMessage])) + dhu.copy(commitmentOpt = Some(cmtHint.commitment.asInstanceOf[FirstDHTupleProverMessage])) }.getOrElse { if (dhu.simulated) { // Step 5 (simulated leaf -- complete the simulation) @@ -412,7 +416,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { case t: ProofTree => error(s"Don't know how to challengeSimulated($t)") }) - private def extractChallenge(pt: ProofTree): Option[Array[Byte]] = pt match { + private def extractChallenge(pt: ProofTree): Option[Challenge] = pt match { case upt: UnprovenTree => upt.challengeOpt case sn: UncheckedSchnorr => Some(sn.challenge) case dh: UncheckedDiffieHellmanTuple => Some(dh.challenge) @@ -461,16 +465,16 @@ trait ProverInterpreter extends Interpreter with ProverUtils { // has a challenge. Other ways are more of a pain because the children can be of different types val challengeOpt = extractChallenge(child) if (challengeOpt.isEmpty) (p, v) - else (p :+ count.toByte, v :+ new GF2_192(challengeOpt.get)) + else (p :+ count.toByte, v :+ new GF2_192(challengeOpt.get.toArray)) } (newPoints, newValues, count + 1) } - val q = GF2_192_Poly.interpolate(points, values, new GF2_192(t.challengeOpt.get)) + val q = GF2_192_Poly.interpolate(points, values, new GF2_192(t.challengeOpt.get.toArray)) val newChildren = t.children.foldLeft(Seq[ProofTree](), 1) { case ((s, count), child) => val newChild = child match { - case r: UnprovenTree if r.real => r.withChallenge(Challenge @@ q.evaluate(count.toByte).toByteArray) + case r: UnprovenTree if r.real => r.withChallenge(Challenge @@ q.evaluate(count.toByte).toByteArray.toColl) case p: ProofTree => p } (s :+ newChild, count + 1) @@ -538,7 +542,7 @@ trait ProverInterpreter extends Interpreter with ProverUtils { provenSchnorr.secondMessage }.getOrElse { val bs = secureRandomBytes(32) - SecondDiffieHellmanTupleProverMessage(new BigInteger(1, bs).mod(CryptoConstants.groupOrder)) + SecondDHTupleProverMessage(new BigInteger(1, bs).mod(CryptoConstants.groupOrder)) } } UncheckedDiffieHellmanTuple(dhu.proposition, None, dhu.challengeOpt.get, z) diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala index dd416d1447..46138ca9d7 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala @@ -122,12 +122,12 @@ trait ProverUtils extends Interpreter { val hints = if (realFound) { Seq( RealCommitment(leaf.proposition, leaf.commitmentOpt.get, position), - RealSecretProof(leaf.proposition, Challenge @@ leaf.challenge, leaf, position) + RealSecretProof(leaf.proposition, leaf.challenge, leaf, position) ) } else { Seq( SimulatedCommitment(leaf.proposition, leaf.commitmentOpt.get, position), - SimulatedSecretProof(leaf.proposition, Challenge @@ leaf.challenge, leaf, position) + SimulatedSecretProof(leaf.proposition, leaf.challenge, leaf, position) ) } hintsBag.addHints(hints: _*) diff --git a/interpreter/shared/src/main/scala/sigmastate/trees.scala b/interpreter/shared/src/main/scala/sigmastate/trees.scala index e6f4cd4230..510aae75c6 100644 --- a/interpreter/shared/src/main/scala/sigmastate/trees.scala +++ b/interpreter/shared/src/main/scala/sigmastate/trees.scala @@ -41,7 +41,7 @@ trait SigmaConjecture extends SigmaBoolean { } /** - * Basic trait for leafs of crypto-trees, such as ProveDlog and ProveDiffieHellman instances + * Basic trait for leafs of crypto-trees, such as [[sigmastate.basics.DLogProtocol.ProveDlog]] and [[sigmastate.basics.ProveDHTuple]] instances */ trait SigmaLeaf extends SigmaBoolean { override def collectLeaves(position: NodePosition, buf: mutable.ArrayBuffer[PositionedLeaf]): Unit = diff --git a/interpreter/shared/src/main/scala/sigmastate/utils/Helpers.scala b/interpreter/shared/src/main/scala/sigmastate/utils/Helpers.scala index df775cbecf..1b16ef05f9 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utils/Helpers.scala +++ b/interpreter/shared/src/main/scala/sigmastate/utils/Helpers.scala @@ -1,5 +1,6 @@ package sigmastate.utils +import debox.cfor import io.circe.Decoder import org.ergoplatform.settings.ErgoAlgos import scalan.{OverloadHack, RType} @@ -37,6 +38,18 @@ object Helpers { def xor(bas: Array[Byte]*): Array[Byte] = bas.reduce({case (ba, ba1) => xor(ba, ba1)}: ((Array[Byte], Array[Byte]) => Array[Byte])) + def xor(bas: Coll[Byte]*): Coll[Byte] = { + require(bas.nonEmpty, "at least one argument is required") + if (bas.length == 1) bas(0) + else { + val res = bas(0).toArray.clone() + cfor(1)(_ < bas.length, _ + 1) { i => + xorU(res, bas(i).toArray) + } + Colls.fromArray(res) + } + } + /** Same as `xor` but makes in-place update of the first argument (hence suffix `U`) * This is boxing-free version. * @return reference to the updated first argument to easy chaining of calls. */ diff --git a/interpreter/shared/src/test/scala/sigmastate/SigmaProtocolSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/SigmaProtocolSpecification.scala index 4177da599b..023058318f 100644 --- a/interpreter/shared/src/test/scala/sigmastate/SigmaProtocolSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/SigmaProtocolSpecification.scala @@ -13,8 +13,8 @@ import special.sigma.SigmaTestingData class SigmaProtocolSpecification extends SigmaTestingData with ScalaCheckPropertyChecks { property("CThresholdUncheckedNode equality") { - val c1 = Challenge @@ Array[Byte](1) - val c2 = Challenge @@ Array[Byte](2) + val c1 = Challenge @@ Coll[Byte](1) + val c2 = Challenge @@ Coll[Byte](2) val n0 = CThresholdUncheckedNode(c1, Seq(), 0, None) val n1 = CThresholdUncheckedNode(c1, Seq(), 0, None) val n2 = CThresholdUncheckedNode(c2, Seq(), 0, None) diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/NegativeTesting.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/NegativeTesting.scala index 158dc2b1bf..fb004c2302 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/NegativeTesting.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/NegativeTesting.scala @@ -114,7 +114,7 @@ trait NegativeTesting extends Matchers { def repeatAndReturnLast[A](nIters: Int)(block: => A): A = { require(nIters > 0) var res = block - cfor(1)(_ < nIters, _ + 1) { i => + cfor(1)(_ < nIters, _ + 1) { _ => res = block } res diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/TestingHelpers.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/TestingHelpers.scala index 0ebac010ae..fa1b9f163c 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/TestingHelpers.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/TestingHelpers.scala @@ -1,20 +1,17 @@ package sigmastate.helpers -import scorex.crypto.hash.Digest32 -import special.collection.{Coll, CollOverArray, PairOfCols} -import scorex.util.ModifierId -import org.ergoplatform.{DataInput, ErgoBox, ErgoBoxCandidate, ErgoLikeContext, ErgoLikeTransaction, ErgoLikeTransactionTemplate, Input, UnsignedInput} -import sigmastate.Values.ErgoTree import org.ergoplatform.ErgoBox.{AdditionalRegisters, Token, allZerosModifierId} import org.ergoplatform.validation.SigmaValidationSettings +import org.ergoplatform._ +import scorex.util.ModifierId import sigmastate.AvlTreeData -import sigmastate.eval.CostingSigmaDslBuilder -import sigmastate.eval._ +import sigmastate.Values.ErgoTree +import sigmastate.eval.{CostingSigmaDslBuilder, _} import sigmastate.interpreter.ContextExtension +import special.collection.{Coll, CollOverArray, PairOfCols} import special.sigma.{Header, PreHeader} import scala.collection.compat.immutable.ArraySeq -import scala.collection.mutable.WrappedArray // TODO refactor: unification is required between two hierarchies of tests // and as part of it, more methods can be moved to TestingHelpers diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala index 6df3cc89d0..884b8d7150 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala @@ -1,17 +1,17 @@ package sigmastate.serialization import java.math.BigInteger -import java.util import org.ergoplatform.settings.ErgoAlgos -import org.scalacheck.{Gen, Arbitrary} +import org.scalacheck.{Arbitrary, Gen} import org.scalatest.Assertion import sigmastate.Values.SigmaBoolean import sigmastate._ import sigmastate.basics.DLogProtocol.{ProveDlog, SecondDLogProverMessage} import sigmastate.basics.VerifierMessage.Challenge -import sigmastate.basics.{SecondDiffieHellmanTupleProverMessage, ProveDHTuple} +import sigmastate.basics.{ProveDHTuple, SecondDHTupleProverMessage} import sigmastate.crypto.GF2_192_Poly -import sigmastate.helpers.{ErgoLikeTransactionTesting, ErgoLikeContextTesting, ContextEnrichingTestProvingInterpreter, TestingCommons} +import sigmastate.eval.Extensions.ArrayOps +import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTransactionTesting, TestingCommons} import sigmastate.interpreter.Interpreter import sigmastate.serialization.generators.ObjectGenerators import sigmastate.utils.Helpers @@ -54,7 +54,7 @@ class SigSerializerSpecification extends TestingCommons // `firstMessageOpt` is not serialized sch1.copy(commitmentOpt = None) == sch2 case (conj1: UncheckedConjecture, conj2: UncheckedConjecture) => - util.Arrays.equals(conj1.challenge, conj2.challenge) && + conj1.challenge == conj2.challenge && conj1.children.zip(conj2.children).forall(t => isEquivalent(t._1, t._2)) case _ => false } @@ -147,7 +147,7 @@ class SigSerializerSpecification extends TestingCommons Helpers.decodeECPoint("02e8e77123e300f8324e7b5c4cbe0f7ac616e0b78fc45f28f54fa6696231fc8ec3") ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("c6429b70f4926a3ba1454f1aec116075f9e9fbe8a8f72114"), + Challenge @@ ErgoAlgos.decodeUnsafe("c6429b70f4926a3ba1454f1aec116075f9e9fbe8a8f72114").toColl, SecondDLogProverMessage( BigInt("b277b8462a8b9098f5d4c934ab2876eb1b5707f3119e209bdbbad831e7cc4a41", 16) ) @@ -172,8 +172,8 @@ class SigSerializerSpecification extends TestingCommons Helpers.decodeECPoint("034132d4c7eb387f12ef40ba3ec03723bda0ee5707f7471185aafc316167e85137") ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("9ec740b57353cb2f6035bb1a481b0066b2fdc0406a6fa67e"), - SecondDiffieHellmanTupleProverMessage( + Challenge @@ ErgoAlgos.decodeUnsafe("9ec740b57353cb2f6035bb1a481b0066b2fdc0406a6fa67e").toColl, + SecondDHTupleProverMessage( new BigInteger("bb2e6f44a38052b3f564fafcd477c4eb8cda1a8a553a4a5f38f1e1084d6a69f0", 16) ) ), @@ -194,7 +194,7 @@ class SigSerializerSpecification extends TestingCommons "a00b476899e583aefc18b237a7a70e73baace72aa533271a561d3432c347dcaec8975fdefb36389abe21656aadcfda0a0259681ce17bc47c9539ae1e7068292bb9646a9ffe4e11653495bd67588cfd6454d82cc455036e5b" ), CAndUncheckedNode( - Challenge @@ ErgoAlgos.decodeUnsafe("a00b476899e583aefc18b237a7a70e73baace72aa533271a"), + Challenge @@ ErgoAlgos.decodeUnsafe("a00b476899e583aefc18b237a7a70e73baace72aa533271a").toColl, List( UncheckedSchnorr( ProveDlog( @@ -203,7 +203,7 @@ class SigSerializerSpecification extends TestingCommons ) ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("a00b476899e583aefc18b237a7a70e73baace72aa533271a"), + Challenge @@ ErgoAlgos.decodeUnsafe("a00b476899e583aefc18b237a7a70e73baace72aa533271a").toColl, SecondDLogProverMessage( BigInt("561d3432c347dcaec8975fdefb36389abe21656aadcfda0a0259681ce17bc47c", 16) ) @@ -215,7 +215,7 @@ class SigSerializerSpecification extends TestingCommons ) ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("a00b476899e583aefc18b237a7a70e73baace72aa533271a"), + Challenge @@ ErgoAlgos.decodeUnsafe("a00b476899e583aefc18b237a7a70e73baace72aa533271a").toColl, SecondDLogProverMessage( BigInt("9539ae1e7068292bb9646a9ffe4e11653495bd67588cfd6454d82cc455036e5b", 16) ) @@ -239,7 +239,7 @@ class SigSerializerSpecification extends TestingCommons "c617e65a2ca62ac97bc33a33b76cb669622129ba0e094ad96287d97c2c6d6c8e48790d7c44961f7d958d59222ab4d7c814808a466a3e66e6f98e02d421757baa2842288b8d02787b5111db2e8924623790175e5bf27a2e4513e8eb196c22c8cf26a9d7b51cd7e386508db9c12b070d84" ), COrUncheckedNode( - Challenge @@ ErgoAlgos.decodeUnsafe("c617e65a2ca62ac97bc33a33b76cb669622129ba0e094ad9"), + Challenge @@ ErgoAlgos.decodeUnsafe("c617e65a2ca62ac97bc33a33b76cb669622129ba0e094ad9").toColl, List( UncheckedSchnorr( ProveDlog( @@ -248,7 +248,7 @@ class SigSerializerSpecification extends TestingCommons ) ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("6287d97c2c6d6c8e48790d7c44961f7d958d59222ab4d7c8"), + Challenge @@ ErgoAlgos.decodeUnsafe("6287d97c2c6d6c8e48790d7c44961f7d958d59222ab4d7c8").toColl, SecondDLogProverMessage( BigInt("14808a466a3e66e6f98e02d421757baa2842288b8d02787b5111db2e89246237", 16) ) @@ -260,7 +260,7 @@ class SigSerializerSpecification extends TestingCommons ) ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("a4903f2600cb464733ba374ff3faa914f7ac709824bd9d11"), + Challenge @@ ErgoAlgos.decodeUnsafe("a4903f2600cb464733ba374ff3faa914f7ac709824bd9d11").toColl, SecondDLogProverMessage( BigInt("90175e5bf27a2e4513e8eb196c22c8cf26a9d7b51cd7e386508db9c12b070d84", 16) ) @@ -295,7 +295,7 @@ class SigSerializerSpecification extends TestingCommons "96addfddcc197bdbacf5c0142fb16c39384b3699fa47da7dffd3149193b042fda134c0e208fefcb791379959ac6fc731adf47e32000fc75e2923dba482c843c7f6b684cbf2ceec5bfdf5fe6d13cabe5d15f8295ca4e8094fba3c4716bfdfc3c462417a79a61fcc487d6997a42739d533eebffa3b420a6e2e44616a1341e5baa1165c6c22e91a81addd97c3bd2fe40ecdbbda6f43bf71240da8dac878c044c16d42a4b34c536bbb1b" ), COrUncheckedNode( - Challenge @@ ErgoAlgos.decodeUnsafe("96addfddcc197bdbacf5c0142fb16c39384b3699fa47da7d"), + Challenge @@ ErgoAlgos.decodeUnsafe("96addfddcc197bdbacf5c0142fb16c39384b3699fa47da7d").toColl, List( UncheckedDiffieHellmanTuple( ProveDHTuple( @@ -305,16 +305,16 @@ class SigSerializerSpecification extends TestingCommons Helpers.decodeECPoint("03f17cefec3911966dc9952090325267a5cf7f9b0be76b02623021989d7f0007a2") ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("ffd3149193b042fda134c0e208fefcb791379959ac6fc731"), - SecondDiffieHellmanTupleProverMessage(new BigInteger("adf47e32000fc75e2923dba482c843c7f6b684cbf2ceec5bfdf5fe6d13cabe5d", 16)) + Challenge @@ ErgoAlgos.decodeUnsafe("ffd3149193b042fda134c0e208fefcb791379959ac6fc731").toColl, + SecondDHTupleProverMessage(new BigInteger("adf47e32000fc75e2923dba482c843c7f6b684cbf2ceec5bfdf5fe6d13cabe5d", 16)) ), COrUncheckedNode( - Challenge @@ ErgoAlgos.decodeUnsafe("697ecb4c5fa939260dc100f6274f908ea97cafc056281d4c"), + Challenge @@ ErgoAlgos.decodeUnsafe("697ecb4c5fa939260dc100f6274f908ea97cafc056281d4c").toColl, List( UncheckedSchnorr( ProveDlog(Helpers.decodeECPoint("03f997167c03aa234732e3a68126b371dffa1e409f62ca8fa18cea6acd1dbe54d5")), None, - Challenge @@ ErgoAlgos.decodeUnsafe("15f8295ca4e8094fba3c4716bfdfc3c462417a79a61fcc48"), + Challenge @@ ErgoAlgos.decodeUnsafe("15f8295ca4e8094fba3c4716bfdfc3c462417a79a61fcc48").toColl, SecondDLogProverMessage(BigInt("7d6997a42739d533eebffa3b420a6e2e44616a1341e5baa1165c6c22e91a81ad", 16)) ), UncheckedDiffieHellmanTuple( @@ -325,8 +325,8 @@ class SigSerializerSpecification extends TestingCommons Helpers.decodeECPoint("02fc58b939b105231da101540c87e56f5703460c179935aaee47137f3c367904f1") ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("7c86e210fb413069b7fd47e09890534acb3dd5b9f037d104"), - SecondDiffieHellmanTupleProverMessage(new BigInteger("dd97c3bd2fe40ecdbbda6f43bf71240da8dac878c044c16d42a4b34c536bbb1b", 16)) + Challenge @@ ErgoAlgos.decodeUnsafe("7c86e210fb413069b7fd47e09890534acb3dd5b9f037d104").toColl, + SecondDHTupleProverMessage(new BigInteger("dd97c3bd2fe40ecdbbda6f43bf71240da8dac878c044c16d42a4b34c536bbb1b", 16)) ) ) ) @@ -370,15 +370,15 @@ class SigSerializerSpecification extends TestingCommons "4fdc76711fd844de0831d8e90ebaf9c622117a062b2f8b63ff8b9c2a4eed345a11c697f6850cf3a38763d738539ad2d2e0a3e44384f23eee260931d88e1f5241a2600a7c98545ada675fd5e627e8e84f140fc95e28775cde52e71bb4d7b5ee2564553fac5b52202530fcbcdf205b7cca145202fb2a5bb181a890eb15536b08b747ea163f6b5d32a116fa9e1eb6b348fd82d3ebc11c125e5bc3f09c499aa0a8db14dc1780b4181f9bae5ed0f743f71b82b18784380814507d810cbef61ebc0b30e7f324083e2d3d08" ), COrUncheckedNode( - Challenge @@ ErgoAlgos.decodeUnsafe("4fdc76711fd844de0831d8e90ebaf9c622117a062b2f8b63"), + Challenge @@ ErgoAlgos.decodeUnsafe("4fdc76711fd844de0831d8e90ebaf9c622117a062b2f8b63").toColl, List( CAndUncheckedNode( - Challenge @@ ErgoAlgos.decodeUnsafe("ff8b9c2a4eed345a11c697f6850cf3a38763d738539ad2d2"), + Challenge @@ ErgoAlgos.decodeUnsafe("ff8b9c2a4eed345a11c697f6850cf3a38763d738539ad2d2").toColl, List( UncheckedSchnorr( ProveDlog(Helpers.decodeECPoint("0368c0d88d9eb2972bbfc23c961de6307f6a944352cbfe316f262401feabdaa87d")), None, - Challenge @@ ErgoAlgos.decodeUnsafe("ff8b9c2a4eed345a11c697f6850cf3a38763d738539ad2d2"), + Challenge @@ ErgoAlgos.decodeUnsafe("ff8b9c2a4eed345a11c697f6850cf3a38763d738539ad2d2").toColl, SecondDLogProverMessage(BigInt("e0a3e44384f23eee260931d88e1f5241a2600a7c98545ada675fd5e627e8e84f", 16)) ), UncheckedDiffieHellmanTuple( @@ -389,13 +389,13 @@ class SigSerializerSpecification extends TestingCommons Helpers.decodeECPoint("029d4ec275379f9212a53e15994aef203dcec43a177c0b1f40afcf592e5753ce67") ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("ff8b9c2a4eed345a11c697f6850cf3a38763d738539ad2d2"), - SecondDiffieHellmanTupleProverMessage(new BigInteger("140fc95e28775cde52e71bb4d7b5ee2564553fac5b52202530fcbcdf205b7cca", 16)) + Challenge @@ ErgoAlgos.decodeUnsafe("ff8b9c2a4eed345a11c697f6850cf3a38763d738539ad2d2").toColl, + SecondDHTupleProverMessage(new BigInteger("140fc95e28775cde52e71bb4d7b5ee2564553fac5b52202530fcbcdf205b7cca", 16)) ) ) ), COrUncheckedNode( - Challenge @@ ErgoAlgos.decodeUnsafe("b057ea5b5135708419f74f1f8bb60a65a572ad3e78b559b1"), + Challenge @@ ErgoAlgos.decodeUnsafe("b057ea5b5135708419f74f1f8bb60a65a572ad3e78b559b1").toColl, List( UncheckedDiffieHellmanTuple( ProveDHTuple( @@ -405,8 +405,8 @@ class SigSerializerSpecification extends TestingCommons Helpers.decodeECPoint("0315d84dba1b29074f766e57bb11843687da899180cf2487ccecd0a3ec5f05365a") ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("145202fb2a5bb181a890eb15536b08b747ea163f6b5d32a1"), - SecondDiffieHellmanTupleProverMessage(new BigInteger("16fa9e1eb6b348fd82d3ebc11c125e5bc3f09c499aa0a8db14dc1780b4181f9b", 16)) + Challenge @@ ErgoAlgos.decodeUnsafe("145202fb2a5bb181a890eb15536b08b747ea163f6b5d32a1").toColl, + SecondDHTupleProverMessage(new BigInteger("16fa9e1eb6b348fd82d3ebc11c125e5bc3f09c499aa0a8db14dc1780b4181f9b", 16)) ), UncheckedDiffieHellmanTuple( ProveDHTuple( @@ -416,8 +416,8 @@ class SigSerializerSpecification extends TestingCommons Helpers.decodeECPoint("0315d84dba1b29074f766e57bb11843687da899180cf2487ccecd0a3ec5f05365a") ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("a405e8a07b6ec105b167a40ad8dd02d2e298bb0113e86b10"), - SecondDiffieHellmanTupleProverMessage(new BigInteger("ae5ed0f743f71b82b18784380814507d810cbef61ebc0b30e7f324083e2d3d08", 16)) + Challenge @@ ErgoAlgos.decodeUnsafe("a405e8a07b6ec105b167a40ad8dd02d2e298bb0113e86b10").toColl, + SecondDHTupleProverMessage(new BigInteger("ae5ed0f743f71b82b18784380814507d810cbef61ebc0b30e7f324083e2d3d08", 16)) ) ) ) @@ -448,12 +448,12 @@ class SigSerializerSpecification extends TestingCommons "c94696c3e3089d9fd1174c18e6dd22f1be8003bbea08011fcf39310e7c9049c1c9966198b8d63a2f19e98843b81b74399f662dba4e764cd548406dd180453dd1bc0e24562f0184d189ca25a41ca8b54ada857dd649d3228a8c359ac499d430ecada3f92d5206cddeffb16248068c1003477d717e04afbf206c87a59ce5263ee7cc4020b5772d91b1df00bd72b15347fd" ), CThresholdUncheckedNode( - Challenge @@ ErgoAlgos.decodeUnsafe("c94696c3e3089d9fd1174c18e6dd22f1be8003bbea08011f"), + Challenge @@ ErgoAlgos.decodeUnsafe("c94696c3e3089d9fd1174c18e6dd22f1be8003bbea08011f").toColl, List( UncheckedSchnorr( ProveDlog(Helpers.decodeECPoint("03a5a5234701fff48be4ed1b3e1fab446657eeddb52e2573c52b9c4021f2403866")), None, - Challenge @@ ErgoAlgos.decodeUnsafe("067fa7cd9f98d45e18812d805e0b18dea7698bf852137526"), + Challenge @@ ErgoAlgos.decodeUnsafe("067fa7cd9f98d45e18812d805e0b18dea7698bf852137526").toColl, SecondDLogProverMessage(BigInt("9f662dba4e764cd548406dd180453dd1bc0e24562f0184d189ca25a41ca8b54a", 16)) ), UncheckedDiffieHellmanTuple( @@ -464,8 +464,8 @@ class SigSerializerSpecification extends TestingCommons Helpers.decodeECPoint("02730455ebb8c01a89dced09c5253c9bfa4b1471d1068ba30ab226104a6551c461") ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("5735f4df1b280e1d423a8f28977057af8c52123c9a3fe96d"), - SecondDiffieHellmanTupleProverMessage(new BigInteger("da857dd649d3228a8c359ac499d430ecada3f92d5206cddeffb16248068c1003", 16)) + Challenge @@ ErgoAlgos.decodeUnsafe("5735f4df1b280e1d423a8f28977057af8c52123c9a3fe96d").toColl, + SecondDHTupleProverMessage(new BigInteger("da857dd649d3228a8c359ac499d430ecada3f92d5206cddeffb16248068c1003", 16)) ), UncheckedDiffieHellmanTuple( ProveDHTuple( @@ -475,8 +475,8 @@ class SigSerializerSpecification extends TestingCommons Helpers.decodeECPoint("03cefefa1511430ca2a873759107085f269f6fbcd4e836db7760749f52b7f7923a") ), None, - Challenge @@ ErgoAlgos.decodeUnsafe("980cc5d167b847dc8baceeb02fa66d8095bb9a7f22249d54"), - SecondDiffieHellmanTupleProverMessage(new BigInteger("477d717e04afbf206c87a59ce5263ee7cc4020b5772d91b1df00bd72b15347fd", 16)) + Challenge @@ ErgoAlgos.decodeUnsafe("980cc5d167b847dc8baceeb02fa66d8095bb9a7f22249d54").toColl, + SecondDHTupleProverMessage(new BigInteger("477d717e04afbf206c87a59ce5263ee7cc4020b5772d91b1df00bd72b15347fd", 16)) ) ), 2, @@ -525,7 +525,9 @@ class SigSerializerSpecification extends TestingCommons r.position = 0 var reported = false - val res = SigSerializer.readBytesChecked(r, nRequested, msg => reported = true) + val res = SigSerializer.readBytesChecked(r, + numRequestedBytes = nRequested, + onError = _ => reported = true) res shouldBe bytes reported shouldBe true } diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala index c4c964cc74..2582d1305c 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala @@ -5,24 +5,24 @@ import org.scalacheck.Arbitrary.arbString import sigmastate._ trait TypeGenerators { - implicit val booleanTypeGen = Gen.const(SBoolean) - implicit val byteTypeGen = Gen.const(SByte) - implicit val shortTypeGen = Gen.const(SShort) - implicit val intTypeGen = Gen.const(SInt) - implicit val longTypeGen = Gen.const(SLong) - implicit val bigIntTypeGen = Gen.const(SBigInt) - implicit val groupElementTypeGen = Gen.const(SGroupElement) - implicit val sigmaPropTypeGen = Gen.const(SSigmaProp) - implicit val boxTypeGen = Gen.const(SBox) - implicit val avlTreeTypeGen = Gen.const(SAvlTree) - implicit val optionSigmaPropTypeGen = Gen.const(SOption(SSigmaProp)) + implicit val booleanTypeGen: Gen[SBoolean.type] = Gen.const(SBoolean) + implicit val byteTypeGen: Gen[SByte.type] = Gen.const(SByte) + implicit val shortTypeGen: Gen[SShort.type] = Gen.const(SShort) + implicit val intTypeGen: Gen[SInt.type] = Gen.const(SInt) + implicit val longTypeGen: Gen[SLong.type] = Gen.const(SLong) + implicit val bigIntTypeGen: Gen[SBigInt.type] = Gen.const(SBigInt) + implicit val groupElementTypeGen: Gen[SGroupElement.type] = Gen.const(SGroupElement) + implicit val sigmaPropTypeGen: Gen[SSigmaProp.type] = Gen.const(SSigmaProp) + implicit val boxTypeGen: Gen[SBox.type] = Gen.const(SBox) + implicit val avlTreeTypeGen: Gen[SAvlTree.type] = Gen.const(SAvlTree) + implicit val optionSigmaPropTypeGen: Gen[SOption[SSigmaProp.type]] = Gen.const(SOption(SSigmaProp)) implicit val primTypeGen: Gen[SPrimType] = Gen.oneOf[SPrimType](SBoolean, SByte, SShort, SInt, SLong, SBigInt, SGroupElement, SSigmaProp, SUnit) - implicit val arbPrimType = Arbitrary(primTypeGen) + implicit val arbPrimType: Arbitrary[SPrimType] = Arbitrary(primTypeGen) implicit val predefTypeGen: Gen[SPredefType] = Gen.oneOf[SPredefType](SBoolean, SByte, SShort, SInt, SLong, SBigInt, SGroupElement, SSigmaProp, SUnit, SBox, SAvlTree) - implicit val arbPredefType = Arbitrary(predefTypeGen) + implicit val arbPredefType: Arbitrary[SPredefType] = Arbitrary(predefTypeGen) implicit def genToArbitrary[T: Gen]: Arbitrary[T] = Arbitrary(implicitly[Gen[T]]) diff --git a/interpreter/shared/src/test/scala/sigmastate/utils/HelpersTests.scala b/interpreter/shared/src/test/scala/sigmastate/utils/HelpersTests.scala index c1accad043..3325035bbd 100644 --- a/interpreter/shared/src/test/scala/sigmastate/utils/HelpersTests.scala +++ b/interpreter/shared/src/test/scala/sigmastate/utils/HelpersTests.scala @@ -5,12 +5,16 @@ import Helpers._ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import sigmastate.eval.Extensions.ArrayOps class HelpersTests extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers with ObjectGenerators { property("xorU") { forAll(arrayGen[Byte]) { arr => val x = xor(arr, arr) + val xColl = xor(arr.toColl, arr.toColl) + x shouldBe xColl.toArray + val cloned = arr.clone() xorU(cloned, arr) cloned shouldBe x @@ -18,7 +22,13 @@ class HelpersTests extends AnyPropSpec with ScalaCheckPropertyChecks with Matche val arr1 = x val arr2 = cloned val arr3 = xor(arr1, arr2) + val arr3Coll = xor(arr1.toColl, arr2.toColl) + arr3 shouldBe arr3Coll.toArray + val res1 = xor(cloned, arr1, arr2, arr3) + val res1Coll = xor(cloned.toColl, arr1.toColl, arr2.toColl, arr3.toColl) + res1 shouldBe res1Coll.toArray + val res2 = cloned xorU(res2, Seq(arr1, arr2, arr3)) diff --git a/interpreter/shared/src/test/scala/sigmastate/utxo/ProverSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/utxo/ProverSpecification.scala index 0e72141d94..c5b049dd63 100644 --- a/interpreter/shared/src/test/scala/sigmastate/utxo/ProverSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/utxo/ProverSpecification.scala @@ -5,7 +5,7 @@ import scorex.crypto.hash.Blake2b256 import sigmastate.Values.SigmaBoolean import sigmastate._ import sigmastate.basics.DLogProtocol.FirstDLogProverMessage -import sigmastate.basics.{FirstDiffieHellmanTupleProverMessage, SecP256K1Group} +import sigmastate.basics.{FirstDHTupleProverMessage, SecP256K1Group} import sigmastate.exceptions.InterpreterException import sigmastate.helpers.{ErgoLikeTestProvingInterpreter, TestingCommons} import sigmastate.interpreter.{HintsBag, ProverInterpreter} @@ -52,7 +52,7 @@ class ProverSpecification extends TestingCommons { h3.realCommitments.head.commitment shouldBe h3.ownCommitments.head.commitment - h3.realCommitments.head.commitment.isInstanceOf[FirstDiffieHellmanTupleProverMessage] shouldBe true + h3.realCommitments.head.commitment.isInstanceOf[FirstDHTupleProverMessage] shouldBe true } property("setPositions - and") { diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala index e8bca398df..cdcbd0d31f 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala +++ b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala @@ -1,30 +1,30 @@ package org.ergoplatform.sdk.js import org.ergoplatform.ErgoBox._ -import org.ergoplatform.{DataInput, ErgoBox, ErgoBoxCandidate, UnsignedErgoLikeTransaction, UnsignedInput} -import org.ergoplatform.sdk.{ExtendedInputBox, Iso} import org.ergoplatform.sdk.JavaHelpers.UniversalConverter -import org.ergoplatform.sdk.wallet.protocol.context +import org.ergoplatform.sdk.wallet.protocol.context.{CErgoLikeStateContext, ErgoLikeStateContext} +import org.ergoplatform.sdk.{ExtendedInputBox, Iso} +import org.ergoplatform._ import scalan.RType -import scorex.crypto.authds.{ADDigest, ADKey} +import scorex.crypto.authds.ADKey import scorex.util.ModifierId import scorex.util.encode.Base16 -import sigmastate.{AvlTreeData, AvlTreeFlags, SType} import sigmastate.Values.{Constant, GroupElementConstant} import sigmastate.eval.Extensions.ArrayOps import sigmastate.eval.{CAvlTree, CBigInt, CHeader, CPreHeader, Colls, Digest32Coll, Evaluation} +import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.Box +import sigmastate.fleetSdkCommon.distEsmTypesCommonMod.HexString +import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters +import sigmastate.fleetSdkCommon.distEsmTypesTokenMod.TokenAmount +import sigmastate.fleetSdkCommon.distEsmTypesTransactionsMod.UnsignedTransaction import sigmastate.fleetSdkCommon.{distEsmTypesBoxesMod => boxesMod, distEsmTypesCommonMod => commonMod, distEsmTypesContextExtensionMod => contextExtensionMod, distEsmTypesInputsMod => inputsMod, distEsmTypesRegistersMod => registersMod, distEsmTypesTokenMod => tokenMod} import sigmastate.interpreter.ContextExtension import sigmastate.serialization.{ErgoTreeSerializer, ValueSerializer} +import sigmastate.{AvlTreeData, AvlTreeFlags, SType} import special.collection.Coll import special.collection.Extensions.CollBytesOps import special.sigma import special.sigma.GroupElement -import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.Box -import sigmastate.fleetSdkCommon.distEsmTypesCommonMod.HexString -import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters -import sigmastate.fleetSdkCommon.distEsmTypesTokenMod.TokenAmount -import sigmastate.fleetSdkCommon.distEsmTypesTransactionsMod.UnsignedTransaction import java.math.BigInteger import scala.collection.immutable.ListMap