Implement block height

This commit is contained in:
Ivan Kuznetsov 2017-10-01 11:02:38 +07:00
parent 130cf66a90
commit 2734285450
2 changed files with 11 additions and 4 deletions

View File

@ -14,11 +14,12 @@ type Block struct {
PrevBlockHash []byte
Hash []byte
Nonce int
Height int
}
// NewBlock creates and returns Block
func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
block := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0}
func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {
block := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}
pow := NewProofOfWork(block)
nonce, hash := pow.Run()
@ -30,7 +31,7 @@ func NewBlock(transactions []*Transaction, prevBlockHash []byte) *Block {
// NewGenesisBlock creates and returns genesis Block
func NewGenesisBlock(coinbase *Transaction) *Block {
return NewBlock([]*Transaction{coinbase}, []byte{})
return NewBlock([]*Transaction{coinbase}, []byte{}, 0)
}
// HashTransactions returns a hash of the transactions in the block

View File

@ -172,6 +172,7 @@ func (bc *Blockchain) Iterator() *BlockchainIterator {
// MineBlock mines a new block with the provided transactions
func (bc *Blockchain) MineBlock(transactions []*Transaction) *Block {
var lastHash []byte
var lastHeight int
for _, tx := range transactions {
if bc.VerifyTransaction(tx) != true {
@ -183,13 +184,18 @@ func (bc *Blockchain) MineBlock(transactions []*Transaction) *Block {
b := tx.Bucket([]byte(blocksBucket))
lastHash = b.Get([]byte("l"))
blockData := b.Get(lastHash)
block := DeserializeBlock(blockData)
lastHeight = block.Height
return nil
})
if err != nil {
log.Panic(err)
}
newBlock := NewBlock(transactions, lastHash)
newBlock := NewBlock(transactions, lastHash, lastHeight+1)
err = bc.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(blocksBucket))