Skip to content

Commit

Permalink
resolve conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
ncying committed Jul 13, 2020
2 parents 977a873 + 77e9f87 commit e7c0357
Show file tree
Hide file tree
Showing 33 changed files with 194 additions and 214 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ object TransactionsGeneratorApp extends App {
val generatorConfig = fromConfig(readConfig(args.headOption))
import generatorConfig._

AddressScheme.current.value = new AddressScheme {
AddressScheme.current = new AddressScheme {
override val chainId: Byte = generatorConfig.chainId.toByte
}

Expand Down
17 changes: 8 additions & 9 deletions src/it/scala/vsys/it/Docker.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import vsys.utils.ScorexLogging
import scala.collection.JavaConverters._
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.util.DynamicVariable

case class NodeInfo(
hostRestApiPort: Int,
Expand All @@ -38,15 +37,15 @@ class Docker(suiteConfig: Config = ConfigFactory.empty) extends AutoCloseable wi
.setRequestTimeout(5000))

private val client = DefaultDockerClient.fromEnv().build()
private val nodes = new DynamicVariable(Map.empty[String, Node])
private val seedAddress = new DynamicVariable(Option.empty[String])
private var nodes = Map.empty[String, Node]
private var seedAddress = Option.empty[String]
private val isStopped = new AtomicBoolean(false)

sys.addShutdownHook {
close()
}

private def knownPeers = seedAddress.value.fold("")(sa => s"-Dvsys.network.known-peers.0=$sa")
private def knownPeers = seedAddress.fold("")(sa => s"-Dvsys.network.known-peers.0=$sa")

private val networkName = "vsys-" + this.##.toLong.toHexString

Expand Down Expand Up @@ -96,10 +95,10 @@ class Docker(suiteConfig: Config = ConfigFactory.empty) extends AutoCloseable wi
containerInfo.networkSettings().networks().asScala(networkName).ipAddress(),
containerId)
val node = new Node(actualConfig, nodeInfo, http)
if (seedAddress.value.isEmpty) {
seedAddress.value = Some(s"${nodeInfo.networkIpAddress}:${nodeInfo.containerNetworkPort}")
if (seedAddress.isEmpty) {
seedAddress = Some(s"${nodeInfo.networkIpAddress}:${nodeInfo.containerNetworkPort}")
}
nodes.value += containerId -> node
nodes += containerId -> node
Await.result(node.lastBlock, Duration.Inf)
node
}
Expand All @@ -111,8 +110,8 @@ class Docker(suiteConfig: Config = ConfigFactory.empty) extends AutoCloseable wi
override def close(): Unit = {
if (isStopped.compareAndSet(false, true)) {
log.info("Stopping containers")
nodes.value.values.foreach(n => n.close())
nodes.value.keys.foreach(id => client.removeContainer(id, RemoveContainerParam.forceKill()))
nodes.values.foreach(n => n.close())
nodes.keys.foreach(id => client.removeContainer(id, RemoveContainerParam.forceKill()))
client.removeNetwork(vsysNetwork.id())
client.close()
http.close()
Expand Down
2 changes: 1 addition & 1 deletion src/it/scala/vsys/it/IntegrationTestsScheme.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package vsys.it
import vsys.account.AddressScheme

trait IntegrationTestsScheme {
AddressScheme.current.value = new AddressScheme {
AddressScheme.current = new AddressScheme {
override val chainId: Byte = 'I'
}
}
22 changes: 11 additions & 11 deletions src/main/scala/vsys/Application.scala
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import vsys.wallet.Wallet
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.reflect.runtime.universe._
import scala.util.{DynamicVariable, Try}
import scala.util.Try

class Application(val actorSystem: ActorSystem, val settings: VsysSettings) extends ScorexLogging {

Expand Down Expand Up @@ -136,7 +136,7 @@ class Application(val actorSystem: ActorSystem, val settings: VsysSettings) exte
if (settings.restAPISettings.enable) {
val combinedRoute: Route = CompositeHttpService(actorSystem, apiTypes, apiRoutes, settings.restAPISettings).compositeRoute
val httpFuture = Http().bindAndHandle(combinedRoute, settings.restAPISettings.bindAddress, settings.restAPISettings.port)
serverBinding.value = Some(Await.result(httpFuture, 10.seconds))
serverBinding = Await.result(httpFuture, 10.seconds)
log.info(s"REST API was bound on ${settings.restAPISettings.bindAddress}:${settings.restAPISettings.port}")
}

Expand All @@ -158,16 +158,16 @@ class Application(val actorSystem: ActorSystem, val settings: VsysSettings) exte
log.info("Genesis block has been added to the state")
}

val shutdownInProgress = new DynamicVariable(false)
val serverBinding: DynamicVariable[Option[ServerBinding]] = new DynamicVariable(None)
@volatile var shutdownInProgress = false
@volatile var serverBinding: ServerBinding = _

def shutdown(): Unit = {
if (!shutdownInProgress.value) {
if (!shutdownInProgress) {
log.info("Stopping network services")
shutdownInProgress.value = true
serverBinding.value.foreach(server =>
Try(Await.ready(server.unbind(), 60.seconds)).failed.map(e => log.error("Failed to unbind REST API port: " + e.getMessage))
)
shutdownInProgress = true
if (settings.restAPISettings.enable) {
Try(Await.ready(serverBinding.unbind(), 60.seconds)).failed.map(e => log.error("Failed to unbind REST API port: " + e.getMessage))
}
for (addr <- settings.networkSettings.declaredAddress if settings.networkSettings.uPnPSettings.enable) {
upnp.deletePort(addr.getPort)
}
Expand Down Expand Up @@ -243,8 +243,8 @@ object Application extends ScorexLogging {
RootActorSystem.start("vsys", config) { actorSystem =>
configureLogging(settings)

// Initialize global dynamic val with actual address scheme
AddressScheme.current.value = new AddressScheme {
// Initialize global var with actual address scheme
AddressScheme.current = new AddressScheme {
override val chainId: Byte = settings.blockchainSettings.addressSchemeCharacter.toByte
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/vsys/account/Address.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ object Address extends ScorexLogging {
val AddressLength = 1 + 1 + ChecksumLength + HashLength
val AddressStringLength = base58Length(AddressLength)

private lazy val scheme = AddressScheme.current.value
private def scheme = AddressScheme.current

private class AddressImpl(val bytes: ByteStr) extends Address with Serializable

Expand Down
4 changes: 1 addition & 3 deletions src/main/scala/vsys/account/AddressScheme.scala
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package vsys.account

import scala.util.DynamicVariable

abstract class AddressScheme {
val chainId: Byte
}

object AddressScheme {
val current: DynamicVariable[AddressScheme] = new DynamicVariable(DefaultAddressScheme)
@volatile var current: AddressScheme = DefaultAddressScheme
}

object DefaultAddressScheme extends AddressScheme {
Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/vsys/account/ContractAccount.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ object ContractAccount extends ScorexLogging {
val AddressStringLength = base58Length(AddressLength)
val systemContractId: ContractAccount = fromId(ByteStr(Array.emptyByteArray))

private lazy val scheme = AddressScheme.current.value
private def scheme = AddressScheme.current

private class ContractAddressImpl(val bytes: ByteStr) extends ContractAccount

Expand Down
7 changes: 3 additions & 4 deletions src/main/scala/vsys/actor/RootActorSystem.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ import vsys.utils.ScorexLogging

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.DynamicVariable

object RootActorSystem extends ScorexLogging {
private val failed = new DynamicVariable(false)
@volatile private var failed = false

final class EscalatingStrategy extends SupervisorStrategyConfigurator {
override def create(): SupervisorStrategy = AllForOneStrategy(loggingEnabled = false) {
case t: Throwable =>
failed.value = true
failed = true
log.error("Root actor got exception, escalate", t)
SupervisorStrategy.Escalate
}
Expand All @@ -31,7 +30,7 @@ object RootActorSystem extends ScorexLogging {
}

Await.result(system.whenTerminated, Duration.Inf)
if (failed.value) {
if (failed) {
sys.exit(1)
} else {
sys.exit(0)
Expand Down
18 changes: 9 additions & 9 deletions src/main/scala/vsys/blockchain/UtxPool.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import vsys.blockchain.transaction._
import vsys.utils.{ScorexLogging, Synchronized, Time}

import scala.concurrent.duration._
import scala.util.{DynamicVariable, Left, Right}
import scala.util.{Left, Right}

class UtxPool(time: Time,
stateReader: StateReader,
Expand Down Expand Up @@ -140,8 +140,8 @@ object UtxPool {
private class PessimisticPortfolios {
private type Portfolios = Map[Account, Portfolio]

private val transactionPortfolios = new DynamicVariable(Map.empty[ByteStr, Portfolios])
private val transactions = new DynamicVariable(Map.empty[Account, Set[ByteStr]])
private var transactionPortfolios = Map.empty[ByteStr, Portfolios]
private var transactions = Map.empty[Account, Set[ByteStr]]

def add(txId: ByteStr, txDiff: Diff): Unit = {
val nonEmptyPessimisticPortfolios = txDiff.portfolios
Expand All @@ -151,27 +151,27 @@ object UtxPool {
}

if (nonEmptyPessimisticPortfolios.nonEmpty) {
transactionPortfolios.value = transactionPortfolios.value + (txId -> nonEmptyPessimisticPortfolios)
transactionPortfolios += txId -> nonEmptyPessimisticPortfolios
nonEmptyPessimisticPortfolios.keys.foreach { address =>
transactions.value = transactions.value + (address -> (transactions.value.getOrElse(address, Set.empty) + txId))
transactions += address -> (transactions.getOrElse(address, Set.empty) + txId)
}
}
}

def getAggregated(accountAddr: Address): Portfolio = {
val portfolios = for {
txIds <- transactions.value.get(accountAddr).toSeq
txIds <- transactions.get(accountAddr).toSeq
txId <- txIds
txPortfolios <- transactionPortfolios.value.get(txId)
txPortfolios <- transactionPortfolios.get(txId)
txAccountPortfolio <- txPortfolios.get(accountAddr)
} yield txAccountPortfolio

Monoid.combineAll[Portfolio](portfolios)
}

def remove(txId: ByteStr): Unit = {
transactionPortfolios.value = transactionPortfolios.value - txId
transactions.value = transactions.value.map { case (k, v) => k -> (v - txId) }
transactionPortfolios -= txId
transactions = transactions.map { case (k, v) => k -> (v - txId) }
}
}

Expand Down
25 changes: 12 additions & 13 deletions src/main/scala/vsys/blockchain/block/Block.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import vsys.settings.GenesisSettings
import vsys.utils.crypto.EllipticCurveImpl
import vsys.utils.ScorexLogging

import scala.util.{DynamicVariable, Failure, Try}
import scala.util.{Failure, Try}

case class Block(timestamp: Long, version: Byte, reference: ByteStr, signerData: SignerData,
consensusData: SposConsensusBlockData, transactionData: Seq[ProcessedTransaction]) extends Signed {
Expand Down Expand Up @@ -117,37 +117,36 @@ object Block extends ScorexLogging {

val version = bytes.head

val positionVal = new DynamicVariable(1)
def position = positionVal.value
var position = 1

val timestamp = Longs.fromByteArray(bytes.slice(position, position + 8))
positionVal.value = position + 8
position += 8

val reference = ByteStr(bytes.slice(position, position + SignatureLength))
positionVal.value = position + SignatureLength
position += SignatureLength

val cBytesLength = Ints.fromByteArray(bytes.slice(position, position + 4))
positionVal.value = position + 4
position += 4
val cBytes = bytes.slice(position, position + cBytesLength)
val mintTimeBytes = cBytes.slice(0, Block.MintTimeLength)
val mintBalanceBytes = cBytes.slice(Block.MintTimeLength, Block.MintTimeLength + Block.MintBalanceLength)
val consData = SposConsensusBlockData(Longs.fromByteArray(mintTimeBytes), Longs.fromByteArray(mintBalanceBytes))
positionVal.value = position + cBytesLength
position += cBytesLength

val fBytesLength = Ints.fromByteArray(bytes.slice(position, position + 4))
positionVal.value = position + 4
positionVal.value = position + fBytesLength
position += 4
position += fBytesLength

positionVal.value = position + TransactionMerkleRootLength
position += TransactionMerkleRootLength

val tBytesLength = Ints.fromByteArray(bytes.slice(position, position + 4))
positionVal.value = position + 4
position += 4
val tBytes = bytes.slice(position, position + tBytesLength)
val txBlockField = transParseBytes(version.toInt, tBytes).get
positionVal.value = position + tBytesLength
position += tBytesLength

val genPK = bytes.slice(position, position + KeyLength)
positionVal.value = position + KeyLength
position += KeyLength

val signature = ByteStr(bytes.slice(position, position + SignatureLength))

Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/vsys/blockchain/consensus/SPoSCalc.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ object SPoSCalc extends ScorexLogging {
val MinimalEffectiveBalanceForContender: Long = 100000000000000L

// update plan: 4 -> 15 slots, 2 -> 30 slots, 1 -> 60 slots
val SlotGap = if (AddressScheme.current.value.chainId == 'M'.toByte) 4 else 1
val SlotGap = if (AddressScheme.current.chainId == 'M'.toByte) 4 else 1

// update plan: 15 slots -> 36 vsys coins, 30 slots -> 18 vsys coins, 60 slots -> 9 vsys coins
val BaseReward = 900000000L
Expand Down
2 changes: 1 addition & 1 deletion src/main/scala/vsys/blockchain/contract/DataEntry.scala
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ case class DataEntry(data: Array[Byte],

object DataEntry {

private lazy val scheme = AddressScheme.current.value
private def scheme = AddressScheme.current

val maxShortTextLength = 140
val maxShortBytesLength = 255
Expand Down
12 changes: 5 additions & 7 deletions src/main/scala/vsys/blockchain/state/StateStorage.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import vsys.blockchain.transaction.TransactionParser.TransactionType
import vsys.db.{Storage, SubStorage}
import vsys.db.StateMap

import scala.util.DynamicVariable

class StateStorage private(db: DB) extends Storage(db){

import StateStorage._
Expand Down Expand Up @@ -83,11 +81,11 @@ class StateStorage private(db: DB) extends Storage(db){
val dbEntries: StateMap[ByteStr, ByteStr] = new StateMap(db, "dbEntries", keyType=DataTypes.byteStr, valueType=DataTypes.byteStr)

override def removeEverything(batchOpt: Option[WriteBatch] = None): Unit = {
val batch = new DynamicVariable(batchOpt)
if (batchOpt.isEmpty) batch.value = createBatch()
new SubStorage(db, "states").removeEverything(batch.value)
setHeight(0, batch.value)
if (batchOpt.isEmpty) commit(batch.value)
var batch = batchOpt
if (batchOpt.isEmpty) batch = createBatch()
new SubStorage(db, "states").removeEverything(batch)
setHeight(0, batch)
if (batchOpt.isEmpty) commit(batch)
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import vsys.utils.crypto.hash.FastCryptographicHash._
import vsys.utils.crypto.hash.FastCryptographicHash
import vsys.blockchain.transaction.TransactionParser._

import scala.util.{DynamicVariable, Failure, Success, Try}
import scala.util.{Failure, Success, Try}

case class GenesisTransaction private(recipient: Address,
amount: Long,
Expand Down Expand Up @@ -84,20 +84,19 @@ object GenesisTransaction extends TransactionParser {
Try {
require(data.length >= BASE_LENGTH, "Data does not match base length")

val positionVal = new DynamicVariable(0)
def position = positionVal.value
var position = 0

val timestampBytes = java.util.Arrays.copyOfRange(data, position, position + TimestampLength)
val timestamp = Longs.fromByteArray(timestampBytes)
positionVal.value = position + TimestampLength
position += TimestampLength

val recipientBytes = java.util.Arrays.copyOfRange(data, position, position + RECIPIENT_LENGTH)
val recipient = Address.fromBytes(recipientBytes).right.get
positionVal.value = position + RECIPIENT_LENGTH
position += RECIPIENT_LENGTH

val amountBytes = java.util.Arrays.copyOfRange(data, position, position + AmountLength)
val amount = Longs.fromByteArray(amountBytes)
positionVal.value = position + AmountLength
position += AmountLength

val slotIdBytes = java.util.Arrays.copyOfRange(data, position, position + SlotIdLength)
val slotId = Ints.fromByteArray(slotIdBytes)
Expand Down
Loading

0 comments on commit e7c0357

Please sign in to comment.