TIL 27 - Golang으로 블록체인 만들기(작업증명 구현하기) 9

프동프동·2023년 2월 10일
0

TIL

목록 보기
27/46
post-thumbnail

작업 증명 구현하기(PoW)

  • 컴퓨터가 풀기는 어렵지만 검증하기는 쉬운 방법
  • n개의 0으로 시작하는hash를 찾도록 하자
    • n개는 Difficulty에 의해 결정된다.
  • 네트워크가 Client의 해시의 시작이 n개의 0으로 되어있는지 검증한다.
  • 시간의 흐름에 따라 Difficulty 값을 바뀌도록 한다.
  • Ex
    package main
    
    import (
    	"crypto/sha256"
    	"fmt"
    )
    
    func main() {
    	hash := sha256.Sum256([]byte("hello"))
    	fmt.Printf("%x\n", hash)
    }
    해당 문자열로 만든 해시값은 앞에 0이 하나도 없다. → 해시는 결정론적 함수이기에 입력값으로 수정으로 출력값을 바꿔줘야한다.
  • 블록체인에서는 블록의 정보를 수정할 수 없다.
    • 해시값을 수정하면 해당 블록을 사용하지 못한다.
    • Data는 유저가 보내주는 것이라 수정할 수 없다.
  • Nonce 값은 채굴자가 변경할 수 있는 유일한 값이다.
    • Nonce값을 변경해가며 해시값을 조건에 맞게 찾아내야한다.
      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의 개수가 맞는 것을 찾아낸다.

  • 소스 코드
    • main.go
      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++
      		}
      	}
      
      }
  • 실행 결과
    • difficulty가 2일 때
      Hash:001b92541ed0a22b0cb89018b561d895503206c0082c0ecf2d0b7e5182191eed
      Target:00
      Nonce:227
      • 227번만에 찾았다.
    • difficulty가 3일 때
      Hash:0006bc9ad4253c42e32b546dc17e5ea3fedaecdabef371b09906cea9387e8695
      Target:000
      Nonce:10284
      • 10284번 걸렸다.
    • difficulty가 4일 때
      Hash:0000e49eab06aa7a6b3aef7708991b91a7e01451fd67f520b832b89b18f4e7de
      Target:0000
      Nonce:60067
      • 60067번
  • 난이도가 조금만 올라가도 엄청나게 연산이 많이 필요한 것을 느낄 수 있다.
  • 실제 비트코인은 좀 더 복잡하다

profile
좋은 개발자가 되고싶은

0개의 댓글