OSDN Git Service

dispatch signature when proccess block (#85)
[bytom/vapor.git] / wallet / annotated.go
1 package wallet
2
3 import (
4         "encoding/json"
5         "fmt"
6
7         log "github.com/sirupsen/logrus"
8
9         "github.com/vapor/account"
10         "github.com/vapor/asset"
11         "github.com/vapor/blockchain/query"
12         "github.com/vapor/common"
13         "github.com/vapor/consensus"
14         "github.com/vapor/consensus/segwit"
15         "github.com/vapor/crypto/sha3pool"
16         dbm "github.com/vapor/database/leveldb"
17         "github.com/vapor/protocol/bc"
18         "github.com/vapor/protocol/bc/types"
19         "github.com/vapor/protocol/vm/vmutil"
20 )
21
22 // annotateTxs adds asset data to transactions
23 func annotateTxsAsset(w *Wallet, txs []*query.AnnotatedTx) {
24         for i, tx := range txs {
25                 for j, input := range tx.Inputs {
26                         alias, definition := w.getAliasDefinition(input.AssetID)
27                         txs[i].Inputs[j].AssetAlias, txs[i].Inputs[j].AssetDefinition = alias, &definition
28                 }
29                 for k, output := range tx.Outputs {
30                         alias, definition := w.getAliasDefinition(output.AssetID)
31                         txs[i].Outputs[k].AssetAlias, txs[i].Outputs[k].AssetDefinition = alias, &definition
32                 }
33         }
34 }
35
36 func (w *Wallet) getExternalDefinition(assetID *bc.AssetID) json.RawMessage {
37         definitionByte := w.DB.Get(asset.ExtAssetKey(assetID))
38         if definitionByte == nil {
39                 return nil
40         }
41
42         definitionMap := make(map[string]interface{})
43         if err := json.Unmarshal(definitionByte, &definitionMap); err != nil {
44                 return nil
45         }
46
47         alias := assetID.String()
48         externalAsset := &asset.Asset{
49                 AssetID:           *assetID,
50                 Alias:             &alias,
51                 DefinitionMap:     definitionMap,
52                 RawDefinitionByte: definitionByte,
53         }
54
55         if err := w.AssetReg.SaveAsset(externalAsset, alias); err != nil {
56                 log.WithFields(log.Fields{"module": logModule, "err": err, "assetID": alias}).Warning("fail on save external asset to internal asset DB")
57         }
58         return definitionByte
59 }
60
61 func (w *Wallet) getAliasDefinition(assetID bc.AssetID) (string, json.RawMessage) {
62         //btm
63         if assetID.String() == consensus.BTMAssetID.String() {
64                 alias := consensus.BTMAlias
65                 definition := []byte(asset.DefaultNativeAsset.RawDefinitionByte)
66
67                 return alias, definition
68         }
69
70         //local asset and saved external asset
71         if localAsset, err := w.AssetReg.FindByID(nil, &assetID); err == nil {
72                 alias := *localAsset.Alias
73                 definition := []byte(localAsset.RawDefinitionByte)
74                 return alias, definition
75         }
76
77         //external asset
78         if definition := w.getExternalDefinition(&assetID); definition != nil {
79                 return assetID.String(), definition
80         }
81
82         return "", nil
83 }
84
85 // annotateTxs adds account data to transactions
86 func annotateTxsAccount(txs []*query.AnnotatedTx, walletDB dbm.DB) {
87         for i, tx := range txs {
88                 for j, input := range tx.Inputs {
89                         //issue asset tx input SpentOutputID is nil
90                         if input.SpentOutputID == nil {
91                                 continue
92                         }
93                         localAccount, err := getAccountFromACP(input.ControlProgram, walletDB)
94                         if localAccount == nil || err != nil {
95                                 continue
96                         }
97                         txs[i].Inputs[j].AccountAlias = localAccount.Alias
98                         txs[i].Inputs[j].AccountID = localAccount.ID
99                 }
100                 for j, output := range tx.Outputs {
101                         localAccount, err := getAccountFromACP(output.ControlProgram, walletDB)
102                         if localAccount == nil || err != nil {
103                                 continue
104                         }
105                         txs[i].Outputs[j].AccountAlias = localAccount.Alias
106                         txs[i].Outputs[j].AccountID = localAccount.ID
107                 }
108         }
109 }
110
111 func getAccountFromACP(program []byte, walletDB dbm.DB) (*account.Account, error) {
112         var hash common.Hash
113         accountCP := account.CtrlProgram{}
114         localAccount := account.Account{}
115
116         sha3pool.Sum256(hash[:], program)
117
118         rawProgram := walletDB.Get(account.ContractKey(hash))
119         if rawProgram == nil {
120                 return nil, fmt.Errorf("failed get account control program:%x ", hash)
121         }
122
123         if err := json.Unmarshal(rawProgram, &accountCP); err != nil {
124                 return nil, err
125         }
126
127         accountValue := walletDB.Get(account.Key(accountCP.AccountID))
128         if accountValue == nil {
129                 return nil, fmt.Errorf("failed get account:%s ", accountCP.AccountID)
130         }
131
132         if err := json.Unmarshal(accountValue, &localAccount); err != nil {
133                 return nil, err
134         }
135
136         return &localAccount, nil
137 }
138
139 var emptyJSONObject = json.RawMessage(`{}`)
140
141 func isValidJSON(b []byte) bool {
142         var v interface{}
143         err := json.Unmarshal(b, &v)
144         return err == nil
145 }
146
147 func (w *Wallet) buildAnnotatedTransaction(orig *types.Tx, b *types.Block, statusFail bool, indexInBlock int) *query.AnnotatedTx {
148         tx := &query.AnnotatedTx{
149                 ID:                     orig.ID,
150                 Timestamp:              b.Timestamp,
151                 BlockID:                b.Hash(),
152                 BlockHeight:            b.Height,
153                 Position:               uint32(indexInBlock),
154                 BlockTransactionsCount: uint32(len(b.Transactions)),
155                 Inputs:                 make([]*query.AnnotatedInput, 0, len(orig.Inputs)),
156                 Outputs:                make([]*query.AnnotatedOutput, 0, len(orig.Outputs)),
157                 StatusFail:             statusFail,
158                 Size:                   orig.SerializedSize,
159         }
160         for i := range orig.Inputs {
161                 tx.Inputs = append(tx.Inputs, w.BuildAnnotatedInput(orig, uint32(i)))
162         }
163         for i := range orig.Outputs {
164                 tx.Outputs = append(tx.Outputs, w.BuildAnnotatedOutput(orig, i))
165         }
166         return tx
167 }
168
169 // BuildAnnotatedInput build the annotated input.
170 func (w *Wallet) BuildAnnotatedInput(tx *types.Tx, i uint32) *query.AnnotatedInput {
171         orig := tx.Inputs[i]
172         in := &query.AnnotatedInput{
173                 AssetDefinition: &emptyJSONObject,
174         }
175         if orig.InputType() != types.CoinbaseInputType {
176                 in.AssetID = orig.AssetID()
177                 in.Amount = orig.Amount()
178         }
179
180         id := tx.Tx.InputIDs[i]
181         in.InputID = id
182         e := tx.Entries[id]
183         switch e := e.(type) {
184         case *bc.Spend:
185                 in.Type = "spend"
186                 in.ControlProgram = orig.ControlProgram()
187                 in.Address = w.getAddressFromControlProgram(in.ControlProgram)
188                 in.SpentOutputID = e.SpentOutputId
189                 arguments := orig.Arguments()
190                 for _, arg := range arguments {
191                         in.WitnessArguments = append(in.WitnessArguments, arg)
192                 }
193         case *bc.Coinbase:
194                 in.Type = "coinbase"
195                 in.Arbitrary = e.Arbitrary
196         }
197         return in
198 }
199
200 func (w *Wallet) getAddressFromControlProgram(prog []byte) string {
201         if segwit.IsP2WPKHScript(prog) {
202                 if pubHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
203                         return buildP2PKHAddress(pubHash)
204                 }
205         } else if segwit.IsP2WSHScript(prog) {
206                 if scriptHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
207                         return buildP2SHAddress(scriptHash)
208                 }
209         }
210
211         return ""
212 }
213
214 func buildP2PKHAddress(pubHash []byte) string {
215         address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
216         if err != nil {
217                 return ""
218         }
219
220         return address.EncodeAddress()
221 }
222
223 func buildP2SHAddress(scriptHash []byte) string {
224         address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
225         if err != nil {
226                 return ""
227         }
228
229         return address.EncodeAddress()
230 }
231
232 // BuildAnnotatedOutput build the annotated output.
233 func (w *Wallet) BuildAnnotatedOutput(tx *types.Tx, idx int) *query.AnnotatedOutput {
234         orig := tx.Outputs[idx]
235         outid := tx.OutputID(idx)
236         out := &query.AnnotatedOutput{
237                 OutputID:        *outid,
238                 Position:        idx,
239                 AssetID:         *orig.AssetAmount().AssetId,
240                 AssetDefinition: &emptyJSONObject,
241                 Amount:          orig.AssetAmount().Amount,
242                 ControlProgram:  orig.ControlProgram(),
243                 Address:         w.getAddressFromControlProgram(orig.ControlProgram()),
244         }
245
246         if vmutil.IsUnspendable(out.ControlProgram) {
247                 out.Type = "retire"
248         } else {
249                 out.Type = "control"
250         }
251         return out
252 }