OSDN Git Service

feat: add build crosschain input (#91)
[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 (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.CrossChainInput:
179                 in.Type = "cross_chain_in"
180                 in.ControlProgram = orig.ControlProgram()
181                 in.Address = w.getAddressFromControlProgram(in.ControlProgram)
182                 in.SpentOutputID = e.MainchainOutputId
183                 arguments := orig.Arguments()
184                 for _, arg := range arguments {
185                         in.WitnessArguments = append(in.WitnessArguments, arg)
186                 }
187
188         case *bc.Spend:
189                 in.Type = "spend"
190                 in.ControlProgram = orig.ControlProgram()
191                 in.Address = w.getAddressFromControlProgram(in.ControlProgram)
192                 in.SpentOutputID = e.SpentOutputId
193                 arguments := orig.Arguments()
194                 for _, arg := range arguments {
195                         in.WitnessArguments = append(in.WitnessArguments, arg)
196                 }
197
198         case *bc.Coinbase:
199                 in.Type = "coinbase"
200                 in.Arbitrary = e.Arbitrary
201         }
202         return in
203 }
204
205 func (w *Wallet) getAddressFromControlProgram(prog []byte) string {
206         if segwit.IsP2WPKHScript(prog) {
207                 if pubHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
208                         return buildP2PKHAddress(pubHash)
209                 }
210         } else if segwit.IsP2WSHScript(prog) {
211                 if scriptHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
212                         return buildP2SHAddress(scriptHash)
213                 }
214         }
215
216         return ""
217 }
218
219 func buildP2PKHAddress(pubHash []byte) string {
220         address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
221         if err != nil {
222                 return ""
223         }
224
225         return address.EncodeAddress()
226 }
227
228 func buildP2SHAddress(scriptHash []byte) string {
229         address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
230         if err != nil {
231                 return ""
232         }
233
234         return address.EncodeAddress()
235 }
236
237 // BuildAnnotatedOutput build the annotated output.
238 func (w *Wallet) BuildAnnotatedOutput(tx *types.Tx, idx int) *query.AnnotatedOutput {
239         orig := tx.Outputs[idx]
240         outid := tx.OutputID(idx)
241         out := &query.AnnotatedOutput{
242                 OutputID:        *outid,
243                 Position:        idx,
244                 AssetID:         *orig.AssetAmount().AssetId,
245                 AssetDefinition: &emptyJSONObject,
246                 Amount:          orig.AssetAmount().Amount,
247                 ControlProgram:  orig.ControlProgram(),
248                 Address:         w.getAddressFromControlProgram(orig.ControlProgram()),
249         }
250
251         if vmutil.IsUnspendable(out.ControlProgram) {
252                 out.Type = "retire"
253         } else {
254                 out.Type = "control"
255         }
256         return out
257 }