BlockChain is a really hot topic in the IT world. Most of the developers have no idea how it works. There are general ideas in the heads, but it’s full of black-boxes. There are several blog posts and toy-projects online to demonstrate some basic idea about Blockchain. This will be one of these. I think the best way to learn a new thing is by trying it out, or in this case, by trying to implement something. And then argue why it would be a bad solution in some real-life situations. (If you are interested, at the end of this post there will be a list of links about the posts I read and I think are worth reading.)

Why is this blockchain thing that interesting? Because it tries to solve problems that we didn’t have before, or we didn’t even know we had. What if we stop trusting? How can we know what the truth is? How can we agree on something if we don’t trust each other? We have a lot of room to play with ideas. We can come up with new ideas of mathematical or logical problems. It’s challenging 🙂

I work with a JVM-based stack, mostly with Scala. In this post I will use Scala too. I like the actor model and reactive things, so I will use Akka where I can. (And in the project there are communications, consensus, work-balancing, and other interesting stuff so I use these where I can as well.) If you don’t understand how the blockchain works but you know the Scala syntax, this post will help you understand the basics, show some of the problems and some way to resolve each of them. If you are familiar with the blockchain basics, you can learn some Scala, or see how actors can work together.

The code is available on GitHub. For some of the core classes, I have tests too. However, because of the “toy” part of the project, and the “minimalist sample implementation,” most of the classes didn’t get tests. (I shrank some of my code-blocks, left out some formatters and actor props.)

Now, let’s jump in.

What is BlockChain?

You will never figure this out, but it is literally a chain of blocks. It depends on the actual implementation, but you can think of it like a linked list. Every block is linked to a previous block(s). What is a block? Some wrapped data. The block is where we store the information, and the whole chain is what makes this information valid. If I want to store something, I need to make a block, and append it to the chain. I know it’s really abstract, but we need to start somewhere.

In this post I will show a blockchain solution which similar to bitcoin. I will not persist the chain (but will talk about serialization), and I will not show how the transactions work, just show the pure “chain” and its building and validating mechanism. (Most posts start with the transactions a.k.a. the data in a block. I think that is why people can’t separate the blockchain and crypto currencies in their heads. You don’t need to know what a transaction is (yet)!)

Let’s code something:

case class SimpleBlock(data: JsObject, prevBlock: Option[SimpleBlock])

Done! Good job! There are two problems here. The first is that we didn’t solve any trust issue (which is the main problem we want to solve), and the second is that this cannot really leave our JVM (or if we try to move it, we need to move the whole chain).

Let’s make it more “movable”:

