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.
64 lines
1.4 KiB
64 lines
1.4 KiB
6 years ago
|
package blockchain
|
||
7 years ago
|
|
||
|
import (
|
||
6 years ago
|
"bytes"
|
||
|
"crypto/sha256"
|
||
|
"encoding/gob"
|
||
|
"log"
|
||
|
"time"
|
||
7 years ago
|
)
|
||
|
|
||
6 years ago
|
// Block keeps block headers.
|
||
7 years ago
|
type Block struct {
|
||
6 years ago
|
Timestamp int64
|
||
|
Transactions []*Transaction
|
||
|
PrevBlockHash []byte
|
||
|
Hash []byte
|
||
7 years ago
|
}
|
||
|
|
||
6 years ago
|
// 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
|
||
|
}
|
||
|
|
||
6 years ago
|
// HashTransactions returns a hash of the transactions in the block
|
||
|
func (b *Block) HashTransactions() []byte {
|
||
6 years ago
|
var txHashes [][]byte
|
||
|
var txHash [32]byte
|
||
|
|
||
|
for _, tx := range b.Transactions {
|
||
6 years ago
|
txHashes = append(txHashes, tx.id)
|
||
6 years ago
|
}
|
||
|
txHash = sha256.Sum256(bytes.Join(txHashes, []byte{}))
|
||
|
return txHash[:]
|
||
7 years ago
|
}
|
||
|
|
||
6 years ago
|
// NewBlock creates and returns Block.
|
||
|
func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
|
||
6 years ago
|
block := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}}
|
||
6 years ago
|
block.Hash = block.HashTransactions()
|
||
|
return block
|
||
7 years ago
|
}
|
||
|
|
||
6 years ago
|
// NewGenesisBlock creates and returns genesis Block.
|
||
6 years ago
|
func NewGenesisBlock(coinbase *Transaction) *Block {
|
||
6 years ago
|
return NewBlock([]*Transaction{coinbase}, []byte{})
|
||
6 years ago
|
}
|