OSDN Git Service

add cancel vote (#172)
[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.VetoInput:
178                 in.Type = "veto"
179                 in.ControlProgram = orig.ControlProgram()
180                 in.Address = w.getAddressFromControlProgram(in.ControlProgram, false)
181                 in.SpentOutputID = e.SpentOutputId
182                 arguments := orig.Arguments()
183                 for _, arg := range arguments {
184                         in.WitnessArguments = append(in.WitnessArguments, arg)
185                 }
186
187         case *bc.CrossChainInput:
188                 in.Type = "cross_chain_in"
189                 in.ControlProgram = orig.ControlProgram()
190                 in.Address = w.getAddressFromControlProgram(in.ControlProgram, true)
191                 in.SpentOutputID = e.MainchainOutputId
192                 arguments := orig.Arguments()
193                 for _, arg := range arguments {
194                         in.WitnessArguments = append(in.WitnessArguments, arg)
195                 }
196
197         case *bc.Spend:
198                 in.Type = "spend"
199                 in.ControlProgram = orig.ControlProgram()
200                 in.Address = w.getAddressFromControlProgram(in.ControlProgram, false)
201                 in.SpentOutputID = e.SpentOutputId
202                 arguments := orig.Arguments()
203                 for _, arg := range arguments {
204                         in.WitnessArguments = append(in.WitnessArguments, arg)
205                 }
206
207         case *bc.Coinbase:
208                 in.Type = "coinbase"
209                 in.Arbitrary = e.Arbitrary
210         }
211         return in
212 }
213
214 func (w *Wallet) getAddressFromControlProgram(prog []byte, isMainchain bool) string {
215         netParams := &consensus.ActiveNetParams
216         if isMainchain {
217                 netParams = &consensus.MainNetParams
218         }
219
220         if segwit.IsP2WPKHScript(prog) {
221                 if pubHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
222                         return buildP2PKHAddress(pubHash, netParams)
223                 }
224         } else if segwit.IsP2WSHScript(prog) {
225                 if scriptHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
226                         return buildP2SHAddress(scriptHash, netParams)
227                 }
228         }
229
230         return ""
231 }
232
233 func buildP2PKHAddress(pubHash []byte, netParams *consensus.Params) string {
234         address, err := common.NewAddressWitnessPubKeyHash(pubHash, netParams)
235         if err != nil {
236                 return ""
237         }
238
239         return address.EncodeAddress()
240 }
241
242 func buildP2SHAddress(scriptHash []byte, netParams *consensus.Params) string {
243         address, err := common.NewAddressWitnessScriptHash(scriptHash, netParams)
244         if err != nil {
245                 return ""
246         }
247
248         return address.EncodeAddress()
249 }
250
251 // BuildAnnotatedOutput build the annotated output.
252 func (w *Wallet) BuildAnnotatedOutput(tx *types.Tx, idx int) *query.AnnotatedOutput {
253         orig := tx.Outputs[idx]
254         outid := tx.OutputID(idx)
255         out := &query.AnnotatedOutput{
256                 OutputID:        *outid,
257                 Position:        idx,
258                 AssetID:         *orig.AssetAmount().AssetId,
259                 AssetDefinition: &emptyJSONObject,
260                 Amount:          orig.AssetAmount().Amount,
261                 ControlProgram:  orig.ControlProgram(),
262         }
263
264         var isMainchainAddress bool
265         switch e := tx.Entries[*outid].(type) {
266         case *bc.IntraChainOutput:
267                 out.Type = "control"
268                 isMainchainAddress = false
269
270         case *bc.CrossChainOutput:
271                 out.Type = "cross_chain_out"
272                 isMainchainAddress = true
273
274         case *bc.VoteOutput:
275                 out.Type = "vote"
276                 out.Vote = e.Vote
277                 isMainchainAddress = false
278         }
279
280         out.Address = w.getAddressFromControlProgram(orig.ControlProgram(), isMainchainAddress)
281         return out
282 }