|
1 | 1 | package com.fluency03.blockchain
|
2 | 2 | package core
|
3 | 3 |
|
| 4 | +import java.security.KeyPair |
| 5 | + |
4 | 6 | import com.fluency03.blockchain.core.BlockHeader.hashOfBlockHeader
|
5 |
| -import com.fluency03.blockchain.core.Transaction.createCoinbaseTx |
| 7 | +import com.fluency03.blockchain.core.Transaction.{COINBASE_AMOUNT, createCoinbaseTx, signTxIn, updateUTxOs} |
6 | 8 | import org.json4s.JValue
|
7 | 9 | import org.json4s.JsonAST.{JArray, JInt, JObject, JString}
|
8 | 10 | import org.json4s.JsonDSL._
|
9 | 11 | import org.json4s.native.JsonMethods.parse
|
10 | 12 | import org.scalatest.{FlatSpec, Matchers}
|
11 | 13 |
|
| 14 | +import scala.collection.mutable |
12 | 15 | import scala.io.Source
|
13 | 16 |
|
14 | 17 | class BlockTest extends FlatSpec with Matchers {
|
@@ -145,5 +148,35 @@ class BlockTest extends FlatSpec with Matchers {
|
145 | 148 | parse(newBlock.toString) shouldEqual json
|
146 | 149 | }
|
147 | 150 |
|
| 151 | + "allTransAreValid" should "check whether all transactions of a Block are valid." in { |
| 152 | + val uTxOs: mutable.Map[Outpoint, TxOut] = mutable.Map.empty[Outpoint, TxOut] |
| 153 | + genesis.allTransAreValid(uTxOs) shouldEqual true |
| 154 | + |
| 155 | + val pair1 = Crypto.generateKeyPair() |
| 156 | + val address1 = pair1.getPublic.toHex |
| 157 | + |
| 158 | + val ts = getCurrentTimestamp |
| 159 | + val tx: Transaction = Transaction( |
| 160 | + Seq(TxIn(Outpoint(genesis.transactions.head.id, 0), "")), |
| 161 | + Seq(TxOut(address1, COINBASE_AMOUNT)), |
| 162 | + ts) |
| 163 | + |
| 164 | + val nextBlock = Block.mineNextBlock(genesis, "This is next Block!", ts, genesis.difficulty, Seq(tx)) |
| 165 | + nextBlock.allTransAreValid(uTxOs) shouldEqual false |
| 166 | + |
| 167 | + val uTxOs2 = updateUTxOs(genesis.transactions, uTxOs.toMap) |
| 168 | + uTxOs ++= uTxOs2 |
| 169 | + nextBlock.allTransAreValid(uTxOs) shouldEqual false |
| 170 | + |
| 171 | + val genesisPrivate: String = Source.fromResource("private-key").getLines.mkString |
| 172 | + val keyPair = new KeyPair(Crypto.recoverPublicKey(genesisMiner), Crypto.recoverPrivateKey(genesisPrivate)) |
| 173 | + val signedTxIns = tx.txIns.map(txIn => signTxIn(tx.id.hex2Bytes, txIn, keyPair, uTxOs)).filter(_.isDefined).map(_.get) |
| 174 | + signedTxIns.length shouldEqual tx.txIns.length |
| 175 | + val signedTx = Transaction(signedTxIns, Seq(TxOut(address1, COINBASE_AMOUNT)), ts) |
| 176 | + |
| 177 | + val validNewBlock = Block.mineNextBlock(genesis, "This is next Block!", ts, genesis.difficulty, |
| 178 | + Seq(signedTx, createCoinbaseTx(1, address1, ts))) |
| 179 | + validNewBlock.allTransAreValid(uTxOs) shouldEqual true |
| 180 | + } |
148 | 181 |
|
149 | 182 | }
|
0 commit comments