OSDN Git Service

Merge pull request #1832 from Bytom/prod
[bytom/bytom.git] / api / miner.go
index 988456e..029993e 100644 (file)
@@ -2,11 +2,13 @@ package api
 
 import (
        "context"
+       "strconv"
 
-       chainjson "github.com/bytom/encoding/json"
-       "github.com/bytom/errors"
-       "github.com/bytom/protocol/bc"
-       "github.com/bytom/protocol/bc/types"
+       chainjson "github.com/bytom/bytom/encoding/json"
+       "github.com/bytom/bytom/errors"
+       "github.com/bytom/bytom/event"
+       "github.com/bytom/bytom/protocol/bc"
+       "github.com/bytom/bytom/protocol/bc/types"
 )
 
 // BlockHeaderJSON struct provides support for get work in json format, when it also follows
@@ -33,7 +35,18 @@ func (a *API) getCoinbaseArbitrary() Response {
        return NewSuccessResponse(resp)
 }
 
+// setCoinbaseArbitrary add arbitary data to the reserved coinbase data.
+// check function createCoinbaseTx in mining/mining.go for detail.
+// arbitraryLenLimit is 107 and can be calculated by:
+//     maxHeight := ^uint64(0)
+//     reserved := append([]byte{0x00}, []byte(strconv.FormatUint(maxHeight, 10))...)
+//     arbitraryLenLimit := consensus.CoinbaseArbitrarySizeLimit - len(reserved)
 func (a *API) setCoinbaseArbitrary(ctx context.Context, req CoinbaseArbitrary) Response {
+       arbitraryLenLimit := 107
+       if len(req.Arbitrary) > arbitraryLenLimit {
+               err := errors.New("Arbitrary exceeds limit: " + strconv.FormatUint(uint64(arbitraryLenLimit), 10))
+               return NewErrorResponse(err)
+       }
        a.wallet.AccountMgr.SetCoinbaseArbitrary(req.Arbitrary)
        return a.getCoinbaseArbitrary()
 }
@@ -56,7 +69,30 @@ func (a *API) getWorkJSON() Response {
        return NewSuccessResponse(work)
 }
 
-// SubmitWorkJSONReq is req struct for submit-work API
+// SubmitBlockReq is req struct for submit-block API
+type SubmitBlockReq struct {
+       Block *types.Block `json:"raw_block"`
+}
+
+// submitBlock trys to submit a raw block to the chain
+func (a *API) submitBlock(ctx context.Context, req *SubmitBlockReq) Response {
+       isOrphan, err := a.chain.ProcessBlock(req.Block)
+       if err != nil {
+               return NewErrorResponse(err)
+       }
+
+       if isOrphan {
+               return NewErrorResponse(errors.New("block submitted is orphan"))
+       }
+
+       if err = a.eventDispatcher.Post(event.NewMinedBlockEvent{Block: *req.Block}); err != nil {
+               return NewErrorResponse(err)
+       }
+
+       return NewSuccessResponse(true)
+}
+
+// SubmitWorkReq is req struct for submit-work API
 type SubmitWorkReq struct {
        BlockHeader *types.BlockHeader `json:"block_header"`
 }