Implement serialization and deserialization of a block

This commit is contained in:
Ivan Kuznetsov 2017-08-28 12:11:51 +07:00
parent 56cb2de106
commit 85022254ec
1 changed files with 29 additions and 0 deletions

View File

@ -1,6 +1,9 @@
package main package main
import ( import (
"bytes"
"encoding/gob"
"log"
"time" "time"
) )
@ -13,6 +16,19 @@ type Block struct {
Nonce int Nonce int
} }
// Serialize serializes the block
func (b *Block) Serialize() []byte {
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
err := encoder.Encode(b)
if err != nil {
log.Panic(err)
}
return result.Bytes()
}
// NewBlock creates and returns Block // NewBlock creates and returns Block
func NewBlock(data string, prevBlockHash []byte) *Block { func NewBlock(data string, prevBlockHash []byte) *Block {
block := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}, 0} block := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}, 0}
@ -29,3 +45,16 @@ func NewBlock(data string, prevBlockHash []byte) *Block {
func NewGenesisBlock() *Block { func NewGenesisBlock() *Block {
return NewBlock("Genesis Block", []byte{}) return NewBlock("Genesis Block", []byte{})
} }
// DeserializeBlock deserializes a block
func DeserializeBlock(d []byte) *Block {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(d))
err := decoder.Decode(&block)
if err != nil {
log.Panic(err)
}
return &block
}