OSDN Git Service

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