区块链笔记-001

一、简单区块链的创建过程

1、创建区块结构体

type Block struct{

    PrevBlockHash []byte    

    Hash []byte   

    Data []byte

    Timestamp int64

    Height int64

}

2、创建新区块

func (block *Block) SetHash() {  //这个是创建区块的hash值,创建的规则是由自己定的

    //将整数转换成 []byte

    heightBytes := IntToHex(block.Height)

    //将时间戳转换成 []byte

    timeString := strconv.FormatInt(block.Timestamp, 2)

    timeBytes := []byte(timeString)

    //拼接所有属性

    blockBytes := bytes.Join([][]byte{

        block.PrevBlockHash,block.Data,timeBytes, heightBytes},[]byte{})

    //生成Hash

    hash := sha256.Sum256(blockBytes)

    block.Hash = hash[:]

}

func NewBlock(data string, height int64, prevBlockHash []byte) *Block{

      // 创建区块

       block := &Block{PrevBlockHash:prevBlockHash, Hash:nil, Data:[]byte(data), Timestamp:time.Now().Unix(), Height:height}

       //设置Hash值

        block.SetHash()

        return block

}

3、创建一个创世区块

//单独写一个创建创世区块

func CreateGenesisBlock(data string) *Block {

    return NewBlock(data, 1, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})

}

4、创建区块链结构体

type Blockchain struct {

      Blocks []*Block  //存储有序的区块

}

5、创建带有创世区块的区块链

func CreateBlockchainWithGenesisBlock() *Blockchain {

    genesisBlock := CreateGenesisBlock("布衣")

    blockchain :=  &Blockchain{ []*Block{genesisBlock } }

    return blockchain 

}

6、增加区块到区块链

func (blc *Blockchain) AddBlockToBlockchain(data string, height int64, prevBlockHash []byte) {

    newBlock := NewBlock(data, height, prevBlcokHash)

    blc.Blocks = append(blc.Blocks, newBlock)

}

你可能感兴趣的:(区块链笔记-001)