blockchain-poc/block.go

70 lines
1.3 KiB
Go

package main
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"math"
"time"
)
var (
maxNonce = math.MaxInt64
)
// Block repressents a block in the blockchain
type Block struct {
Timestamp int64
Transactions []*Transaction
PrevBlockHash []byte
Hash []byte
Nonce int
}
// NewBlock returns a new block, ready to be added to the chain
func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
block := &Block{
Timestamp: time.Now().Unix(),
Transactions: transactions,
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 {
exitWithError(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 {
exitWithError(err)
}
return &block
}
func (b *Block) HashTransactions() []byte {
var txHashes [][]byte
var txHash [32]byte
for _, tx := range b.Transactions {
txHashes = append(txHashes, tx.ID)
}
txHash = sha256.Sum256(bytes.Join(txHashes, []byte{}))
return txHash[:]
}