diff --git a/block.go b/block.go index 65a0a6e..e403e54 100644 --- a/block.go +++ b/block.go @@ -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 diff --git a/blockchain.go b/blockchain.go index 842905a..8d1cab7 100644 --- a/blockchain.go +++ b/blockchain.go @@ -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))