Skip to content

Instantly share code, notes, and snippets.

@fernandoporazzi
Created January 18, 2019 13:34
Show Gist options
  • Save fernandoporazzi/94932a96999d22dd1d3ea2fd63fc223f to your computer and use it in GitHub Desktop.
Save fernandoporazzi/94932a96999d22dd1d3ea2fd63fc223f to your computer and use it in GitHub Desktop.
func (b *Block) GenerateHash() {
index := strconv.Itoa(b.Index)
nonce := strconv.Itoa(b.Nonce)
b.Hash = fmt.Sprintf("%x", sha256.Sum256([]byte(index+b.PreviousHash+b.Data+b.Timestamp.String()+nonce)))
}
func (b *Block) Mine() {
prefix := getPrefix(b.Difficulty)
for {
b.GenerateHash()
if strings.HasPrefix(b.Hash, prefix) {
break
} else {
b.Nonce = b.Nonce + 1
b.GenerateHash()
}
}
}
func getPrefix(length int) string {
letterBytes := "0"
b := make([]byte, length)
for i := range b {
b[i] = letterBytes[0]
}
return string(b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment