OSDN Git Service

feat(federation): add address in /list-txs (#224)
[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 )
20
21 // annotateTxs adds asset data to transactions
22 func annotateTxsAsset(w *Wallet, txs []*query.AnnotatedTx) {
23         for i, tx := range txs {
24                 for j, input := range tx.Inputs {
25                         alias, definition := w.getAliasDefinition(input.AssetID)
26                         txs[i].Inputs[j].AssetAlias, txs[i].Inputs[j].AssetDefinition = alias, &definition
27                 }
28                 for k, output := range tx.Outputs {
29                         alias, definition := w.getAliasDefinition(output.AssetID)
30                         txs[i].Outputs[k].AssetAlias, txs[i].Outputs[k].AssetDefinition = alias, &definition
31                 }
32         }
33 }
34
35 func (w *Wallet) getExternalDefinition(assetID *bc.AssetID) json.RawMessage {
36         // definitionByte := w.DB.Get(asset.ExtAssetKey(assetID))
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 (w *Wallet) buildAnnotatedTransaction(orig *types.Tx, b *types.Block, statusFail bool, indexInBlock int) *query.AnnotatedTx {
142         tx := &query.AnnotatedTx{
143                 ID:                     orig.ID,
144                 Timestamp:              b.Timestamp,
145                 BlockID:                b.Hash(),
146                 BlockHeight:            b.Height,
147                 Position:               uint32(indexInBlock),
148                 BlockTransactionsCount: uint32(len(b.Transactions)),
149                 Inputs:                 make([]*query.AnnotatedInput, 0, len(orig.Inputs)),
150                 Outputs:                make([]*query.AnnotatedOutput, 0, len(orig.Outputs)),
151                 StatusFail:             statusFail,
152                 Size:                   orig.SerializedSize,
153         }
154         for i := range orig.Inputs {
155                 tx.Inputs = append(tx.Inputs, w.BuildAnnotatedInput(orig, uint32(i)))
156         }
157         for i := range orig.Outputs {
158                 tx.Outputs = append(tx.Outputs, w.BuildAnnotatedOutput(orig, i))
159         }
160         return tx
161 }
162
163 // BuildAnnotatedInput build the annotated input.
164 func (w *Wallet) BuildAnnotatedInput(tx *types.Tx, i uint32) *query.AnnotatedInput {
165         orig := tx.Inputs[i]
166         in := &query.AnnotatedInput{
167                 AssetDefinition: &emptyJSONObject,
168         }
169         if orig.InputType() != types.CoinbaseInputType {
170                 in.AssetID = orig.AssetID()
171                 in.Amount = orig.Amount()
172         }
173
174         id := tx.Tx.InputIDs[i]
175         in.InputID = id
176         e := tx.Entries[id]
177         switch e := e.(type) {
178         case *bc.VetoInput:
179                 in.Type = "veto"
180                 in.ControlProgram = orig.ControlProgram()
181                 in.Address = w.getAddressFromControlProgram(in.ControlProgram, false)
182                 in.SpentOutputID = e.SpentOutputId
183                 arguments := orig.Arguments()
184                 for _, arg := range arguments {
185                         in.WitnessArguments = append(in.WitnessArguments, arg)
186                 }
187
188         case *bc.CrossChainInput:
189                 in.Type = "cross_chain_in"
190                 in.ControlProgram = orig.ControlProgram()
191                 in.Address = w.getAddressFromControlProgram(in.ControlProgram, true)
192                 in.SpentOutputID = e.MainchainOutputId
193                 arguments := orig.Arguments()
194                 for _, arg := range arguments {
195                         in.WitnessArguments = append(in.WitnessArguments, arg)
196                 }
197
198         case *bc.Spend:
199                 in.Type = "spend"
200                 in.ControlProgram = orig.ControlProgram()
201                 in.Address = w.getAddressFromControlProgram(in.ControlProgram, false)
202                 in.SpentOutputID = e.SpentOutputId
203                 arguments := orig.Arguments()
204                 for _, arg := range arguments {
205                         in.WitnessArguments = append(in.WitnessArguments, arg)
206                 }
207
208         case *bc.Coinbase:
209                 in.Type = "coinbase"
210                 in.Arbitrary = e.Arbitrary
211         }
212         return in
213 }
214
215 func (w *Wallet) getAddressFromControlProgram(prog []byte, isMainchain bool) string {
216         netParams := &consensus.ActiveNetParams
217         if isMainchain {
218                 netParams = &consensus.MainNetParams
219         }
220
221         if segwit.IsP2WPKHScript(prog) {
222                 if pubHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
223                         return BuildP2PKHAddress(pubHash, netParams)
224                 }
225         } else if segwit.IsP2WSHScript(prog) {
226                 if scriptHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
227                         return BuildP2SHAddress(scriptHash, netParams)
228                 }
229         }
230
231         return ""
232 }
233
234 func BuildP2PKHAddress(pubHash []byte, netParams *consensus.Params) string {
235         address, err := common.NewAddressWitnessPubKeyHash(pubHash, netParams)
236         if err != nil {
237                 return ""
238         }
239
240         return address.EncodeAddress()
241 }
242
243 func BuildP2SHAddress(scriptHash []byte, netParams *consensus.Params) string {
244         address, err := common.NewAddressWitnessScriptHash(scriptHash, netParams)
245         if err != nil {
246                 return ""
247         }
248
249         return address.EncodeAddress()
250 }
251
252 // BuildAnnotatedOutput build the annotated output.
253 func (w *Wallet) BuildAnnotatedOutput(tx *types.Tx, idx int) *query.AnnotatedOutput {
254         orig := tx.Outputs[idx]
255         outid := tx.OutputID(idx)
256         out := &query.AnnotatedOutput{
257                 OutputID:        *outid,
258                 Position:        idx,
259                 AssetID:         *orig.AssetAmount().AssetId,
260                 AssetDefinition: &emptyJSONObject,
261                 Amount:          orig.AssetAmount().Amount,
262                 ControlProgram:  orig.ControlProgram(),
263         }
264
265         var isMainchainAddress bool
266         switch e := tx.Entries[*outid].(type) {
267         case *bc.IntraChainOutput:
268                 out.Type = "control"
269                 isMainchainAddress = false
270
271         case *bc.CrossChainOutput:
272                 out.Type = "cross_chain_out"
273                 isMainchainAddress = true
274
275         case *bc.VoteOutput:
276                 out.Type = "vote"
277                 out.Vote = e.Vote
278                 isMainchainAddress = false
279         }
280
281         out.Address = w.getAddressFromControlProgram(orig.ControlProgram(), isMainchainAddress)
282         return out
283 }