blockchain-poc/block.go

57 lines
1002 B
Go

package main
import (
"bytes"
"encoding/gob"
"log"
"math"
"time"
)
var (
maxNonce = math.MaxInt64
)
type Block struct {
Timestamp int64
Data []byte
PrevBlockHash []byte
Hash []byte
Nonce int
}
// NewBlock returns a new block, ready to be added to the chain
func NewBlock(data string, prevBlockHash []byte) *Block {
block := &Block{
Timestamp: time.Now().Unix(),
Data: []byte(data),
PrevBlockHash: prevBlockHash,
Hash: []byte{},
}
pow := NewProofOfWork(block)
nonce, hash := pow.Run()
block.Hash = hash[:]
block.Nonce = nonce
return block
}
func (b *Block) Serialize() []byte {
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
if err := encoder.Encode(b); err != nil {
log.Panic(err)
}
return result.Bytes()
}
func DeserializeBlock(d []byte) *Block {
var block Block
decoder := gob.NewDecoder(bytes.NewReader(d))
if err := decoder.Decode(&block); err != nil {
log.Panic(err)
}
return &block
}