OSDN Git Service

fix: use mainchain address for cross_chain_out (#131)
[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         if definitionByte == nil {
38                 return nil
39         }
40
41         definitionMap := make(map[string]interface{})
42         if err := json.Unmarshal(definitionByte, &definitionMap); err != nil {
43                 return nil
44         }
45
46         alias := assetID.String()
47         externalAsset := &asset.Asset{
48                 AssetID:           *assetID,
49                 Alias:             &alias,
50                 DefinitionMap:     definitionMap,
51                 RawDefinitionByte: definitionByte,
52         }
53
54         if err := w.AssetReg.SaveAsset(externalAsset, alias); err != nil {
55                 log.WithFields(log.Fields{"module": logModule, "err": err, "assetID": alias}).Warning("fail on save external asset to internal asset DB")
56         }
57         return definitionByte
58 }
59
60 func (w *Wallet) getAliasDefinition(assetID bc.AssetID) (string, json.RawMessage) {
61         //btm
62         if assetID.String() == consensus.BTMAssetID.String() {
63                 alias := consensus.BTMAlias
64                 definition := []byte(asset.DefaultNativeAsset.RawDefinitionByte)
65
66                 return alias, definition
67         }
68
69         //local asset and saved external asset
70         if localAsset, err := w.AssetReg.FindByID(nil, &assetID); err == nil {
71                 alias := *localAsset.Alias
72                 definition := []byte(localAsset.RawDefinitionByte)
73                 return alias, definition
74         }
75
76         //external asset
77         if definition := w.getExternalDefinition(&assetID); definition != nil {
78                 return assetID.String(), definition
79         }
80
81         return "", nil
82 }
83
84 // annotateTxs adds account data to transactions
85 func annotateTxsAccount(txs []*query.AnnotatedTx, walletDB dbm.DB) {
86         for i, tx := range txs {
87                 for j, input := range tx.Inputs {
88                         //issue asset tx input SpentOutputID is nil
89                         if input.SpentOutputID == nil {
90                                 continue
91                         }
92                         localAccount, err := getAccountFromACP(input.ControlProgram, walletDB)
93                         if localAccount == nil || err != nil {
94                                 continue
95                         }
96                         txs[i].Inputs[j].AccountAlias = localAccount.Alias
97                         txs[i].Inputs[j].AccountID = localAccount.ID
98                 }
99                 for j, output := range tx.Outputs {
100                         localAccount, err := getAccountFromACP(output.ControlProgram, walletDB)
101                         if localAccount == nil || err != nil {
102                                 continue
103                         }
104                         txs[i].Outputs[j].AccountAlias = localAccount.Alias
105                         txs[i].Outputs[j].AccountID = localAccount.ID
106                 }
107         }
108 }
109
110 func getAccountFromACP(program []byte, walletDB dbm.DB) (*account.Account, error) {
111         var hash common.Hash
112         accountCP := account.CtrlProgram{}
113         localAccount := account.Account{}
114
115         sha3pool.Sum256(hash[:], program)
116
117         rawProgram := walletDB.Get(account.ContractKey(hash))
118         if rawProgram == nil {
119                 return nil, fmt.Errorf("failed get account control program:%x ", hash)
120         }
121
122         if err := json.Unmarshal(rawProgram, &accountCP); err != nil {
123                 return nil, err
124         }
125
126         accountValue := walletDB.Get(account.Key(accountCP.AccountID))
127         if accountValue == nil {
128                 return nil, fmt.Errorf("failed get account:%s ", accountCP.AccountID)
129         }
130
131         if err := json.Unmarshal(accountValue, &localAccount); err != nil {
132                 return nil, err
133         }
134
135         return &localAccount, nil
136 }
137
138 var emptyJSONObject = json.RawMessage(`{}`)
139
140 func (w *Wallet) buildAnnotatedTransaction(orig *types.Tx, b *types.Block, statusFail bool, indexInBlock int) *query.AnnotatedTx {
141         tx := &query.AnnotatedTx{
142                 ID:                     orig.ID,
143                 Timestamp:              b.Timestamp,
144                 BlockID:                b.Hash(),
145                 BlockHeight:            b.Height,
146                 Position:               uint32(indexInBlock),
147                 BlockTransactionsCount: uint32(len(b.Transactions)),
148                 Inputs:                 make([]*query.AnnotatedInput, 0, len(orig.Inputs)),
149                 Outputs:                make([]*query.AnnotatedOutput, 0, len(orig.Outputs)),
150                 StatusFail:             statusFail,
151                 Size:                   orig.SerializedSize,
152         }
153         for i := range orig.Inputs {
154                 tx.Inputs = append(tx.Inputs, w.BuildAnnotatedInput(orig, uint32(i)))
155         }
156         for i := range orig.Outputs {
157                 tx.Outputs = append(tx.Outputs, w.BuildAnnotatedOutput(orig, i))
158         }
159         return tx
160 }
161
162 // BuildAnnotatedInput build the annotated input.
163 func (w *Wallet) BuildAnnotatedInput(tx *types.Tx, i uint32) *query.AnnotatedInput {
164         orig := tx.Inputs[i]
165         in := &query.AnnotatedInput{
166                 AssetDefinition: &emptyJSONObject,
167         }
168         if orig.InputType() != types.CoinbaseInputType {
169                 in.AssetID = orig.AssetID()
170                 in.Amount = orig.Amount()
171         }
172
173         id := tx.Tx.InputIDs[i]
174         in.InputID = id
175         e := tx.Entries[id]
176         switch e := e.(type) {
177         case *bc.CrossChainInput:
178                 in.Type = "cross_chain_in"
179                 in.ControlProgram = orig.ControlProgram()
180                 in.Address = w.getAddressFromControlProgram(in.ControlProgram, true)
181                 in.SpentOutputID = e.MainchainOutputId
182                 arguments := orig.Arguments()
183                 for _, arg := range arguments {
184                         in.WitnessArguments = append(in.WitnessArguments, arg)
185                 }
186
187         case *bc.Spend:
188                 in.Type = "spend"
189                 in.ControlProgram = orig.ControlProgram()
190                 in.Address = w.getAddressFromControlProgram(in.ControlProgram, false)
191                 in.SpentOutputID = e.SpentOutputId
192                 arguments := orig.Arguments()
193                 for _, arg := range arguments {
194                         in.WitnessArguments = append(in.WitnessArguments, arg)
195                 }
196
197         case *bc.Coinbase:
198                 in.Type = "coinbase"
199                 in.Arbitrary = e.Arbitrary
200         }
201         return in
202 }
203
204 func (w *Wallet) getAddressFromControlProgram(prog []byte, isMainchain bool) string {
205         netParams := &consensus.ActiveNetParams
206         if isMainchain {
207                 netParams = &consensus.MainNetParams
208         }
209
210         if segwit.IsP2WPKHScript(prog) {
211                 if pubHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
212                         return buildP2PKHAddress(pubHash, netParams)
213                 }
214         } else if segwit.IsP2WSHScript(prog) {
215                 if scriptHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
216                         return buildP2SHAddress(scriptHash, netParams)
217                 }
218         }
219
220         return ""
221 }
222
223 func buildP2PKHAddress(pubHash []byte, netParams *consensus.Params) string {
224         address, err := common.NewAddressWitnessPubKeyHash(pubHash, netParams)
225         if err != nil {
226                 return ""
227         }
228
229         return address.EncodeAddress()
230 }
231
232 func buildP2SHAddress(scriptHash []byte, netParams *consensus.Params) string {
233         address, err := common.NewAddressWitnessScriptHash(scriptHash, netParams)
234         if err != nil {
235                 return ""
236         }
237
238         return address.EncodeAddress()
239 }
240
241 // BuildAnnotatedOutput build the annotated output.
242 func (w *Wallet) BuildAnnotatedOutput(tx *types.Tx, idx int) *query.AnnotatedOutput {
243         orig := tx.Outputs[idx]
244         outid := tx.OutputID(idx)
245         out := &query.AnnotatedOutput{
246                 OutputID:        *outid,
247                 Position:        idx,
248                 AssetID:         *orig.AssetAmount().AssetId,
249                 AssetDefinition: &emptyJSONObject,
250                 Amount:          orig.AssetAmount().Amount,
251                 ControlProgram:  orig.ControlProgram(),
252         }
253
254         var isMainchainAddress bool
255         switch e := tx.Entries[*outid].(type) {
256         case *bc.IntraChainOutput:
257                 out.Type = "control"
258                 isMainchainAddress = false
259
260         case *bc.CrossChainOutput:
261                 out.Type = "cross_chain_out"
262                 isMainchainAddress = true
263
264         case *bc.VoteOutput:
265                 out.Type = "vote"
266                 out.Vote = e.Vote
267                 isMainchainAddress = false
268         }
269
270         out.Address = w.getAddressFromControlProgram(orig.ControlProgram(), isMainchainAddress)
271         return out
272 }