请问有源码吗?
老师,请问有源码吗?能分享一下给大家吗?
老师,请问有源码吗?能分享一下给大家吗?
2019-09-19
package core import ( "fmt" "log" ) type Blockchain struct { Blocks []*Block } //创世区块链 func NewBlockChain() *Blockchain { genesis := GenerateOriginBlock() blockchain := Blockchain{} blockchain.AppendBlock(&genesis) return &blockchain } //每一个新数据都创建一个区块,方便外部调用 func (bc *Blockchain)SendData(data string) { preBlock := bc.Blocks[len(bc.Blocks) - 1] newBlock := GenerateNewBlock(*preBlock, data) bc.AppendBlock(&newBlock) } //往区块链里添加区块 func (bc *Blockchain) AppendBlock(newBlock *Block) { if len(bc.Blocks) == 0 {//第一个区块 bc.Blocks = append(bc.Blocks,newBlock) return } if !isValid(*newBlock,*bc.Blocks[len(bc.Blocks) - 1]) { log.Fatal("Invalid block") } bc.Blocks = append(bc.Blocks,newBlock) } //打印区块链 func (bc *Blockchain) Print() { for _,block := range bc.Blocks { fmt.Printf("Index:%d\n",block.Index) fmt.Printf("PrevHash:%s\n",block.PrevBlockHash) fmt.Printf("Hash:%s\n",block.Hash) fmt.Printf("Timestamp:%d\n",block.Timestamp) fmt.Printf("Data:%s\n",block.Data) } } //新区块校验 func isValid(newBlock Block,oldBlock Block) bool { if newBlock.Index - 1 != oldBlock.Index { return false } if newBlock.PrevBlockHash != oldBlock.Hash { return false } if calculateHash(newBlock) != newBlock.Hash { return false } return true }
package core import ( "fmt" "log" ) type Blockchain struct { Blocks []*Block } //创世区块链 func NewBlockChain() *Blockchain { genesis := GenerateOriginBlock() blockchain := Blockchain{} blockchain.AppendBlock(&genesis) return &blockchain } //每一个新数据都创建一个区块,方便外部调用 func (bc *Blockchain)SendData(data string) { preBlock := bc.Blocks[len(bc.Blocks) - 1] newBlock := GenerateNewBlock(*preBlock, data) bc.AppendBlock(&newBlock) } //往区块链里添加区块 func (bc *Blockchain) AppendBlock(newBlock *Block) { if len(bc.Blocks) == 0 {//第一个区块 bc.Blocks = append(bc.Blocks,newBlock) return } if !isValid(*newBlock,*bc.Blocks[len(bc.Blocks) - 1]) { log.Fatal("Invalid block") } bc.Blocks = append(bc.Blocks,newBlock) } //打印区块链 func (bc *Blockchain) Print() { for _,block := range bc.Blocks { fmt.Printf("Index:%d\n",block.Index) fmt.Printf("PrevHash:%s\n",block.PrevBlockHash) fmt.Printf("Hash:%s\n",block.Hash) fmt.Printf("Timestamp:%d\n",block.Timestamp) fmt.Printf("Data:%s\n",block.Data) } } //新区块校验 func isValid(newBlock Block,oldBlock Block) bool { if newBlock.Index - 1 != oldBlock.Index { return false } if newBlock.PrevBlockHash != oldBlock.Hash { return false } if calculateHash(newBlock) != newBlock.Hash { return false } return true }
举报