Skip to content

Commit

Permalink
Bug fix: validate scripts before utxo update to avoid missing referen…
Browse files Browse the repository at this point in the history
…ced utxo
  • Loading branch information
xhliu committed Oct 24, 2018
1 parent 3647cc5 commit ee502ed
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
9 changes: 5 additions & 4 deletions core/chain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,6 @@ func (chain *BlockChain) ProcessBlock(block *types.Block, broadcast bool) (bool,
logger.Error(err)
return false, false, err
}

prevHash := block.Header.PrevBlockHash
if prevHashExists := chain.blockExists(prevHash); !prevHashExists {
// Orphan block.
Expand Down Expand Up @@ -350,6 +349,11 @@ func (chain *BlockChain) tryConnectBlockToMainChain(block *types.Block, utxoSet
// str := "the coinbase for the genesis block is not spendable"
// return ErrMissingTxOut
// }
// Validate scripts here before utxoSet is updated; otherwise it may fail mistakenly
if err := validateBlockScripts(utxoSet, block); err != nil {
return err
}

transactions := block.Txs
// Perform several checks on the inputs for each transaction.
// Also accumulate the total fees.
Expand Down Expand Up @@ -400,9 +404,6 @@ func (chain *BlockChain) tryConnectBlockToMainChain(block *types.Block, utxoSet
}
}

if err := validateBlockScripts(utxoSet, block); err != nil {
return err
}
chain.SetTailBlock(block, utxoSet)
// Notify others such as mempool.
chain.notifyBlockConnectionUpdate(block, true)
Expand Down
9 changes: 6 additions & 3 deletions core/chain/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,12 @@ func ValidateTxScripts(utxoSet *UtxoSet, tx *types.Transaction) error {
for txInIdx, txIn := range tx.Vin {
// Ensure the referenced input transaction exists and is not spent.
utxo := utxoSet.FindUtxo(txIn.PrevOutPoint)
if utxo == nil || utxo.IsSpent {
logger.Errorf("output %v referenced from transaction %s:%d does not exist or"+
"has already been spent", txIn.PrevOutPoint, txHash, txInIdx)
if utxo == nil {
logger.Errorf("output %v referenced from transaction %s:%d does not exist", txIn.PrevOutPoint, txHash, txInIdx)
return core.ErrMissingTxOut
}
if utxo.IsSpent {
logger.Errorf("output %v referenced from transaction %s:%d has already been spent", txIn.PrevOutPoint, txHash, txInIdx)
return core.ErrMissingTxOut
}

Expand Down

0 comments on commit ee502ed

Please sign in to comment.