OSDN Git Service

491d98cfa4da293b2be3517231ebb9d7f027d48f
[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, vote 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 vote && accountUtxo.Vote == nil {
41                         continue
42                 }
43
44                 if accountID == accountUtxo.AccountID || accountID == "" {
45                         accountUtxos = append(accountUtxos, accountUtxo)
46                 }
47         }
48         return accountUtxos
49 }
50
51 func (w *Wallet) attachUtxos(batch dbm.Batch, b *types.Block, txStatus *bc.TransactionStatus) {
52         for txIndex, tx := range b.Transactions {
53                 statusFail, err := txStatus.GetStatus(txIndex)
54                 if err != nil {
55                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("attachUtxos fail on get tx status")
56                         continue
57                 }
58
59                 //hand update the transaction input utxos
60                 inputUtxos := txInToUtxos(tx, statusFail)
61                 for _, inputUtxo := range inputUtxos {
62                         if segwit.IsP2WScript(inputUtxo.ControlProgram) {
63                                 batch.Delete(account.StandardUTXOKey(inputUtxo.OutputID))
64                         } else {
65                                 batch.Delete(account.ContractUTXOKey(inputUtxo.OutputID))
66                         }
67                 }
68
69                 //hand update the transaction output utxos
70                 validHeight := uint64(0)
71                 if txIndex == 0 {
72                         validHeight = b.Height + consensus.CoinbasePendingBlockNumber
73                 }
74                 outputUtxos := txOutToUtxos(tx, statusFail, validHeight)
75                 utxos := w.filterAccountUtxo(outputUtxos)
76                 if err := batchSaveUtxos(utxos, batch); err != nil {
77                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("attachUtxos fail on batchSaveUtxos")
78                 }
79         }
80 }
81
82 func (w *Wallet) detachUtxos(batch dbm.Batch, b *types.Block, txStatus *bc.TransactionStatus) {
83         for txIndex := len(b.Transactions) - 1; txIndex >= 0; txIndex-- {
84                 tx := b.Transactions[txIndex]
85                 for j := range tx.Outputs {
86                         code := []byte{}
87                         switch resOut := tx.Entries[*tx.ResultIds[j]].(type) {
88                         case *bc.IntraChainOutput:
89                                 code = resOut.ControlProgram.Code
90                         case *bc.VoteOutput:
91                                 code = resOut.ControlProgram.Code
92                         default:
93                                 continue
94                         }
95
96                         if segwit.IsP2WScript(code) {
97                                 batch.Delete(account.StandardUTXOKey(*tx.ResultIds[j]))
98                         } else {
99                                 batch.Delete(account.ContractUTXOKey(*tx.ResultIds[j]))
100                         }
101                 }
102
103                 statusFail, err := txStatus.GetStatus(txIndex)
104                 if err != nil {
105                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("detachUtxos fail on get tx status")
106                         continue
107                 }
108
109                 inputUtxos := txInToUtxos(tx, statusFail)
110                 utxos := w.filterAccountUtxo(inputUtxos)
111                 if err := batchSaveUtxos(utxos, batch); err != nil {
112                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("detachUtxos fail on batchSaveUtxos")
113                         return
114                 }
115         }
116 }
117
118 func (w *Wallet) filterAccountUtxo(utxos []*account.UTXO) []*account.UTXO {
119         outsByScript := make(map[string][]*account.UTXO, len(utxos))
120         for _, utxo := range utxos {
121                 scriptStr := string(utxo.ControlProgram)
122                 outsByScript[scriptStr] = append(outsByScript[scriptStr], utxo)
123         }
124
125         result := make([]*account.UTXO, 0, len(utxos))
126         for s := range outsByScript {
127                 if !segwit.IsP2WScript([]byte(s)) {
128                         for _, utxo := range outsByScript[s] {
129                                 result = append(result, utxo)
130                         }
131                         continue
132                 }
133
134                 var hash [32]byte
135                 sha3pool.Sum256(hash[:], []byte(s))
136                 data := w.DB.Get(account.ContractKey(hash))
137                 if data == nil {
138                         continue
139                 }
140
141                 cp := &account.CtrlProgram{}
142                 if err := json.Unmarshal(data, cp); err != nil {
143                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("filterAccountUtxo fail on unmarshal control program")
144                         continue
145                 }
146
147                 for _, utxo := range outsByScript[s] {
148                         utxo.AccountID = cp.AccountID
149                         utxo.Address = cp.Address
150                         utxo.ControlProgramIndex = cp.KeyIndex
151                         utxo.Change = cp.Change
152                         result = append(result, utxo)
153                 }
154         }
155         return result
156 }
157
158 func batchSaveUtxos(utxos []*account.UTXO, batch dbm.Batch) error {
159         for _, utxo := range utxos {
160                 data, err := json.Marshal(utxo)
161                 if err != nil {
162                         return errors.Wrap(err, "failed marshal accountutxo")
163                 }
164
165                 if segwit.IsP2WScript(utxo.ControlProgram) {
166                         batch.Set(account.StandardUTXOKey(utxo.OutputID), data)
167                 } else {
168                         batch.Set(account.ContractUTXOKey(utxo.OutputID), data)
169                 }
170         }
171         return nil
172 }
173
174 func txInToUtxos(tx *types.Tx, statusFail bool) []*account.UTXO {
175         utxos := []*account.UTXO{}
176         for _, inpID := range tx.Tx.InputIDs {
177
178                 e, err := tx.Entry(inpID)
179                 if err != nil {
180                         continue
181                 }
182                 utxo := &account.UTXO{}
183                 switch inp := e.(type) {
184                 case *bc.Spend:
185                         resOut, err := tx.IntraChainOutput(*inp.SpentOutputId)
186                         if err != nil {
187                                 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("txInToUtxos fail on get resOut for spedn")
188                                 continue
189                         }
190                         if statusFail && *resOut.Source.Value.AssetId != *consensus.BTMAssetID {
191                                 continue
192                         }
193                         utxo = &account.UTXO{
194                                 OutputID:       *inp.SpentOutputId,
195                                 AssetID:        *resOut.Source.Value.AssetId,
196                                 Amount:         resOut.Source.Value.Amount,
197                                 ControlProgram: resOut.ControlProgram.Code,
198                                 SourceID:       *resOut.Source.Ref,
199                                 SourcePos:      resOut.Source.Position,
200                         }
201                 case *bc.VetoInput:
202                         resOut, err := tx.VoteOutput(*inp.SpentOutputId)
203                         if err != nil {
204                                 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("txInToUtxos fail on get resOut for vetoInput")
205                                 continue
206                         }
207                         if statusFail && *resOut.Source.Value.AssetId != *consensus.BTMAssetID {
208                                 continue
209                         }
210                         utxo = &account.UTXO{
211                                 OutputID:       *inp.SpentOutputId,
212                                 AssetID:        *resOut.Source.Value.AssetId,
213                                 Amount:         resOut.Source.Value.Amount,
214                                 ControlProgram: resOut.ControlProgram.Code,
215                                 SourceID:       *resOut.Source.Ref,
216                                 SourcePos:      resOut.Source.Position,
217                                 Vote:           resOut.Vote,
218                         }
219                 default:
220                         log.WithFields(log.Fields{"module": logModule, "err": errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", inpID.Bytes(), e)}).Error("txInToUtxos fail on get resOut")
221                         continue
222                 }
223                 utxos = append(utxos, utxo)
224         }
225         return utxos
226 }
227
228 func txOutToUtxos(tx *types.Tx, statusFail bool, vaildHeight uint64) []*account.UTXO {
229         utxos := []*account.UTXO{}
230         for i, out := range tx.Outputs {
231                 entryOutput, err := tx.Entry(*tx.ResultIds[i])
232                 if err != nil {
233                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("txOutToUtxos fail on get entryOutput")
234                         continue
235                 }
236
237                 utxo := &account.UTXO{}
238                 switch bcOut := entryOutput.(type) {
239                 case *bc.IntraChainOutput:
240                         if statusFail && *out.AssetAmount().AssetId != *consensus.BTMAssetID {
241                                 continue
242                         }
243                         utxo = &account.UTXO{
244                                 OutputID:       *tx.OutputID(i),
245                                 AssetID:        *out.AssetAmount().AssetId,
246                                 Amount:         out.AssetAmount().Amount,
247                                 ControlProgram: out.ControlProgram(),
248                                 SourceID:       *bcOut.Source.Ref,
249                                 SourcePos:      bcOut.Source.Position,
250                                 ValidHeight:    vaildHeight,
251                         }
252
253                 case *bc.VoteOutput:
254                         if statusFail && *out.AssetAmount().AssetId != *consensus.BTMAssetID {
255                                 continue
256                         }
257                         utxo = &account.UTXO{
258                                 OutputID:       *tx.OutputID(i),
259                                 AssetID:        *out.AssetAmount().AssetId,
260                                 Amount:         out.AssetAmount().Amount,
261                                 ControlProgram: out.ControlProgram(),
262                                 SourceID:       *bcOut.Source.Ref,
263                                 SourcePos:      bcOut.Source.Position,
264                                 ValidHeight:    vaildHeight,
265                                 Vote:           bcOut.Vote,
266                         }
267
268                 default:
269                         log.WithFields(log.Fields{"module": logModule}).Warn("txOutToUtxos fail on get bcOut")
270                         continue
271                 }
272
273                 utxos = append(utxos, utxo)
274         }
275         return utxos
276 }