Implement Blockchain.AddBlock

This commit is contained in:
Ivan Kuznetsov 2017-10-01 20:30:21 +07:00
parent 470adef2c3
commit a79d78ad8c
2 changed files with 21 additions and 3 deletions

View File

@ -102,6 +102,24 @@ func (bc *Blockchain) Reset() {
} }
// AddBlock saves the block into the blockchain
func (bc *Blockchain) AddBlock(block *Block) {
err := bc.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(blocksBucket))
blockInDb := b.Get(block.Hash)
if blockInDb != nil {
blockData := block.Serialize()
b.Put(block.Hash, blockData)
}
return nil
})
if err != nil {
log.Panic(err)
}
}
// FindTransaction finds a transaction by its ID // FindTransaction finds a transaction by its ID
func (bc *Blockchain) FindTransaction(ID []byte) (Transaction, error) { func (bc *Blockchain) FindTransaction(ID []byte) (Transaction, error) {
bci := bc.Iterator() bci := bc.Iterator()

View File

@ -183,7 +183,7 @@ func handleBlock(request []byte, bc *Blockchain) {
block := DeserializeBlock(blockData) block := DeserializeBlock(blockData)
fmt.Println("Recevied a new block!") fmt.Println("Recevied a new block!")
fmt.Println(block) bc.AddBlock(block)
} }
func handleInv(request []byte, bc *Blockchain) { func handleInv(request []byte, bc *Blockchain) {
@ -201,8 +201,8 @@ func handleInv(request []byte, bc *Blockchain) {
blocks := bc.GetBlockHashes() blocks := bc.GetBlockHashes()
if len(blocks) < len(payload.Items) { if len(blocks) < len(payload.Items) {
for _, blockHash := range invResponse.Items { for _, blockHash := range payload.Items {
sendGetData(sourceNode, "block", blockHash) sendGetData(payload.AddrFrom, "block", blockHash)
} }
} }
} }