case class Block(index: Long, prevBlockHash: String, data: JsObject) {
  override def toString: String = this.toJson.toString
  def hash: String = HashHelpers.sha256Hash(this.toString)
case class BlockChain(blocks: List[Block])

A bit better. An index is generally a good idea. The toString can be the json representation of this object (debugging and future serialization/store reasons, the JsObject is used here as a more structural Any alternative). And a hash function, using all of the fields is a pretty good start for a “pointer.” I should talk about the hash a bit, or rather why it’s better than just using the index? If you give me three blocks (1, 0, a), (2, 1, b), (3, 2, c), and I want to change the data in the second block, I can easily do so with (2, 1, e). So I can modify any of the blocks without breaking the chain-links. If the pointer is the full content of the previous block, I need to modify all the blocks built on that. For the prev. example (1, {}, a), (2, { (1, {}, a)}, b), (3, {(2, { (1, {}, a)}, b)}, c) is your three blocks, and if I want to modify the second to (2, { (1, [], a)}, e) I need to modify the third too. If I want to change a little in one of the early blocks; I need to rewrite the whole chain. (It will not stop me because I’m not lazy, but we will solve that situation later.) Of course I don’t want to store every block in a new block, so I need to come up with an algorithm. An algorithm that guarantees that if I use it on the same input, it will generate the same output. And it will be “really hard” to find an another input which has the same output. (The really hard part is guaranteed by mathematicians.) More about hashes and cryptographic hash functions.

Our chain is not so good, I can add independent blocks to it. Solve this issue and add some more logic:

case class BlockChain(blocks: List[Block]) {
  def addBlock(newBlock: Block): (Boolean, BlockChain) = {
    if(isNewBlockValid(newBlock)) {
      (true, BlockChain(newBlock :: blocks))
    } else {
      (false, this)
  private def isNewBlockValid(newBlock: Block) = {
     blocks.head.index == newBlock.index -1 &&
       blocks.head.hash == newBlock.prevBlockHash &&

With this implementation, if you give me a new block, I can decide whether or not it can be appended to my chain. And because of the hash function (if we want to stay consistent (with the same chain)), I can’t modify any block in my chain; the hashes will not mach. I need to recreate all of the blocks after the modified one. If I do this, the next block you give me will not fit to my chain, or the next block I try to send to you will not fit to your chain. (So we won’t agree on a general truth.)

But if it’s not just two of us, we need to consider two other things; concurrency, and communication failures. If there are three people, you, me and Alice, the network can ruin our chain state. What if Alice sends us a new block, but you never get it. And then I try to build a new block on top of Alice’s block and send it to you? You will not accept it, because you’ll see a missing block. But if you let me send both blocks (the missing one and mine), I can modify the block from Alice. And you can’t tell whether Alice or I’m messing with you later. (You can’t tell which blocks contain truth and which blocks are modified.) We need to solve this situation, and the method developed first is: try to restrict the block creation somehow.

Proof of Work

There are many algorithms to solve the block creation problem. I will show the bitcoin method, which is based on the ‘proof of work.’ The idea behind this is simple: every participant will try to solve a mathematical problem. Whoever solves it first broadcasts the new block (and the result in it), and the others can check whether the result was right. If the block is accepted, a new round starts. The winner block is appended to the others’ chain every time. If you want to come up with a new block, you need to solve the problem. If you want to modify a block, you need to solve that block’s problem, and all of the modified blocks’ problems too. Which means that if you want to modify a block, you need to solve problems faster than the others altogether. The given work (problem solving) verifies that the longest chain is the valid one. (Take a break here, and if you need to, read this section again.)

We have an interesting challenge with this idea! We need to create a “hard” problem with fast result-validation. And if we want some scaling in users but want to restrict the block creation intensity (for example one block every one minute), we need to make this problem scalable. (The more people join our chain, the harder the problem we need to create for them. Hence the bigger (sum) computing capacity we’ll need to solve the problem in (roughly) the same timeframe the lower computing capacity solved the easier problem before.)

One very good idea is: we can modify something in our new block freely and give some restrictions about the hash generated. For example, the hash could be a String, def isValid = newBlock.hash.startsWith(“a”). You might be surprised, but bitcoin builds on the exact same idea. They extended this to a better scale. They tried to create a function with two input parameters, where one parameter is some kind of difficulty, and the other is a hash, and the output is the answer to the ultimate question: “isValid?”. One interesting part is that the difficulty needs to scale linearly. So if I want a block in 10 minutes, and new nodes come up, and the block generation speed drops to ~9 minutes, I can multiply my difficulty by 1.1 and the block generation time will go back to ~10 minutes. (When I talk about block generation time I mean the average time of the last N successfully created blocks.)

Take a look at a working concept:

case class Block(index: Long, prevBlockHash: String, data: JsObject, difficulty: Double, timeStamp: Long, nonce: String = "1") {
  override def toString: String = this.toJson.toString
  def hash: String = HashHelpers.sha256Hash(this.toString)
object Block {
  val genesis = Block(0, "", JsObject(), 1, 0)
  def mine(block: Block): Block = {
    val b = block.copy(nonce = (BigInt(block.nonce, 16) + BigInteger.ONE).toString(16))
    if(DifficultyHelper.checkHash(b.hash, b.difficulty)) {
    } else {

We need a difficulty to carry on, and a nonce. The nonce is the part of the block that we can freely modify. The “mine” function will do exactly this. (When we reach the transaction part, I will explain the name of the function. But now you can think of it like creating a new block from nowhere.) Modify the nonce of the given block, and if it’s valid; return it, if not; call it recursively.

I added a time-stamp too. If we want to adjust the difficulty, we will need that.

The DifficultyHelper is a piece of art mathematical formula. If you want to understand how it works, I advise you to read this. (The difficulty adjust uses down rounding for a more consistent double value across nodes.)

object DifficultyHelper {
  val tMax = BigDecimal(BigInt("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16))
  def checkHash(hash: String, difficulty: Double): Boolean = {
    val t = (tMax / difficulty).toBigInt
    val h = BigInt(hash, 16)
    h < t
  def adjustDifficulty(currentDiff: Double, elapsedTime: Long, expectedTime: Long): Double = {
    BigDecimal(expectedTime.toDouble / elapsedTime.toDouble * currentDiff).setScale(2, RoundingMode.DOWN).toDouble

So far It is just some basic mathematical concept. We have about 50 lines of code. We have blocks, and we can add them one-by-one to the chain. The fun part begins when we start to communicate with others!

Distributed blocks

As I said before, the whole blockchain thingy is trying to solve some kind of a distributed data storage problem with trust issues. It’s like a big, slow, distributed database. One big difference between here and a “simple” distributed database is that there, the participants don’t trust each other. What we are talking about here is not a 10-node-cluster created by one sysadmin (from the same source). It’s an N-node-cluster, where everybody can have a node (or at least bitcoin was build with this idea, there are some newer concepts, too). And If everybody can have a node, somebody will try to attack the network (or try to create a “tricky” node). So instead of restricting who can host a node, we restrict the chances of the system being attacked.

Okay, so we want to share our data with others. We want to get data from others. We want to communicate.

Our node has two fairly separated states. When we start a node, we want to synchronize the blocks from the other nodes to get the “latest general truth”, and when we have synchronized, we want to create a new block with our “truth” (faster than the others). When we find a valid block, we want to tell the others. So that the others can validate it and broadcast to even further nodes. If someone sends us a block, we can validate it, append to our chain and broadcast to some others. What happens if we get a block not valid? We drop it. What happens if the given block has a higher id then our next id should be? We missed some blocks. We went out of sync, so we need to synchronize again. Sounds easy! Do some implementation! Start with the supporting object and the classes inside it.

object SyncActor {
  sealed trait SyncMessage
  case class SyncDown(lastLocalBlockIndex: Long) extends SyncMessage
  case class SyncRequest(idx: Long) extends SyncMessage
  case class SyncResponse(blocks: Seq[Block]) extends SyncMessage
  case class NewBlockCreated(block: Block) extends SyncMessage
  sealed trait State
  case object Syncing extends State
  case object Ready extends State
  sealed trait Data{
    def actualChain: BlockChain
  case class StableData(chain: BlockChain) extends Data {
    override def actualChain: BlockChain = chain
  case class SyncData(oldChain: BlockChain, inprogressChain: BlockChain) extends Data {
    override def actualChain: BlockChain = inprogressChain

The messages are mostly clear. If this actor sends a SyncRequest (with the last id it has) to an other actor, that actor will respond with a SyncResponse in a list of blocks. When a new block is created, we broadcast NewBlockCreated with the new block. The only strange thing is the SyncDown, which is an inner communication message, signaling that this actor needs to be synced.

The states are separated to syncing or ready.

The data should be clear too, when we are in a stable state, we have one chain. When we are syncing, we need to remember the original chain (in case we are under attack and need to restore). And, we need to manage the operations on the new (inProgress) chain. The actualChain function will help us determinate the needed lastLocalBlockIndex to the SyncDown message.

Here, I assume a minor refactor in our BlockChain class. First, I cut it to a trait and an in-memory implementation. Second, I implemented a new function which can add a list of blocks to an existing chain.

trait BlockChain {
  def newerThen(idx: Long): Seq[Block]
  def latest: Block
  def size: Int
  def isEmpty: Boolean
  def nextEmptyBlock: Block
  def addBlock(newBlock: Block): (Boolean, BlockChain)
  def addBlocks(newBlocks: Seq[Block]): (Boolean, BlockChain)

(Okay, I could use some of the tricks from this blogpost, but now it is fine enough for demonstration. Later I can easily change my in-memory instance to a file-stored variation.)

case class InMemoryBlockChain(protected val blocks: List[Block])(implicit protected val difficultyConf: DifficultyConf, protected val now: () => Long) extends BlockChain {
  def newerThen(idx: Long): Seq[Block] = blocks.filter(_.index > idx)
  def latest: Block = blocks.head
  def size: Int = blocks.size
  def isEmpty: Boolean = blocks.isEmpty
  def nextEmptyBlock: Block = Block(latest.index + 1, latest.hash, JsObject(), calcNextDiff, now())
  def addBlock(newBlock: Block): (Boolean, InMemoryBlockChain) = {
    if (isNewBlockValid(newBlock)) {
      (true, InMemoryBlockChain(newBlock :: blocks))
    } else {
      (false, this)
  def addBlocks(newBlocks: Seq[Block]): (Boolean, InMemoryBlockChain) = {
    def rec(sortedBlocks: Seq[Block], bc: InMemoryBlockChain): (Boolean, InMemoryBlockChain) = {
      sortedBlocks match {
        case Nil => (true, bc)
        case head :: tail =>
          val (isValid, chain) = bc.addBlock(head)
          if (isValid) rec(tail, chain)
          else (false, InMemoryBlockChain(Nil))
    val sortedNewBlocks = newBlocks.sortBy(_.index).reverse
    val missingNewBlocks = sortedNewBlocks.takeWhile(nb => blocks.exists(ob => ob.hash != nb.hash)).reverse
    if (!blocks.exists(ob => ob.hash == missingNewBlocks.head.prevBlockHash)) {
      val shortened = blocks.drop(15)
      val ret = if (shortened != Nil) shortened else blocks.last :: Nil
      (false, InMemoryBlockChain(ret))
    } else {
      rec(missingNewBlocks, InMemoryBlockChain(blocks.dropWhile(b => b.hash != missingNewBlocks.head.prevBlockHash)))
  private def isNewBlockValid(newBlock: Block) = {
    blocks.head.index == newBlock.index - 1 &&
      blocks.head.hash == newBlock.prevBlockHash &&
      blocks.head.timeStamp <= newBlock.timeStamp &&
      calcNextDiff == newBlock.difficulty &&
      DifficultyHelper.checkHash(newBlock.hash, newBlock.difficulty)
  private def calcNextDiff = {
    if (blocks.size >= difficultyConf.blockPeriod && blocks.size % difficultyConf.blockPeriod == 1) {
      val sample = blocks.take(difficultyConf.blockPeriod)
      val timeElapsed = sample.head.timeStamp - sample.last.timeStamp
      val expectedTime = difficultyConf.expectedTime * difficultyConf.blockPeriod
      DifficultyHelper.adjustDifficulty(latest.difficulty, timeElapsed, expectedTime)
    } else {
object InMemoryBlockChain {
  case class DifficultyConf(blockPeriod: Int, expectedTime: Long)
  object DifficultyConf {
    def apply(blockPeriod: Int, expectedTime: FiniteDuration): DifficultyConf = new DifficultyConf(blockPeriod, expectedTime.toMillis)

I modified the constructor a bit with some implicit parameters, for easier instance creation (and testing). I encapsulated the config parameters of the difficulty to a new value holder class. Most of the interface implementation is really straightforward. The new things came with calculateNextDiff (which will modify the difficulty of the next empty block, and help check the block validation), the isNewBlockValid (which now uses the difficulty in the validation process) and the addBlocks. The add blocks function is not as clear at first. We need to sort the new blocks. If some of the new blocks can be added to the old chain, we add them one by one (and validate them while adding, this is the recursive function). When we have no intersection in the given blocks and our original ones, we drop some blocks from the start of the list, and return a smaller list. (So the caller will sync again maybe with more luck.) The return params are a bit messy too. If we return with true, that means the second param is valid and gets enhanced with the newly given blocks. If we return a false, we tell the caller that this operation has failed, and that the caller can try again: something else with the given second parameter. If the second parameter is empty that means that someone tried to attack us, and its genesis block is not matching to our genesis block, or its given blocks are not valid. (This part could use a refactor, if you have any modification idea pls comment or PR in the repo.)

Going back to our SyncActor:

class SyncActor(data: JsObject, startupChain: BlockChain, communicator: ActorRef) extends FSM[State, Data] {
  startWith(Syncing, SyncData(startupChain, startupChain))
  when(Syncing) {
    case Event(SyncDown(idx), d: SyncData) =>
      stay using d
    case Event(NewBlockCreated(newBlock), d: SyncData) =>
      self.tell(NewBlockCreated(newBlock), sender)
      goto(Ready) using StableData(d.oldChain)
    case Event(SyncRequest(idx), d: SyncData) =>
      self.tell(SyncRequest(idx), sender)
      goto(Ready) using StableData(d.oldChain)
    case Event(SyncResponse(newBlocks), d: SyncData) if newBlocks.isEmpty =>
      goto(Ready) using StableData(d.oldChain)
    case Event(SyncResponse(newBlocks), d: SyncData) if newBlocks.nonEmpty =>
      val (ok, newChain) = d.inprogressChain.addBlocks(newBlocks)"sync in progress, get ${newBlocks.size} new block, $ok, ${newChain.size}")
      if (ok) {
        if (newChain.size > d.oldChain.size) {
          goto(Ready) using StableData(newChain)
        } else {
          goto(Ready) using StableData(d.oldChain)
      } else if (!newChain.isEmpty) {
        sender ! SyncRequest(newChain.latest.index)
        stay using SyncData(d.oldChain, newChain)
      } else {
        goto(Ready) using StableData(d.oldChain) //somebody just messing with us

Our actor is a finite state machine (FSM in akka). It starts with a syncing state, with the data we get from the actor creator.

When someone wants us to sync down, we send a sync request to a random node and keep our state. If we get a NewBlockCreated message, we redirect that message to ourselves (with the “tell” operator we keep the original sender), and try to handle that again in the Ready state. We do the same when we get a SyncRequest. (These two handlers are needed for a low number of node setups, so some nodes can leave the Syncing state.) When we get a SyncResponse with no data, we know that our state is the last state in the network so we can move to the Ready state. If we get a nonempty response, we try to add the new blocks to our chain. If we don’t need to retry the sync, we go to the Ready state with the original or the newly constructed chain (based on which is the longest). When we can’t apply the given blocks to the old chain, our returning “newChain” will be shorter, so we can sync down from a smaller index (and then we will get a longer response next time). If somehow our newly given blocks aren’t valid, the “newChain” will be empty and we can leave our Sync state.

when(Ready) {
  case Event(SyncDown(idx), StableData(chain)) =>
    goto(Syncing) using SyncData(chain, chain)
  case Event(SyncRequest(idx), StableData(chain)) =>
    sender ! SyncResponse(chain.newerThen(idx))
    stay using StableData(chain)
  case Event(NewBlockCreated(newBlock), StableData(chain)) =>
    val (isValid, newChain) = chain.addBlock(newBlock)
    if (isValid) {
      stay using StableData(newChain)
    } else {
      if (newBlock.index > chain.latest.index) {
        sender ! SyncRequest(chain.latest.index - 1)
        goto(Syncing) using SyncData(chain, chain)
      } else {
        //its just wrong...
        stay using StableData(chain)

When we are in the ready state three things can happen.

  1. We need to sync, so we go to the syncing state.
  2. We get a SyncRequest, so we respond with the requested blocks.
  3. We get a new block, so we check it. If it’s valid, we broadcast it. If it’s not valid, but it has a larger index than our last block, we try to sync. Otherwise the given block is just “bad,” so we do nothing.

(Ofc if sb found a new block, we need to mine that! See below.)

whenUnhandled {
  case Event(Tick, s: Data) =>
    self ! SyncDown(s.actualChain.latest.index)
  case Event(e, s) =>
    log.warning("received unhandled request {} in state {}", e, stateName)

We will have some kind of timer, so we do a general sync time-to-time. We log the unhandled messages, just in case.

onTransition {
  case Syncing -> Ready =>
    nextStateData match {
      case StableData(stableChain) =>"last block is: ${stableChain.latest}")
      case _ => log.error(s"inconsistent state change, $nextStateData")
  case Ready -> Syncing =>"sync started")

One really cool feature in the FSM actors is the onTransition handler. When we leave the Sync state, we start mining (and log the last block). When we start Syncing, we just simply log this.

private def sendToRandomNode[T](msg: T) = {
  communicator ! SendToRandomNode(msg)
private def sendToRandomNodes[T](msg: T) = {
  communicator ! SendToRandomNodes(msg)
private def startMining(chain: BlockChain) = {
  val miner = context.actorOf(MinerActor.props())
  miner ! MinerActor.Mine(data, chain.nextEmptyBlock)
private def stopMining() = {
  context.children.foreach(_ ! PoisonPill)

Our private functions are mostly just call/message delegations. (Before we start mining with a new actor, we kill all of the previously created actors.) (If you are a good observer, you can already see some flaws in our logic. For example if we just change states to Sync and then back to Ready, we will start mining from the beginning again. But these “bugs” are not as harmful in an experimental piece of code. We will need to delegate some tasks from this actor to others on the long run anyway, so I will live with that now and resolve them later.)

Now we can synchronize. Or at least we will if we write our last (four) components.

I told you something about an external **timer **which will force the actor to Sync state from time to time.

class TickerActor(needToTick: ActorRef, interval: FiniteDuration) extends Actor with Timers with ActorLogging{
  override def receive: Receive = {
    case Tick => needToTick ! Tick
    case ResumeTick => timers.startPeriodicTimer("tick", Tick, interval)
    case PauseTick => timers.cancel("tick")
    case msg => log.warning(s"Ticker recieved a msg $msg")
  override def preStart(): Unit = {
    timers.startPeriodicTimer("tick", Tick, interval)
object TickerActor {
  case object Tick
  case object ResumeTick
  case object PauseTick

Akka has a Timers trait, really handy in these cases.

We need a **miner **too:

class MinerActor extends Actor with ActorLogging{
  val start = System.currentTimeMillis()
  var lastLog = start
  override def receive: Receive = {
    case Mine(data, block, cycle) =>
      val b = block.copy(data = data, nonce = (BigInt(block.nonce, 16) + BigInteger.ONE).toString(16))
      if(DifficultyHelper.checkHash(b.hash, b.difficulty)) {"new block found! $b")
        context.parent ! NewBlockCreated(b)
      } else {
        self ! Mine(data, b, cycle + 1)
      logHashRate(cycle, block.index, block.difficulty)
  def logHashRate(cycle: Int, index: Long, diff: Double) = {
    val now = System.currentTimeMillis()
    val elasped = now - lastLog
    if(elasped>5000) {
      val hashRate = cycle/((now - start)/1000.0)/1000.0"spd: $hashRate kH/s | idx: $index | diff: $diff")
      lastLog = now
object MinerActor {
  case class Mine(data: JsObject, blockBefore: Block, cycle: Int = 0)

This is exactly the same functionality as the previously shown miner function. It has some logging in it, and the recursion handled with actor messages.

These two were logical. But the **communication **actor will be strange…

First of all, I used akka clusters. Akka clusters are for trusted ~100 node problems. So this implementation happened because it’s one of the fastest implementations I could come up with, and is not a non-trusted environment. But it is just an actor. We let the code be flexible enough to change the communication component to REST or have a p2p implementation later.

Secondly, I used FSM to solve the egg vs chicken problem (the sync actor needs a communication actor, but the communication actor needs a target too). (TBH it’s an interesting and non-trivial problem to solve in akka, still I tried to find the best way to solve this.)

class CommunicationActor[E](rnd: Random, path: String, emptyMessage: E) extends FSM[State, ActorRef] {
  val cluster = Cluster(context.system)
  startWith(Uninitialized, null)
  when(Uninitialized) {
    case Event(SendToRandomNode(msg), _) =>
      goto(Initialized) using sender
    case _ =>
      //drop other cluster msges
  when(Initialized) {
    case Event(SendToRandomNode(msg), _) =>
    case Event(SendToRandomNodes(msg), _) =>
    case Event(msg, ref) =>
      ref.tell(msg, sender)

When we get our first SendToRandomNode message, we get initialized with the sender. And we just deliver messages.

def sendToRandomNodes[T](msg: T) = {
  val members = upMembers
  if(members.nonEmpty) {
    rnd.shuffle(members).take((members.size / 5) + 1).foreach { randomMember =>
      val destinationAddr = randomMember.address + (if (path.startsWith("/")) path else "/" + path)
      context.actorSelection(ActorPath.fromString(destinationAddr)) ! msg
def sendToRandomNode[T](msg: T) = {
  val members = upMembers
  if(members.nonEmpty) {
    val randomMember = members.toVector(rnd.nextInt(members.size))
    val destinationAddr = randomMember.address + (if (path.startsWith("/")) path else "/" + path)
    context.actorSelection(ActorPath.fromString(destinationAddr)) ! msg
  } else {
    sender ! emptyMessage
def upMembers = cluster.state.members.filter(_.status == MemberStatus.Up).filter(_.uniqueAddress != cluster.selfUniqueAddress)

We will send random messages to Up nodes (and only to others, so we filter out ourselves).

At this point, we don’t need any direct block serialization. All of the block movements are handled by akka. But if we want to make this chain implementation usable for others, we will need to change this layer to some p2p and rest based layer. (And for example json serialization will help us describe blocks outside of the JVM.)

What do we have?

We have some implementation! But we can’t try it out yet :( We need to write one last component; the main function(/class/object/whatever) (and an appconf)!

object Main extends App {
  val port = if(args.length > 0) args(0).toInt else 4500
  val msg = JsObject("port" -> JsString(port.toString))
  implicit val now: () => Long = System.currentTimeMillis
  implicit val diffConf = DifficultyConf(20, 30 seconds)
  val emptyChain = InMemoryBlockChain(Block.genesis :: Nil)
  val config = ConfigFactory.parseString(s"akka.remote.netty.tcp.port=$port").
  val actorSystem = ActorSystem("ClusterSystem", config)
  val communicationActor = actorSystem.actorOf(CommunicationActor.props(new Random(),s"user/comm",SyncResponse(Seq())), "comm")
  val syncActor = actorSystem.actorOf(SyncActor.props(msg, emptyChain, communicationActor))
  val tickerActor = actorSystem.actorOf(TickerActor.props(syncActor, 30 seconds))
  syncActor ! Tick

Now we can start our first node with ‘sbt “run 4500″‘ and a second node with ‘sbt “run 4501″‘ and we can scale our node number up. If we stop and start instances we will see that they synchronize up quickly and start the race for the new block.

A list of our features and a quick recap:

A list of missing features and flaws:

Closing thoughts

What I learned from this (and hopefully you too)?

First of all I think this is far less of a rocket science than most of the IT world thinks. There are some really good ideas in it, the whole concept is really interesting (and more humanistic with the non trusting part), and if we learn the basics, we get a new perspective.

While I played with it, I learned some akka features, like FSM, and Clusters. I want to play more with the actor hierarchy and clusters too. So in the next part I will definitely try to implement a mining pool.

We barely touched the blocks. In the next episode I will implement transactions and block validation with transactions. I will write a digital wallet, and try to make a clearer picture as to why this non trusting thing is important in the banking and financial era.

While I implemented this, I read a bunch of blogposts, wiki pages, and other sources. I think implementing a problem will give way to more interesting questions than just reading about it. So if you are interested in this technology, I think you need to start implement some silly “will never work” solution to face the same problems the “big players” had. (Maybe writing a virtual machine for smart contract execution is a bit of an overkill for a petproject :) ) I really want to try some Byzantine algo and some DAG implementation too in the future.


Wanari is an 18-year-old custom software development company located at the heart of Budapest, Hungary. As you can see we keep up with the times and are pretty tech-savvy 😀 To learn more about us, check out our website. For more content like this, follow us on social media just like Fb or LinkedIn.

member photo

His precision is only coupled by his attention to detail. (Really.) He is passionate about becoming more and more effective in software development and loves experimenting with new technologies.

Latest post by Gergő Törcsvári

Learning by Doing – BlockChain & Akka Tutorial