Skip to content

Instantly share code, notes, and snippets.

@matiasvillaverde
Created December 18, 2017 15:48
Show Gist options
  • Save matiasvillaverde/50d287656c1042238c9c632d73fcf38b to your computer and use it in GitHub Desktop.
Save matiasvillaverde/50d287656c1042238c9c632d73fcf38b to your computer and use it in GitHub Desktop.
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