Created
January 18, 2019 13:34
-
-
Save fernandoporazzi/94932a96999d22dd1d3ea2fd63fc223f 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
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