Created
December 18, 2017 15:48
-
-
Save matiasvillaverde/50d287656c1042238c9c632d73fcf38b to your computer and use it in GitHub Desktop.
This file contains 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
import Foundation | |
struct Block { | |
init(timestamp: Date, data: String, previousBlockHash: Int) { | |
self.timestamp = timestamp | |
self.data = data | |
self.previousBlockHash = previousBlockHash | |
// Simpified version, blockchain uses a proof of work. | |
let basicHash = String(previousBlockHash) + data + String(timestamp.timeIntervalSince1970) | |
hash = basicHash.hashValue | |
} | |
let timestamp: Date // to know when this block was created | |
let data: String // Important data that we want to record | |
let previousBlockHash: Int // Linked to the previous block | |
let hash: Int // Hash of the current block | |
// Hardcoded the cration of the first block. | |
static func NewGenesisBlock() -> Block { | |
return Block(timestamp: Date(), data: "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks", previousBlockHash: 0) | |
} | |
} | |
struct Blockchain { | |
// Add the first block called genesis | |
init(genesis: Block) { | |
blocks = [Block]() | |
blocks.append(genesis) | |
} | |
// Back-linked, ordered list of blocks | |
var blocks: [Block] | |
// Add a new record | |
mutating func addBlock(_ data: String) { | |
guard let lastBlock = blocks.last else { fatalError("Failed to find genesis block.") } | |
let newBlock = Block(timestamp: Date(), data: data, previousBlockHash: lastBlock.hash) | |
blocks.append(newBlock) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment