github.com/johnathanhowell/sia@v0.5.1-beta.0.20160524050156-83dcc3d37c94/api/miner.go (about)

     1  package api
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/NebulousLabs/Sia/encoding"
     7  	"github.com/NebulousLabs/Sia/types"
     8  
     9  	"github.com/julienschmidt/httprouter"
    10  )
    11  
    12  type (
    13  	// MinerGET contains the information that is returned after a GET request
    14  	// to /miner.
    15  	MinerGET struct {
    16  		BlocksMined      int  `json:"blocksmined"`
    17  		CPUHashrate      int  `json:"cpuhashrate"`
    18  		CPUMining        bool `json:"cpumining"`
    19  		StaleBlocksMined int  `json:"staleblocksmined"`
    20  	}
    21  )
    22  
    23  // minerHandler handles the API call that queries the miner's status.
    24  func (srv *Server) minerHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
    25  	blocksMined, staleMined := srv.miner.BlocksMined()
    26  	mg := MinerGET{
    27  		BlocksMined:      blocksMined,
    28  		CPUHashrate:      srv.miner.CPUHashrate(),
    29  		CPUMining:        srv.miner.CPUMining(),
    30  		StaleBlocksMined: staleMined,
    31  	}
    32  	writeJSON(w, mg)
    33  }
    34  
    35  // minerStartHandler handles the API call that starts the miner.
    36  func (srv *Server) minerStartHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
    37  	srv.miner.StartCPUMining()
    38  	writeSuccess(w)
    39  }
    40  
    41  // minerStopHandler handles the API call to stop the miner.
    42  func (srv *Server) minerStopHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
    43  	srv.miner.StopCPUMining()
    44  	writeSuccess(w)
    45  }
    46  
    47  // minerHeaderHandlerGET handles the API call that retrieves a block header
    48  // for work.
    49  func (srv *Server) minerHeaderHandlerGET(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
    50  	bhfw, target, err := srv.miner.HeaderForWork()
    51  	if err != nil {
    52  		writeError(w, err.Error(), http.StatusBadRequest)
    53  		return
    54  	}
    55  	w.Write(encoding.MarshalAll(target, bhfw))
    56  }
    57  
    58  // minerHeaderHandlerPOST handles the API call to submit a block header to the
    59  // miner.
    60  func (srv *Server) minerHeaderHandlerPOST(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
    61  	var bh types.BlockHeader
    62  	err := encoding.NewDecoder(req.Body).Decode(&bh)
    63  	if err != nil {
    64  		writeError(w, err.Error(), http.StatusBadRequest)
    65  		return
    66  	}
    67  	err = srv.miner.SubmitHeader(bh)
    68  	if err != nil {
    69  		writeError(w, err.Error(), http.StatusBadRequest)
    70  		return
    71  	}
    72  	writeSuccess(w)
    73  }