Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade sigma to v5.0.7 #1984

Merged
merged 9 commits into from
Apr 24, 2023
3 changes: 2 additions & 1 deletion avldb/build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ name := "avldb"
libraryDependencies ++= Seq(
"javax.xml.bind" % "jaxb-api" % "2.4.0-b180830.0359",
"ch.qos.logback" % "logback-classic" % "1.2.3",
"org.scorexfoundation" %% "scrypto" % "2.2.1"
"com.google.guava" % "guava" % "23.0",
"org.scorexfoundation" %% "scrypto" % "2.3.0"
)

libraryDependencies ++= Seq(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class ProverNodeSerializer(store: LDBVersionedStore) extends ErgoSerializer[Prov
if (store != null) {
new ProxyInternalProverNode(key, leftKey, rightKey, balance)(store)
} else {
new ProxyInternalNode[DigestType](key, Digest32 @@ leftKey, Digest32 @@ rightKey, balance)(hashFn)
new ProxyInternalNode[DigestType](key, Digest32 @@@ leftKey, Digest32 @@@ rightKey, balance)(hashFn)
}
case LeafPrefix =>
val key = ADKey @@ r.getBytes(StateTreeParameters.keySize)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ class VersionedLDBAVLStorage(store: LDBVersionedStore)
val node = VersionedLDBAVLStorage.noStoreSerializer.parseBytes(nodeBytes)
node match {
case in: ProxyInternalNode[DigestType] =>
subtreeLoop(Digest32 @@ in.leftLabel, builder)
subtreeLoop(Digest32 @@ in.rightLabel, builder)
subtreeLoop(Digest32 @@@ in.leftLabel, builder)
subtreeLoop(Digest32 @@@ in.rightLabel, builder)
case _ =>
}
}
Expand All @@ -125,8 +125,8 @@ class VersionedLDBAVLStorage(store: LDBVersionedStore)
val node = VersionedLDBAVLStorage.noStoreSerializer.parseBytes(nodeBytes)
node match {
case in: ProxyInternalNode[DigestType] if level == manifestDepth =>
dumpSubtree(Digest32 @@ in.leftLabel)
dumpSubtree(Digest32 @@ in.rightLabel)
dumpSubtree(Digest32 @@@ in.leftLabel)
dumpSubtree(Digest32 @@@ in.rightLabel)
case in: ProxyInternalNode[DigestType] =>
manifestLoop(in.leftLabel, level + 1, manifestBuilder)
manifestLoop(in.rightLabel, level + 1, manifestBuilder)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ class VersionedLDBAVLStorageSpecification extends AnyPropSpec
val rollbackVersionsTest: (PERSISTENT_PROVER, STORAGE) => Assertion = { (prover: PERSISTENT_PROVER, storage: STORAGE) =>
(0L until 50L).foreach { long =>
val insert = Insert(ADKey @@ RandomBytes.randomBytes(32),
ADValue @@ com.google.common.primitives.Longs.toByteArray(long))
ADValue @@ Longs.toByteArray(long))
prover.performOneOperation(insert)
prover.generateProofAndUpdateStorage()
prover.digest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ object OOMTest extends App {
Longs.toByteArray(value) ++ propBytes ++ (0.toByte +: Array.emptyByteArray) ++
transactionId ++ Shorts.toByteArray(boxId)
val id = Blake2b256.hash(bytes)
ADKey @@ id -> ADValue @@ bytes
ADKey @@@ id -> ADValue @@@ bytes
}

private def metadata(modId: Array[Byte], stateRoot: ADDigest): Seq[(Array[Byte], Array[Byte])] = {
Expand Down
2 changes: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ val circeVersion = "0.13.0"
val akkaVersion = "2.6.10"
val akkaHttpVersion = "10.2.4"

val sigmaStateVersion = "5.0.5"
val sigmaStateVersion = "5.0.7"

// for testing current sigmastate build (see sigmastate-ergo-it jenkins job)
val effectiveSigmaStateVersion = Option(System.getenv().get("SIGMASTATE_VERSION")).getOrElse(sigmaStateVersion)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.bouncycastle.math.ec.custom.sec.SecP256K1Point;
import scala.math.BigInt;
import sigmastate.crypto.Platform;

import java.math.BigInteger;

Expand All @@ -25,7 +26,7 @@ public byte[] sign(byte[] msg, BigInteger sk) {
* @return `true` is the signature is valid, `false` otherwise
*/
public boolean verify(byte[] msg, byte[] signature, SecP256K1Point pk) {
return org.ergoplatform.wallet.crypto.ErgoSignature.verify(msg, signature, pk);
return org.ergoplatform.wallet.crypto.ErgoSignature.verify(msg, signature, new Platform.Ecp(pk));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package org.ergoplatform.wallet.interpreter
import org.ergoplatform.ErgoLikeContext.Height
import org.ergoplatform.wallet.protocol.Constants
import org.ergoplatform.wallet.protocol.context.ErgoLikeParameters
import org.ergoplatform.{ErgoLikeContext, ErgoBox, ErgoBoxCandidate, ErgoLikeInterpreter}
import org.ergoplatform.{ErgoBox, ErgoBoxCandidate, ErgoLikeContext, ErgoLikeInterpreter}
import scorex.crypto.authds.ADDigest
import scorex.util.ScorexLogging
import sigmastate.Values.ErgoTree
import sigmastate.interpreter.Interpreter.{VerificationResult, ScriptEnv}
import sigmastate.interpreter.Interpreter.{ScriptEnv, VerificationResult}
import sigmastate.{AvlTreeData, AvlTreeFlags}

import scala.util.Try
Expand All @@ -18,7 +19,15 @@ import scala.util.Try
* @param params - current values of adjustable blockchain settings
*/
class ErgoInterpreter(params: ErgoLikeParameters)
extends ErgoLikeInterpreter {
extends ErgoLikeInterpreter with ScorexLogging {

/** Override default logging for all Ergo interpreters. */
override protected def logMessage(msg: String): Unit = {
log.error(msg)
}
override protected def logMessage(msg: String, t: Throwable): Unit = {
log.error(msg, t)
}

override type CTX = ErgoLikeContext

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package org.ergoplatform.wallet.secrets

import java.util
import org.bouncycastle.math.ec.ECPoint
kushti marked this conversation as resolved.
Show resolved Hide resolved

import java.util
import org.bouncycastle.util.BigIntegers
import org.ergoplatform.wallet.Constants
import org.ergoplatform.wallet.crypto.HmacSHA512
import org.ergoplatform.wallet.serialization.ErgoWalletSerializer
import scorex.util.serialization.{Reader, Writer}
import sigmastate.basics.DLogProtocol.{DLogProverInput, ProveDlog}
import sigmastate.crypto.CryptoFacade
import sigmastate.interpreter.CryptoConstants

import scala.annotation.tailrec
Expand All @@ -24,7 +26,7 @@ final class ExtendedPublicKey(private[secrets] val keyBytes: Array[Byte],
def selfReflection: ExtendedPublicKey = this

def key: ProveDlog = ProveDlog(
CryptoConstants.dlogGroup.curve.decodePoint(keyBytes).asInstanceOf[CryptoConstants.EcPointType]
CryptoConstants.dlogGroup.ctx.decodePoint(keyBytes)
)

def child(idx: Int): ExtendedPublicKey = ExtendedPublicKey.deriveChildPublicKey(this, idx)
Expand Down Expand Up @@ -56,11 +58,15 @@ object ExtendedPublicKey {
.hash(parentKey.chainCode, parentKey.keyBytes ++ Index.serializeIndex(idx))
.splitAt(Constants.SecretKeyLength)
val childKeyProtoDecoded = BigIntegers.fromUnsignedByteArray(childKeyProto)
val childKey = DLogProverInput(childKeyProtoDecoded).publicImage.value.add(parentKey.key.value)
if (childKeyProtoDecoded.compareTo(CryptoConstants.groupOrder) >= 0 || childKey.isInfinity) {
val childKey = CryptoFacade.multiplyPoints(
DLogProverInput(childKeyProtoDecoded).publicImage.value,
parentKey.key.value)
if (childKeyProtoDecoded.compareTo(CryptoConstants.groupOrder) >= 0 || CryptoFacade.isInfinityPoint(childKey)) {
deriveChildPublicKey(parentKey, idx + 1)
} else {
new ExtendedPublicKey(childKey.getEncoded(true), childChainCode, parentKey.path.extended(idx))
new ExtendedPublicKey(
CryptoFacade.encodePoint(childKey, true),
childChainCode, parentKey.path.extended(idx))
kushti marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
package org.ergoplatform.wallet.secrets

import org.bouncycastle.math.ec.ECPoint
kushti marked this conversation as resolved.
Show resolved Hide resolved

import java.math.BigInteger
import java.util

import org.bouncycastle.util.BigIntegers
import org.ergoplatform.wallet.Constants
import org.ergoplatform.wallet.crypto.HmacSHA512
import org.ergoplatform.wallet.serialization.ErgoWalletSerializer
import scorex.util.serialization.{Reader, Writer}
import sigmastate.basics.DLogProtocol
import sigmastate.basics.DLogProtocol.DLogProverInput
import sigmastate.crypto.CryptoFacade
import sigmastate.interpreter.CryptoConstants

/**
Expand All @@ -30,8 +32,11 @@ final class ExtendedSecretKey(private[secrets] val keyBytes: Array[Byte],

def child(idx: Int): ExtendedSecretKey = ExtendedSecretKey.deriveChildSecretKey(this, idx)

/** Returns extended public key corresponding to this secret key. */
def publicKey: ExtendedPublicKey =
new ExtendedPublicKey(privateInput.publicImage.value.getEncoded(true), chainCode, path.toPublicBranch)
new ExtendedPublicKey(
CryptoFacade.encodePoint(privateInput.publicImage.value, compressed = true),
chainCode, path.toPublicBranch)
kushti marked this conversation as resolved.
Show resolved Hide resolved

def isErased: Boolean = keyBytes.forall(_ == 0x00)

Expand Down Expand Up @@ -60,7 +65,7 @@ object ExtendedSecretKey {
def deriveChildSecretKey(parentKey: ExtendedSecretKey, idx: Int): ExtendedSecretKey = {
val keyCoded: Array[Byte] =
if (Index.isHardened(idx)) (0x00: Byte) +: parentKey.keyBytes
else parentKey.privateInput.publicImage.value.getEncoded(true)
else CryptoFacade.encodePoint(parentKey.privateInput.publicImage.value, compressed = true)
val (childKeyProto, childChainCode) = HmacSHA512
.hash(parentKey.chainCode, keyCoded ++ Index.serializeIndex(idx))
.splitAt(Constants.SecretKeyLength)
Expand All @@ -85,7 +90,8 @@ object ExtendedSecretKey {

def deriveChildPublicKey(parentKey: ExtendedSecretKey, idx: Int): ExtendedPublicKey = {
val derivedSecret = deriveChildSecretKey(parentKey, idx)
val derivedPk = derivedSecret.privateInput.publicImage.value.getEncoded(true)
val derivedPk = CryptoFacade.encodePoint(
derivedSecret.privateInput.publicImage.value, compressed = true)
val derivedPath = derivedSecret.path.copy(publicBranch = true)
new ExtendedPublicKey(derivedPk, derivedSecret.chainCode, derivedPath)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ class DefaultBoxSelectorSpec extends AnyPropSpec with Matchers with EitherValues
val tokenData = genTokens(3).last
tokenData._2 shouldBe 2

val tokenId = ModifierId @@ bytesToId(tokenData._1)
val tokenId = ModifierId @@@ bytesToId(tokenData._1)

val ergValue = 10 * MinBoxValue

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class ErgoSignatureSpec extends AnyPropSpec with Matchers with Generators {

val sig = sign(msg, secret.w)

verify(msg, sig, pk.h) shouldBe true
verify(msg, sig, pk.value) shouldBe true
}

property("always produce signature of fixed length") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ class ErgoProvingInterpreterSpec

signedTxFull.inputs.map(_.spendingProof.proof).zip(signedTxFull.inputs.map(_.spendingProof.proof))
.foreach { case (fullProof, unsafeProof) =>
ErgoSignature.verify(unsignedTx.messageToSign, fullProof, extendedSecretKey.publicKey.key.h) shouldBe
ErgoSignature.verify(unsignedTx.messageToSign, unsafeProof, extendedSecretKey.publicKey.key.h)
ErgoSignature.verify(unsignedTx.messageToSign, fullProof, extendedSecretKey.publicKey.key.value) shouldBe
ErgoSignature.verify(unsignedTx.messageToSign, unsafeProof, extendedSecretKey.publicKey.key.value)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ class ErgoUnsafeProverSpec

signedTxFull.inputs.map(_.spendingProof.proof).zip(signedTxFull.inputs.map(_.spendingProof.proof))
.foreach { case (fullProof, unsafeProof) =>
ErgoSignature.verify(unsignedTx.messageToSign, fullProof, extendedSecretKey.publicKey.key.h) shouldBe
ErgoSignature.verify(unsignedTx.messageToSign, unsafeProof, extendedSecretKey.publicKey.key.h)
ErgoSignature.verify(unsignedTx.messageToSign, fullProof, extendedSecretKey.publicKey.key.value) shouldBe
ErgoSignature.verify(unsignedTx.messageToSign, unsafeProof, extendedSecretKey.publicKey.key.value)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class TransactionBuilderSpec extends WalletTestHelpers with Matchers {

property("token minting") {
val inputBox = box(minBoxValue * 2)
val tokenId = Digest32 @@ inputBox.id
val tokenId = Digest32 @@@ inputBox.id
val outBox = boxCandidate(minBoxValue, Seq(tokenId -> 100L))
val res = transaction(inputBox, outBox)

Expand All @@ -87,7 +87,7 @@ class TransactionBuilderSpec extends WalletTestHelpers with Matchers {

property("token burning") {
val inputBox = box(minBoxValue * 3, Seq(Digest32 @@ idToBytes(tid1) -> 1000L, Digest32 @@ idToBytes(tid2) -> 2000L))
val tokenId = Digest32 @@ inputBox.id
val tokenId = Digest32 @@@ inputBox.id
val outBox = boxCandidate(minBoxValue, Seq(tokenId -> 100L))
val res = transaction(inputBox, outBox, burnTokens = Map(tid1 -> 400L, tid2 -> 800L))

Expand All @@ -105,7 +105,7 @@ class TransactionBuilderSpec extends WalletTestHelpers with Matchers {

property("no fees") {
val inputBox = box(minBoxValue)
val tokenId = Digest32 @@ inputBox.id
val tokenId = Digest32 @@@ inputBox.id
val outBox = boxCandidate(minBoxValue, Seq(tokenId -> 100L))
val res = transaction(inputBox, outBox, fee = None)

Expand All @@ -117,7 +117,7 @@ class TransactionBuilderSpec extends WalletTestHelpers with Matchers {

property("change goes to fee, but no outFee box") {
val inputBox = box(minBoxValue + minBoxValue / 2)
val tokenId = Digest32 @@ inputBox.id
val tokenId = Digest32 @@@ inputBox.id
val outBox = boxCandidate(minBoxValue, Seq(tokenId -> 100L))
val res = transaction(inputBox, outBox, fee = None)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ trait Generators {
val assetGen: Gen[(TokenId, Long)] = for {
id <- boxIdGen
amt <- Gen.oneOf(1, 500, 20000, 10000000, Long.MaxValue)
} yield Digest32 @@ id -> amt
} yield Digest32 @@@ id -> amt

def additionalTokensGen(cnt: Int): Gen[Seq[(TokenId, Long)]] = Gen.listOfN(cnt, assetGen)

Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/org/ergoplatform/http/api/ApiCodecs.scala
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ trait ApiCodecs extends JsonCodecs {
sigma =>
val op = sigma.opCode.toByte.asJson
sigma match {
case dlog: ProveDlog => Map("op" -> op, "h" -> dlog.h.asJson).asJson
case dlog: ProveDlog => Map("op" -> op, "h" -> dlog.value.asJson).asJson
case dht: ProveDHTuple => Map("op" -> op, "g" -> dht.g.asJson, "h" -> dht.h.asJson, "u" -> dht.u.asJson, "v" -> dht.v.asJson).asJson
case tp: TrivialProp => Map("op" -> op, "condition" -> tp.condition.asJson).asJson
case and: CAND =>
Expand Down
11 changes: 7 additions & 4 deletions src/main/scala/org/ergoplatform/mining/AutolykosPowScheme.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import scorex.crypto.authds.{ADDigest, SerializedAdProof}
import scorex.crypto.hash.{Blake2b256, Digest32}
import scorex.util.{ModifierId, ScorexLogging}
import sigmastate.basics.DLogProtocol.ProveDlog
import sigmastate.crypto.CryptoFacade

import scala.annotation.tailrec
import scala.math.BigInt
Expand Down Expand Up @@ -126,8 +127,8 @@ class AutolykosPowScheme(val k: Int, val n: Int) extends ScorexLogging {
val N = calcN(header)

require(s.d < b, s"Incorrect d = ${s.d} for b = $b")
require(s.pk.getCurve == group.curve && !s.pk.isInfinity, "pk is incorrect")
require(s.w.getCurve == group.curve && !s.w.isInfinity, "w is incorrect")
require(CryptoFacade.getCurve(s.pk) == group.ctx.curve && !CryptoFacade.isInfinityPoint(s.pk), "pk is incorrect")
require(CryptoFacade.getCurve(s.w) == group.ctx.curve && !CryptoFacade.isInfinityPoint(s.w), "w is incorrect")

val pkBytes = groupElemToBytes(s.pk)
val wBytes = groupElemToBytes(s.w)
Expand All @@ -137,8 +138,10 @@ class AutolykosPowScheme(val k: Int, val n: Int) extends ScorexLogging {

//height is not used in v1
val f = indexes.map(idx => genElement(version, msg, pkBytes, wBytes, Ints.toByteArray(idx), null)).sum.mod(q)
val left = s.w.multiply(f.bigInteger)
val right = group.generator.multiply(s.d.bigInteger).add(s.pk)
val left = CryptoFacade.exponentiatePoint(s.w, f.bigInteger)
val right = CryptoFacade.multiplyPoints(
CryptoFacade.exponentiatePoint(group.generator, s.d.bigInteger),
s.pk)
left == right
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import org.ergoplatform.modifiers.history.header.{Header, HeaderWithoutPow}
import org.ergoplatform.modifiers.history.popow.NipopowAlgos
import org.ergoplatform.modifiers.mempool.{ErgoTransaction, UnconfirmedTransaction}
import org.ergoplatform.network.ErgoNodeViewSynchronizer.ReceivableMessages
import ReceivableMessages.{ChangedHistory, ChangedMempool, ChangedState, NodeViewChange, FullBlockApplied}
import ReceivableMessages.{ChangedHistory, ChangedMempool, ChangedState, FullBlockApplied, NodeViewChange}
import org.ergoplatform.nodeView.ErgoReadersHolder.{GetReaders, Readers}
import org.ergoplatform.nodeView.history.ErgoHistory.Height
import org.ergoplatform.nodeView.history.{ErgoHistory, ErgoHistoryReader}
Expand All @@ -29,6 +29,7 @@ import scorex.util.encode.Base16
import scorex.util.{ModifierId, ScorexLogging}
import sigmastate.SType.ErgoBoxRType
import sigmastate.basics.DLogProtocol.ProveDlog
import sigmastate.crypto.CryptoFacade
import sigmastate.eval.Extensions._
import sigmastate.eval._
import sigmastate.interpreter.ProverResult
Expand Down Expand Up @@ -183,7 +184,7 @@ class CandidateGenerator(
if state.solvedBlock.isEmpty && state.cache.nonEmpty =>
// Inject node pk if it is not externally set (in Autolykos 2)
val solution =
if (preSolution.pk.isInfinity) {
if (CryptoFacade.isInfinityPoint(preSolution.pk)) {
AutolykosSolution(minerPk.value, preSolution.w, preSolution.n, preSolution.d)
} else {
preSolution
Expand Down Expand Up @@ -506,7 +507,7 @@ object CandidateGenerator extends ScorexLogging {
)

val upcomingContext = state.stateContext.upcoming(
minerPk.h,
minerPk.value,
timestamp,
nBits,
votes,
Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/org/ergoplatform/mining/mining.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ package object mining {

val PublicKeyLength: Byte = 33

val group: BcDlogGroup[EcPointType] = CryptoConstants.dlogGroup
val group: BcDlogGroup = CryptoConstants.dlogGroup

// Group order, used in Autolykos V.1 for non-outsourceability,
// and also to obtain target in both Autolykos v1 and v2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,10 @@ case class ErgoTransaction(override val inputs: IndexedSeq[Input],
lazy val reemissionSettings = stateContext.ergoSettings.chainSettings.reemission
lazy val reemissionRules = reemissionSettings.reemissionRules

lazy val reemissionTokenId = ModifierId @@ reemissionSettings.reemissionTokenId
lazy val reemissionTokenId = ModifierId @@@ reemissionSettings.reemissionTokenId
lazy val reemissionTokenIdBytes = reemissionSettings.reemissionTokenIdBytes

lazy val emissionNftId = ModifierId @@ reemissionSettings.emissionNftId
lazy val emissionNftId = ModifierId @@@ reemissionSettings.emissionNftId
lazy val emissionNftIdBytes = reemissionSettings.emissionNftIdBytes

lazy val chainSettings = stateContext.ergoSettings.chainSettings
Expand Down
Loading