OSDN Git Service

7316623fdc7de568580d9842ad8251d625bb55f4
[bytom/vapor.git] / wallet / utxo.go
1 package wallet
2
3 import (
4         "encoding/json"
5
6         log "github.com/sirupsen/logrus"
7
8         "github.com/vapor/account"
9         "github.com/vapor/consensus"
10         "github.com/vapor/consensus/segwit"
11         "github.com/vapor/crypto/sha3pool"
12         dbm "github.com/vapor/database/leveldb"
13         "github.com/vapor/errors"
14         "github.com/vapor/protocol/bc"
15         "github.com/vapor/protocol/bc/types"
16 )
17
18 // GetAccountUtxos return all account unspent outputs
19 func (w *Wallet) GetAccountUtxos(accountID string, id string, unconfirmed, isSmartContract bool) []*account.UTXO {
20         prefix := account.UTXOPreFix
21         if isSmartContract {
22                 prefix = account.SUTXOPrefix
23         }
24
25         accountUtxos := []*account.UTXO{}
26         if unconfirmed {
27                 accountUtxos = w.AccountMgr.ListUnconfirmedUtxo(accountID, isSmartContract)
28         }
29
30         accountUtxoIter := w.DB.IteratorPrefix([]byte(prefix + id))
31         defer accountUtxoIter.Release()
32
33         for accountUtxoIter.Next() {
34                 accountUtxo := &account.UTXO{}
35                 if err := json.Unmarshal(accountUtxoIter.Value(), accountUtxo); err != nil {
36                         log.WithFields(log.Fields{"module": logModule, "err": err}).Warn("GetAccountUtxos fail on unmarshal utxo")
37                         continue
38                 }
39
40                 if accountID == accountUtxo.AccountID || accountID == "" {
41                         accountUtxos = append(accountUtxos, accountUtxo)
42                 }
43         }
44         return accountUtxos
45 }
46
47 func (w *Wallet) attachUtxos(batch dbm.Batch, b *types.Block, txStatus *bc.TransactionStatus) {
48         for txIndex, tx := range b.Transactions {
49                 statusFail, err := txStatus.GetStatus(txIndex)
50                 if err != nil {
51                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("attachUtxos fail on get tx status")
52                         continue
53                 }
54
55                 //hand update the transaction input utxos
56                 inputUtxos := txInToUtxos(tx, statusFail)
57                 for _, inputUtxo := range inputUtxos {
58                         if segwit.IsP2WScript(inputUtxo.ControlProgram) {
59                                 batch.Delete(account.StandardUTXOKey(inputUtxo.OutputID))
60                         } else {
61                                 batch.Delete(account.ContractUTXOKey(inputUtxo.OutputID))
62                         }
63                 }
64
65                 //hand update the transaction output utxos
66                 validHeight := uint64(0)
67                 if txIndex == 0 {
68                         validHeight = b.Height + consensus.CoinbasePendingBlockNumber
69                 }
70                 outputUtxos := txOutToUtxos(tx, statusFail, validHeight)
71                 utxos := w.filterAccountUtxo(outputUtxos)
72                 if err := batchSaveUtxos(utxos, batch); err != nil {
73                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("attachUtxos fail on batchSaveUtxos")
74                 }
75         }
76 }
77
78 func (w *Wallet) detachUtxos(batch dbm.Batch, b *types.Block, txStatus *bc.TransactionStatus) {
79         for txIndex := len(b.Transactions) - 1; txIndex >= 0; txIndex-- {
80                 tx := b.Transactions[txIndex]
81                 for j := range tx.Outputs {
82                         resOut, err := tx.IntraChainOutput(*tx.ResultIds[j])
83                         if err != nil {
84                                 continue
85                         }
86
87                         if segwit.IsP2WScript(resOut.ControlProgram.Code) {
88                                 batch.Delete(account.StandardUTXOKey(*tx.ResultIds[j]))
89                         } else {
90                                 batch.Delete(account.ContractUTXOKey(*tx.ResultIds[j]))
91                         }
92                 }
93
94                 statusFail, err := txStatus.GetStatus(txIndex)
95                 if err != nil {
96                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("detachUtxos fail on get tx status")
97                         continue
98                 }
99
100                 inputUtxos := txInToUtxos(tx, statusFail)
101                 utxos := w.filterAccountUtxo(inputUtxos)
102                 if err := batchSaveUtxos(utxos, batch); err != nil {
103                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("detachUtxos fail on batchSaveUtxos")
104                         return
105                 }
106         }
107 }
108
109 func (w *Wallet) filterAccountUtxo(utxos []*account.UTXO) []*account.UTXO {
110         outsByScript := make(map[string][]*account.UTXO, len(utxos))
111         for _, utxo := range utxos {
112                 scriptStr := string(utxo.ControlProgram)
113                 outsByScript[scriptStr] = append(outsByScript[scriptStr], utxo)
114         }
115
116         result := make([]*account.UTXO, 0, len(utxos))
117         for s := range outsByScript {
118                 if !segwit.IsP2WScript([]byte(s)) {
119                         for _, utxo := range outsByScript[s] {
120                                 result = append(result, utxo)
121                         }
122                         continue
123                 }
124
125                 var hash [32]byte
126                 sha3pool.Sum256(hash[:], []byte(s))
127                 data := w.DB.Get(account.ContractKey(hash))
128                 if data == nil {
129                         continue
130                 }
131
132                 cp := &account.CtrlProgram{}
133                 if err := json.Unmarshal(data, cp); err != nil {
134                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("filterAccountUtxo fail on unmarshal control program")
135                         continue
136                 }
137
138                 for _, utxo := range outsByScript[s] {
139                         utxo.AccountID = cp.AccountID
140                         utxo.Address = cp.Address
141                         utxo.ControlProgramIndex = cp.KeyIndex
142                         utxo.Change = cp.Change
143                         result = append(result, utxo)
144                 }
145         }
146         return result
147 }
148
149 func batchSaveUtxos(utxos []*account.UTXO, batch dbm.Batch) error {
150         for _, utxo := range utxos {
151                 data, err := json.Marshal(utxo)
152                 if err != nil {
153                         return errors.Wrap(err, "failed marshal accountutxo")
154                 }
155
156                 if segwit.IsP2WScript(utxo.ControlProgram) {
157                         batch.Set(account.StandardUTXOKey(utxo.OutputID), data)
158                 } else {
159                         batch.Set(account.ContractUTXOKey(utxo.OutputID), data)
160                 }
161         }
162         return nil
163 }
164
165 func txInToUtxos(tx *types.Tx, statusFail bool) []*account.UTXO {
166         utxos := []*account.UTXO{}
167         for _, inpID := range tx.Tx.InputIDs {
168                 sp, err := tx.Spend(inpID)
169                 if err != nil {
170                         continue
171                 }
172
173                 resOut, err := tx.IntraChainOutput(*sp.SpentOutputId)
174                 if err != nil {
175                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("txInToUtxos fail on get resOut")
176                         continue
177                 }
178
179                 if statusFail && *resOut.Source.Value.AssetId != *consensus.BTMAssetID {
180                         continue
181                 }
182
183                 utxos = append(utxos, &account.UTXO{
184                         OutputID:       *sp.SpentOutputId,
185                         AssetID:        *resOut.Source.Value.AssetId,
186                         Amount:         resOut.Source.Value.Amount,
187                         ControlProgram: resOut.ControlProgram.Code,
188                         SourceID:       *resOut.Source.Ref,
189                         SourcePos:      resOut.Source.Position,
190                 })
191         }
192         return utxos
193 }
194
195 func txOutToUtxos(tx *types.Tx, statusFail bool, vaildHeight uint64) []*account.UTXO {
196         utxos := []*account.UTXO{}
197         for i, out := range tx.Outputs {
198                 bcOut, err := tx.IntraChainOutput(*tx.ResultIds[i])
199                 if err != nil {
200                         continue
201                 }
202
203                 if statusFail && *out.AssetAmount().AssetId != *consensus.BTMAssetID {
204                         continue
205                 }
206
207                 utxos = append(utxos, &account.UTXO{
208                         OutputID:       *tx.OutputID(i),
209                         AssetID:        *out.AssetAmount().AssetId,
210                         Amount:         out.AssetAmount().Amount,
211                         ControlProgram: out.ControlProgram(),
212                         SourceID:       *bcOut.Source.Ref,
213                         SourcePos:      bcOut.Source.Position,
214                         ValidHeight:    vaildHeight,
215                 })
216         }
217         return utxos
218 }