The core protocol of WoopChain
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
woop/blockchain/block.go

76 lines
1.7 KiB

package blockchain
import (
7 years ago
"bytes"
"crypto/sha256"
"encoding/gob"
"fmt"
7 years ago
"log"
"time"
)
// Block keeps block headers.
type Block struct {
7 years ago
Timestamp int64
Transactions []*Transaction
PrevBlockHash []byte
Hash []byte
}
// 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()
}
// 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
}
// Used for debuging.
func (b *Block) String() string {
res := fmt.Sprintf("Block created at %v\n", b.Timestamp)
for id, tx := range b.Transactions {
res += fmt.Sprintf("Transaction %v: %v\n", id, *tx)
}
res += fmt.Sprintf("previous blockhash: %v\n", b.PrevBlockHash)
res += fmt.Sprintf("hash: %v\n", b.Hash)
return res
}
// HashTransactions returns a hash of the transactions in the block
func (b *Block) HashTransactions() []byte {
7 years ago
var txHashes [][]byte
var txHash [32]byte
for _, tx := range b.Transactions {
7 years ago
txHashes = append(txHashes, tx.ID)
7 years ago
}
txHash = sha256.Sum256(bytes.Join(txHashes, []byte{}))
return txHash[:]
}
// NewBlock creates and returns a neew block.
func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
block := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}}
7 years ago
block.Hash = block.HashTransactions()
return block
}
// NewGenesisBlock creates and returns genesis Block.
func NewGenesisBlock(coinbase *Transaction) *Block {
7 years ago
return NewBlock([]*Transaction{coinbase}, []byte{})
}