OSDN Git Service

Merge pull request #935 from Bytom/dev
[bytom/bytom.git] / protocol / tx.go
1 package protocol
2
3 import (
4         "github.com/bytom/errors"
5         "github.com/bytom/protocol/bc"
6         "github.com/bytom/protocol/bc/types"
7         "github.com/bytom/protocol/state"
8         "github.com/bytom/protocol/validation"
9 )
10
11 // ErrBadTx is returned for transactions failing validation
12 var ErrBadTx = errors.New("invalid transaction")
13
14 // GetTransactionStatus return the transaction status of give block
15 func (c *Chain) GetTransactionStatus(hash *bc.Hash) (*bc.TransactionStatus, error) {
16         return c.store.GetTransactionStatus(hash)
17 }
18
19 // GetTransactionsUtxo return all the utxos that related to the txs' inputs
20 func (c *Chain) GetTransactionsUtxo(view *state.UtxoViewpoint, txs []*bc.Tx) error {
21         return c.store.GetTransactionsUtxo(view, txs)
22 }
23
24 // ValidateTx validates the given transaction. A cache holds
25 // per-transaction validation results and is consulted before
26 // performing full validation.
27 func (c *Chain) ValidateTx(tx *types.Tx) (bool, error) {
28         if ok := c.txPool.HaveTransaction(&tx.ID); ok {
29                 return false, c.txPool.GetErrCache(&tx.ID)
30         }
31
32         view := c.txPool.GetTransactionUTXO(tx.Tx)
33         if err := c.GetTransactionsUtxo(view, []*bc.Tx{tx.Tx}); err != nil {
34                 return true, err
35         }
36
37         bh := c.BestBlockHeader()
38         block := types.MapBlock(&types.Block{BlockHeader: *bh})
39         if err := view.ApplyTransaction(block, tx.Tx, false); err != nil {
40                 return true, err
41         }
42
43         gasStatus, err := validation.ValidateTx(tx.Tx, block)
44         if gasStatus.GasValid == false {
45                 c.txPool.AddErrCache(&tx.ID, err)
46                 return false, err
47         }
48
49         _, err = c.txPool.AddTransaction(tx, err != nil, block.BlockHeader.Height, gasStatus.BTMValue)
50         return false, err
51 }