OSDN Git Service

merge with dev
authorpaladz <453256728@qq.com>
Wed, 18 Apr 2018 15:16:35 +0000 (23:16 +0800)
committerpaladz <453256728@qq.com>
Wed, 18 Apr 2018 15:16:35 +0000 (23:16 +0800)
18 files changed:
.travis.yml
Makefile
account/accounts.go
account/builder.go
api/accounts.go
api/api.go
api/query.go
asset/asset.go
asset/asset_test.go
blockchain/pseudohsm/keycache.go
blockchain/txbuilder/actions.go
cmd/bytomcli/commands/asset.go
cmd/bytomcli/commands/bytomcli.go
cmd/bytomcli/commands/transaction.go
consensus/general.go
node/node.go
protocol/txpool.go
wallet/annotated.go

index 94fe4a5..b248347 100644 (file)
@@ -17,4 +17,4 @@ branches:
         - dev
 
 script:
-    - make test
+    - make ci
index 4a8d510..a834c6e 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -114,4 +114,6 @@ benchmark:
 functional-tests:
        @go test -v -timeout=30m -tags=functional ./test
 
+ci: test functional-tests
+
 .PHONY: all target release-all clean test benchmark
index 38922ae..81f1f3a 100644 (file)
@@ -288,7 +288,7 @@ func (m *Manager) createP2PKH(ctx context.Context, account *Account, change bool
        pubHash := crypto.Ripemd160(derivedPK)
 
        // TODO: pass different params due to config
-       address, err := common.NewAddressWitnessPubKeyHash(pubHash, consensus.ActiveNetParams)
+       address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
        if err != nil {
                return nil, err
        }
@@ -319,7 +319,7 @@ func (m *Manager) createP2SH(ctx context.Context, account *Account, change bool)
        scriptHash := crypto.Sha256(signScript)
 
        // TODO: pass different params due to config
-       address, err := common.NewAddressWitnessScriptHash(scriptHash, consensus.ActiveNetParams)
+       address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
        if err != nil {
                return nil, err
        }
index 53a4a6c..693e8f8 100644 (file)
@@ -152,7 +152,7 @@ func UtxoToInputs(signer *signers.Signer, u *UTXO) (*types.TxInput, *txbuilder.S
                return txInput, sigInst, nil
        }
 
-       address, err := common.DecodeAddress(u.Address, consensus.ActiveNetParams)
+       address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
        if err != nil {
                return nil, nil, err
        }
index 2d0d217..87a39e0 100644 (file)
@@ -55,7 +55,7 @@ func (a *API) validateAddress(ctx context.Context, ins struct {
                Vaild:   false,
                IsLocal: false,
        }
-       address, err := common.DecodeAddress(ins.Address, consensus.ActiveNetParams)
+       address, err := common.DecodeAddress(ins.Address, &consensus.ActiveNetParams)
        if err != nil {
                return NewSuccessResponse(resp)
        }
index d35481e..3034579 100644 (file)
@@ -177,6 +177,7 @@ func (a *API) buildHandler() {
 
                m.Handle("/create-asset", jsonHandler(a.createAsset))
                m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
+               m.Handle("/get-asset", jsonHandler(a.getAsset))
                m.Handle("/list-assets", jsonHandler(a.listAssets))
 
                m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
index ac3c37d..4a4737e 100644 (file)
@@ -29,11 +29,22 @@ func (a *API) listAccounts(ctx context.Context) Response {
        return NewSuccessResponse(annotatedAccounts)
 }
 
-// POST /list-assets
-func (a *API) listAssets(ctx context.Context, filter struct {
+// POST /get-asset
+func (a *API) getAsset(ctx context.Context, filter struct {
        ID string `json:"id"`
 }) Response {
-       assets, err := a.wallet.AssetReg.ListAssets(filter.ID)
+       asset, err := a.wallet.AssetReg.GetAsset(filter.ID)
+       if err != nil {
+               log.Errorf("getAsset: %v", err)
+               return NewErrorResponse(err)
+       }
+
+       return NewSuccessResponse(asset)
+}
+
+// POST /list-assets
+func (a *API) listAssets(ctx context.Context) Response {
+       assets, err := a.wallet.AssetReg.ListAssets()
        if err != nil {
                log.Errorf("listAssets: %v", err)
                return NewErrorResponse(err)
@@ -121,6 +132,11 @@ func (a *API) getUnconfirmedTx(ctx context.Context, filter struct {
        return NewSuccessResponse(tx)
 }
 
+type unconfirmedTxsResp struct {
+       Total uint64    `json:"total"`
+       TxIDs []bc.Hash `json:"tx_ids"`
+}
+
 // POST /list-unconfirmed-transactions
 func (a *API) listUnconfirmedTxs(ctx context.Context) Response {
        txIDs := []bc.Hash{}
@@ -131,7 +147,10 @@ func (a *API) listUnconfirmedTxs(ctx context.Context) Response {
                txIDs = append(txIDs, bc.Hash(txDesc.Tx.ID))
        }
 
-       return NewSuccessResponse(txIDs)
+       return NewSuccessResponse(&unconfirmedTxsResp{
+               Total: uint64(len(txIDs)),
+               TxIDs: txIDs,
+       })
 }
 
 // POST /list-unspent-outputs
index 1696642..e8cdbcb 100644 (file)
@@ -272,8 +272,31 @@ func (reg *Registry) GetAliasByID(id string) string {
        return *asset.Alias
 }
 
+// GetAsset get asset by assetID
+func (reg *Registry) GetAsset(id string) (*Asset, error) {
+       asset := &Asset{}
+
+       if strings.Compare(id, DefaultNativeAsset.AssetID.String()) == 0 {
+               return DefaultNativeAsset, nil
+       }
+
+       if interAsset := reg.db.Get([]byte(assetPrefix + id)); interAsset != nil {
+               if err := json.Unmarshal(interAsset, asset); err != nil {
+                       return nil, err
+               }
+               return asset, nil
+       }
+
+       if extAsset := reg.db.Get([]byte(ExternalAssetPrefix + id)); extAsset != nil {
+               if err := json.Unmarshal(extAsset, asset); err != nil {
+                       return nil, err
+               }
+       }
+       return asset, nil
+}
+
 // ListAssets returns the accounts in the db
-func (reg *Registry) ListAssets(id string) ([]*Asset, error) {
+func (reg *Registry) ListAssets() ([]*Asset, error) {
        assets := []*Asset{DefaultNativeAsset}
        assetIter := reg.db.IteratorPrefix(assetPrefix)
        defer assetIter.Release()
@@ -285,6 +308,7 @@ func (reg *Registry) ListAssets(id string) ([]*Asset, error) {
                }
                assets = append(assets, asset)
        }
+
        return assets, nil
 }
 
index 0c81c1b..6552857 100644 (file)
@@ -131,7 +131,7 @@ func TestListAssets(t *testing.T) {
 
        wantAssets := []*Asset{DefaultNativeAsset, firstAsset, secondAsset}
 
-       gotAssets, err := reg.ListAssets("")
+       gotAssets, err := reg.ListAssets()
        if err != nil {
                testutil.FatalErr(t, err)
        }
index 4423998..7af8805 100644 (file)
@@ -13,6 +13,8 @@ import (
        "sync"
        "time"
 
+       log "github.com/sirupsen/logrus"
+
        "github.com/bytom/crypto/ed25519/chainkd"
 )
 
@@ -167,7 +169,7 @@ func (kc *keyCache) find(xpub XPub) (XPub, error) {
 func (kc *keyCache) reload() {
        keys, err := kc.scan()
        if err != nil {
-               fmt.Printf("can't load keys: %v\n", err.Error())
+               log.WithField("load keys error", err).Error("can't load keys")
        }
        kc.all = keys
        sort.Sort(kc.all)
@@ -177,7 +179,7 @@ func (kc *keyCache) reload() {
        for _, k := range keys {
                kc.byPubs[k.XPub] = append(kc.byPubs[k.XPub], k)
        }
-       fmt.Printf("reloaded keys, cache has %d keys\n", len(kc.all))
+       log.WithField("cache has keys:", len(kc.all)).Debug("reloaded keys")
 }
 
 func (kc *keyCache) scan() ([]XPub, error) {
@@ -212,9 +214,9 @@ func (kc *keyCache) scan() ([]XPub, error) {
                err = json.NewDecoder(buf).Decode(&keyJSON)
                switch {
                case err != nil:
-                       fmt.Printf("can't decode key %s: %v", path, err)
+                       log.WithField("decode json err", err).Errorf("can't decode key %s: %v", path, err)
                case (keyJSON.Alias == ""):
-                       fmt.Printf("can't decode key %s: missing or void alias", path)
+                       log.WithField("can't decode key, key path:", path).Warn("missing or void alias")
                default:
                        keys = append(keys, XPub{XPub: keyJSON.XPub, Alias: keyJSON.Alias, File: path})
                }
index 01bbd89..996c01e 100644 (file)
@@ -72,7 +72,7 @@ func (a *controlAddressAction) Build(ctx context.Context, b *TemplateBuilder) er
                return MissingFieldsError(missing...)
        }
 
-       address, err := common.DecodeAddress(a.Address, consensus.ActiveNetParams)
+       address, err := common.DecodeAddress(a.Address, &consensus.ActiveNetParams)
        if err != nil {
                return err
        }
index 11a6a8a..563c053 100644 (file)
@@ -15,12 +15,9 @@ func init() {
        createAssetCmd.PersistentFlags().IntVarP(&assetQuorum, "quorom", "q", 1, "quorum must be greater than 0 and less than or equal to the number of signers")
        createAssetCmd.PersistentFlags().StringVarP(&assetToken, "access", "a", "", "access token")
        createAssetCmd.PersistentFlags().StringVarP(&assetDefiniton, "definition", "d", "", "definition for the asset")
-
-       listAssetsCmd.PersistentFlags().StringVar(&assetID, "id", "", "ID of asset")
 }
 
 var (
-       assetID        = ""
        assetQuorum    = 1
        assetToken     = ""
        assetDefiniton = ""
@@ -65,16 +62,30 @@ var createAssetCmd = &cobra.Command{
        },
 }
 
+var getAssetCmd = &cobra.Command{
+       Use:   "get-asset <assetID>",
+       Short: "get asset by assetID",
+       Args:  cobra.ExactArgs(1),
+       Run: func(cmd *cobra.Command, args []string) {
+               filter := struct {
+                       ID string `json:"id"`
+               }{ID: args[0]}
+
+               data, exitCode := util.ClientCall("/get-asset", &filter)
+               if exitCode != util.Success {
+                       os.Exit(exitCode)
+               }
+
+               printJSON(data)
+       },
+}
+
 var listAssetsCmd = &cobra.Command{
        Use:   "list-assets",
        Short: "List the existing assets",
        Args:  cobra.NoArgs,
        Run: func(cmd *cobra.Command, args []string) {
-               filter := struct {
-                       ID string `json:"id"`
-               }{ID: assetID}
-
-               data, exitCode := util.ClientCall("/list-assets", &filter)
+               data, exitCode := util.ClientCall("/list-assets")
                if exitCode != util.Success {
                        os.Exit(exitCode)
                }
index afec764..b221bd7 100644 (file)
@@ -86,6 +86,7 @@ func AddCommands() {
        BytomcliCmd.AddCommand(validateAddressCmd)
 
        BytomcliCmd.AddCommand(createAssetCmd)
+       BytomcliCmd.AddCommand(getAssetCmd)
        BytomcliCmd.AddCommand(listAssetsCmd)
        BytomcliCmd.AddCommand(updateAssetAliasCmd)
 
index ef2a5fe..ddc8329 100644 (file)
@@ -345,7 +345,7 @@ var listUnconfirmedTransactionsCmd = &cobra.Command{
                        os.Exit(exitCode)
                }
 
-               printJSONList(data)
+               printJSON(data)
        },
 }
 
index 53406d7..f8ea21c 100644 (file)
@@ -90,7 +90,13 @@ type Params struct {
        Bech32HRPSegwit string
 }
 
-var ActiveNetParams = &MainNetParams
+var ActiveNetParams = MainNetParams
+
+// NetParams is the correspondence between chain_id and Params
+var NetParams = map[string]Params{
+       "mainnet": MainNetParams,
+       "testnet": TestNetParams,
+}
 
 // MainNetParams is the config for production
 var MainNetParams = Params{
index 3ccee7b..9cfb885 100644 (file)
@@ -59,9 +59,7 @@ type Node struct {
 
 func NewNode(config *cfg.Config) *Node {
        ctx := context.Background()
-       if config.ChainID == "testnet" {
-               consensus.ActiveNetParams = &consensus.TestNetParams
-       }
+       initActiveNetParams(config)
        // Get store
        txDB := dbm.NewDB("txdb", config.DBBackend, config.DBDir())
        store := leveldb.NewStore(txDB)
@@ -149,6 +147,14 @@ func NewNode(config *cfg.Config) *Node {
        return node
 }
 
+func initActiveNetParams(config *cfg.Config) {
+       var exist bool
+       consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
+       if !exist {
+               cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
+       }
+}
+
 func initOrRecoverAccount(hsm *pseudohsm.HSM, wallet *w.Wallet) error {
        xpubs := hsm.ListKeys()
 
index c177cef..4017db7 100644 (file)
@@ -96,7 +96,7 @@ func (tp *TxPool) AddTransaction(tx *types.Tx, gasOnlyTx bool, height, fee uint6
        }
 
        tp.newTxCh <- tx
-       log.WithField("tx_id", tx.Tx.ID.String()).Info("Add tx to mempool")
+       log.WithField("tx_id", tx.Tx.ID.String()).Debug("Add tx to mempool")
        return txD, nil
 }
 
@@ -136,7 +136,7 @@ func (tp *TxPool) RemoveTransaction(txHash *bc.Hash) {
        delete(tp.pool, *txHash)
        atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
 
-       log.WithField("tx_id", txHash).Info("remove tx from mempool")
+       log.WithField("tx_id", txHash).Debug("remove tx from mempool")
 }
 
 // GetTransaction return the TxDesc by hash
index 571f852..a2c674b 100644 (file)
@@ -241,7 +241,7 @@ func (w *Wallet) getAddressFromControlProgram(prog []byte) string {
 }
 
 func buildP2PKHAddress(pubHash []byte) string {
-       address, err := common.NewAddressWitnessPubKeyHash(pubHash, consensus.ActiveNetParams)
+       address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
        if err != nil {
                return ""
        }
@@ -250,7 +250,7 @@ func buildP2PKHAddress(pubHash []byte) string {
 }
 
 func buildP2SHAddress(scriptHash []byte) string {
-       address, err := common.NewAddressWitnessScriptHash(scriptHash, consensus.ActiveNetParams)
+       address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
        if err != nil {
                return ""
        }