package main
import (
"crypto/sha256"
"fmt"
)
func main() {
hash := sha256.Sum256([]byte("hello"))
fmt.Printf("%x\n", hash)
}
해당 문자열로 만든 해시값은 앞에 0이 하나도 없다. → 해시는 결정론적 함수이기에 입력값으로 수정으로 출력값을 바꿔줘야한다.func main() {
hash := sha256.Sum256([]byte("hello1"))
fmt.Printf("%x\n", hash)
}
func main() {
hash := sha256.Sum256([]byte("hello2"))
fmt.Printf("%x\n", hash)
}
func main() {
hash := sha256.Sum256([]byte("hello3"))
fmt.Printf("%x\n", hash)
}
func main() {
hash := sha256.Sum256([]byte("hello4"))
fmt.Printf("%x\n", hash)
}
네트워크 : difficulty의 값만큼 0의 개수를 증가시켜 난이도를 어렵게 만든다
채굴자 : nonce 값을 변경해가며 0의 개수가 맞는 것을 찾아낸다.
package main
import (
"crypto/sha256"
"fmt"
"strings"
)
func main() {
difficulty := 2
// target := "0" * 2
// 첫번째 인자값을 두번째 인자값 만큼 연결해서 출력해준다.
target := strings.Repeat("0", difficulty)
nonce := 1
for {
// 16진수 string으로 변환
hash := fmt.Sprintf("%x", sha256.Sum256([]byte("hello"+fmt.Sprint(nonce))))
fmt.Printf("Hash:%s\nTarget:%s\nNonce:%d\n\n", hash, target, nonce)
if strings.HasPrefix(hash, target) {
return
} else {
nonce++
}
}
}
Hash:001b92541ed0a22b0cb89018b561d895503206c0082c0ecf2d0b7e5182191eed
Target:00
Nonce:227
Hash:0006bc9ad4253c42e32b546dc17e5ea3fedaecdabef371b09906cea9387e8695
Target:000
Nonce:10284
Hash:0000e49eab06aa7a6b3aef7708991b91a7e01451fd67f520b832b89b18f4e7de
Target:0000
Nonce:60067