随机数(Nonce)值:随机数(Nonce)表示“一次性使用的数字”,是一种独特的数值,用于调整区块数据的哈希值以满足难度要求。随机数通常从 0 开始递增。难度值(Difficulty)要求意味着哈希值低于某个目标值。难度是为了维持恒定的区块生成速度而引入的阈值。
package main import ( "crypto/sha256" "encoding/hex" "fmt" "strings" ) func main() { data := "Hello, world!" difficulty := 4 target := strings.Repeat("0", difficulty) // "0000" // 堆代码 duidaima.com // 1. Start with nonce at 0 nonce := 0 for { // 2. Combine the block data and Nonce, i.e., the calculation target is the string "Hello, // world!0." dataToHash := data + fmt.Sprint(nonce) // 3. Apply the SHA-256 hash function to "Hello, world!0" and calculate the hash value. hasher := sha256.New() hasher.Write([]byte(dataToHash)) hash := hex.EncodeToString(hasher.Sum(nil)) // 4. Check if the calculated hash value meets the Difficulty conditions (starting with "0000"). if strings.HasPrefix(hash, target) { // 6. If true, the calculation is complete. fmt.Printf("Found a valid hash: %s (Nonce: %d)\n", hash, nonce) break } else { // 5. If not met, increase the Nonce by 1 and repeat steps 2–4. nonce++ } } }当你运行它时,你会得到类似这样的结果:
Found a valid hash: 0000c3af42fc31103f1fdc0151fa747ff87349a4714df7cc52ea464e12dcd4e9 (Nonce: 4250)在这个计算示例中,当随机数(Nonce)为 4250 时,找到了一个满足难度条件(哈希值以“0000”开头)的哈希值。
package main import ( "crypto/sha256" "encoding/hex" "fmt" "strings" ) // 堆代码 duidaima.com type Block struct { Timestamp int64 Transactions string PrevBlockHash string Nonce int } func main() { block := &Block{ Timestamp: 1633022800, Transactions: `{Sender: "Alice", Recipient: "Bob", Amount: 10}`, PrevBlockHash: "abcd1234", Nonce: 0, } data := strconv.FormatInt(block.Timestamp, 10) + block.Transactions + block.PrevBlockHash + strconv.Itoa(block.Nonce) difficulty := 3 target := strings.Repeat("0", difficulty) // "000" nonce := 0 for { dataToHash := data + fmt.Sprint(nonce) hasher := sha256.New() hasher.Write([]byte(dataToHash)) hash := hex.EncodeToString(hasher.Sum(nil)) if strings.HasPrefix(hash, target) { fmt.Printf("Found a valid hash: %s (Nonce: %d)\n", hash, nonce) break } else { nonce++ } } }当你运行它时,你会得到类似这样的结果:
Found a valid hash: 000d162f9ed911a43771dcc0159a92a8372bf4aa9f452f6cbc195e000192c8c4 (Nonce: 8098)通过增加随机数(Nonce),我们能够生成不同的哈希值,并找到满足难度条件的哈希值。
Found a valid hash: 0000cd54202992361b10644a6596b12e9d19e89fb8a325062fb0499dbe1a3a23 (Nonce: 13655)
可以发现随机数(Nonce)值增加了,这意味着计算所需的时间更长了。随着难度值的增加,计算所需的时间也会增加,也就需要更多的计算资源。因此,全球的矿工们投入大量计算资源,以在竞争对手之前找到满足难度条件的哈希值。