Add nonce & timestamp to block
This commit is contained in:
@@ -10,12 +10,27 @@ import Foundation
|
||||
import CryptoSwift
|
||||
|
||||
class Block {
|
||||
var hash: String!
|
||||
var data: String!
|
||||
var previousHash: String!
|
||||
var index: Int!
|
||||
var hash: String
|
||||
var data: String
|
||||
var previousHash: String
|
||||
var index: Int
|
||||
var nonce: Int
|
||||
var timestamp: Int
|
||||
|
||||
init(hash: String = "", data: String = "", previousHash: String = "", index: Int = 0, nonce: Int = 0, timestamp: Int = 0) {
|
||||
self.data = data
|
||||
self.previousHash = previousHash
|
||||
self.index = index
|
||||
self.nonce = nonce
|
||||
self.timestamp = timestamp
|
||||
self.hash = hash
|
||||
}
|
||||
|
||||
func generateHash() -> String {
|
||||
return data.sha256()
|
||||
}
|
||||
|
||||
func generateTimestamp() -> Int {
|
||||
return Int(Date().timeIntervalSince1970)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ class Blockchain {
|
||||
genesisBlock.data = data
|
||||
genesisBlock.previousHash = "0000"
|
||||
genesisBlock.index = 0
|
||||
genesisBlock.nonce = 0
|
||||
genesisBlock.timestamp = genesisBlock.generateTimestamp()
|
||||
genesisBlock.hash = genesisBlock.generateHash()
|
||||
chain.append(genesisBlock)
|
||||
print("Genesis block created -- hash: \(genesisBlock.hash ?? "")")
|
||||
@@ -26,6 +28,8 @@ class Blockchain {
|
||||
newBlock.data = data
|
||||
newBlock.previousHash = chain[chain.count-1].hash
|
||||
newBlock.index = chain.count
|
||||
newBlock.nonce = 0
|
||||
newBlock.timestamp = newBlock.generateTimestamp()
|
||||
newBlock.hash = newBlock.generateHash()
|
||||
chain.append(newBlock)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user