Created
December 29, 2017 19:59
-
-
Save azamsharp/80eb67a4527dab1d2239648b85ac6fbf to your computer and use it in GitHub Desktop.
Blockchain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Blockchain : Codable { | |
var blocks :[Block] = [Block]() | |
init() { | |
} | |
init(_ genesisBlock :Block) { | |
self.addBlock(genesisBlock) | |
} | |
func addBlock(_ block :Block) { | |
if self.blocks.isEmpty { | |
// add the genesis block | |
// no previous has was found for the first block | |
block.previousHash = "0" | |
} else { | |
let previousBlock = getPreviousBlock() | |
block.previousHash = previousBlock.hash | |
block.index = self.blocks.count | |
} | |
block.hash = generateHash(for: block) | |
self.blocks.append(block) | |
block.message = "Block added to the Blockchain" | |
} | |
private func getPreviousBlock() -> Block { | |
return self.blocks[self.blocks.count - 1] | |
} | |
private func displayBlock(_ block :Block) { | |
print("------ Block \(block.index) ---------") | |
print("Date Created : \(block.dateCreated) ") | |
//print("Data : \(block.data) ") | |
print("Nonce : \(block.nonce) ") | |
print("Previous Hash : \(block.previousHash!) ") | |
print("Hash : \(block.hash!) ") | |
} | |
private func generateHash(for block: Block) -> String { | |
var hash = block.key.sha256()! | |
// setting the proof of work. | |
// In "00" is good to start since "0000" will take forever and Playground will eventually crash :) | |
while(!hash.hasPrefix(DIFFICULTY)) { | |
block.nonce += 1 | |
hash = block.key.sha256()! | |
print(hash) | |
} | |
return hash | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment