Golang Blockchain Development 001-Initialization of Blockchain

Source: Internet
Author: User

I. Code STRUCTURE


block.go: Defining block structures and methods

blockchain.go: Defining blockchain structures and methods

help.go: Encapsulates a common code block to form a help library

main.go: Test code


two. Defining the block structure and method


package blcimport  (    "Time"     "StrConv"     "bytes"     "crypto/sha256")//define chunk TYPE BLOCK STRUCT {   //1. Block height, which is the block number, Number of blocks    HEIGHT INT64   //2. The hash value of the previous chunk    preblockhash [ ]BYTE   //3. Transaction data (which ultimately belongs to transaction  transaction)    data []byte   / /4. Timestamp of creation time    TIMESTAMP INT64   //5. The hash value of the current chunk    hash [ ]byte   //6.nonce  random number, used to verify the work proof    nonce int64}//defines the method of generating hash in block func   (Block *block)  sethash ()  {   //1. Convert height  to byte array  []byte    heightbytes := inttohex (block. Height)    //2. Convert timestamp  to byte array  []byte   //2.1  Int64 timestamp   converted to binary    timestring := strconv. Formatint (block. TimeSTAMP, 2)    //2.2  convert binary string to byte array    timebytes := []byte ( timestring)    //3. Stitching all attributes to form a two-dimensional byte array    blockbytes := bytes. Join ([][]byte{heightbytes, block. Preblockhash, block. Data, timebytes, block. hash}, []byte{})    //4. Generate hash   hash := sha256. Sum256 (blockbytes)    block. hash = hash[:]}//1.  Create a new chunk Func newblock (data string, height int64,  Preblockhash []byte)  *block {   //Create block    block := & block{      height,      preblockhash,       []byte (data),       time. Now (). Unix (),      nil,      0,   }    //set Hash   block.Sethash ()    return block}//2. Generate Genesis Block 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})}



three. Define blockchain and method

package blctype blockchain struct {   blocks []*block //stores an ordered chunk} func  (Blc *blockchain) addblockchain (data string,height int64,prehash []byte) {    //Create new block    newblock := newblock (Data,height,prehash)    // Add chunk    BLC to the chain. Blocks=append (BLC. Blocks,newblock)}//1. Creating Blockchain with Genesis blocks Func createblockchainwithgenesisblock ()  *BlockChain {    //Creating the Genesis Block    genesisblock := creategenesisblock ("Genesis Data ...")    //return the Blockchain Object    return &blockchain{[]*block{genesisblock}}} 


four. Help code base

package blcimport  (    "bytes"     "Encoding/binary"     " Log ")//convert Int64 to byte array Func inttohex (Num int64)  []byte {   buff :=  New (bytes. Buffer)    err := binary. Write (buff, binary. Bigendian, num)    if err != nil {       Log. Panic (Err)    }   return buff. Bytes ()} 


five. Test code

package mainimport  (    "PUBLICCHAIN/BLC"     "FMT") Func main ()  {   //Create the Genesis block    BLOCKCHAIN := BLC. Createblockchainwithgenesisblock ()    //creates a new chunk    blockchain.addblockchain ("Send  $100 to bruce ",  blockchain.blocks[len (Blockchain.blocks)-1]. Height+1, blockchain.blocks[len (Blockchain.blocks)-1]. Hash)    blockchain.addblockchain ("Send $200 to apple",  blockChain.Blocks[ Len (Blockchain.blocks)-1]. Height+1, blockchain.blocks[len (Blockchain.blocks)-1]. Hash)    blockchain.addblockchain ("Send $300 to alice",  blockChain.Blocks[ Len (Blockchain.blocks)-1]. Height+1, blockchain.blocks[len (Blockchain.blocks)-1]. Hash)    blockchain.addblockchain ("Send $400 to bob",  blockchain.blocks[len ( Blockchain.blocks)-1]. Height+1, blockchain.blocks[len (BLOCKCHAIN.BLocks)-1]. Hash)    fmt. Printf ("Created Blockchain: \t%v\n",  blockchain)    fmt. Printf ("Blockchain-stored chunks: \t%v\n",  blockchain.blocks)    fmt. PRINTF ("Data information for the second chunk (trading information) is: \t%v\n",  string (blockchain.blocks[1). Data)}


six. The results show that


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.