Created
April 8, 2018 16:55
-
-
Save azamsharp/9776870ae548dc933938f4030f8e6721 to your computer and use it in GitHub Desktop.
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(genesisBlock :Block) { | |
addBlock(genesisBlock) | |
} | |
func addBlock(_ block :Block) { | |
if self.blocks.isEmpty { | |
block.previousHash = "0000000000000000" | |
block.hash = generateHash(for :block) | |
} | |
self.blocks.append(block) | |
} | |
func getNextBlock(transactions :[Transaction]) -> Block { | |
let block = Block() | |
transactions.forEach { transaction in | |
block.addTransaction(transaction: transaction) | |
} | |
let previousBlock = getPreviousBlock() | |
block.index = self.blocks.count | |
block.previousHash = previousBlock.hash | |
block.hash = generateHash(for: block) | |
return block | |
} | |
private func getPreviousBlock() -> Block { | |
return self.blocks[self.blocks.count - 1] | |
} | |
func generateHash(for block :Block) -> String { | |
var hash = block.key.sha1Hash() | |
while(!hash.hasPrefix("00")) { | |
block.nonce += 1 | |
hash = block.key.sha1Hash() | |
print(hash) | |
} | |
return hash | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment