Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
vsuharnikov committed Nov 8, 2024
1 parent 2776740 commit 6d10175
Show file tree
Hide file tree
Showing 20 changed files with 133 additions and 147 deletions.
2 changes: 2 additions & 0 deletions consensus-client-it/src/test/scala/units/Accounts.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ trait Accounts {
val clRichAccount1 = mkKeyPair("devnet rich", 0)
val clRichAccount2 = mkKeyPair("devnet rich", 1)

val elBridgeAddress = EthAddress.unsafeFrom("0x0000000000000000000000000000000000006a7e")

val elRichAccount1 = Credentials.create("8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63")
val elRichAccount2 = Credentials.create("ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class AlternativeChainTestSuite extends BaseDockerTestSuite {
"L2-383 Start an alternative chain after not getting an EL-block" in {
step("EL miner #2 join")
waves1.api.broadcastAndWait(
chainContract.join(
ChainContract.join(
minerAccount = miner21Account,
elRewardAddress = miner21RewardAddress
)
Expand All @@ -19,10 +19,10 @@ class AlternativeChainTestSuite extends BaseDockerTestSuite {
waitMinerEpoch(miner21Account)

step("Issue miner #2 block confirmation")
val lastContractBlock = waves1.chainContract.getLastBlockMeta(0).getOrElse(fail("Can't get last block"))
val lastContractBlock = chainContract.getLastBlockMeta(0).getOrElse(fail("Can't get last block"))
val lastWavesBlock = waves1.api.blockHeader(waves1.api.height).getOrElse(fail("Can't get current block header"))
waves1.api.broadcastAndWait(
chainContract.extendMainChain(
ChainContract.extendMainChain(
minerAccount = miner21Account,
blockHash = BlockHash("0x0000000000000000000000000000000000000000000000000000000000000001"),
parentBlockHash = lastContractBlock.hash,
Expand All @@ -37,14 +37,14 @@ class AlternativeChainTestSuite extends BaseDockerTestSuite {

step("Checking an alternative chain started")
retry {
waves1.chainContract.getChainInfo(1L).getOrElse(fail("Can't get an alternative chain info"))
chainContract.getChainInfo(1L).getOrElse(fail("Can't get an alternative chain info"))
}
}

private def waitMinerEpoch(minerAccount: KeyPair): Unit = {
val expectedGenerator = minerAccount.toAddress
retry {
val actualGenerator = waves1.chainContract.computedGenerator
val actualGenerator = chainContract.computedGenerator
if (actualGenerator != expectedGenerator) fail(s"Expected $expectedGenerator generator, got $actualGenerator")
}(patienceConfig.copy(timeout = WavesNodeContainer.AverageBlockDelay * 5))
}
Expand Down
21 changes: 15 additions & 6 deletions consensus-client-it/src/test/scala/units/BaseDockerTestSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@ import monix.execution.atomic.AtomicBoolean
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import org.scalatest.{BeforeAndAfterAll, EitherValues, OptionValues}
import sttp.client3.{HttpClientSyncBackend, Identity, SttpBackend}
import units.BaseDockerTestSuite.generateWavesGenesisConfig
import units.client.HttpChainContractClient
import units.client.contract.HasConsensusLayerDappTxHelpers
import units.client.engine.model.BlockNumber
import units.docker.{EcContainer, Networks, WavesNodeContainer}
import units.el.ElBridgeClient
import units.eth.Gwei
import units.test.TestEnvironment.*
import units.test.{CustomMatchers, HasRetry}
Expand Down Expand Up @@ -41,6 +44,8 @@ trait BaseDockerTestSuite

protected lazy val wavesGenesisConfigPath = generateWavesGenesisConfig()

private implicit val httpClientBackend: SttpBackend[Identity, Any] = HttpClientSyncBackend()

protected lazy val ec1: EcContainer = new EcContainer(
network = network,
number = 1,
Expand All @@ -52,12 +57,14 @@ trait BaseDockerTestSuite
number = 1,
ip = Networks.ipForNode(3),
baseSeed = "devnet-1",
clMinerKeyPair = mkKeyPair("devnet-1", 0),
chainContractAddress = chainContractAddress,
ecEngineApiUrl = s"http://${ec1.hostName}:${EcContainer.EnginePort}",
ecEngineApiUrl = ec1.engineApiDockerUrl,
genesisConfigPath = wavesGenesisConfigPath
)

protected lazy val chainContract = new HttpChainContractClient(waves1.api, chainContractAddress)
protected lazy val elBridge = new ElBridgeClient(ec1.web3j, elBridgeAddress)

protected def startNodes(): Unit = {
ec1.start()
ec1.logPorts()
Expand All @@ -74,24 +81,24 @@ trait BaseDockerTestSuite

protected def setupNetwork(): Unit = {
log.info("Set script")
waves1.api.broadcastAndWait(chainContract.setScript())
waves1.api.broadcastAndWait(ChainContract.setScript())

log.info("Setup chain contract")
val genesisBlock = ec1.engineApi.getBlockByNumber(BlockNumber.Number(0)).explicitGet().getOrElse(failRetry("No EL genesis block"))
waves1.api.broadcastAndWait(
chainContract.setup(
ChainContract.setup(
genesisBlock = genesisBlock,
elMinerReward = rewardAmount.amount.longValue(),
daoAddress = None,
daoReward = 0,
invoker = chainContractAccount
)
)
log.info(s"Token id: ${waves1.chainContract.token}")
log.info(s"Token id: ${chainContract.token}")

log.info("EL miner #1 join")
val joinMiner1Result = waves1.api.broadcastAndWait(
chainContract.join(
ChainContract.join(
minerAccount = miner11Account,
elRewardAddress = miner11RewardAddress
)
Expand All @@ -117,6 +124,8 @@ trait BaseDockerTestSuite
}

override protected def afterAll(): Unit = {
httpClientBackend.close()

stopNodes()
network.close()
super.afterAll()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,19 @@ class BridgeC2ETestSuite extends BaseDockerTestSuite {
private val gweiAmount = UnitsConvert.toGwei(userAmount)

"L2-380 Checking balances in CL->EL transfers" in {
def clAssetQuantity: Long = waves1.api.assetQuantity(waves1.chainContract.token)
def chainContractBalance: Long = waves1.api.balance(chainContractAddress, waves1.chainContract.token)
def clAssetQuantity: Long = waves1.api.assetQuantity(chainContract.token)
def chainContractBalance: Long = waves1.api.balance(chainContractAddress, chainContract.token)

val clAssetQuantityBefore = clAssetQuantity
val chainContractBalanceBefore = chainContractBalance

val elCurrHeight = ec1.web3j.ethBlockNumber().send().getBlockNumber.intValueExact()

waves1.api.broadcastAndWait(
chainContract.transfer(
ChainContract.transfer(
sender = clSender,
destElAddress = elReceiverAddress,
asset = waves1.chainContract.token,
asset = chainContract.token,
amount = wavesAmount
)
)
Expand Down Expand Up @@ -62,7 +62,7 @@ class BridgeC2ETestSuite extends BaseDockerTestSuite {
step("Prepare: issue tokens on chain contract and transfer to a user")
waves1.api.broadcastAndWait(
TxHelpers.reissue(
asset = waves1.chainContract.token,
asset = chainContract.token,
sender = chainContractAccount,
amount = wavesAmount
)
Expand All @@ -72,7 +72,7 @@ class BridgeC2ETestSuite extends BaseDockerTestSuite {
from = chainContractAccount,
to = clSender.toAddress,
amount = wavesAmount,
asset = waves1.chainContract.token
asset = chainContract.token
)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class BridgeE2CTestSuite extends BaseDockerTestSuite {
private val wavesAmount = UnitsConvert.toWavesAmount(userAmount)

private def sendNative(amount: BigInt = UnitsConvert.toWei(userAmount)): TransactionReceipt =
ec1.elBridge.sendNative(elSender, clRecipient.toAddress, amount)
elBridge.sendNative(elSender, clRecipient.toAddress, amount)

private val tenGwei = BigInt(Convert.toWei("10", Convert.Unit.GWEI).toBigIntegerExact)

Expand Down Expand Up @@ -67,7 +67,7 @@ class BridgeE2CTestSuite extends BaseDockerTestSuite {

"L2-379 Checking balances in EL->CL transfers" in {
step("Broadcast Bridge.sendNative transaction")
def bridgeBalance = ec1.web3j.ethGetBalance(ec1.elBridge.address.hex, DefaultBlockParameterName.LATEST).send().getBalance
def bridgeBalance = ec1.web3j.ethGetBalance(elBridgeAddress.hex, DefaultBlockParameterName.LATEST).send().getBalance
val bridgeBalanceBefore = bridgeBalance
val sendTxnReceipt = sendNative()

Expand All @@ -79,7 +79,7 @@ class BridgeE2CTestSuite extends BaseDockerTestSuite {
val blockHash = BlockHash(sendTxnReceipt.getBlockHash)
step(s"Block with transaction: $blockHash")

val logsInBlock = ec1.engineApi.getLogs(blockHash, ec1.elBridge.address, Bridge.ElSentNativeEventTopic).explicitGet()
val logsInBlock = ec1.engineApi.getLogs(blockHash, elBridgeAddress, Bridge.ElSentNativeEventTopic).explicitGet()

val transferEvents = logsInBlock.map { x =>
Bridge.ElSentNativeEvent.decodeArgs(x.data).explicitGet()
Expand All @@ -91,12 +91,12 @@ class BridgeE2CTestSuite extends BaseDockerTestSuite {

step(s"Wait block $blockHash on contract")
val blockConfirmationHeight = retry {
waves1.chainContract.getBlock(blockHash).get.height
chainContract.getBlock(blockHash).get.height
}

step(s"Wait block $blockHash ($blockConfirmationHeight) finalization")
retry {
val currFinalizedHeight = waves1.chainContract.getFinalizedBlock.height
val currFinalizedHeight = chainContract.getFinalizedBlock.height
step(s"Current finalized height: $currFinalizedHeight")
if (currFinalizedHeight < blockConfirmationHeight) fail("Not yet finalized")
}
Expand All @@ -107,11 +107,11 @@ class BridgeE2CTestSuite extends BaseDockerTestSuite {
s"merkleProof={${transferProofs.map(EthEncoding.toHexString).mkString(",")}}"
)

def receiverBalance: Long = waves1.api.balance(clRecipient.toAddress, waves1.chainContract.token)
def receiverBalance: Long = waves1.api.balance(clRecipient.toAddress, chainContract.token)
val receiverBalanceBefore = receiverBalance

waves1.api.broadcastAndWait(
chainContract.withdraw(
ChainContract.withdraw(
sender = clRecipient,
blockHash = BlockHash(sendTxnReceipt.getBlockHash),
merkleProof = transferProofs,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class RewardTestSuite extends BaseDockerTestSuite {
}

val epoch1FirstContractBlock = retry {
waves1.chainContract.getBlock(epoch1FirstEcBlock.hash).getOrElse(failRetry(s"No first block ${epoch1FirstEcBlock.hash} confirmation"))
chainContract.getBlock(epoch1FirstEcBlock.hash).getOrElse(failRetry(s"No first block ${epoch1FirstEcBlock.hash} confirmation"))
}

val epoch1Number = epoch1FirstContractBlock.epoch
Expand All @@ -24,7 +24,7 @@ class RewardTestSuite extends BaseDockerTestSuite {

step(s"Wait for epoch #$epoch2Number data on chain contract")
val epoch2FirstContractBlock = retry {
waves1.chainContract.getEpochFirstBlock(epoch2Number).get
chainContract.getEpochFirstBlock(epoch2Number).get
}

val epoch2FirstEcBlock = ec1.engineApi
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class SyncingTestSuite extends BaseDockerTestSuite {
step(s"Waiting blocks ${blocksWithTxns.mkString(", ")} on contract")
blocksWithTxns.foreach { case (_, blockHash) =>
retry {
waves1.chainContract.getBlock(BlockHash(blockHash)).get
chainContract.getBlock(BlockHash(blockHash)).get
}
}

Expand All @@ -47,7 +47,7 @@ class SyncingTestSuite extends BaseDockerTestSuite {
step(s"Waiting blocks ${blocksWithTxns.mkString(", ")} disappear")
blocksWithTxns.foreach { case (_, blockHash) =>
retry {
if (waves1.chainContract.getBlock(BlockHash(blockHash)).nonEmpty) throw new RuntimeException(s"Expected $blockHash to disappear")
if (chainContract.getBlock(BlockHash(blockHash)).nonEmpty) throw new RuntimeException(s"Expected $blockHash to disappear")
}
}

Expand Down
50 changes: 13 additions & 37 deletions consensus-client-it/src/test/scala/units/docker/EcContainer.scala
Original file line number Diff line number Diff line change
@@ -1,33 +1,28 @@
package units.docker

import com.google.common.io.Files
import com.typesafe.config.{ConfigFactory, ConfigValueFactory}
import net.ceedubs.ficus.Ficus.toFicusConfig
import org.testcontainers.containers.BindMode
import org.testcontainers.containers.Network.NetworkImpl
import org.web3j.protocol.Web3j
import org.web3j.protocol.http.HttpService
import sttp.client3.HttpClientSyncBackend
import units.ClientConfig
import sttp.client3.{Identity, SttpBackend}
import units.client.JsonRpcClient
import units.client.engine.{HttpEngineApiClient, LoggedEngineApiClient}
import units.docker.EcContainer.{EnginePort, RpcPort, mkConfig}
import units.el.ElBridgeClient
import units.eth.EthAddress
import units.docker.EcContainer.{EnginePort, RpcPort}
import units.http.OkHttpLogger
import units.test.TestEnvironment.*

import java.io.File
import java.nio.charset.StandardCharsets
import scala.jdk.CollectionConverters.CollectionHasAsScala
import scala.concurrent.duration.DurationInt

class EcContainer(network: NetworkImpl, number: Int, ip: String) extends BaseContainer(s"ec-$number") {
class EcContainer(network: NetworkImpl, number: Int, ip: String)(implicit httpClientBackend: SttpBackend[Identity, Any])
extends BaseContainer(s"ec-$number") {
private val logFile = new File(s"$DefaultLogsDir/besu-$number.log")
Files.touch(logFile)

protected override val container = new GenericContainer(DockerImages.ExecutionClient)
.withNetwork(network)
.withExposedPorts(RpcPort, EnginePort)
.withEnv(EcContainer.peersEnv, EcContainer.peersVal.mkString(","))
.withEnv("LOG4J_CONFIGURATION_FILE", "/config/log4j2.xml")
.withFileSystemBind(s"$ConfigsDir/ec-common/genesis.json", "/genesis.json", BindMode.READ_ONLY)
.withFileSystemBind(s"$ConfigsDir/besu", "/config", BindMode.READ_ONLY)
Expand All @@ -46,8 +41,13 @@ class EcContainer(network: NetworkImpl, number: Int, ip: String) extends BaseCon
lazy val rpcPort = container.getMappedPort(RpcPort)
lazy val enginePort = container.getMappedPort(EnginePort)

private val httpClientBackend = HttpClientSyncBackend()
lazy val engineApi = new LoggedEngineApiClient(new HttpEngineApiClient(mkConfig(container.getHost, enginePort), httpClientBackend))
lazy val engineApiDockerUrl = s"http://$hostName:${EcContainer.EnginePort}"
lazy val engineApi = new LoggedEngineApiClient(
new HttpEngineApiClient(
JsonRpcClient.Config(apiUrl = s"http://${container.getHost}:$enginePort", apiRequestRetries = 5, apiRequestRetryWaitTime = 1.second),
httpClientBackend
)
)

lazy val web3j = Web3j.build(
new HttpService(
Expand All @@ -58,11 +58,8 @@ class EcContainer(network: NetworkImpl, number: Int, ip: String) extends BaseCon
)
)

lazy val elBridge = new ElBridgeClient(web3j, EthAddress.unsafeFrom("0x0000000000000000000000000000000000006a7e"))

override def stop(): Unit = {
web3j.shutdown()
httpClientBackend.close()
super.stop()
}

Expand All @@ -72,25 +69,4 @@ class EcContainer(network: NetworkImpl, number: Int, ip: String) extends BaseCon
object EcContainer {
val RpcPort = 8545
val EnginePort = 8551

// TODO move
private val baseConfig = ConfigFactory.load(this.getClass.getClassLoader, "application.conf")
private def mkConfig(host: String, port: Int): ClientConfig = baseConfig
.getConfig("units.defaults")
.withValue("chain-contract", ConfigValueFactory.fromAnyRef("")) // Doesn't matter for HttpEngineApiClient
.withValue("execution-client-address", ConfigValueFactory.fromAnyRef(s"http://$host:$port"))
.resolve()
.as[ClientConfig]

val (peersEnv, peersVal) = {
val file = new File(s"$ConfigsDir/ec-common/peers.env")
Files
.readLines(file, StandardCharsets.UTF_8)
.asScala
.mkString("")
.split('=') match {
case Array(peersEnv, peersVal, _*) => (peersEnv, peersVal.split(',').map(_.trim))
case xs => throw new RuntimeException(s"Wrong $file content: ${xs.mkString(", ")}")
}
}
}
Loading

0 comments on commit 6d10175

Please sign in to comment.