OSDN Git Service

add mining api
authorwz <mars@bytom.io>
Wed, 11 Apr 2018 03:17:56 +0000 (11:17 +0800)
committerwz <mars@bytom.io>
Wed, 11 Apr 2018 07:26:25 +0000 (15:26 +0800)
api/api.go
api/miner.go
cmd/bytomcli/commands/mining.go

index 3b71e08..5970713 100644 (file)
@@ -231,6 +231,7 @@ func (a *API) buildHandler() {
        m.Handle("/gas-rate", jsonHandler(a.gasRate))
        m.Handle("/get-work", jsonHandler(a.getWork))
        m.Handle("/submit-work", jsonHandler(a.submitWork))
+       m.Handle("/set-mining", jsonHandler(a.setMining))
 
        handler := latencyHandler(m, walletEnable)
        handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
index f59bad9..9b48b2d 100644 (file)
@@ -3,6 +3,7 @@ package api
 import (
        "context"
 
+       "github.com/bytom/errors"
        "github.com/bytom/protocol/bc"
        "github.com/bytom/protocol/bc/types"
 )
@@ -67,3 +68,29 @@ func (a *API) GetWork() (*GetWorkResp, error) {
 func (a *API) SubmitWork(bh *types.BlockHeader) error {
        return a.miningPool.SubmitWork(bh)
 }
+
+func (a *API) setMining(in struct {
+       IsMining bool `json:"is_mining"`
+}) Response {
+       if in.IsMining {
+               return a.StartMining()
+       } else {
+               return a.StopMining()
+       }
+}
+
+func (a *API) StartMining() Response {
+       if a.cpuMiner.IsMining() {
+               return NewErrorResponse(errors.New("Mining is already running"))
+       }
+       a.cpuMiner.Start()
+       return NewSuccessResponse("")
+}
+
+func (a *API) StopMining() Response {
+       a.cpuMiner.Stop()
+       if a.cpuMiner.IsMining() {
+               return NewErrorResponse(errors.New("Failed to stop mining"))
+       }
+       return NewSuccessResponse("")
+}
index 35d6daf..9b6e29c 100644 (file)
@@ -2,6 +2,7 @@ package commands
 
 import (
        "os"
+       "strings"
 
        "github.com/bytom/util"
        "github.com/spf13/cobra"
@@ -19,3 +20,27 @@ var isMiningCmd = &cobra.Command{
                printJSON(data)
        },
 }
+
+var miningCmd = &cobra.Command{
+       Use:   "set-mining <true or false>",
+       Short: "start or stop mining",
+       Args:  cobra.ExactArgs(1),
+       Run: func(cmd *cobra.Command, args []string) {
+               param := strings.ToLower(args[0])
+               isMining := false
+               switch param {
+               case "true":
+                       isMining = true
+               default:
+                       isMining = false
+               }
+               miningInfo := &struct {
+                       IsMining bool `json:"is_mining"`
+               }{IsMining: isMining}
+               data, exitCode := util.ClientCall("/set-mining", miningInfo)
+               if exitCode != util.Success {
+                       os.Exit(exitCode)
+               }
+               printJSON(data)
+       },
+}