sss.openstar.nodebuilder.WalletBuilder.scala Maven / Gradle / Ivy
package sss.openstar.nodebuilder
import akka.actor.ActorRef
import sss.openstar.account.NodeIdentity
import sss.openstar.chains.Chains.GlobalChainIdBuilder
import sss.openstar.common.builders.{IOExecutionContextBuilder, RequireNodeIdentity}
import sss.openstar.db.Builder.RequireDb
import sss.openstar.ledger.LedgerId
import sss.openstar.wallet._
import sss.openstar.{Currency, UniqueNodeIdentifier}
import java.util.concurrent.atomic.AtomicReference
import scala.reflect.runtime.universe._
/**
* Created by alan on 6/30/16.
*/
trait WalletBuilder {
self: RequireNodeIdentity with
IdentityServiceBuilder with
BlockChainBuilder with
RequireDb with
RequireMessageEventBus with
AmountBuilderBuilder with
SendTxBuilder =>
private def buildWalletPersistence(nodeId: UniqueNodeIdentifier): WalletPersistence =
new WalletPersistence(nodeId, db)
private def buildClientWallet(nodeId: UniqueNodeIdentifier, ledgerId: LedgerId): ClientWallet =
new ClientWallet(s"${nodeId}_${ledgerId.id}")
type AtomicWalletCacheMap[C <: Currency] = AtomicReference[Map[UniqueNodeIdentifier, Wallet[C]]]
def createAtomicWalletCacheMap[C <: Currency]: AtomicWalletCacheMap[C] = new AtomicReference[Map[UniqueNodeIdentifier, Wallet[C]]](Map.empty)
def buildWallet[C <: Currency: TypeTag](nodeId: UniqueNodeIdentifier, ledgerId: LedgerId)(implicit walletCache: AtomicWalletCacheMap[C]): Wallet[C] = {
lazy val newWallet = new Wallet[C](nodeId,
ledgerId,
new PublicKeyTracker(nodeId).isTracked,
identityService,
buildWalletPersistence(nodeId),
buildClientWallet(nodeId, ledgerId),
() => currentBlockHeight()
)
walletCache.updateAndGet(oldMap =>
oldMap.get(nodeId) match {
case None => oldMap + (nodeId -> newWallet)
case Some(_) => oldMap
})(nodeId)
}
def buildUnlockedWallet[C <: Currency: TypeTag](
nodeIdentity: NodeIdentity,
ledgerId: LedgerId)(implicit walletCache: AtomicWalletCacheMap[C])
: UnlockedWallet[C] =
buildWallet[C](nodeIdentity.id, ledgerId).unlockWallet(nodeIdentity)
def buildHostNodeUnlockedWallet[C <: Currency: TypeTag](ledgerId: LedgerId)(implicit walletCache: AtomicWalletCacheMap[C]): UnlockedWallet[C] =
buildUnlockedWallet[C](nodeIdentity, ledgerId)
}
trait UtxoTrackerBuilder {
self: RequireActorContext
with WalletBuilder
with RequireMessageEventBus
with IOExecutionContextBuilder
with GlobalChainIdBuilder =>
def startUtxoTracker[C <: Currency: TypeTag](hostNode: UniqueNodeIdentifier, ledgerId: LedgerId)(implicit walletCacheMap: AtomicWalletCacheMap[C]): ActorRef = {
UtxoTracker[C](Seq(buildWallet[C](hostNode, ledgerId)),ledgerId)
}
}