OSDN Git Service

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