OSDN Git Service

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