5개의 블록체인이 있다면.. 서로 이런식으로 구성되어 있다.
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}
// ...
// ...
}
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()
}