TIL 13 - Golang으로 블록체인 만들기 1

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

TIL

목록 보기
13/46
post-thumbnail

5개의 블록체인이 있다면.. 서로 이런식으로 구성되어 있다.

  • A BlockChain Hash = Data.. + “ ”
  • B BlockChain Hash = Data… + A BlockChain Hash
  • C BlockChain Hash = Data… + B BlockChain Hash
  • D BlockChain Hash = Data… + C BlcokChain Hash
  • E BlockChain Hash = Data… + D BlockChain Hash
  • Hash, 일방향 함수
  • 데이터가 변경되면 전혀 다른 값의 결과물이 출력된다.
    • 예를 들어 C의 데이터가 변경되면
      • C의 Hash값을 이용해 만든 D, E 블록들이 변하게된다.
      • D,E의 블록들이 의미가없어진다.

Genesis Block 가볍게 만들어보기(Hash 학습)

type block struct {
	data     string
	hash     string
	prevHash string
}

func main() {
	genesisBlock := block{"Genisis Block", "", ""}
	// hash의 byte값을 가져온다.
	// []byte : string을 byte 슬라이스로 변환해준다.
	// Sum256(): byte slice를 받고 32byte Hash를 반환한다.
	hash := sha256.Sum256([]byte(genesisBlock.data + genesisBlock.prevHash))
	fmt.Println(hash)
	//[214 90 147 214 18 203 25 150 137 60 38 253 83 217 147 203 170 241 232 254 24 20 53 154 51 150 223 9 92 207 42 12]
	// Bitcoin, Ethereum은 16진수(base16) hash로 되어있다.
	// base16로 포맷된 hash 값을 string type으로 저장.
	hexHash := fmt.Sprintf("%x", hash)
	// 블록에 저장
	genesisBlock.hash = hexHash

  // 두번째 블록...
	// genesisBlock := block{"Genisis Block", "", genesisBlock.hash}
  // ...
  // ...
}
  • genesisBlock.hash에서 마지막에 공백이 있는 이유는 prevHash 값이 비어있기 때문이다.

Genesis Block, Second Block.. 만들어보기

type block struct {
	data     string
	hash     string
	prevHash string
}
type blockchain struct {
	blocks []block
}

// 마지막 블록의 해시를 불러오는 함수
func (b *blockchain) getLastHash() string {
	if len(b.blocks) > 0 {
		// 블록체인에 등록된 블록이 0개가 아니라면 새로 생성되는 블록은 제네시스 블록이 아니다.
		// 두번째 블록 부터는 이전 블록의 해시값을 블록에 함께 저장해준다.
		return b.blocks[len(b.blocks)-1].hash
	}
	// 0개라면 제네시스 블록이므로 이전 해시값을 저장하지 않는다.
	return ""
}

func (b *blockchain) addBlock(data string) {
	newBlock := block{data, "", b.getLastHash()}
	hash := sha256.Sum256([]byte(newBlock.data + newBlock.prevHash))
	newBlock.hash = fmt.Sprintf("%x", hash)
	// 블록체인에 앞서 생성한 블록을 넣어준다.
	b.blocks = append(b.blocks, newBlock)
}
func (b *blockchain) listBlocks() {
	for _, block := range b.blocks {
		fmt.Printf("Data : %s\n", block.data)
		fmt.Printf("Hash : %s\n", block.hash)
		fmt.Printf("Prev Hash : %s\n", block.prevHash)
	}
}
func main() {
	chain := blockchain{}
	chain.addBlock("Genesis Block")
	chain.addBlock("Second Block")
	chain.addBlock("Third Block")
	chain.listBlocks()
}
profile
좋은 개발자가 되고싶은

0개의 댓글