You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
1.7 KiB

10 months ago
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
trialset := []int{}
numtrials := 100
for i := 0; i < numtrials; i++ {
trialset = append(trialset, hashTrial())
}
fmt.Println("Mean Trials: " + fmt.Sprint(mean(trialset)))
fmt.Println()
fmt.Println("Median Trials: " + fmt.Sprint(median(trialset)))
fmt.Println()
}
func median(numbers []int) float64 {
sort.Ints(numbers)
n := len(numbers)
if n%2 == 0 {
return float64(numbers[n/2-1]+numbers[n/2]) / 2
}
return float64(numbers[n/2])
}
func mean(numbers []int) float64 {
var sum int
for _, n := range numbers {
sum += n
}
return float64(sum) / float64(len(numbers))
}
func hashTrial() int {
// puzzle difficulty
difficulty := 5
// string to match leading zeros
m := ""
for i := 0; i < difficulty; i++ {
m += "0"
}
// counter for number of trials
trials := 1
// original message to hash
s := "Hello"
// random seed using time and generation of a nonce
rand.Seed(time.Now().UnixNano())
nonce := rand.Intn(1000000)
// compute first sha256
h := sha256.New()
p := string(s) + " " + fmt.Sprint(nonce)
h.Write([]byte(p))
fmt.Println()
fmt.Println(s)
fmt.Println()
fmt.Println(p)
fmt.Println()
fmt.Println(hex.EncodeToString(h.Sum(nil)))
fmt.Println()
// compute sha256 until leading zeros are found
for string(hex.EncodeToString(h.Sum(nil))[:difficulty]) != m {
h.Reset()
nonce++
p = string(s) + " " + fmt.Sprint(nonce)
h.Write([]byte(p))
fmt.Println(p)
fmt.Println()
fmt.Println(hex.EncodeToString(h.Sum(nil)))
fmt.Println()
trials++
}
fmt.Println("Trials: " + fmt.Sprint(trials))
fmt.Println()
return trials
}