OSDN Git Service

add test case (#1636)
[bytom/bytom.git] / wallet / annotated.go
old mode 100755 (executable)
new mode 100644 (file)
index 9936053..9ac57c6
@@ -13,8 +13,8 @@ import (
        "github.com/bytom/blockchain/signers"
        "github.com/bytom/common"
        "github.com/bytom/consensus"
+       "github.com/bytom/consensus/segwit"
        "github.com/bytom/crypto/sha3pool"
-       chainjson "github.com/bytom/encoding/json"
        "github.com/bytom/protocol/bc"
        "github.com/bytom/protocol/bc/types"
        "github.com/bytom/protocol/vm/vmutil"
@@ -24,19 +24,18 @@ import (
 func annotateTxsAsset(w *Wallet, txs []*query.AnnotatedTx) {
        for i, tx := range txs {
                for j, input := range tx.Inputs {
-                       txs[i].Inputs[j].AssetAlias, txs[i].Inputs[j].AssetDefinition =
-                               w.getAliasDefinition(input.AssetID)
+                       alias, definition := w.getAliasDefinition(input.AssetID)
+                       txs[i].Inputs[j].AssetAlias, txs[i].Inputs[j].AssetDefinition = alias, &definition
                }
                for k, output := range tx.Outputs {
-                       txs[i].Outputs[k].AssetAlias, txs[i].Outputs[k].AssetDefinition =
-                               w.getAliasDefinition(output.AssetID)
+                       alias, definition := w.getAliasDefinition(output.AssetID)
+                       txs[i].Outputs[k].AssetAlias, txs[i].Outputs[k].AssetDefinition = alias, &definition
                }
        }
 }
 
-func (w *Wallet) getExternalDefinition(assetID *bc.AssetID) *chainjson.HexBytes {
-
-       definitionByte := w.DB.Get(asset.CalcExtAssetKey(assetID))
+func (w *Wallet) getExternalDefinition(assetID *bc.AssetID) json.RawMessage {
+       definitionByte := w.DB.Get(asset.ExtAssetKey(assetID))
        if definitionByte == nil {
                return nil
        }
@@ -46,27 +45,26 @@ func (w *Wallet) getExternalDefinition(assetID *bc.AssetID) *chainjson.HexBytes
                return nil
        }
 
-       saveAlias := assetID.String()
-       storeBatch := w.DB.NewBatch()
-
-       externalAsset := &asset.Asset{AssetID: *assetID, Alias: &saveAlias, DefinitionMap: definitionMap, Signer: &signers.Signer{Type: "external"}}
-       if rawAsset, err := json.Marshal(externalAsset); err == nil {
-               log.WithFields(log.Fields{"assetID": assetID.String(), "alias": saveAlias}).Info("index external asset")
-               storeBatch.Set(asset.Key(assetID), rawAsset)
+       alias := assetID.String()
+       externalAsset := &asset.Asset{
+               AssetID:           *assetID,
+               Alias:             &alias,
+               DefinitionMap:     definitionMap,
+               RawDefinitionByte: definitionByte,
+               Signer:            &signers.Signer{Type: "external"},
        }
-       storeBatch.Set(asset.AliasKey(saveAlias), []byte(assetID.String()))
-       storeBatch.Write()
-
-       d := chainjson.HexBytes(definitionByte)
-       return &d
 
+       if err := w.AssetReg.SaveAsset(externalAsset, alias); err != nil {
+               log.WithFields(log.Fields{"module": logModule, "err": err, "assetID": alias}).Warning("fail on save external asset to internal asset DB")
+       }
+       return definitionByte
 }
 
-func (w *Wallet) getAliasDefinition(assetID bc.AssetID) (string, *chainjson.HexBytes) {
+func (w *Wallet) getAliasDefinition(assetID bc.AssetID) (string, json.RawMessage) {
        //btm
        if assetID.String() == consensus.BTMAssetID.String() {
                alias := consensus.BTMAlias
-               definition := &asset.DefaultNativeAsset.RawDefinitionByte
+               definition := []byte(asset.DefaultNativeAsset.RawDefinitionByte)
 
                return alias, definition
        }
@@ -74,7 +72,7 @@ func (w *Wallet) getAliasDefinition(assetID bc.AssetID) (string, *chainjson.HexB
        //local asset and saved external asset
        if localAsset, err := w.AssetReg.FindByID(nil, &assetID); err == nil {
                alias := *localAsset.Alias
-               definition := &localAsset.RawDefinitionByte
+               definition := []byte(localAsset.RawDefinitionByte)
                return alias, definition
        }
 
@@ -94,7 +92,7 @@ func annotateTxsAccount(txs []*query.AnnotatedTx, walletDB db.DB) {
                        if input.SpentOutputID == nil {
                                continue
                        }
-                       localAccount, err := getAccountFromUTXO(*input.SpentOutputID, walletDB)
+                       localAccount, err := getAccountFromACP(input.ControlProgram, walletDB)
                        if localAccount == nil || err != nil {
                                continue
                        }
@@ -112,30 +110,6 @@ func annotateTxsAccount(txs []*query.AnnotatedTx, walletDB db.DB) {
        }
 }
 
-func getAccountFromUTXO(outputID bc.Hash, walletDB db.DB) (*account.Account, error) {
-       accountUTXO := account.UTXO{}
-       localAccount := account.Account{}
-
-       accountUTXOValue := walletDB.Get(account.StandardUTXOKey(outputID))
-       if accountUTXOValue == nil {
-               return nil, fmt.Errorf("failed get account utxo:%x ", outputID)
-       }
-
-       if err := json.Unmarshal(accountUTXOValue, &accountUTXO); err != nil {
-               return nil, err
-       }
-
-       accountValue := walletDB.Get(account.Key(accountUTXO.AccountID))
-       if accountValue == nil {
-               return nil, fmt.Errorf("failed get account:%s ", accountUTXO.AccountID)
-       }
-       if err := json.Unmarshal(accountValue, &localAccount); err != nil {
-               return nil, err
-       }
-
-       return &localAccount, nil
-}
-
 func getAccountFromACP(program []byte, walletDB db.DB) (*account.Account, error) {
        var hash common.Hash
        accountCP := account.CtrlProgram{}
@@ -143,7 +117,7 @@ func getAccountFromACP(program []byte, walletDB db.DB) (*account.Account, error)
 
        sha3pool.Sum256(hash[:], program)
 
-       rawProgram := walletDB.Get(account.CPKey(hash))
+       rawProgram := walletDB.Get(account.ContractKey(hash))
        if rawProgram == nil {
                return nil, fmt.Errorf("failed get account control program:%x ", hash)
        }
@@ -164,7 +138,7 @@ func getAccountFromACP(program []byte, walletDB db.DB) (*account.Account, error)
        return &localAccount, nil
 }
 
-var emptyJSONObject = chainjson.HexBytes(`{}`)
+var emptyJSONObject = json.RawMessage(`{}`)
 
 func isValidJSON(b []byte) bool {
        var v interface{}
@@ -172,7 +146,7 @@ func isValidJSON(b []byte) bool {
        return err == nil
 }
 
-func buildAnnotatedTransaction(orig *types.Tx, b *types.Block, statusFail bool, indexInBlock int) *query.AnnotatedTx {
+func (w *Wallet) buildAnnotatedTransaction(orig *types.Tx, b *types.Block, statusFail bool, indexInBlock int) *query.AnnotatedTx {
        tx := &query.AnnotatedTx{
                ID:                     orig.ID,
                Timestamp:              b.Timestamp,
@@ -183,37 +157,52 @@ func buildAnnotatedTransaction(orig *types.Tx, b *types.Block, statusFail bool,
                Inputs:                 make([]*query.AnnotatedInput, 0, len(orig.Inputs)),
                Outputs:                make([]*query.AnnotatedOutput, 0, len(orig.Outputs)),
                StatusFail:             statusFail,
+               Size:                   orig.SerializedSize,
        }
        for i := range orig.Inputs {
-               tx.Inputs = append(tx.Inputs, BuildAnnotatedInput(orig, uint32(i)))
+               tx.Inputs = append(tx.Inputs, w.BuildAnnotatedInput(orig, uint32(i)))
        }
        for i := range orig.Outputs {
-               tx.Outputs = append(tx.Outputs, BuildAnnotatedOutput(orig, i))
+               tx.Outputs = append(tx.Outputs, w.BuildAnnotatedOutput(orig, i))
        }
        return tx
 }
 
 // BuildAnnotatedInput build the annotated input.
-func BuildAnnotatedInput(tx *types.Tx, i uint32) *query.AnnotatedInput {
+func (w *Wallet) BuildAnnotatedInput(tx *types.Tx, i uint32) *query.AnnotatedInput {
        orig := tx.Inputs[i]
        in := &query.AnnotatedInput{
                AssetDefinition: &emptyJSONObject,
        }
-       if !orig.IsCoinbase() {
+       if orig.InputType() != types.CoinbaseInputType {
                in.AssetID = orig.AssetID()
                in.Amount = orig.Amount()
        }
 
        id := tx.Tx.InputIDs[i]
+       in.InputID = id
        e := tx.Entries[id]
        switch e := e.(type) {
        case *bc.Spend:
                in.Type = "spend"
                in.ControlProgram = orig.ControlProgram()
+               in.Address = w.getAddressFromControlProgram(in.ControlProgram)
                in.SpentOutputID = e.SpentOutputId
+               arguments := orig.Arguments()
+               for _, arg := range arguments {
+                       in.WitnessArguments = append(in.WitnessArguments, arg)
+               }
        case *bc.Issuance:
                in.Type = "issue"
                in.IssuanceProgram = orig.IssuanceProgram()
+               arguments := orig.Arguments()
+               for _, arg := range arguments {
+                       in.WitnessArguments = append(in.WitnessArguments, arg)
+               }
+               if assetDefinition := orig.AssetDefinition(); isValidJSON(assetDefinition) {
+                       assetDefinition := json.RawMessage(assetDefinition)
+                       in.AssetDefinition = &assetDefinition
+               }
        case *bc.Coinbase:
                in.Type = "coinbase"
                in.Arbitrary = e.Arbitrary
@@ -221,8 +210,40 @@ func BuildAnnotatedInput(tx *types.Tx, i uint32) *query.AnnotatedInput {
        return in
 }
 
+func (w *Wallet) getAddressFromControlProgram(prog []byte) string {
+       if segwit.IsP2WPKHScript(prog) {
+               if pubHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
+                       return buildP2PKHAddress(pubHash)
+               }
+       } else if segwit.IsP2WSHScript(prog) {
+               if scriptHash, err := segwit.GetHashFromStandardProg(prog); err == nil {
+                       return buildP2SHAddress(scriptHash)
+               }
+       }
+
+       return ""
+}
+
+func buildP2PKHAddress(pubHash []byte) string {
+       address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
+       if err != nil {
+               return ""
+       }
+
+       return address.EncodeAddress()
+}
+
+func buildP2SHAddress(scriptHash []byte) string {
+       address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
+       if err != nil {
+               return ""
+       }
+
+       return address.EncodeAddress()
+}
+
 // BuildAnnotatedOutput build the annotated output.
-func BuildAnnotatedOutput(tx *types.Tx, idx int) *query.AnnotatedOutput {
+func (w *Wallet) BuildAnnotatedOutput(tx *types.Tx, idx int) *query.AnnotatedOutput {
        orig := tx.Outputs[idx]
        outid := tx.OutputID(idx)
        out := &query.AnnotatedOutput{
@@ -232,7 +253,9 @@ func BuildAnnotatedOutput(tx *types.Tx, idx int) *query.AnnotatedOutput {
                AssetDefinition: &emptyJSONObject,
                Amount:          orig.Amount,
                ControlProgram:  orig.ControlProgram,
+               Address:         w.getAddressFromControlProgram(orig.ControlProgram),
        }
+
        if vmutil.IsUnspendable(out.ControlProgram) {
                out.Type = "retire"
        } else {