update packages
add some docs
This commit is contained in:
@@ -11,6 +11,12 @@ import Foundation
|
||||
class Blockchain {
|
||||
var chain = [Block]()
|
||||
|
||||
/**
|
||||
Initialize the first block of the blockchain.
|
||||
|
||||
- Parameters:
|
||||
- data: The datas of the block
|
||||
*/
|
||||
func createGenesisBlock(data: String) {
|
||||
let genesisBlock = Block()
|
||||
genesisBlock.data = data
|
||||
@@ -20,19 +26,63 @@ class Blockchain {
|
||||
genesisBlock.timestamp = genesisBlock.generateTimestamp()
|
||||
genesisBlock.hash = genesisBlock.generateHash()
|
||||
chain.append(genesisBlock)
|
||||
print("Genesis block created -- hash: \(genesisBlock.hash ?? "")")
|
||||
print("Genesis block created -- hash: \(genesisBlock.hash)")
|
||||
}
|
||||
|
||||
/**
|
||||
Initialize a new block of the blockchain.
|
||||
|
||||
- Parameters:
|
||||
- data: The datas of the block
|
||||
*/
|
||||
func createBlock(data: String) {
|
||||
let newBlock = Block()
|
||||
newBlock.data = data
|
||||
newBlock.previousHash = chain[chain.count-1].hash
|
||||
newBlock.previousHash = chain.last!.hash
|
||||
newBlock.index = chain.count
|
||||
newBlock.nonce = 0
|
||||
newBlock.timestamp = newBlock.generateTimestamp()
|
||||
newBlock.hash = newBlock.generateHash()
|
||||
chain.append(newBlock)
|
||||
|
||||
print("Block \(newBlock.index ?? 0) created -- hash: \(newBlock.hash ?? "") previous hash: \(newBlock.previousHash ?? "") data: \(newBlock.data ?? "")")
|
||||
print("-- Block \(newBlock.index) created --\n hash: \(newBlock.hash)\n previous hash: \(newBlock.previousHash)\n data: \(newBlock.data)")
|
||||
}
|
||||
|
||||
/**
|
||||
Insert a corrupted block in the blockhain.
|
||||
(for testing purpose)
|
||||
*/
|
||||
func insertCorruptedBlock() {
|
||||
let newCorruptedBlock = Block()
|
||||
newCorruptedBlock.data = "Corrupted block"
|
||||
newCorruptedBlock.previousHash = "1234567890"
|
||||
newCorruptedBlock.index = chain.count
|
||||
newCorruptedBlock.nonce = 0
|
||||
newCorruptedBlock.timestamp = newCorruptedBlock.generateTimestamp()
|
||||
newCorruptedBlock.hash = newCorruptedBlock.generateHash()
|
||||
chain.append(newCorruptedBlock)
|
||||
|
||||
print("-- Corrupted block \(newCorruptedBlock.index) created --\n hash: \(newCorruptedBlock.hash)\n previous hash: \(newCorruptedBlock.previousHash)\n data: \(newCorruptedBlock.data)")
|
||||
}
|
||||
|
||||
/**
|
||||
Check validity of the blockchain.
|
||||
*/
|
||||
func chainValidity() {
|
||||
var isChainValid = true
|
||||
var corruptedBlock = Block()
|
||||
|
||||
for i in 1...chain.count-1 {
|
||||
if chain[i].previousHash != chain[i-1].hash {
|
||||
isChainValid = false
|
||||
corruptedBlock = chain[i]
|
||||
}
|
||||
}
|
||||
|
||||
print("Chain is valid : \(isChainValid)")
|
||||
|
||||
if !isChainValid {
|
||||
print("Corrupted block is : \(corruptedBlock.index)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user