OSDN Git Service

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