블록체인 생성 v1

다음은 블록체인의 실현에 대해 간단하게 설명한다.
block.go
package main

import (
    "time"
    "crypto/sha256"
    "bytes"
)

//     
type Block struct{
    Version int64
    PrevBlockHash []byte
    Hash []byte
    TimeStamp int64
    TargetBits  int64
    Nonce int64
    MerKelRoot []byte

    Data []byte
}

//        
func NewBlock(data string, prevBlockHash []byte) *Block{
    block := &Block{
        Version:1,
        PrevBlockHash:prevBlockHash,
        //Hash:
        TimeStamp:time.Now().Unix(),
        TargetBits:10,
        Nonce:5,
        MerKelRoot:[]byte{},
        Data:[]byte(data),
    }
    block.SetHash() //        
    return block
}

//      
func (block *Block)SetHash(){
    tmp := [][]byte{
        //  int     byte       
        IntToByte(block.Version),
        block.PrevBlockHash,
        IntToByte(block.TimeStamp),
        block.MerKelRoot,
        IntToByte(block.Nonce),
        block.Data,
    }
    //               ,  【】byte{}    ,             
    data := bytes.Join(tmp,[]byte{})

    //     sha256    ,    [32]byte  ,    
    hash := sha256.Sum256(data)
    block.Hash = hash[:]//        
}

//       ,              
func NewGenesisBlock() *Block{
    return NewBlock("Genesis Block!",[]byte{})
}

blockchain.go
package main

import "os"

//      
type  BlockChain struct{
    blocks []*Block
}

//      ,       
func NewBlockChain() *BlockChain{
    return &BlockChain{[]*Block{
        NewGenesisBlock(),
    }}
}

//    
func (bc *BlockChain)AddBlock(data string){
    //    
    if len(bc.blocks) <= 0 {
        os.Exit(1)
    }

    //      ,      
    lastblock := bc.blocks[len(bc.blocks)-1]
    prevBlockHash := lastblock.Hash
    block := NewBlock(data, prevBlockHash)

    //        
    bc.blocks = append(bc.blocks, block)
}

utils
package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
    "os"
)

func IntToByte(num int64)[]byte{
    var buffer  bytes.Buffer
    err := binary.Write(&buffer, binary.BigEndian, num)
    //if err != nil{
    //  fmt.Println("IntToByte err occur:",err)
    //  os.Exit(1)
    //}
    CheckErr(err)
    return buffer.Bytes()
}

func CheckErr(err error){
    if err != nil{
        fmt.Println("err occur:",err)
        os.Exit(1)
    }
}

main.go
package main

import "fmt"

func main(){
    bc := NewBlockChain()
    bc.AddBlock("           ")
    bc.AddBlock("            ")

    for i, block := range bc.blocks{
        fmt.Println("====block num:", i)
        fmt.Printf("Data:%s
", block.Data) fmt.Println("Version:",block.Version) fmt.Printf("PrevHash:%x
",block.Version) fmt.Printf("Hash:%x
",block.TimeStamp) fmt.Printf("TimeStamp:%d
",block.TimeStamp) fmt.Printf("MerKel:%x
",block.MerKelRoot) fmt.Printf("Nonce:%d
",block.Nonce) } }

마지막으로 gopath 경로에서 보기 효과를 컴파일합니다.

좋은 웹페이지 즐겨찾기