Skip to content

Instantly share code, notes, and snippets.

@blogscot
Created December 1, 2018 16:17
Show Gist options
  • Save blogscot/38387faaf809de8354c0e3003bf3fec9 to your computer and use it in GitHub Desktop.
Save blogscot/38387faaf809de8354c0e3003bf3fec9 to your computer and use it in GitHub Desktop.
An basic Blockchain example in Kotlin
import com.google.gson.GsonBuilder
import java.security.MessageDigest
import java.util.Date
// This example is a port of the Java version described by:
// https://medium.com/programmers-blockchain/create-simple-blockchain-java-tutorial-from-scratch-6eeed3cb03fa
typealias BlockChain = ArrayList<Block>
fun applySha256(input: String): String {
try {
val digest = MessageDigest.getInstance("SHA-256")
val hash = digest.digest(input.toByteArray())
val hexString = StringBuffer()
for (item in hash) {
val hex = Integer.toHexString(0xff and item.toInt())
if (hex.length == 1) hexString.append('0')
hexString.append(hex)
}
return hexString.toString()
} catch (e: Exception) {
throw RuntimeException(e)
}
}
class Block(private val data: String, val previousHash: String) {
private val timeStamp = Date().time
var hash: String = calculateHash()
var nonce = 0
fun calculateHash() = applySha256("$previousHash$timeStamp$nonce$data")
fun mineBlock(difficulty: Int) {
val target = "0".repeat(difficulty)
while (hash.substring(0, difficulty) != target) {
nonce++
hash = calculateHash()
}
println("Block Mined!!! : $hash")
}
}
fun BlockChain.isChainValid(difficulty: Int): Boolean {
for (i in 1 until this.size) {
val currentBlock = this[i]
val previousBlock = this[i - 1]
if (currentBlock.hash != currentBlock.calculateHash() ||
currentBlock.hash.substring(0, difficulty) != "0".repeat(difficulty) ||
previousBlock.hash != currentBlock.previousHash
) {
return false
}
}
return true
}
fun main() {
val blockChain = BlockChain()
blockChain.add(Block("Hi I'm the first block", "0"))
blockChain[0].mineBlock(difficulty = 5)
blockChain.add(Block("Yo I'm the second block", blockChain.last().hash))
blockChain[1].mineBlock(difficulty = 5)
blockChain.add(Block("Yo I'm the third block", blockChain.last().hash))
blockChain[2].mineBlock(difficulty = 5)
val result = GsonBuilder().setPrettyPrinting().create().toJson(blockChain)
println(result)
println("Blockchain is valid: ${blockChain.isChainValid(difficulty = 5)}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment