Preface:

Simple principle code description

Core: block, block implementation main: example run

BlockMain execution directory:

package main
 
import "Chains/core"
 
func main() {
	sc := core.NewBlockChain()
	sc.SendData("send 1 btc to jacky")
	sc.SendData("send 1 eos to jack")
	sc.Print()
}Copy the code


Block, Block:

package core
 
import (
    "crypto/sha256"
    "encoding/hex"
    "time"
)
 
typeBlock struct {Index int64 // Block number Timestamp int64 // Block Timestamp PreBlockHash string // Hash of the previous Block // Hash of the current Block Data String // Block data} func calculateHash(b Block) string{blockData := String (B.index) + string(B.timstamp) + B.preblockHashhashInBytes := sha256.Sum256([]byte(blockData))
 
    return hex.EncodeToString(hashInBytes[:])
}
 
func GenerateNewBlock(preBlock Block,data string) Block{
    newBlock := Block{}
    newBlock.Index = preBlock.Index + 1
    newBlock.PreBlockHash = preBlock.Hash
    newBlock.Timestamp = time.Now().Unix()
    newBlock.Hash = calculateHash(newBlock)
 
    return newBlock
}
 
func GenerateGenesisBlock() Block  {
    preBlock := Block{}
    preBlock.Index = 1
    preBlock.Hash = ""
 
    return GenerateNewBlock(preBlock,"Genesies Block")}Copy the code


How to implement the BlockChain BlockChain

package core
 
import (
    "log"
    "fmt"
)
 
type BlockChain struct {
    Blocks []*Block
}
 
func NewBlockChain() *BlockChain {
    genesisBlock := GenerateGenesisBlock()
    blockchain := BlockChain{}
    blockchain.ApendBlock(&genesisBlock)
    return &blockchain
}
 
func (bc *BlockChain) SendData(data string){
 
    preBlock := bc.Blocks[len(bc.Blocks)-1 ]
    newBlock := GenerateNewBlock(*preBlock,data)
    bc.ApendBlock(&newBlock)
}
 
func (bc *BlockChain)  ApendBlock(newBlock *Block){
    if len(bc.Blocks) == 0{
        bc.Blocks = append(bc.Blocks,newBlock)
        return
    }
    if  isValid(*newBlock,*bc.Blocks[len(bc.Blocks)-1]){
            bc.Blocks =  append(bc.Blocks,newBlock)
        }else{
            log.Fatal("invalid block")
    }
}
 
func (bc *BlockChain) Print() {for _,block := range bc.Blocks{
        fmt.Printf("Index:%d\n",block.Index)
        fmt.Printf("Pre.Hash:%s\n",block.PreBlockHash)
        fmt.Printf("Curr.Hash:%s\n",block.Hash)
        fmt.Printf("Data:%s\n",block.Data)
        fmt.Printf("TimeStamp:%d\n",block.Timestamp)
    }
}
 
func isValid(newBlock Block,oldBlack Block) bool{
 
    ifnewBlock.Index - 1 ! = oldBlack.Index {return false
    }
    ifnewBlock.PreBlockHash ! = oldBlack.Hash{return false
    }
    ifcalculateHash(newBlock) ! = newBlock.Hash{return false
    }
    return true

}Copy the code