Skip to content

Instantly share code, notes, and snippets.

@harshvishu
Created January 8, 2019 12:53
Show Gist options
  • Save harshvishu/29d417e93a1ef35860d1a54cc41959b0 to your computer and use it in GitHub Desktop.
Save harshvishu/29d417e93a1ef35860d1a54cc41959b0 to your computer and use it in GitHub Desktop.
Swift-Blockchain-Proof
/**
Simple Proof of Work Algorithm:
- Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p'
- p is the previous proof, and p' is the new proof
- Parameter: last_proof: Int64
- returns: Int64
*/
func proofOfWork(last_proof: Int64) -> Int64 {
var proof: Int64 = 0
while !self.validProof(last_proof: last_proof, proof: proof) {
proof += 1
}
return proof
}
/**
Validates the Proof: Does hash(last_proof, proof) contain 4 leading zeroes?
- Parameter last_proof: <int> Previous Proof
- Parameter proof: <int> Current Proof
- returns: True if correct, False if not.
*/
func validProof(last_proof: Int64, proof: Int64) -> Bool {
let guess = "\(last_proof)\(proof)"
let guess_hash = guess.sha256()
return guess_hash.suffix(4) == "0000"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment