OSDN Git Service

e1373f529215e7259824d9d629173ad3c916dfd9
[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                 sp, err := tx.Spend(inpID)
178                 if err != nil {
179                         continue
180                 }
181
182                 entryOutput, err := tx.Entry(*sp.SpentOutputId)
183                 if err != nil {
184                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("txInToUtxos fail on get entryOutput")
185                         continue
186                 }
187
188                 utxo := &account.UTXO{}
189                 switch resOut := entryOutput.(type) {
190                 case *bc.IntraChainOutput:
191                         if statusFail && *resOut.Source.Value.AssetId != *consensus.BTMAssetID {
192                                 continue
193                         }
194                         utxo = &account.UTXO{
195                                 OutputID:       *sp.SpentOutputId,
196                                 AssetID:        *resOut.Source.Value.AssetId,
197                                 Amount:         resOut.Source.Value.Amount,
198                                 ControlProgram: resOut.ControlProgram.Code,
199                                 SourceID:       *resOut.Source.Ref,
200                                 SourcePos:      resOut.Source.Position,
201                         }
202
203                 case *bc.VoteOutput:
204                         if statusFail && *resOut.Source.Value.AssetId != *consensus.BTMAssetID {
205                                 continue
206                         }
207                         utxo = &account.UTXO{
208                                 OutputID:       *sp.SpentOutputId,
209                                 AssetID:        *resOut.Source.Value.AssetId,
210                                 Amount:         resOut.Source.Value.Amount,
211                                 ControlProgram: resOut.ControlProgram.Code,
212                                 SourceID:       *resOut.Source.Ref,
213                                 SourcePos:      resOut.Source.Position,
214                                 Vote:           resOut.Vote,
215                         }
216
217                 default:
218                         log.WithFields(log.Fields{"module": logModule}).Error("txInToUtxos fail on get resOut")
219                         continue
220                 }
221
222                 utxos = append(utxos, utxo)
223         }
224         return utxos
225 }
226
227 func txOutToUtxos(tx *types.Tx, statusFail bool, vaildHeight uint64) []*account.UTXO {
228         utxos := []*account.UTXO{}
229         for i, out := range tx.Outputs {
230                 entryOutput, err := tx.Entry(*tx.ResultIds[i])
231                 if err != nil {
232                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("txOutToUtxos fail on get entryOutput")
233                         continue
234                 }
235
236                 utxo := &account.UTXO{}
237                 switch bcOut := entryOutput.(type) {
238                 case *bc.IntraChainOutput:
239                         if statusFail && *out.AssetAmount().AssetId != *consensus.BTMAssetID {
240                                 continue
241                         }
242                         utxo = &account.UTXO{
243                                 OutputID:       *tx.OutputID(i),
244                                 AssetID:        *out.AssetAmount().AssetId,
245                                 Amount:         out.AssetAmount().Amount,
246                                 ControlProgram: out.ControlProgram(),
247                                 SourceID:       *bcOut.Source.Ref,
248                                 SourcePos:      bcOut.Source.Position,
249                                 ValidHeight:    vaildHeight,
250                         }
251
252                 case *bc.VoteOutput:
253                         if statusFail && *out.AssetAmount().AssetId != *consensus.BTMAssetID {
254                                 continue
255                         }
256                         utxo = &account.UTXO{
257                                 OutputID:       *tx.OutputID(i),
258                                 AssetID:        *out.AssetAmount().AssetId,
259                                 Amount:         out.AssetAmount().Amount,
260                                 ControlProgram: out.ControlProgram(),
261                                 SourceID:       *bcOut.Source.Ref,
262                                 SourcePos:      bcOut.Source.Position,
263                                 ValidHeight:    vaildHeight,
264                                 Vote:           bcOut.Vote,
265                         }
266
267                 default:
268                         log.WithFields(log.Fields{"module": logModule}).Warn("txOutToUtxos fail on get bcOut")
269                         continue
270                 }
271
272                 utxos = append(utxos, utxo)
273         }
274         return utxos
275 }