diff --git a/mining.go b/mining.go index 185a004a..0e9f415d 100644 --- a/mining.go +++ b/mining.go @@ -10,9 +10,56 @@ import ( "errors" "github.com/btcsuite/btcd/btcjson" + "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcutil" ) +// FutureGenerateResult is a future promise to deliver the result of a +// GenerateAsync RPC invocation (or an applicable error). +type FutureGenerateResult chan *response + +// Receive waits for the response promised by the future and returns a list of +// block hashes generated by the call. +func (r FutureGenerateResult) Receive() ([]*wire.ShaHash, error) { + res, err := receiveFuture(r) + if err != nil { + return nil, err + } + + // Unmarshal result as a list of strings. + var result []string + err = json.Unmarshal(res, &result) + if err != nil { + return nil, err + } + + // Convert each block hash to a wire.ShaHash and store a pointer to each. + convertedResult := make([]*wire.ShaHash, len(result)) + for i, hashString := range result { + convertedResult[i], err = wire.NewShaHashFromStr(hashString) + if err != nil { + return nil, err + } + } + + return convertedResult, nil +} + +// GenerateAsync returns an instance of a type that can be used to get +// the result of the RPC at some future time by invoking the Receive function on +// the returned instance. +// +// See Generate for the blocking version and more details. +func (c *Client) GenerateAsync(numBlocks uint32) FutureGenerateResult { + cmd := btcjson.NewGenerateCmd(numBlocks) + return c.sendCmd(cmd) +} + +// Generate generates numBlocks blocks and returns their hashes. +func (c *Client) Generate(numBlocks uint32) ([]*wire.ShaHash, error) { + return c.GenerateAsync(numBlocks).Receive() +} + // FutureGetGenerateResult is a future promise to deliver the result of a // GetGenerateAsync RPC invocation (or an applicable error). type FutureGetGenerateResult chan *response