Skip to content

Commit 1dc98cf

Browse files
committed
add some tests for Blockchain
1 parent 11b81de commit 1dc98cf

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

src/main/scala/com/fluency03/blockchain/core/Blockchain.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import com.fluency03.blockchain.core.Blockchain._
66
import org.json4s.native.JsonMethods.{compact, render}
77
import org.json4s.{Extraction, JValue}
88

9+
import scala.annotation.tailrec
10+
911
/**
1012
* Blockchain with difficulty and the chain of Blocks.
1113
* @param difficulty Difficulty of a Blockchain
@@ -45,6 +47,7 @@ object Blockchain {
4547

4648
def apply(difficulty: Int): Blockchain = new Blockchain(difficulty, Seq(Block.genesis(difficulty)))
4749

50+
@tailrec
4851
def isValidChain(chain: Seq[Block]): Boolean = chain match {
4952
case Nil => true
5053
case g +: Nil => g.previousHash == ZERO64 && g.index == 0 && g.hasValidHash

src/main/scala/com/fluency03/blockchain/core/Merkle.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package com.fluency03.blockchain
22
package core
33

4+
import scala.annotation.tailrec
5+
46
object Merkle {
57
def computeRoot(trans: Seq[Transaction]): String = computeRootOfHashes(trans.map(_.id))
68

9+
@tailrec
710
def computeRootOfHashes(hashes: Seq[String]): String = hashes.length match {
811
case 0 => ZERO64
912
case 1 => hashes.head

src/test/scala/com/fluency03/blockchain/core/BlockchainTest.scala

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.fluency03.blockchain
22
package core
33

4+
import com.fluency03.blockchain.core.Blockchain.isValidChain
45
import com.fluency03.blockchain.core.Transaction.createCoinbaseTx
56
import org.json4s.JsonDSL._
67
import org.json4s.JValue
@@ -64,10 +65,16 @@ class BlockchainTest extends FlatSpec with Matchers {
6465
blockchainAdded.lastBlock().get shouldEqual expected
6566
blockchainAdded.isValid shouldEqual true
6667
blockchainAdded.length shouldEqual 2
68+
69+
val blockchainAdded2 = blockchainToAdd.addBlock("This is next Block!", Seq(t1, t2))
70+
blockchainAdded2.lastBlock().get shouldEqual expected
71+
blockchainAdded2.isValid shouldEqual true
72+
blockchainAdded2.length shouldEqual 2
6773
}
6874

6975
"Blockchain" should "have be validatable." in {
7076
// TODO (Chang): isValidChain
77+
isValidChain(Nil) shouldEqual false
7178
}
7279

7380
}

0 commit comments

Comments
 (0)