Skip to content

Instantly share code, notes, and snippets.

@harshvishu
Last active January 8, 2019 12:52
Show Gist options
  • Save harshvishu/9c1877f71982c95951bae33d0af1fdd1 to your computer and use it in GitHub Desktop.
Save harshvishu/9c1877f71982c95951bae33d0af1fdd1 to your computer and use it in GitHub Desktop.
Swift-Blockchain-New-Block
// MARK: - Initializers
init() {
chain = []
current_transactions = []
nodes = Set()
// Create the genesis block
self.newBlock(previous_hash: "1", proof: 100)
}
/**
# Creates a new block and adds it to the chain
- Parameter proof: <int> The proof given by the Proof of Work algorithm
- Parameter previous_hash: (Optional) <str> Hash of previous Block
- returns: _dict_ New Block
*/
func newBlock(previous_hash: String?, proof: Int64) -> Block {
let block = Block(index: Int64(self.chain.count + 1),
timestamp: Date(),
transactions: self.current_transactions,
proof: proof,
previous_hash: previous_hash ?? self.hash(block: self.last_block)
)
// Reset the current list of transactions
self.current_transactions = []
self.chain.append(block)
return block
}
/**
Returns the last Block in the chain
*/
var last_block: Block {
return self.chain[self.chain.count - 1]
}
/**
Creates a SHA-256 hash of a Block
- Parameter block: <dict> Block
- returns: String
*/
func hash(block: Block) -> String {
let encoder = JSONEncoder()
// We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
if #available(OSX 10.13, *) {
encoder.outputFormatting = .sortedKeys
}
let str = try! String(data: encoder.encode(block), encoding: .utf8)!
return str.sha256()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment