Implement serialization and deserialization of a block
This commit is contained in:
parent
56cb2de106
commit
85022254ec
29
block.go
29
block.go
|
@ -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
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue