OSDN Git Service

set password and show tx output address (#591)
[bytom/bytom.git] / wallet / annotated.go
1 package wallet
2
3 import (
4         "encoding/json"
5         "fmt"
6
7         log "github.com/sirupsen/logrus"
8         "github.com/tendermint/tmlibs/db"
9
10         "github.com/bytom/account"
11         "github.com/bytom/asset"
12         "github.com/bytom/blockchain/query"
13         "github.com/bytom/blockchain/signers"
14         "github.com/bytom/common"
15         "github.com/bytom/consensus"
16         "github.com/bytom/consensus/segwit"
17         "github.com/bytom/crypto/sha3pool"
18         "github.com/bytom/protocol/bc"
19         "github.com/bytom/protocol/bc/types"
20         "github.com/bytom/protocol/vm/vmutil"
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.CalcExtAssetKey(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         saveAlias := assetID.String()
49         storeBatch := w.DB.NewBatch()
50
51         externalAsset := &asset.Asset{AssetID: *assetID, Alias: &saveAlias, DefinitionMap: definitionMap, Signer: &signers.Signer{Type: "external"}}
52         if rawAsset, err := json.Marshal(externalAsset); err == nil {
53                 log.WithFields(log.Fields{"assetID": assetID.String(), "alias": saveAlias}).Info("index external asset")
54                 storeBatch.Set(asset.Key(assetID), rawAsset)
55         }
56         storeBatch.Set(asset.AliasKey(saveAlias), []byte(assetID.String()))
57         storeBatch.Write()
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 db.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 := getAccountFromUTXO(*input.SpentOutputID, 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 getAccountFromUTXO(outputID bc.Hash, walletDB db.DB) (*account.Account, error) {
113         accountUTXO := account.UTXO{}
114         localAccount := account.Account{}
115
116         accountUTXOValue := walletDB.Get(account.StandardUTXOKey(outputID))
117         if accountUTXOValue == nil {
118                 return nil, fmt.Errorf("failed get account utxo:%x ", outputID)
119         }
120
121         if err := json.Unmarshal(accountUTXOValue, &accountUTXO); err != nil {
122                 return nil, err
123         }
124
125         accountValue := walletDB.Get(account.Key(accountUTXO.AccountID))
126         if accountValue == nil {
127                 return nil, fmt.Errorf("failed get account:%s ", accountUTXO.AccountID)
128         }
129         if err := json.Unmarshal(accountValue, &localAccount); err != nil {
130                 return nil, err
131         }
132
133         return &localAccount, nil
134 }
135
136 func getAccountFromACP(program []byte, walletDB db.DB) (*account.Account, error) {
137         var hash common.Hash
138         accountCP := account.CtrlProgram{}
139         localAccount := account.Account{}
140
141         sha3pool.Sum256(hash[:], program)
142
143         rawProgram := walletDB.Get(account.CPKey(hash))
144         if rawProgram == nil {
145                 return nil, fmt.Errorf("failed get account control program:%x ", hash)
146         }
147
148         if err := json.Unmarshal(rawProgram, &accountCP); err != nil {
149                 return nil, err
150         }
151
152         accountValue := walletDB.Get(account.Key(accountCP.AccountID))
153         if accountValue == nil {
154                 return nil, fmt.Errorf("failed get account:%s ", accountCP.AccountID)
155         }
156
157         if err := json.Unmarshal(accountValue, &localAccount); err != nil {
158                 return nil, err
159         }
160
161         return &localAccount, nil
162 }
163
164 var emptyJSONObject = json.RawMessage(`{}`)
165
166 func isValidJSON(b []byte) bool {
167         var v interface{}
168         err := json.Unmarshal(b, &v)
169         return err == nil
170 }
171
172 func (w *Wallet) buildAnnotatedTransaction(orig *types.Tx, b *types.Block, statusFail bool, indexInBlock int) *query.AnnotatedTx {
173         tx := &query.AnnotatedTx{
174                 ID:                     orig.ID,
175                 Timestamp:              b.Timestamp,
176                 BlockID:                b.Hash(),
177                 BlockHeight:            b.Height,
178                 Position:               uint32(indexInBlock),
179                 BlockTransactionsCount: uint32(len(b.Transactions)),
180                 Inputs:                 make([]*query.AnnotatedInput, 0, len(orig.Inputs)),
181                 Outputs:                make([]*query.AnnotatedOutput, 0, len(orig.Outputs)),
182                 StatusFail:             statusFail,
183         }
184         for i := range orig.Inputs {
185                 tx.Inputs = append(tx.Inputs, w.BuildAnnotatedInput(orig, uint32(i)))
186         }
187         for i := range orig.Outputs {
188                 tx.Outputs = append(tx.Outputs, w.BuildAnnotatedOutput(orig, i))
189         }
190         return tx
191 }
192
193 // BuildAnnotatedInput build the annotated input.
194 func (w *Wallet) BuildAnnotatedInput(tx *types.Tx, i uint32) *query.AnnotatedInput {
195         orig := tx.Inputs[i]
196         in := &query.AnnotatedInput{
197                 AssetDefinition: &emptyJSONObject,
198         }
199         if orig.InputType() != types.CoinbaseInputType {
200                 in.AssetID = orig.AssetID()
201                 in.Amount = orig.Amount()
202         }
203
204         id := tx.Tx.InputIDs[i]
205         e := tx.Entries[id]
206         switch e := e.(type) {
207         case *bc.Spend:
208                 in.Type = "spend"
209                 in.ControlProgram = orig.ControlProgram()
210                 in.Address = w.getAddressFromControlProgram(in.ControlProgram)
211                 in.SpentOutputID = e.SpentOutputId
212         case *bc.Issuance:
213                 in.Type = "issue"
214                 in.IssuanceProgram = orig.IssuanceProgram()
215         case *bc.Coinbase:
216                 in.Type = "coinbase"
217                 in.Arbitrary = e.Arbitrary
218         }
219         return in
220 }
221
222 func (w *Wallet) getAddressFromControlProgram(prog []byte) string {
223         if segwit.IsP2WPKHScript(prog) {
224                 if pubHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
225                         return buildP2PKHAddress(pubHash)
226                 }
227         } else if segwit.IsP2WSHScript(prog) {
228                 if scriptHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
229                         return buildP2SHAddress(scriptHash)
230                 }
231         }
232
233         return ""
234 }
235
236 func buildP2PKHAddress(pubHash []byte) string {
237         address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.MainNetParams)
238         if err != nil {
239                 return ""
240         }
241
242         return address.EncodeAddress()
243 }
244
245 func buildP2SHAddress(scriptHash []byte) string {
246         address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.MainNetParams)
247         if err != nil {
248                 return ""
249         }
250
251         return address.EncodeAddress()
252 }
253
254 // BuildAnnotatedOutput build the annotated output.
255 func (w *Wallet) BuildAnnotatedOutput(tx *types.Tx, idx int) *query.AnnotatedOutput {
256         orig := tx.Outputs[idx]
257         outid := tx.OutputID(idx)
258         out := &query.AnnotatedOutput{
259                 OutputID:        *outid,
260                 Position:        idx,
261                 AssetID:         *orig.AssetId,
262                 AssetDefinition: &emptyJSONObject,
263                 Amount:          orig.Amount,
264                 ControlProgram:  orig.ControlProgram,
265                 Address:         w.getAddressFromControlProgram(orig.ControlProgram),
266         }
267
268         if vmutil.IsUnspendable(out.ControlProgram) {
269                 out.Type = "retire"
270         } else {
271                 out.Type = "control"
272         }
273         return out
274 }