From d8a4423b905d84320f741adde7555fe0fab4181c Mon Sep 17 00:00:00 2001 From: Dave Collins Date: Sun, 5 Apr 2015 23:15:49 -0500 Subject: [PATCH] btcjson: Replace btcjson with version 2. This commit removes the old and deprecated btcjsonv1 package, moves the new version 2 package into its place, and updates all imports accordingly. --- btcjson/README.md | 65 +- btcjson/{v2/btcjson => }/btcdextcmds.go | 0 btcjson/{v2/btcjson => }/btcdextcmds_test.go | 2 +- btcjson/{v2/btcjson => }/btcwalletextcmds.go | 0 .../{v2/btcjson => }/btcwalletextcmds_test.go | 2 +- btcjson/btcws/README.md | 88 - btcjson/btcws/cmds.go | 1664 ---- btcjson/btcws/cmds_test.go | 364 - btcjson/btcws/notifications.go | 1249 --- btcjson/btcws/notifications_test.go | 290 - btcjson/{v2/btcjson => }/chainsvrcmds.go | 0 btcjson/{v2/btcjson => }/chainsvrcmds_test.go | 2 +- btcjson/{v2/btcjson => }/chainsvrresults.go | 0 .../{v2/btcjson => }/chainsvrresults_test.go | 2 +- btcjson/{v2/btcjson => }/chainsvrwscmds.go | 0 .../{v2/btcjson => }/chainsvrwscmds_test.go | 2 +- btcjson/{v2/btcjson => }/chainsvrwsntfns.go | 0 .../{v2/btcjson => }/chainsvrwsntfns_test.go | 2 +- btcjson/cmdhelp.go | 828 -- btcjson/{v2/btcjson => }/cmdinfo.go | 0 btcjson/{v2/btcjson => }/cmdinfo_test.go | 2 +- btcjson/{v2/btcjson => }/cmdparse.go | 0 btcjson/{v2/btcjson => }/cmdparse_test.go | 2 +- btcjson/doc.go | 204 +- btcjson/{v2/btcjson => }/error.go | 0 btcjson/{v2/btcjson => }/error_test.go | 2 +- btcjson/{v2/btcjson => }/example_test.go | 2 +- btcjson/{v2/btcjson => }/export_test.go | 0 btcjson/{v2/btcjson => }/help.go | 0 btcjson/{v2/btcjson => }/help_test.go | 2 +- btcjson/{v2/btcjson => }/helpers.go | 0 btcjson/{v2/btcjson => }/helpers_test.go | 2 +- btcjson/internal_test.go | 59 - btcjson/jsonapi.go | 821 -- btcjson/jsonapi_test.go | 395 - btcjson/jsoncmd.go | 7283 ----------------- btcjson/jsoncmd_test.go | 1814 ---- btcjson/jsonerr.go | 175 - btcjson/jsonfxns.go | 79 - btcjson/jsonfxns_test.go | 56 - btcjson/jsonresults.go | 750 -- btcjson/jsonresults_test.go | 99 - btcjson/{v2/btcjson => }/jsonrpc.go | 0 btcjson/{v2/btcjson => }/jsonrpc_test.go | 2 +- btcjson/{v2/btcjson => }/jsonrpcerr.go | 0 btcjson/{v2/btcjson => }/register.go | 0 btcjson/{v2/btcjson => }/register_test.go | 2 +- btcjson/v2/btcjson/README.md | 87 - btcjson/v2/btcjson/doc.go | 146 - btcjson/{v2/btcjson => }/walletsvrcmds.go | 0 .../{v2/btcjson => }/walletsvrcmds_test.go | 2 +- btcjson/{v2/btcjson => }/walletsvrresults.go | 0 btcjson/{v2/btcjson => }/walletsvrwscmds.go | 0 .../{v2/btcjson => }/walletsvrwscmds_test.go | 2 +- btcjson/{v2/btcjson => }/walletsvrwsntfns.go | 0 .../{v2/btcjson => }/walletsvrwsntfns_test.go | 2 +- cmd/btcctl/btcctl.go | 2 +- cmd/btcctl/config.go | 2 +- cmd/btcctl/httpclient.go | 2 +- rpcserver.go | 5 +- rpcserverhelp.go | 2 +- rpcwebsocket.go | 2 +- server.go | 2 +- 63 files changed, 166 insertions(+), 16401 deletions(-) rename btcjson/{v2/btcjson => }/btcdextcmds.go (100%) rename btcjson/{v2/btcjson => }/btcdextcmds_test.go (99%) rename btcjson/{v2/btcjson => }/btcwalletextcmds.go (100%) rename btcjson/{v2/btcjson => }/btcwalletextcmds_test.go (99%) delete mode 100644 btcjson/btcws/README.md delete mode 100644 btcjson/btcws/cmds.go delete mode 100644 btcjson/btcws/cmds_test.go delete mode 100644 btcjson/btcws/notifications.go delete mode 100644 btcjson/btcws/notifications_test.go rename btcjson/{v2/btcjson => }/chainsvrcmds.go (100%) rename btcjson/{v2/btcjson => }/chainsvrcmds_test.go (99%) rename btcjson/{v2/btcjson => }/chainsvrresults.go (100%) rename btcjson/{v2/btcjson => }/chainsvrresults_test.go (96%) rename btcjson/{v2/btcjson => }/chainsvrwscmds.go (100%) rename btcjson/{v2/btcjson => }/chainsvrwscmds_test.go (99%) rename btcjson/{v2/btcjson => }/chainsvrwsntfns.go (100%) rename btcjson/{v2/btcjson => }/chainsvrwsntfns_test.go (99%) delete mode 100644 btcjson/cmdhelp.go rename btcjson/{v2/btcjson => }/cmdinfo.go (100%) rename btcjson/{v2/btcjson => }/cmdinfo_test.go (99%) rename btcjson/{v2/btcjson => }/cmdparse.go (100%) rename btcjson/{v2/btcjson => }/cmdparse_test.go (99%) rename btcjson/{v2/btcjson => }/error.go (100%) rename btcjson/{v2/btcjson => }/error_test.go (97%) rename btcjson/{v2/btcjson => }/example_test.go (99%) rename btcjson/{v2/btcjson => }/export_test.go (100%) rename btcjson/{v2/btcjson => }/help.go (100%) rename btcjson/{v2/btcjson => }/help_test.go (99%) rename btcjson/{v2/btcjson => }/helpers.go (100%) rename btcjson/{v2/btcjson => }/helpers_test.go (97%) delete mode 100644 btcjson/internal_test.go delete mode 100644 btcjson/jsonapi.go delete mode 100644 btcjson/jsonapi_test.go delete mode 100644 btcjson/jsoncmd.go delete mode 100644 btcjson/jsoncmd_test.go delete mode 100644 btcjson/jsonerr.go delete mode 100644 btcjson/jsonfxns.go delete mode 100644 btcjson/jsonfxns_test.go delete mode 100644 btcjson/jsonresults.go delete mode 100644 btcjson/jsonresults_test.go rename btcjson/{v2/btcjson => }/jsonrpc.go (100%) rename btcjson/{v2/btcjson => }/jsonrpc_test.go (98%) rename btcjson/{v2/btcjson => }/jsonrpcerr.go (100%) rename btcjson/{v2/btcjson => }/register.go (100%) rename btcjson/{v2/btcjson => }/register_test.go (99%) delete mode 100644 btcjson/v2/btcjson/README.md delete mode 100644 btcjson/v2/btcjson/doc.go rename btcjson/{v2/btcjson => }/walletsvrcmds.go (100%) rename btcjson/{v2/btcjson => }/walletsvrcmds_test.go (99%) rename btcjson/{v2/btcjson => }/walletsvrresults.go (100%) rename btcjson/{v2/btcjson => }/walletsvrwscmds.go (100%) rename btcjson/{v2/btcjson => }/walletsvrwscmds_test.go (99%) rename btcjson/{v2/btcjson => }/walletsvrwsntfns.go (100%) rename btcjson/{v2/btcjson => }/walletsvrwsntfns_test.go (99%) diff --git a/btcjson/README.md b/btcjson/README.md index e3662c6d..525a30b8 100644 --- a/btcjson/README.md +++ b/btcjson/README.md @@ -7,12 +7,11 @@ btcjson Package btcjson implements concrete types for marshalling to and from the bitcoin JSON-RPC API. A comprehensive suite of tests is provided to ensure -proper functionality. Package btcjson is licensed under the copyfree ISC -license. +proper functionality. -Although this package was primarily written for btcd, it has intentionally been -designed so it can be used as a standalone package for any projects needing to -marshal to and from bitcoin JSON-RPC requests and responses. +Although this package was primarily written for the btcsuite, it has +intentionally been designed so it can be used as a standalone package for any +projects needing to marshal to and from bitcoin JSON-RPC requests and responses. Note that although it's possible to use this package directly to implement an RPC client, it is not recommended since it is only intended as an infrastructure @@ -23,42 +22,6 @@ management, websocket support, automatic notification re-registration on reconnect, and conversion from the raw underlying RPC types (strings, floats, ints, etc) to higher-level types with many nice and useful properties. -## JSON RPC - -Bitcoin provides an extensive API call list to control the chain and wallet -servers through JSON-RPC. These can be used to get information from the server -or to cause the server to perform some action. - -The general form of the commands are: - -```JSON - {"jsonrpc": "1.0", "id":"test", "method": "getinfo", "params": []} -``` - -btcjson provides code to easily create these commands from go (as some of the -commands can be fairly complex), to send the commands to a running bitcoin RPC -server, and to handle the replies (putting them in useful Go data structures). - -## Sample Use - -```Go - // Create a new command. - cmd, err := btcjson.NewGetBlockCountCmd() - if err != nil { - // Handle error - } - - // Marshal the command to a JSON-RPC formatted byte slice. - marshalled, err := btcjson.MarshalCmd(id, cmd) - if err != nil { - // Handle error - } - - // At this point marshalled contains the raw bytes that are ready to send - // to the RPC server to issue the command. - fmt.Printf("%s\n", marshalled) -``` - ## Documentation [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)] @@ -78,6 +41,26 @@ http://localhost:6060/pkg/github.com/btcsuite/btcd/btcjson $ go get github.com/btcsuite/btcd/btcjson ``` +## Examples + +* [Marshal Command] + (http://godoc.org/github.com/btcsuite/btcd/btcjson#example-MarshalCmd) + Demonstrates how to create and marshal a command into a JSON-RPC request. + +* [Unmarshal Command] + (http://godoc.org/github.com/btcsuite/btcd/btcjson#example-UnmarshalCmd) + Demonstrates how to unmarshal a JSON-RPC request and then unmarshal the + concrete request into a concrete command. + +* [Marshal Response] + (http://godoc.org/github.com/btcsuite/btcd/btcjson#example-MarshalResponse) + Demonstrates how to marshal a JSON-RPC response. + +* [Unmarshal Response] + (http://godoc.org/github.com/btcsuite/btcd/btcjson#example-package--UnmarshalResponse) + Demonstrates how to unmarshal a JSON-RPC response and then unmarshal the + result field in the response to a concrete type. + ## GPG Verification Key All official release tags are signed by Conformal so users can ensure the code diff --git a/btcjson/v2/btcjson/btcdextcmds.go b/btcjson/btcdextcmds.go similarity index 100% rename from btcjson/v2/btcjson/btcdextcmds.go rename to btcjson/btcdextcmds.go diff --git a/btcjson/v2/btcjson/btcdextcmds_test.go b/btcjson/btcdextcmds_test.go similarity index 99% rename from btcjson/v2/btcjson/btcdextcmds_test.go rename to btcjson/btcdextcmds_test.go index 9dd003c3..89fb478a 100644 --- a/btcjson/v2/btcjson/btcdextcmds_test.go +++ b/btcjson/btcdextcmds_test.go @@ -11,7 +11,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestBtcdExtCmds tests all of the btcd extended commands marshal and unmarshal diff --git a/btcjson/v2/btcjson/btcwalletextcmds.go b/btcjson/btcwalletextcmds.go similarity index 100% rename from btcjson/v2/btcjson/btcwalletextcmds.go rename to btcjson/btcwalletextcmds.go diff --git a/btcjson/v2/btcjson/btcwalletextcmds_test.go b/btcjson/btcwalletextcmds_test.go similarity index 99% rename from btcjson/v2/btcjson/btcwalletextcmds_test.go rename to btcjson/btcwalletextcmds_test.go index 78ad9952..5057d4b5 100644 --- a/btcjson/v2/btcjson/btcwalletextcmds_test.go +++ b/btcjson/btcwalletextcmds_test.go @@ -11,7 +11,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestBtcWalletExtCmds tests all of the btcwallet extended commands marshal and diff --git a/btcjson/btcws/README.md b/btcjson/btcws/README.md deleted file mode 100644 index cd1bb925..00000000 --- a/btcjson/btcws/README.md +++ /dev/null @@ -1,88 +0,0 @@ -btcws -===== - -[![Build Status](https://travis-ci.org/btcsuite/btcd.png?branch=master)] -(https://travis-ci.org/btcsuite/btcws) - -Package btcws implements extensions to the standard bitcoind JSON-RPC -API for the btcd suite of programs (btcd, btcwallet, and btcgui). -Importing this package registers all implemented custom requests with -btcjson (using btcjson.RegisterCustomCmd). - -## Sample Use -```Go -// Client Side -import ( - "golang.org/x/net/websocket" - "github.com/btcsuite/btcd/btcjson/btcws" -) - -// Create rescan command. -id := 0 -addrs := map[string]struct{}{ - "17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH": struct{}, -} -cmd, err := btcws.NewRescanCmd(id, 270000, addrs) - -// Set up a handler for a reply with id 0. -AddReplyHandler(id, func(reply map[string]interface{}) { - // Deal with reply. -}) - -// JSON marshal and send rescan request to websocket connection. -websocket.JSON.Send(btcdWSConn, cmd) - - -// Server Side -import ( - "golang.org/x/net/websocket" - "github.com/btcsuite/btcd/btcjson" - "github.com/btcsuite/btcd/btcjson/btcws" -) - -// Get marshaled request. -var b []byte -err := websocket.Message.Receive(clientWSConn, &b) - -// Parse marshaled command. -cmd, err := btcjson.ParseMarshaledCmd(b) - -// If this is a rescan command, handle and reply. -rcmd, ok := cmd.(*btcws.RescanCmd) -if ok { - // Do stuff - var reply []byte - err := websocket.Message.Send(clientWSConn, reply) -} - -``` - -## Installation - -```bash -$ go get github.com/btcsuite/btcd/btcjson/btcws -``` - -## GPG Verification Key - -All official release tags are signed by Conformal so users can ensure the code -has not been tampered with and is coming from Conformal. To verify the -signature perform the following: - -- Download the public key from the Conformal website at - https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt - -- Import the public key into your GPG keyring: - ```bash - gpg --import GIT-GPG-KEY-conformal.txt - ``` - -- Verify the release tag with the following command where `TAG_NAME` is a - placeholder for the specific tag: - ```bash - git tag -v TAG_NAME - ``` - -## License - -Package btcws is licensed under the liberal ISC License. diff --git a/btcjson/btcws/cmds.go b/btcjson/btcws/cmds.go deleted file mode 100644 index e79df6f3..00000000 --- a/btcjson/btcws/cmds.go +++ /dev/null @@ -1,1664 +0,0 @@ -// Copyright (c) 2013 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcws - -import ( - "encoding/json" - "errors" - - "github.com/btcsuite/btcd/btcjson" - "github.com/btcsuite/btcd/wire" -) - -// Help texts -const ( - authenticateHelp = `authenticate "username" "passphrase" -Authenticate the websocket with the RPC server. This is only required if the -credentials were not already supplied via HTTP auth headers. It must be the -first command sent or you will be disconnected.` - - createNewAccountHelp = `createnewaccount "accountname" -Create a new account with the given name.` - - renameAccountHelp = `renameaccount "oldname" "newname" -Rename an account to the given new name.` -) - -func init() { - btcjson.RegisterCustomCmd("authenticate", parseAuthenticateCmd, nil, - authenticateHelp) - btcjson.RegisterCustomCmd("createencryptedwallet", - parseCreateEncryptedWalletCmd, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("createnewaccount", - parseCreateNewAccountCmd, nil, createNewAccountHelp) - btcjson.RegisterCustomCmd("exportwatchingwallet", - parseExportWatchingWalletCmd, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("getbestblock", parseGetBestBlockCmd, - parseGetBestBlockCmdReply, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("getcurrentnet", parseGetCurrentNetCmd, nil, - `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("getunconfirmedbalance", - parseGetUnconfirmedBalanceCmd, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("listaddresstransactions", - parseListAddressTransactionsCmd, - parseListAddressTransactionsCmdReply, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("listalltransactions", - parseListAllTransactionsCmd, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("notifyblocks", parseNotifyBlocksCmd, nil, - `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("notifyreceived", parseNotifyReceivedCmd, nil, - `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("notifynewtransactions", - parseNotifyNewTransactionsCmd, nil, `TODO(flam) fillmein`) - btcjson.RegisterCustomCmd("notifyspent", parseNotifySpentCmd, - nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("recoveraddresses", parseRecoverAddressesCmd, - nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("renameaccount", parseRenameAccountCmd, - nil, renameAccountHelp) - btcjson.RegisterCustomCmd("rescan", parseRescanCmd, - nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd("walletislocked", parseWalletIsLockedCmd, - nil, `TODO(jrick) fillmein`) -} - -// AuthenticateCmd is a type handling custom marshaling and -// unmarshaling of authenticate JSON websocket extension -// commands. -type AuthenticateCmd struct { - id interface{} - Username string - Passphrase string -} - -// Enforce that AuthenticateCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &AuthenticateCmd{} - -// NewAuthenticateCmd creates a new GetCurrentNetCmd. -func NewAuthenticateCmd(id interface{}, username, passphrase string) *AuthenticateCmd { - return &AuthenticateCmd{ - id: id, - Username: username, - Passphrase: passphrase, - } -} - -// parseAuthenticateCmd parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the custom -// command with the btcjson parser. -func parseAuthenticateCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var username string - if err := json.Unmarshal(r.Params[0], &username); err != nil { - return nil, errors.New("first parameter 'username' must be " + - "a string: " + err.Error()) - } - - var passphrase string - if err := json.Unmarshal(r.Params[1], &passphrase); err != nil { - return nil, errors.New("second parameter 'passphrase' must " + - "be a string: " + err.Error()) - } - - return NewAuthenticateCmd(r.Id, username, passphrase), nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *AuthenticateCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *AuthenticateCmd) Method() string { - return "authenticate" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *AuthenticateCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Username, - cmd.Passphrase, - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *AuthenticateCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseAuthenticateCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*AuthenticateCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// GetCurrentNetCmd is a type handling custom marshaling and -// unmarshaling of getcurrentnet JSON websocket extension -// commands. -type GetCurrentNetCmd struct { - id interface{} -} - -// Enforce that GetCurrentNetCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &GetCurrentNetCmd{} - -// NewGetCurrentNetCmd creates a new GetCurrentNetCmd. -func NewGetCurrentNetCmd(id interface{}) *GetCurrentNetCmd { - return &GetCurrentNetCmd{id: id} -} - -// parseGetCurrentNetCmd parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the custom -// command with the btcjson parser. -func parseGetCurrentNetCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 0 { - return nil, btcjson.ErrWrongNumberOfParams - } - - return NewGetCurrentNetCmd(r.Id), nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *GetCurrentNetCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *GetCurrentNetCmd) Method() string { - return "getcurrentnet" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetCurrentNetCmd) MarshalJSON() ([]byte, error) { - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetCurrentNetCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseGetCurrentNetCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*GetCurrentNetCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// ExportWatchingWalletCmd is a type handling custom marshaling and -// unmarshaling of exportwatchingwallet JSON websocket extension -// commands. -type ExportWatchingWalletCmd struct { - id interface{} - Account string - Download bool -} - -// Enforce that ExportWatchingWalletCmd satisifies the btcjson.Cmd -// interface. -var _ btcjson.Cmd = &ExportWatchingWalletCmd{} - -// NewExportWatchingWalletCmd creates a new ExportWatchingWalletCmd. -func NewExportWatchingWalletCmd(id interface{}, optArgs ...interface{}) (*ExportWatchingWalletCmd, error) { - if len(optArgs) > 2 { - return nil, btcjson.ErrTooManyOptArgs - } - - // Optional parameters set to their defaults. - account := "" - dl := false - - if len(optArgs) > 0 { - a, ok := optArgs[0].(string) - if !ok { - return nil, errors.New("first optarg account must be a string") - } - account = a - } - if len(optArgs) > 1 { - b, ok := optArgs[1].(bool) - if !ok { - return nil, errors.New("second optarg zip must be a boolean") - } - dl = b - } - - return &ExportWatchingWalletCmd{ - id: id, - Account: account, - Download: dl, - }, nil -} - -// parseExportWatchingWalletCmd parses a RawCmd into a concrete type -// satisifying the btcjson.Cmd interface. This is used when registering -// the custom command with the btcjson parser. -func parseExportWatchingWalletCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) > 2 { - return nil, btcjson.ErrTooManyOptArgs - } - - optArgs := make([]interface{}, 0, 2) - if len(r.Params) > 0 { - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return nil, errors.New("first optional parameter " + - " 'account' must be a string: " + err.Error()) - } - optArgs = append(optArgs, account) - } - - if len(r.Params) > 1 { - var download bool - if err := json.Unmarshal(r.Params[1], &download); err != nil { - return nil, errors.New("second optional parameter " + - " 'download' must be a bool: " + err.Error()) - } - optArgs = append(optArgs, download) - } - - return NewExportWatchingWalletCmd(r.Id, optArgs...) -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *ExportWatchingWalletCmd) Id() interface{} { - return cmd.id -} - -// Method satisifies the Cmd interface by returning the RPC method. -func (cmd *ExportWatchingWalletCmd) Method() string { - return "exportwatchingwallet" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ExportWatchingWalletCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 2) - if cmd.Account != "" || cmd.Download { - params = append(params, cmd.Account) - } - if cmd.Download { - params = append(params, cmd.Download) - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ExportWatchingWalletCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseExportWatchingWalletCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*ExportWatchingWalletCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// GetUnconfirmedBalanceCmd is a type handling custom marshaling and -// unmarshaling of getunconfirmedbalance JSON websocket extension -// commands. -type GetUnconfirmedBalanceCmd struct { - id interface{} - Account string -} - -// Enforce that GetUnconfirmedBalanceCmd satisifies the btcjson.Cmd -// interface. -var _ btcjson.Cmd = &GetUnconfirmedBalanceCmd{} - -// NewGetUnconfirmedBalanceCmd creates a new GetUnconfirmedBalanceCmd. -func NewGetUnconfirmedBalanceCmd(id interface{}, - optArgs ...string) (*GetUnconfirmedBalanceCmd, error) { - - if len(optArgs) > 1 { - return nil, btcjson.ErrTooManyOptArgs - } - - // Optional parameters set to their defaults. - account := "" - - if len(optArgs) == 1 { - account = optArgs[0] - } - - return &GetUnconfirmedBalanceCmd{ - id: id, - Account: account, - }, nil -} - -// parseGetUnconfirmedBalanceCmd parses a RawCmd into a concrete type -// satisifying the btcjson.Cmd interface. This is used when registering -// the custom command with the btcjson parser. -func parseGetUnconfirmedBalanceCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) > 1 { - return nil, btcjson.ErrWrongNumberOfParams - } - - optArgs := make([]string, 0, 1) - if len(r.Params) > 0 { - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return nil, errors.New("first optional parameter " + - " 'account' must be a string: " + err.Error()) - } - optArgs = append(optArgs, account) - } - - return NewGetUnconfirmedBalanceCmd(r.Id, optArgs...) -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *GetUnconfirmedBalanceCmd) Id() interface{} { - return cmd.id -} - -// Method satisifies the Cmd interface by returning the RPC method. -func (cmd *GetUnconfirmedBalanceCmd) Method() string { - return "getunconfirmedbalance" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetUnconfirmedBalanceCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.Account != "" { - params = append(params, cmd.Account) - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetUnconfirmedBalanceCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseGetUnconfirmedBalanceCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*GetUnconfirmedBalanceCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// GetBestBlockResult holds the result of a getbestblock response. -type GetBestBlockResult struct { - Hash string `json:"hash"` - Height int32 `json:"height"` -} - -// GetBestBlockCmd is a type handling custom marshaling and -// unmarshaling of getbestblock JSON websocket extension -// commands. -type GetBestBlockCmd struct { - id interface{} -} - -// Enforce that GetBestBlockCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &GetBestBlockCmd{} - -// NewGetBestBlockCmd creates a new GetBestBlock. -func NewGetBestBlockCmd(id interface{}) *GetBestBlockCmd { - return &GetBestBlockCmd{id: id} -} - -// parseGetBestBlockCmd parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the custom -// command with the btcjson parser. -func parseGetBestBlockCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 0 { - return nil, btcjson.ErrWrongNumberOfParams - } - - return NewGetBestBlockCmd(r.Id), nil -} - -// parseGetBestBlockCmdReply parses a the reply to a GetBestBlockCmd into a -// concrete type and returns it packed into an interface. This is used when -// registering the custom command with btcjson. -func parseGetBestBlockCmdReply(message json.RawMessage) (interface{}, error) { - var res *GetBestBlockResult - if err := json.Unmarshal(message, &res); err != nil { - return nil, err - } - return res, nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *GetBestBlockCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *GetBestBlockCmd) Method() string { - return "getbestblock" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetBestBlockCmd) MarshalJSON() ([]byte, error) { - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetBestBlockCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseGetBestBlockCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*GetBestBlockCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// RecoverAddressesCmd is a type handling custom marshaling and -// unmarshaling of recoveraddresses JSON websocket extension -// commands. -type RecoverAddressesCmd struct { - id interface{} - Account string - N int -} - -// Enforce that RecoverAddressesCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &RecoverAddressesCmd{} - -// NewRecoverAddressesCmd creates a new RecoverAddressesCmd. -func NewRecoverAddressesCmd(id interface{}, account string, n int) *RecoverAddressesCmd { - return &RecoverAddressesCmd{ - id: id, - Account: account, - N: n, - } -} - -// parseRecoverAddressesCmd parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the custom -// command with the btcjson parser. -func parseRecoverAddressesCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return nil, errors.New("first parameter 'account' must be a " + - "string: " + err.Error()) - } - - var n int - if err := json.Unmarshal(r.Params[1], &n); err != nil { - return nil, errors.New("second parameter 'n' must be an " + - "integer: " + err.Error()) - } - - return NewRecoverAddressesCmd(r.Id, account, n), nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *RecoverAddressesCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *RecoverAddressesCmd) Method() string { - return "recoveraddresses" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *RecoverAddressesCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Account, - cmd.N, - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *RecoverAddressesCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseRecoverAddressesCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*RecoverAddressesCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// RenameAccountCmd is a type handling custom marshaling and -// unmarshaling of renameaccount JSON websocket extension -// commands. -type RenameAccountCmd struct { - id interface{} - OldAccount string - NewAccount string -} - -// Enforce that RenameAccountCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &RenameAccountCmd{} - -// NewRenameAccountCmd creates a new GetCurrentNetCmd. -func NewRenameAccountCmd(id interface{}, oldaccount, newaccount string) *RenameAccountCmd { - return &RenameAccountCmd{ - id: id, - OldAccount: oldaccount, - NewAccount: newaccount, - } -} - -// parseRenameAccountCmd parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the custom -// command with the btcjson parser. -func parseRenameAccountCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var oldaccount string - if err := json.Unmarshal(r.Params[0], &oldaccount); err != nil { - return nil, errors.New("first parameter 'oldaccount' must be " + - "a string: " + err.Error()) - } - - var newaccount string - if err := json.Unmarshal(r.Params[1], &newaccount); err != nil { - return nil, errors.New("second parameter 'newaccount' must " + - "be a string: " + err.Error()) - } - - return NewRenameAccountCmd(r.Id, oldaccount, newaccount), nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *RenameAccountCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *RenameAccountCmd) Method() string { - return "renameaccount" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *RenameAccountCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.OldAccount, - cmd.NewAccount, - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *RenameAccountCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseRenameAccountCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*RenameAccountCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// OutPoint describes a transaction outpoint that will be marshalled to and -// from JSON. -type OutPoint struct { - Hash string `json:"hash"` - Index uint32 `json:"index"` -} - -// NewOutPointFromWire creates a new OutPoint from the OutPoint structure -// of the wire package. -func NewOutPointFromWire(op *wire.OutPoint) *OutPoint { - return &OutPoint{ - Hash: op.Hash.String(), - Index: op.Index, - } -} - -// RescanCmd is a type handling custom marshaling and -// unmarshaling of rescan JSON websocket extension -// commands. -type RescanCmd struct { - id interface{} - BeginBlock string - Addresses []string - OutPoints []OutPoint - EndBlock string -} - -// Enforce that RescanCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &RescanCmd{} - -// NewRescanCmd creates a new RescanCmd, parsing the optional -// arguments optArgs which may either be empty or a single upper -// block hash. -func NewRescanCmd(id interface{}, begin string, addresses []string, - outpoints []OutPoint, optArgs ...string) (*RescanCmd, error) { - - // Optional parameters set to their defaults. - var end string - - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, btcjson.ErrTooManyOptArgs - } - end = optArgs[0] - } - - return &RescanCmd{ - id: id, - BeginBlock: begin, - Addresses: addresses, - OutPoints: outpoints, - EndBlock: end, - }, nil -} - -// parseRescanCmd parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the custom -// command with the btcjson parser. -func parseRescanCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) < 3 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var begin string - if err := json.Unmarshal(r.Params[0], &begin); err != nil { - return nil, errors.New("first parameter 'begin' must be a " + - "string: " + err.Error()) - } - - var addresses []string - if err := json.Unmarshal(r.Params[1], &addresses); err != nil { - return nil, errors.New("second parameter 'addresses' must be " + - "an array of strings: " + err.Error()) - } - - var outpoints []OutPoint - if err := json.Unmarshal(r.Params[2], &outpoints); err != nil { - return nil, errors.New("third parameter 'outpoints' must be " + - "an array of transaction outpoint JSON objects: " + - err.Error()) - } - - optArgs := make([]string, 0, 1) - if len(r.Params) > 3 { - var endblock string - if err := json.Unmarshal(r.Params[3], &endblock); err != nil { - return nil, errors.New("fourth optional parameter " + - "'endblock' must be a string: " + err.Error()) - } - optArgs = append(optArgs, endblock) - } - - return NewRescanCmd(r.Id, begin, addresses, outpoints, optArgs...) -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *RescanCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *RescanCmd) Method() string { - return "rescan" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *RescanCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 3, 4) - params[0] = cmd.BeginBlock - params[1] = cmd.Addresses - params[2] = cmd.OutPoints - if cmd.EndBlock != "" { - params = append(params, cmd.EndBlock) - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *RescanCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseRescanCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*RescanCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// NotifyBlocksCmd is a type handling custom marshaling and -// unmarshaling of notifyblocks JSON websocket extension -// commands. -type NotifyBlocksCmd struct { - id interface{} -} - -// Enforce that NotifyBlocksCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &NotifyBlocksCmd{} - -// NewNotifyBlocksCmd creates a new NotifyBlocksCmd. -func NewNotifyBlocksCmd(id interface{}) *NotifyBlocksCmd { - return &NotifyBlocksCmd{ - id: id, - } -} - -// parseNotifyBlocksCmd parses a NotifyBlocksCmd into a concrete type -// satisifying the btcjson.Cmd interface. This is used when registering -// the custom command with the btcjson parser. -func parseNotifyBlocksCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 0 { - return nil, btcjson.ErrWrongNumberOfParams - } - return NewNotifyBlocksCmd(r.Id), nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *NotifyBlocksCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *NotifyBlocksCmd) Method() string { - return "notifyblocks" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *NotifyBlocksCmd) MarshalJSON() ([]byte, error) { - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *NotifyBlocksCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseNotifyBlocksCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*NotifyBlocksCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// NotifyReceivedCmd is a type handling custom marshaling and -// unmarshaling of notifyreceived JSON websocket extension -// commands. -type NotifyReceivedCmd struct { - id interface{} - Addresses []string -} - -// Enforce that NotifyReceivedCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &NotifyReceivedCmd{} - -// NewNotifyReceivedCmd creates a new NotifyReceivedCmd. -func NewNotifyReceivedCmd(id interface{}, addresses []string) *NotifyReceivedCmd { - return &NotifyReceivedCmd{ - id: id, - Addresses: addresses, - } -} - -// parseNotifyReceivedCmd parses a NotifyNewTXsCmd into a concrete type -// satisifying the btcjson.Cmd interface. This is used when registering -// the custom command with the btcjson parser. -func parseNotifyReceivedCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 1 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var addresses []string - if err := json.Unmarshal(r.Params[0], &addresses); err != nil { - return nil, errors.New("first parameter 'addresses' must be " + - "an array of strings: " + err.Error()) - } - - return NewNotifyReceivedCmd(r.Id, addresses), nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *NotifyReceivedCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *NotifyReceivedCmd) Method() string { - return "notifyreceived" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *NotifyReceivedCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Addresses, - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *NotifyReceivedCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseNotifyReceivedCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*NotifyReceivedCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// NotifyNewTransactionsCmd is a type handling custom marshaling and -// unmarshaling of notifynewtransactions JSON websocket extension -// commands. -type NotifyNewTransactionsCmd struct { - id interface{} - Verbose bool -} - -// Enforce that NotifyNewTransactionsCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &NotifyNewTransactionsCmd{} - -// NewNotifyNewTransactionsCmd creates a new NotifyNewTransactionsCmd that -// optionally takes a single verbose parameter that defaults to false. -func NewNotifyNewTransactionsCmd(id interface{}, optArgs ...bool) (*NotifyNewTransactionsCmd, error) { - verbose := false - - optArgsLen := len(optArgs) - if optArgsLen > 0 { - if optArgsLen > 1 { - return nil, btcjson.ErrTooManyOptArgs - } - verbose = optArgs[0] - } - - return &NotifyNewTransactionsCmd{ - id: id, - Verbose: verbose, - }, nil -} - -// parseNotifyNewTransactionsCmd parses a NotifyNewTransactionsCmd into a -// concrete type satisifying the btcjson.Cmd interface. This is used when -// registering the custom command with the btcjson parser. -func parseNotifyNewTransactionsCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) > 1 { - return nil, btcjson.ErrWrongNumberOfParams - } - - optArgs := make([]bool, 0, 1) - if len(r.Params) > 0 { - var verbose bool - if err := json.Unmarshal(r.Params[0], &verbose); err != nil { - return nil, errors.New("first optional parameter " + - "'verbose' must be a bool: " + err.Error()) - } - optArgs = append(optArgs, verbose) - } - - return NewNotifyNewTransactionsCmd(r.Id, optArgs...) -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *NotifyNewTransactionsCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *NotifyNewTransactionsCmd) Method() string { - return "notifynewtransactions" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *NotifyNewTransactionsCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Verbose, - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *NotifyNewTransactionsCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseNotifyNewTransactionsCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*NotifyNewTransactionsCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// NotifySpentCmd is a type handling custom marshaling and -// unmarshaling of notifyspent JSON websocket extension -// commands. -type NotifySpentCmd struct { - id interface{} - OutPoints []OutPoint -} - -// Enforce that NotifySpentCmd satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &NotifySpentCmd{} - -// NewNotifySpentCmd creates a new NotifySpentCmd. -func NewNotifySpentCmd(id interface{}, outpoints []OutPoint) *NotifySpentCmd { - return &NotifySpentCmd{ - id: id, - OutPoints: outpoints, - } -} - -// parseNotifySpentCmd parses a NotifySpentCmd into a concrete type -// satisifying the btcjson.Cmd interface. This is used when registering -// the custom command with the btcjson parser. -func parseNotifySpentCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 1 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var outpoints []OutPoint - if err := json.Unmarshal(r.Params[0], &outpoints); err != nil { - return nil, errors.New("first parameter 'outpoints' must be a " + - "an array of transaction outpoint JSON objects: " + - err.Error()) - } - - return NewNotifySpentCmd(r.Id, outpoints), nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *NotifySpentCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *NotifySpentCmd) Method() string { - return "notifyspent" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *NotifySpentCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.OutPoints, - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *NotifySpentCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseNotifySpentCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*NotifySpentCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// CreateEncryptedWalletCmd is a type handling custom -// marshaling and unmarshaling of createencryptedwallet -// JSON websocket extension commands. -type CreateEncryptedWalletCmd struct { - id interface{} - Passphrase string -} - -// Enforce that CreateEncryptedWalletCmd satisifies the btcjson.Cmd -// interface. -var _ btcjson.Cmd = &CreateEncryptedWalletCmd{} - -// NewCreateEncryptedWalletCmd creates a new CreateEncryptedWalletCmd. -func NewCreateEncryptedWalletCmd(id interface{}, passphrase string) *CreateEncryptedWalletCmd { - return &CreateEncryptedWalletCmd{ - id: id, - Passphrase: passphrase, - } -} - -// parseCreateEncryptedWalletCmd parses a CreateEncryptedWalletCmd -// into a concrete type satisifying the btcjson.Cmd interface. -// This is used when registering the custom command with the btcjson -// parser. -func parseCreateEncryptedWalletCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 1 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var passphrase string - if err := json.Unmarshal(r.Params[0], &passphrase); err != nil { - return nil, errors.New("first parameter 'passphrase' must be " + - "a string: " + err.Error()) - } - - return NewCreateEncryptedWalletCmd(r.Id, passphrase), nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *CreateEncryptedWalletCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *CreateEncryptedWalletCmd) Method() string { - return "createencryptedwallet" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *CreateEncryptedWalletCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Passphrase, - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *CreateEncryptedWalletCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseCreateEncryptedWalletCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*CreateEncryptedWalletCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// CreateNewAccountCmd is a type handling custom -// marshaling and unmarshaling of createnewaccount -// JSON websocket extension commands. -type CreateNewAccountCmd struct { - id interface{} - Account string -} - -// Enforce that CreateNewAccountCmd satisifies the btcjson.Cmd -// interface. -var _ btcjson.Cmd = &CreateNewAccountCmd{} - -// NewCreateNewAccountCmd creates a new CreateNewAccountCmd. -func NewCreateNewAccountCmd(id interface{}, account string) *CreateNewAccountCmd { - return &CreateNewAccountCmd{ - id: id, - Account: account, - } -} - -// parseCreateNewAccountCmd parses a CreateNewAccountCmd -// into a concrete type satisifying the btcjson.Cmd interface. -// This is used when registering the custom command with the btcjson -// parser. -func parseCreateNewAccountCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) != 1 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return nil, errors.New("first parameter 'account' must be " + - "a string: " + err.Error()) - } - - return NewCreateNewAccountCmd(r.Id, account), nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *CreateNewAccountCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *CreateNewAccountCmd) Method() string { - return "createnewaccount" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *CreateNewAccountCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Account, - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *CreateNewAccountCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseCreateNewAccountCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*CreateNewAccountCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// WalletIsLockedCmd is a type handling custom marshaling and -// unmarshaling of walletislocked JSON websocket extension commands. -type WalletIsLockedCmd struct { - id interface{} - Account string -} - -// Enforce that WalletIsLockedCmd satisifies the btcjson.Cmd -// interface. -var _ btcjson.Cmd = &WalletIsLockedCmd{} - -// NewWalletIsLockedCmd creates a new WalletIsLockedCmd. -func NewWalletIsLockedCmd(id interface{}, - optArgs ...string) (*WalletIsLockedCmd, error) { - - // Optional arguments set to their default values. - account := "" - - if len(optArgs) > 1 { - return nil, btcjson.ErrInvalidParams - } - - if len(optArgs) == 1 { - account = optArgs[0] - } - - return &WalletIsLockedCmd{ - id: id, - Account: account, - }, nil -} - -// parseWalletIsLockedCmd parses a WalletIsLockedCmd into a concrete -// type satisifying the btcjson.Cmd interface. This is used when -// registering the custom command with the btcjson parser. -func parseWalletIsLockedCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) > 1 { - return nil, btcjson.ErrInvalidParams - } - - if len(r.Params) == 0 { - return NewWalletIsLockedCmd(r.Id) - } - - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return nil, errors.New("first parameter 'account' must be a " + - "string: " + err.Error()) - } - - return NewWalletIsLockedCmd(r.Id, account) -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *WalletIsLockedCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *WalletIsLockedCmd) Method() string { - return "walletislocked" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *WalletIsLockedCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.Account != "" { - params = append(params, cmd.Account) - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *WalletIsLockedCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseWalletIsLockedCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*WalletIsLockedCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// ListAddressTransactionsCmd is a type handling custom marshaling and -// unmarshaling of listaddresstransactions JSON websocket extension commands. -type ListAddressTransactionsCmd struct { - id interface{} - Account string - Addresses []string -} - -// Enforce that ListAddressTransactionsCmd satisifies the btcjson.Cmd -// interface. -var _ btcjson.Cmd = &ListAddressTransactionsCmd{} - -// NewListAddressTransactionsCmd creates a new ListAddressTransactionsCmd. -func NewListAddressTransactionsCmd(id interface{}, addresses []string, - optArgs ...string) (*ListAddressTransactionsCmd, error) { - - if len(optArgs) > 1 { - return nil, btcjson.ErrTooManyOptArgs - } - - // Optional arguments set to their default values. - account := "" - - if len(optArgs) == 1 { - account = optArgs[0] - } - - return &ListAddressTransactionsCmd{ - id: id, - Account: account, - Addresses: addresses, - }, nil -} - -// parseListAddressTransactionsCmd parses a ListAddressTransactionsCmd into -// a concrete type satisifying the btcjson.Cmd interface. This is used -// when registering the custom command with the btcjson parser. -func parseListAddressTransactionsCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) == 0 || len(r.Params) > 2 { - return nil, btcjson.ErrInvalidParams - } - - var addresses []string - if err := json.Unmarshal(r.Params[0], &addresses); err != nil { - return nil, errors.New("first parameter 'addresses' must be " + - "an array of strings: " + err.Error()) - } - - optArgs := make([]string, 0, 1) - if len(r.Params) > 1 { - var account string - if err := json.Unmarshal(r.Params[1], &account); err != nil { - return nil, errors.New("second optional parameter " + - "'account' must be a string: " + err.Error()) - } - optArgs = append(optArgs, account) - } - - return NewListAddressTransactionsCmd(r.Id, addresses, optArgs...) -} - -// parseListAddressTransactionsCmdReply parses a the reply to a -// ListAddressTransactionsCmd into a concrete type and returns it packed into -// an interface. This is used when registering the custom command with btcjson. -func parseListAddressTransactionsCmdReply(message json.RawMessage) (interface{}, error) { - var res []btcjson.ListTransactionsResult - if err := json.Unmarshal(message, &res); err != nil { - return nil, err - } - return res, nil -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *ListAddressTransactionsCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *ListAddressTransactionsCmd) Method() string { - return "listaddresstransactions" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListAddressTransactionsCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.Addresses - if cmd.Account != "" { - params = append(params, cmd.Account) - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListAddressTransactionsCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseListAddressTransactionsCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*ListAddressTransactionsCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} - -// ListAllTransactionsCmd is a type handling custom marshaling and -// unmarshaling of listalltransactions JSON websocket extension commands. -type ListAllTransactionsCmd struct { - id interface{} - Account *string -} - -// Enforce that ListAllTransactionsCmd satisifies the btcjson.Cmd -// interface. -var _ btcjson.Cmd = &ListAllTransactionsCmd{} - -// NewListAllTransactionsCmd creates a new ListAllTransactionsCmd. -func NewListAllTransactionsCmd(id interface{}, - optArgs ...string) (*ListAllTransactionsCmd, error) { - - // Optional arguments set to their default values. - var account *string - - if len(optArgs) > 1 { - return nil, btcjson.ErrInvalidParams - } - - if len(optArgs) == 1 { - account = &optArgs[0] - } - - return &ListAllTransactionsCmd{ - id: id, - Account: account, - }, nil -} - -// parseListAllTransactionsCmd parses a ListAllTransactionsCmd into a concrete -// type satisifying the btcjson.Cmd interface. This is used when -// registering the custom command with the btcjson parser. -func parseListAllTransactionsCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if len(r.Params) > 1 { - return nil, btcjson.ErrInvalidParams - } - - optArgs := make([]string, 0, 1) - if len(r.Params) > 0 { - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return nil, errors.New("first optional parameter " + - "'account' must be a string: " + err.Error()) - } - optArgs = append(optArgs, account) - } - - return NewListAllTransactionsCmd(r.Id, optArgs...) -} - -// Id satisifies the Cmd interface by returning the ID of the command. -func (cmd *ListAllTransactionsCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the RPC method. -func (cmd *ListAllTransactionsCmd) Method() string { - return "listalltransactions" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListAllTransactionsCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.Account != nil { - params = append(params, cmd.Account) - } - - raw, err := btcjson.NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListAllTransactionsCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newCmd, err := parseListAllTransactionsCmd(&r) - if err != nil { - return err - } - - concreteCmd, ok := newCmd.(*ListAllTransactionsCmd) - if !ok { - return btcjson.ErrInternal - } - *cmd = *concreteCmd - return nil -} diff --git a/btcjson/btcws/cmds_test.go b/btcjson/btcws/cmds_test.go deleted file mode 100644 index f6c8f173..00000000 --- a/btcjson/btcws/cmds_test.go +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright (c) 2013 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -// this has to be in the real package so we can mock up structs -package btcws - -import ( - "reflect" - "testing" - - "github.com/btcsuite/btcd/btcjson" - "github.com/davecgh/go-spew/spew" -) - -var testAccount = "account" - -var cmdtests = []struct { - name string - f func() (btcjson.Cmd, error) - result btcjson.Cmd // after marshal and unmarshal -}{ - { - name: "createencryptedwallet", - f: func() (btcjson.Cmd, error) { - return NewCreateEncryptedWalletCmd( - float64(1), - "banana"), nil - }, - result: &CreateEncryptedWalletCmd{ - id: float64(1), - Passphrase: "banana", - }, - }, - { - name: "createnewaccount", - f: func() (btcjson.Cmd, error) { - return NewCreateNewAccountCmd( - float64(1), - "account"), nil - }, - result: &CreateNewAccountCmd{ - id: float64(1), - Account: "account", - }, - }, - { - name: "getbestblock", - f: func() (btcjson.Cmd, error) { - return NewGetBestBlockCmd(float64(1)), nil - }, - result: &GetBestBlockCmd{ - id: float64(1), - }, - }, - { - name: "getcurrentnet", - f: func() (btcjson.Cmd, error) { - return NewGetCurrentNetCmd(float64(1)), nil - }, - result: &GetCurrentNetCmd{ - id: float64(1), - }, - }, - { - name: "getunconfirmedbalance no optargs", - f: func() (btcjson.Cmd, error) { - return NewGetUnconfirmedBalanceCmd(float64(1)) - }, - result: &GetUnconfirmedBalanceCmd{ - id: float64(1), - Account: "", - }, - }, - { - name: "getunconfirmedbalance one optarg", - f: func() (btcjson.Cmd, error) { - return NewGetUnconfirmedBalanceCmd(float64(1), - testAccount) - }, - result: &GetUnconfirmedBalanceCmd{ - id: float64(1), - Account: testAccount, - }, - }, - { - name: "listaddresstransactions no optargs", - f: func() (btcjson.Cmd, error) { - addrs := []string{ - "17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH", - } - return NewListAddressTransactionsCmd( - float64(1), - addrs) - }, - result: &ListAddressTransactionsCmd{ - id: float64(1), - Account: "", - Addresses: []string{ - "17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH", - }, - }, - }, - { - name: "listaddresstransactions one optarg", - f: func() (btcjson.Cmd, error) { - addrs := []string{ - "17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH", - } - return NewListAddressTransactionsCmd( - float64(1), - addrs, - testAccount) - }, - result: &ListAddressTransactionsCmd{ - id: float64(1), - Account: testAccount, - Addresses: []string{ - "17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH", - }, - }, - }, - { - name: "listalltransactions no optargs", - f: func() (btcjson.Cmd, error) { - return NewListAllTransactionsCmd(float64(1)) - }, - result: &ListAllTransactionsCmd{ - id: float64(1), - Account: nil, - }, - }, - { - name: "listalltransactions one optarg", - f: func() (btcjson.Cmd, error) { - return NewListAllTransactionsCmd( - float64(1), - testAccount) - }, - result: &ListAllTransactionsCmd{ - id: float64(1), - Account: &testAccount, - }, - }, - { - name: "notifyreceived", - f: func() (btcjson.Cmd, error) { - addrs := []string{ - "17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH", - } - return NewNotifyReceivedCmd( - float64(1), - addrs), nil - }, - result: &NotifyReceivedCmd{ - id: float64(1), - Addresses: []string{ - "17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH", - }, - }, - }, - { - name: "notifynewtransactions", - f: func() (btcjson.Cmd, error) { - return NewNotifyNewTransactionsCmd( - float64(1), - true) - }, - result: &NotifyNewTransactionsCmd{ - id: float64(1), - Verbose: true, - }, - }, - { - name: "notifyspent", - f: func() (btcjson.Cmd, error) { - ops := []OutPoint{ - { - Hash: "000102030405060708091011121314" + - "1516171819202122232425262728" + - "293031", - Index: 1, - }, - } - return NewNotifySpentCmd(float64(1), ops), nil - }, - result: &NotifySpentCmd{ - id: float64(1), - OutPoints: []OutPoint{ - { - Hash: "000102030405060708091011121314" + - "1516171819202122232425262728" + - "293031", - Index: 1, - }, - }, - }, - }, - { - name: "renameaccount", - f: func() (btcjson.Cmd, error) { - return NewRenameAccountCmd( - float64(1), - "old", - "new"), nil - }, - result: &RenameAccountCmd{ - id: float64(1), - OldAccount: "old", - NewAccount: "new", - }, - }, - { - name: "rescan no optargs", - f: func() (btcjson.Cmd, error) { - addrs := []string{"17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH"} - ops := []OutPoint{ - { - Hash: "000102030405060708091011121314" + - "1516171819202122232425262728" + - "293031", - Index: 1, - }, - } - return NewRescanCmd( - float64(1), - "0000000000000002a775aec59dc6a9e4bb1c025cf1b8c2195dd9dc3998c827c5", - addrs, - ops) - }, - result: &RescanCmd{ - id: float64(1), - BeginBlock: "0000000000000002a775aec59dc6a9e4bb1c025cf1b8c2195dd9dc3998c827c5", - Addresses: []string{"17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH"}, - OutPoints: []OutPoint{ - { - Hash: "000102030405060708091011121314" + - "1516171819202122232425262728" + - "293031", - Index: 1, - }, - }, - EndBlock: "", - }, - }, - { - name: "rescan one optarg", - f: func() (btcjson.Cmd, error) { - addrs := []string{"17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH"} - ops := []OutPoint{ - { - Hash: "000102030405060708091011121314" + - "1516171819202122232425262728" + - "293031", - Index: 1, - }, - } - return NewRescanCmd( - float64(1), - "0000000000000002a775aec59dc6a9e4bb1c025cf1b8c2195dd9dc3998c827c5", - addrs, - ops, - "0000000000000001c091ada69f444dc0282ecaabe4808ddbb2532e5555db0c03") - }, - result: &RescanCmd{ - id: float64(1), - BeginBlock: "0000000000000002a775aec59dc6a9e4bb1c025cf1b8c2195dd9dc3998c827c5", - Addresses: []string{"17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH"}, - OutPoints: []OutPoint{ - { - Hash: "000102030405060708091011121314" + - "1516171819202122232425262728" + - "293031", - Index: 1, - }, - }, - EndBlock: "0000000000000001c091ada69f444dc0282ecaabe4808ddbb2532e5555db0c03", - }, - }, - { - name: "walletislocked no optargs", - f: func() (btcjson.Cmd, error) { - return NewWalletIsLockedCmd(float64(1)) - }, - result: &WalletIsLockedCmd{ - id: float64(1), - Account: "", - }, - }, - { - name: "walletislocked one optarg", - f: func() (btcjson.Cmd, error) { - return NewWalletIsLockedCmd( - float64(1), - testAccount) - }, - result: &WalletIsLockedCmd{ - id: float64(1), - Account: testAccount, - }, - }, -} - -func TestCmds(t *testing.T) { - for _, test := range cmdtests { - c, err := test.f() - if err != nil { - t.Errorf("%s: failed to run func: %v", - test.name, err) - continue - } - - mc, err := c.MarshalJSON() - if err != nil { - t.Errorf("%s: failed to marshal cmd: %v", - test.name, err) - continue - } - - c2, err := btcjson.ParseMarshaledCmd(mc) - if err != nil { - t.Errorf("%s: failed to ummarshal cmd: %v", - test.name, err) - continue - } - - if !reflect.DeepEqual(test.result, c2) { - t.Errorf("%s: unmarshal not as expected. "+ - "got %v wanted %v", test.name, spew.Sdump(c2), - spew.Sdump(test.result)) - } - if !reflect.DeepEqual(c, c2) { - t.Errorf("%s: unmarshal not as we started with. "+ - "got %v wanted %v", test.name, spew.Sdump(c2), - spew.Sdump(c)) - } - - // id from Id func must match result. - if c.Id() != test.result.Id() { - t.Errorf("%s: Id returned incorrect id. "+ - "got %v wanted %v", test.name, c.Id(), - test.result.Id()) - } - - // method from Method func must match result. - if c.Method() != test.result.Method() { - t.Errorf("%s: Method returned incorrect method. "+ - "got %v wanted %v", test.name, c.Method(), - test.result.Method()) - } - - // Read marshaled command back into c. Should still - // match result. - if err := c.UnmarshalJSON(mc); err != nil { - t.Errorf("%s: error while unmarshalling: %v", test.name, - err) - } - if !reflect.DeepEqual(test.result, c) { - t.Errorf("%s: unmarshal not as expected. "+ - "got %v wanted %v", test.name, spew.Sdump(c), - spew.Sdump(test.result)) - } - } -} diff --git a/btcjson/btcws/notifications.go b/btcjson/btcws/notifications.go deleted file mode 100644 index d06d5410..00000000 --- a/btcjson/btcws/notifications.go +++ /dev/null @@ -1,1249 +0,0 @@ -// Copyright (c) 2013 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcws - -import ( - "encoding/json" - "errors" - - "github.com/btcsuite/btcd/btcjson" -) - -var ( - // ErrNotANtfn describes an error where a JSON-RPC Request - // object cannot be successfully parsed as a notification - // due to having an ID. - ErrNotANtfn = errors.New("notifications may not have IDs") -) - -const ( - // AccountBalanceNtfnMethod is the method of the btcwallet - // accountbalance notification. - AccountBalanceNtfnMethod = "accountbalance" - - // TxAcceptedNtfnMethod is the method of the btcd txaccepted - // notification - TxAcceptedNtfnMethod = "txaccepted" - - // TxAcceptedVerboseNtfnMethod is the method of the btcd - // txacceptedverbose notifications. - TxAcceptedVerboseNtfnMethod = "txacceptedverbose" - - // BlockConnectedNtfnMethod is the method of the btcd - // blockconnected notification. - BlockConnectedNtfnMethod = "blockconnected" - - // BlockDisconnectedNtfnMethod is the method of the btcd - // blockdisconnected notification. - BlockDisconnectedNtfnMethod = "blockdisconnected" - - // BtcdConnectedNtfnMethod is the method of the btcwallet - // btcdconnected notification. - BtcdConnectedNtfnMethod = "btcdconnected" - - // RecvTxNtfnMethod is the method of the btcd recvtx notification. - RecvTxNtfnMethod = "recvtx" - - // TxNtfnMethod is the method of the btcwallet newtx - // notification. - TxNtfnMethod = "newtx" - - // RedeemingTxNtfnMethod is the method of the btcd redeemingtx - // notification. - RedeemingTxNtfnMethod = "redeemingtx" - - // RescanFinishedNtfnMethod is the method of the btcd rescanfinished - // notification. - RescanFinishedNtfnMethod = "rescanfinished" - - // RescanProgressNtfnMethod is the method of the btcd rescanprogress - // notification. - RescanProgressNtfnMethod = "rescanprogress" - - // WalletLockStateNtfnMethod is the method of the btcwallet - // walletlockstate notification. - WalletLockStateNtfnMethod = "walletlockstate" -) - -// Register notifications with btcjson. -func init() { - btcjson.RegisterCustomCmd(AccountBalanceNtfnMethod, - parseAccountBalanceNtfn, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(BlockConnectedNtfnMethod, - parseBlockConnectedNtfn, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(BlockDisconnectedNtfnMethod, - parseBlockDisconnectedNtfn, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(BtcdConnectedNtfnMethod, - parseBtcdConnectedNtfn, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(RecvTxNtfnMethod, - parseRecvTxNtfn, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(RescanFinishedNtfnMethod, - parseRescanFinishedNtfn, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(RescanProgressNtfnMethod, - parseRescanProgressNtfn, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(RedeemingTxNtfnMethod, parseRedeemingTxNtfn, - nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(TxNtfnMethod, parseTxNtfn, nil, - `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(WalletLockStateNtfnMethod, - parseWalletLockStateNtfn, nil, `TODO(jrick) fillmein`) - btcjson.RegisterCustomCmd(TxAcceptedNtfnMethod, parseTxAcceptedNtfn, nil, - `TODO(flam) fillmein`) - btcjson.RegisterCustomCmd(TxAcceptedVerboseNtfnMethod, - parseTxAcceptedVerboseNtfn, nil, `TODO(flam) fillmein`) -} - -// BlockDetails describes details of a tx in a block. -type BlockDetails struct { - Height int32 `json:"height"` - Hash string `json:"hash"` - Index int `json:"index"` - Time int64 `json:"time"` -} - -// AccountBalanceNtfn is a type handling custom marshaling and -// unmarshaling of accountbalance JSON websocket notifications. -type AccountBalanceNtfn struct { - Account string - Balance float64 - Confirmed bool // Whether Balance is confirmed or unconfirmed. -} - -// Enforce that AccountBalanceNtfn satisifes the btcjson.Cmd interface. -var _ btcjson.Cmd = &AccountBalanceNtfn{} - -// NewAccountBalanceNtfn creates a new AccountBalanceNtfn. -func NewAccountBalanceNtfn(account string, balance float64, - confirmed bool) *AccountBalanceNtfn { - - return &AccountBalanceNtfn{ - Account: account, - Balance: balance, - Confirmed: confirmed, - } -} - -// parseAccountBalanceNtfn parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the notification -// with the btcjson parser. -func parseAccountBalanceNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 3 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return nil, errors.New("first parameter 'account' must be a string: " + err.Error()) - } - - var balance float64 - if err := json.Unmarshal(r.Params[1], &balance); err != nil { - return nil, errors.New("second parameter 'balance' must be a number: " + err.Error()) - } - - var confirmed bool - if err := json.Unmarshal(r.Params[2], &confirmed); err != nil { - return nil, errors.New("third parameter 'confirmed' must be a bool: " + err.Error()) - } - - return NewAccountBalanceNtfn(account, balance, confirmed), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *AccountBalanceNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *AccountBalanceNtfn) Method() string { - return AccountBalanceNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *AccountBalanceNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.Account, - n.Balance, - n.Confirmed, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *AccountBalanceNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseAccountBalanceNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*AccountBalanceNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// BlockConnectedNtfn is a type handling custom marshaling and -// unmarshaling of blockconnected JSON websocket notifications. -type BlockConnectedNtfn struct { - Hash string - Height int32 -} - -// Enforce that BlockConnectedNtfn satisfies the btcjson.Cmd interface. -var _ btcjson.Cmd = &BlockConnectedNtfn{} - -// NewBlockConnectedNtfn creates a new BlockConnectedNtfn. -func NewBlockConnectedNtfn(hash string, height int32) *BlockConnectedNtfn { - return &BlockConnectedNtfn{ - Hash: hash, - Height: height, - } -} - -// parseBlockConnectedNtfn parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the notification -// with the btcjson parser. -func parseBlockConnectedNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var hash string - if err := json.Unmarshal(r.Params[0], &hash); err != nil { - return nil, errors.New("first parameter 'hash' must be a string: " + err.Error()) - } - - var height int32 - if err := json.Unmarshal(r.Params[1], &height); err != nil { - return nil, errors.New("second parameter 'height' must be a 32-bit integer: " + err.Error()) - } - - return NewBlockConnectedNtfn(hash, height), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *BlockConnectedNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *BlockConnectedNtfn) Method() string { - return BlockConnectedNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *BlockConnectedNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.Hash, - n.Height, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *BlockConnectedNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseBlockConnectedNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*BlockConnectedNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// BlockDisconnectedNtfn is a type handling custom marshaling and -// unmarshaling of blockdisconnected JSON websocket notifications. -type BlockDisconnectedNtfn struct { - Hash string - Height int32 -} - -// Enforce that BlockDisconnectedNtfn satisfies the btcjson.Cmd interface. -var _ btcjson.Cmd = &BlockDisconnectedNtfn{} - -// NewBlockDisconnectedNtfn creates a new BlockDisconnectedNtfn. -func NewBlockDisconnectedNtfn(hash string, height int32) *BlockDisconnectedNtfn { - return &BlockDisconnectedNtfn{ - Hash: hash, - Height: height, - } -} - -// parseBlockDisconnectedNtfn parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the notification -// with the btcjson parser. -func parseBlockDisconnectedNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var hash string - if err := json.Unmarshal(r.Params[0], &hash); err != nil { - return nil, errors.New("first parameter 'hash' must be a string: " + err.Error()) - } - - var height int32 - if err := json.Unmarshal(r.Params[1], &height); err != nil { - return nil, errors.New("second parameter 'height' must be a 32-bit integer: " + err.Error()) - } - - return NewBlockDisconnectedNtfn(hash, height), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *BlockDisconnectedNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *BlockDisconnectedNtfn) Method() string { - return BlockDisconnectedNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *BlockDisconnectedNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.Hash, - n.Height, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *BlockDisconnectedNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseBlockDisconnectedNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*BlockDisconnectedNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// BtcdConnectedNtfn is a type handling custom marshaling and -// unmarshaling of btcdconnected JSON websocket notifications. -type BtcdConnectedNtfn struct { - Connected bool -} - -// Enforce that BtcdConnectedNtfn satisifies the btcjson.Cmd -// interface. -var _ btcjson.Cmd = &BtcdConnectedNtfn{} - -// NewBtcdConnectedNtfn creates a new BtcdConnectedNtfn. -func NewBtcdConnectedNtfn(connected bool) *BtcdConnectedNtfn { - return &BtcdConnectedNtfn{connected} -} - -// parseBtcdConnectedNtfn parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the notification -// with the btcjson parser. -func parseBtcdConnectedNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 1 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var connected bool - if err := json.Unmarshal(r.Params[0], &connected); err != nil { - return nil, errors.New("first parameter 'connected' must be a bool: " + err.Error()) - } - - return NewBtcdConnectedNtfn(connected), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *BtcdConnectedNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *BtcdConnectedNtfn) Method() string { - return BtcdConnectedNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *BtcdConnectedNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.Connected, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *BtcdConnectedNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseBtcdConnectedNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*BtcdConnectedNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// RecvTxNtfn is a type handling custom marshaling and unmarshaling -// of recvtx JSON websocket notifications. -type RecvTxNtfn struct { - HexTx string - Block *BlockDetails -} - -// Enforce that RecvTxNtfn satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &RecvTxNtfn{} - -// NewRecvTxNtfn creates a new RecvTxNtfn. -func NewRecvTxNtfn(hextx string, block *BlockDetails) *RecvTxNtfn { - return &RecvTxNtfn{ - HexTx: hextx, - Block: block, - } -} - -// parsRecvTxNtfn parses a RawCmd into a concrete type satisifying the -// btcjson.Cmd interface. This is used when registering the notification with -// the btcjson parser. -func parseRecvTxNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - // Must have one or two parameters. - if len(r.Params) == 0 || len(r.Params) > 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var hextx string - if err := json.Unmarshal(r.Params[0], &hextx); err != nil { - return nil, errors.New("first parameter 'hextx' must be a " + - "string: " + err.Error()) - } - - var blockDetails *BlockDetails - if len(r.Params) > 1 { - if err := json.Unmarshal(r.Params[1], &blockDetails); err != nil { - return nil, errors.New("second optional parameter " + - "'details' must be a JSON oject of block " + - "details: " + err.Error()) - } - } - - return NewRecvTxNtfn(hextx, blockDetails), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *RecvTxNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *RecvTxNtfn) Method() string { - return RecvTxNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *RecvTxNtfn) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = n.HexTx - if n.Block != nil { - params = append(params, n.Block) - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *RecvTxNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseRecvTxNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*RecvTxNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// RedeemingTxNtfn is a type handling custom marshaling and unmarshaling -// of redeemingtx JSON websocket notifications. -type RedeemingTxNtfn struct { - HexTx string - Block *BlockDetails -} - -// Enforce that RedeemingTxNtfn satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &RedeemingTxNtfn{} - -// NewRedeemingTxNtfn creates a new RedeemingTxNtfn. -func NewRedeemingTxNtfn(hextx string, block *BlockDetails) *RedeemingTxNtfn { - return &RedeemingTxNtfn{ - HexTx: hextx, - Block: block, - } -} - -// parseRedeemingTxNtfn parses a RawCmd into a concrete type satisifying the -// btcjson.Cmd interface. This is used when registering the notification with -// the btcjson parser. -func parseRedeemingTxNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - // Must have one or two parameters. - if len(r.Params) == 0 || len(r.Params) > 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var hextx string - if err := json.Unmarshal(r.Params[0], &hextx); err != nil { - return nil, errors.New("first parameter 'hextx' must be a " + - "string: " + err.Error()) - } - - var blockDetails *BlockDetails - if len(r.Params) > 1 { - if err := json.Unmarshal(r.Params[1], &blockDetails); err != nil { - return nil, errors.New("second optional parameter " + - "'details' must be a JSON oject of block " + - "details: " + err.Error()) - } - } - - return NewRedeemingTxNtfn(hextx, blockDetails), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *RedeemingTxNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *RedeemingTxNtfn) Method() string { - return RedeemingTxNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *RedeemingTxNtfn) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = n.HexTx - if n.Block != nil { - params = append(params, n.Block) - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *RedeemingTxNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseRedeemingTxNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*RedeemingTxNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// RescanFinishedNtfn is type handling custom marshaling and -// unmarshaling of rescanfinished JSON websocket notifications. -type RescanFinishedNtfn struct { - Hash string - Height int32 - Time int64 -} - -// Enforce that RescanFinishedNtfn satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &RescanFinishedNtfn{} - -// NewRescanFinishedNtfn creates a new RescanFinshedNtfn. -func NewRescanFinishedNtfn(hash string, height int32, time int64) *RescanFinishedNtfn { - return &RescanFinishedNtfn{hash, height, time} -} - -// parseRescanFinishedNtfn parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the notification -// with the btcjson parser. -func parseRescanFinishedNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 3 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var hash string - if err := json.Unmarshal(r.Params[0], &hash); err != nil { - return nil, errors.New("first parameter 'hash' must be a " + - "string: " + err.Error()) - } - - var height int32 - if err := json.Unmarshal(r.Params[1], &height); err != nil { - return nil, errors.New("second parameter 'height' must be a " + - "32-bit integer: " + err.Error()) - } - - var time int64 - if err := json.Unmarshal(r.Params[2], &time); err != nil { - return nil, errors.New("third parameter 'time' must be a " + - "64-bit integer: " + err.Error()) - } - - return NewRescanFinishedNtfn(hash, height, time), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *RescanFinishedNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *RescanFinishedNtfn) Method() string { - return RescanFinishedNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *RescanFinishedNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.Hash, - n.Height, - n.Time, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *RescanFinishedNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseRescanFinishedNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*RescanFinishedNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// RescanProgressNtfn is type handling custom marshaling and -// unmarshaling of rescanprogress JSON websocket notifications. -type RescanProgressNtfn struct { - Hash string - Height int32 - Time int64 -} - -// Enforce that RescanProgressNtfn satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &RescanProgressNtfn{} - -// NewRescanProgressNtfn creates a new RescanProgressNtfn. -func NewRescanProgressNtfn(hash string, height int32, time int64) *RescanProgressNtfn { - return &RescanProgressNtfn{hash, height, time} -} - -// parseRescanProgressNtfn parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the notification -// with the btcjson parser. -func parseRescanProgressNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 3 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var hash string - if err := json.Unmarshal(r.Params[0], &hash); err != nil { - return nil, errors.New("first parameter 'hash' must be a " + - "string: " + err.Error()) - } - - var height int32 - if err := json.Unmarshal(r.Params[1], &height); err != nil { - return nil, errors.New("second parameter 'height' must be a " + - "32-bit integer: " + err.Error()) - } - - var time int64 - if err := json.Unmarshal(r.Params[2], &time); err != nil { - return nil, errors.New("third parameter 'time' must be a " + - "64-bit integer: " + err.Error()) - } - - return NewRescanProgressNtfn(hash, height, time), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *RescanProgressNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *RescanProgressNtfn) Method() string { - return RescanProgressNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *RescanProgressNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.Hash, - n.Height, - n.Time, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *RescanProgressNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseRescanProgressNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*RescanProgressNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// TxNtfn is a type handling custom marshaling and -// unmarshaling of newtx JSON websocket notifications. -type TxNtfn struct { - Account string - Details *btcjson.ListTransactionsResult -} - -// Enforce that TxNtfn satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &TxNtfn{} - -// NewTxNtfn creates a new TxNtfn. -func NewTxNtfn(account string, details *btcjson.ListTransactionsResult) *TxNtfn { - return &TxNtfn{ - Account: account, - Details: details, - } -} - -// parseTxNtfn parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the notification -// with the btcjson parser. -func parseTxNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return nil, errors.New("first parameter 'account' must be a " + - "string: " + err.Error()) - } - - var details btcjson.ListTransactionsResult - if err := json.Unmarshal(r.Params[1], &details); err != nil { - return nil, errors.New("second parameter 'details' must be a " + - "JSON object of transaction details: " + err.Error()) - } - - return NewTxNtfn(account, &details), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *TxNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *TxNtfn) Method() string { - return TxNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *TxNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.Account, - n.Details, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *TxNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseTxNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*TxNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// WalletLockStateNtfn is a type handling custom marshaling and -// unmarshaling of walletlockstate JSON websocket notifications. -type WalletLockStateNtfn struct { - Account string - Locked bool -} - -// Enforce that WalletLockStateNtfnMethod satisifies the btcjson.Cmd -// interface. -var _ btcjson.Cmd = &WalletLockStateNtfn{} - -// NewWalletLockStateNtfn creates a new WalletLockStateNtfn. -func NewWalletLockStateNtfn(account string, - locked bool) *WalletLockStateNtfn { - - return &WalletLockStateNtfn{ - Account: account, - Locked: locked, - } -} - -// parseWalletLockStateNtfn parses a RawCmd into a concrete type -// satisifying the btcjson.Cmd interface. This is used when registering -// the notification with the btcjson parser. -func parseWalletLockStateNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return nil, errors.New("first parameter 'account' must be a " + - "string: " + err.Error()) - } - - var locked bool - if err := json.Unmarshal(r.Params[1], &locked); err != nil { - return nil, errors.New("second parameter 'locked' must be a " + - "bool: " + err.Error()) - } - - return NewWalletLockStateNtfn(account, locked), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *WalletLockStateNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *WalletLockStateNtfn) Method() string { - return WalletLockStateNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *WalletLockStateNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.Account, - n.Locked, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *WalletLockStateNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseWalletLockStateNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*WalletLockStateNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// TxAcceptedNtfn is a type handling custom marshaling and -// unmarshaling of txmined JSON websocket notifications. -type TxAcceptedNtfn struct { - TxID string `json:"txid"` - Amount int64 `json:"amount"` -} - -// Enforce that TxAcceptedNtfn satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &TxAcceptedNtfn{} - -// NewTxAcceptedNtfn creates a new TxAcceptedNtfn. -func NewTxAcceptedNtfn(txid string, amount int64) *TxAcceptedNtfn { - return &TxAcceptedNtfn{ - TxID: txid, - Amount: amount, - } -} - -// parseTxAcceptedNtfn parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the notification -// with the btcjson parser. -func parseTxAcceptedNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 2 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var txid string - if err := json.Unmarshal(r.Params[0], &txid); err != nil { - return nil, errors.New("first parameter 'txid' must be a " + - "string: " + err.Error()) - } - - var amount int64 - if err := json.Unmarshal(r.Params[1], &amount); err != nil { - return nil, errors.New("second parameter 'amount' must be an " + - "integer: " + err.Error()) - } - - return NewTxAcceptedNtfn(txid, amount), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *TxAcceptedNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *TxAcceptedNtfn) Method() string { - return TxAcceptedNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *TxAcceptedNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.TxID, - n.Amount, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *TxAcceptedNtfn) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd. - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseTxAcceptedNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*TxAcceptedNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} - -// TxAcceptedVerboseNtfn is a type handling custom marshaling and -// unmarshaling of txmined JSON websocket notifications. -type TxAcceptedVerboseNtfn struct { - RawTx *btcjson.TxRawResult `json:"rawtx"` -} - -// Enforce that TxAcceptedNtfn satisifies the btcjson.Cmd interface. -var _ btcjson.Cmd = &TxAcceptedVerboseNtfn{} - -// NewTxAcceptedVerboseNtfn creates a new TxAcceptedVerboseNtfn. -func NewTxAcceptedVerboseNtfn(rawTx *btcjson.TxRawResult) *TxAcceptedVerboseNtfn { - return &TxAcceptedVerboseNtfn{ - RawTx: rawTx, - } -} - -// parseTxAcceptedVerboseNtfn parses a RawCmd into a concrete type satisifying -// the btcjson.Cmd interface. This is used when registering the notification -// with the btcjson parser. -func parseTxAcceptedVerboseNtfn(r *btcjson.RawCmd) (btcjson.Cmd, error) { - if r.Id != nil { - return nil, ErrNotANtfn - } - - if len(r.Params) != 1 { - return nil, btcjson.ErrWrongNumberOfParams - } - - var rawTx *btcjson.TxRawResult - if err := json.Unmarshal(r.Params[0], &rawTx); err != nil { - return nil, err - } - - return NewTxAcceptedVerboseNtfn(rawTx), nil -} - -// Id satisifies the btcjson.Cmd interface by returning nil for a -// notification ID. -func (n *TxAcceptedVerboseNtfn) Id() interface{} { - return nil -} - -// Method satisifies the btcjson.Cmd interface by returning the method -// of the notification. -func (n *TxAcceptedVerboseNtfn) Method() string { - return TxAcceptedVerboseNtfnMethod -} - -// MarshalJSON returns the JSON encoding of n. Part of the btcjson.Cmd -// interface. -func (n *TxAcceptedVerboseNtfn) MarshalJSON() ([]byte, error) { - params := []interface{}{ - n.RawTx, - } - - // No ID for notifications. - raw, err := btcjson.NewRawCmd(nil, n.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of n into n. Part of -// the btcjson.Cmd interface. -func (n *TxAcceptedVerboseNtfn) UnmarshalJSON(b []byte) error { - var r btcjson.RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - newNtfn, err := parseTxAcceptedVerboseNtfn(&r) - if err != nil { - return err - } - - concreteNtfn, ok := newNtfn.(*TxAcceptedVerboseNtfn) - if !ok { - return btcjson.ErrInternal - } - *n = *concreteNtfn - return nil -} diff --git a/btcjson/btcws/notifications_test.go b/btcjson/btcws/notifications_test.go deleted file mode 100644 index 1df4e2d6..00000000 --- a/btcjson/btcws/notifications_test.go +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright (c) 2013 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcws_test - -import ( - "reflect" - "testing" - - "github.com/btcsuite/btcd/btcjson" - "github.com/btcsuite/btcd/btcjson/btcws" - "github.com/davecgh/go-spew/spew" -) - -var ntfntests = []struct { - name string - f func() btcjson.Cmd - result btcjson.Cmd // after marshal and unmarshal -}{ - { - name: "accountbalance", - f: func() btcjson.Cmd { - return btcws.NewAccountBalanceNtfn("abcde", 1.2345, true) - }, - result: &btcws.AccountBalanceNtfn{ - Account: "abcde", - Balance: 1.2345, - Confirmed: true, - }, - }, - { - name: "blockconnected", - f: func() btcjson.Cmd { - return btcws.NewBlockConnectedNtfn( - "000000004811dda1c320ad5d0ea184a20a53acd92292c5f1cb926c3ee82abf70", - 153469) - }, - result: &btcws.BlockConnectedNtfn{ - Hash: "000000004811dda1c320ad5d0ea184a20a53acd92292c5f1cb926c3ee82abf70", - Height: 153469, - }, - }, - { - name: "blockdisconnected", - f: func() btcjson.Cmd { - return btcws.NewBlockDisconnectedNtfn( - "000000004811dda1c320ad5d0ea184a20a53acd92292c5f1cb926c3ee82abf70", - 153469) - }, - result: &btcws.BlockDisconnectedNtfn{ - Hash: "000000004811dda1c320ad5d0ea184a20a53acd92292c5f1cb926c3ee82abf70", - Height: 153469, - }, - }, - { - name: "btcdconnected", - f: func() btcjson.Cmd { - return btcws.NewBtcdConnectedNtfn(true) - }, - result: &btcws.BtcdConnectedNtfn{ - Connected: true, - }, - }, - { - name: "recvtx no block", - f: func() btcjson.Cmd { - return btcws.NewRecvTxNtfn("lalala the hex tx", nil) - }, - result: &btcws.RecvTxNtfn{ - HexTx: "lalala the hex tx", - Block: nil, - }, - }, - { - name: "recvtx with block", - f: func() btcjson.Cmd { - block := &btcws.BlockDetails{ - Height: 153469, - Hash: "000000004811dda1c320ad5d0ea184a20a53acd92292c5f1cb926c3ee82abf70", - Index: 1, - Time: 1386944019, - } - return btcws.NewRecvTxNtfn("lalala the hex tx", block) - }, - result: &btcws.RecvTxNtfn{ - HexTx: "lalala the hex tx", - Block: &btcws.BlockDetails{ - Height: 153469, - Hash: "000000004811dda1c320ad5d0ea184a20a53acd92292c5f1cb926c3ee82abf70", - Index: 1, - Time: 1386944019, - }, - }, - }, - { - name: "redeemingtx", - f: func() btcjson.Cmd { - return btcws.NewRedeemingTxNtfn("lalala the hex tx", nil) - }, - result: &btcws.RedeemingTxNtfn{ - HexTx: "lalala the hex tx", - Block: nil, - }, - }, - { - name: "redeemingtx with block", - f: func() btcjson.Cmd { - block := &btcws.BlockDetails{ - Height: 153469, - Hash: "000000004811dda1c320ad5d0ea184a20a53acd92292c5f1cb926c3ee82abf70", - Index: 1, - Time: 1386944019, - } - return btcws.NewRedeemingTxNtfn("lalala the hex tx", block) - }, - result: &btcws.RedeemingTxNtfn{ - HexTx: "lalala the hex tx", - Block: &btcws.BlockDetails{ - Height: 153469, - Hash: "000000004811dda1c320ad5d0ea184a20a53acd92292c5f1cb926c3ee82abf70", - Index: 1, - Time: 1386944019, - }, - }, - }, - { - name: "rescanfinished", - f: func() btcjson.Cmd { - return btcws.NewRescanFinishedNtfn( - "00000000b8980ec1fe96bc1b4425788ddc88dd36699521a448ebca2020b38699", - 12345, 1240784732) - }, - result: &btcws.RescanFinishedNtfn{ - Hash: "00000000b8980ec1fe96bc1b4425788ddc88dd36699521a448ebca2020b38699", - Height: 12345, - Time: 1240784732, - }, - }, - { - name: "rescanprogress", - f: func() btcjson.Cmd { - return btcws.NewRescanProgressNtfn( - "00000000b8980ec1fe96bc1b4425788ddc88dd36699521a448ebca2020b38699", - 12345, 1240784732) - }, - result: &btcws.RescanProgressNtfn{ - Hash: "00000000b8980ec1fe96bc1b4425788ddc88dd36699521a448ebca2020b38699", - Height: 12345, - Time: 1240784732, - }, - }, - { - name: "newtx", - f: func() btcjson.Cmd { - details := &btcjson.ListTransactionsResult{ - Account: "original", - Address: "mnSsMBY8j4AhQzbR6XqawND7NPTECVdtLd", - Category: "receive", - Amount: 100, - Fee: 0.0, - Confirmations: 6707, - Generated: false, - BlockHash: "000000000b20bf5fe8e25b19f9ec340744cda321a17ade12af9838530a75098b", - BlockIndex: 2, - BlockTime: 1397079345, - TxID: "cb082a63b29f446551829d03fa8bac02d3825a18994d5feec564f14101fc5fad", - WalletConflicts: []string{}, - Time: 123123123, - TimeReceived: 1397079169, - Comment: "comment", - OtherAccount: "", - } - return btcws.NewTxNtfn("abcde", details) - }, - result: &btcws.TxNtfn{ - Account: "abcde", - Details: &btcjson.ListTransactionsResult{ - Account: "original", - Address: "mnSsMBY8j4AhQzbR6XqawND7NPTECVdtLd", - Category: "receive", - Amount: 100, - Fee: 0.0, - Confirmations: 6707, - Generated: false, - BlockHash: "000000000b20bf5fe8e25b19f9ec340744cda321a17ade12af9838530a75098b", - BlockIndex: 2, - BlockTime: 1397079345, - TxID: "cb082a63b29f446551829d03fa8bac02d3825a18994d5feec564f14101fc5fad", - WalletConflicts: []string{}, - Time: 123123123, - TimeReceived: 1397079169, - Comment: "comment", - OtherAccount: "", - }, - }, - }, - { - name: "walletlockstate", - f: func() btcjson.Cmd { - return btcws.NewWalletLockStateNtfn("abcde", true) - }, - result: &btcws.WalletLockStateNtfn{ - Account: "abcde", - Locked: true, - }, - }, - { - name: "txaccepted", - f: func() btcjson.Cmd { - return btcws.NewTxAcceptedNtfn( - "062f2b5f7d28c787e0f3aee382132241cd590efb7b83bd2c7f506de5aa4ef275", - 34567765) - }, - result: &btcws.TxAcceptedNtfn{ - TxID: "062f2b5f7d28c787e0f3aee382132241cd590efb7b83bd2c7f506de5aa4ef275", - Amount: 34567765, - }, - }, - { - name: "txacceptedverbose", - f: func() btcjson.Cmd { - return btcws.NewTxAcceptedVerboseNtfn(&btcjson.TxRawResult{ - Hex: "01000000010cdf900074a3622499a2f28f44a94476f27a8900a2bdd60e042754b6cab09741000000008a473044022012e11012fad1eb21ba1c82deb8da98778b08e714b72f281293064528343fae0502204294d7520f469f9673087a55395de0ce0e9074dce236db9fe7f30013b5fd00b90141047b6ff7832b4a763666e5481a0bd9eedb656d9f882d215c16fe9563d7b191cd67b2a41601a853a9f9d92773ae6f912ef451a089148e510623759cf55c408efdefffffffff02f4063f00000000001976a914b269e0ceec5d5b5e192cf580ae42341e0f79b0b588aca8c84b02000000001976a91439233c0d43a1411e547c60bad8985bae3530b6af88ac00000000", - Txid: "0cfeb968fb5d0f6b9a2a1de37c0607a1964dd3e335f203377cec90e03b20869e", - Version: 0x1, - LockTime: 0x0, - }) - }, - result: &btcws.TxAcceptedVerboseNtfn{ - RawTx: &btcjson.TxRawResult{ - Hex: "01000000010cdf900074a3622499a2f28f44a94476f27a8900a2bdd60e042754b6cab09741000000008a473044022012e11012fad1eb21ba1c82deb8da98778b08e714b72f281293064528343fae0502204294d7520f469f9673087a55395de0ce0e9074dce236db9fe7f30013b5fd00b90141047b6ff7832b4a763666e5481a0bd9eedb656d9f882d215c16fe9563d7b191cd67b2a41601a853a9f9d92773ae6f912ef451a089148e510623759cf55c408efdefffffffff02f4063f00000000001976a914b269e0ceec5d5b5e192cf580ae42341e0f79b0b588aca8c84b02000000001976a91439233c0d43a1411e547c60bad8985bae3530b6af88ac00000000", - Txid: "0cfeb968fb5d0f6b9a2a1de37c0607a1964dd3e335f203377cec90e03b20869e", - Version: 0x1, - LockTime: 0x0, - }, - }, - }, -} - -func TestNtfns(t *testing.T) { - for _, test := range ntfntests { - // create notification. - n := test.f() - - // verify that id is nil. - if n.Id() != nil { - t.Errorf("%s: notification should not have non-nil id %v", - test.name, n.Id()) - continue - } - - mn, err := n.MarshalJSON() - if err != nil { - t.Errorf("%s: failed to marshal notification: %v", - test.name, err) - continue - } - - n2, err := btcjson.ParseMarshaledCmd(mn) - if err != nil { - t.Errorf("%s: failed to ummarshal cmd: %v", - test.name, err) - continue - } - - if !reflect.DeepEqual(test.result, n2) { - t.Errorf("%s: unmarshal not as expected. "+ - "got %v wanted %v", test.name, spew.Sdump(n2), - spew.Sdump(test.result)) - } - if !reflect.DeepEqual(n, n2) { - t.Errorf("%s: unmarshal not as we started with. "+ - "got %v wanted %v", test.name, spew.Sdump(n2), - spew.Sdump(n)) - } - - // Read marshaled notification back into n. Should still - // match result. - if err := n.UnmarshalJSON(mn); err != nil { - t.Errorf("%s: unmarshal failed: %v", test.name, err) - continue - } - if !reflect.DeepEqual(test.result, n) { - t.Errorf("%s: unmarshal not as expected. "+ - "got %v wanted %v", test.name, spew.Sdump(n), - spew.Sdump(test.result)) - } - } -} diff --git a/btcjson/v2/btcjson/chainsvrcmds.go b/btcjson/chainsvrcmds.go similarity index 100% rename from btcjson/v2/btcjson/chainsvrcmds.go rename to btcjson/chainsvrcmds.go diff --git a/btcjson/v2/btcjson/chainsvrcmds_test.go b/btcjson/chainsvrcmds_test.go similarity index 99% rename from btcjson/v2/btcjson/chainsvrcmds_test.go rename to btcjson/chainsvrcmds_test.go index ba8d0b05..b2f864b8 100644 --- a/btcjson/v2/btcjson/chainsvrcmds_test.go +++ b/btcjson/chainsvrcmds_test.go @@ -11,7 +11,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestChainSvrCmds tests all of the chain server commands marshal and unmarshal diff --git a/btcjson/v2/btcjson/chainsvrresults.go b/btcjson/chainsvrresults.go similarity index 100% rename from btcjson/v2/btcjson/chainsvrresults.go rename to btcjson/chainsvrresults.go diff --git a/btcjson/v2/btcjson/chainsvrresults_test.go b/btcjson/chainsvrresults_test.go similarity index 96% rename from btcjson/v2/btcjson/chainsvrresults_test.go rename to btcjson/chainsvrresults_test.go index 98d6b1c7..54658856 100644 --- a/btcjson/v2/btcjson/chainsvrresults_test.go +++ b/btcjson/chainsvrresults_test.go @@ -8,7 +8,7 @@ import ( "encoding/json" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestChainSvrCustomResults ensures any results that have custom marshalling diff --git a/btcjson/v2/btcjson/chainsvrwscmds.go b/btcjson/chainsvrwscmds.go similarity index 100% rename from btcjson/v2/btcjson/chainsvrwscmds.go rename to btcjson/chainsvrwscmds.go diff --git a/btcjson/v2/btcjson/chainsvrwscmds_test.go b/btcjson/chainsvrwscmds_test.go similarity index 99% rename from btcjson/v2/btcjson/chainsvrwscmds_test.go rename to btcjson/chainsvrwscmds_test.go index 32f7bfa1..425a7257 100644 --- a/btcjson/v2/btcjson/chainsvrwscmds_test.go +++ b/btcjson/chainsvrwscmds_test.go @@ -11,7 +11,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestChainSvrWsCmds tests all of the chain server websocket-specific commands diff --git a/btcjson/v2/btcjson/chainsvrwsntfns.go b/btcjson/chainsvrwsntfns.go similarity index 100% rename from btcjson/v2/btcjson/chainsvrwsntfns.go rename to btcjson/chainsvrwsntfns.go diff --git a/btcjson/v2/btcjson/chainsvrwsntfns_test.go b/btcjson/chainsvrwsntfns_test.go similarity index 99% rename from btcjson/v2/btcjson/chainsvrwsntfns_test.go rename to btcjson/chainsvrwsntfns_test.go index bc5e3464..9d8adbe2 100644 --- a/btcjson/v2/btcjson/chainsvrwsntfns_test.go +++ b/btcjson/chainsvrwsntfns_test.go @@ -11,7 +11,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestChainSvrWsNtfns tests all of the chain server websocket-specific diff --git a/btcjson/cmdhelp.go b/btcjson/cmdhelp.go deleted file mode 100644 index a1d973e2..00000000 --- a/btcjson/cmdhelp.go +++ /dev/null @@ -1,828 +0,0 @@ -// Copyright (c) 2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson - -import ( - "errors" -) - -// defaultHelpStrings contains the help text for all commands that are supported -// by btcjson by default. -var defaultHelpStrings = map[string]string{ - "addmultisigaddress": `addmultisigaddress nrequired ["key",...] ("account" ) -Add a multisignature address to the wallet where 'nrequired' signatures are -required for spending. Each key is an address of publickey. Optionally, account -may be provided to assign the address to that account.`, - - "addnode": `addnode "node" "{add|remove|onetry}" -Add or remove a node from the list of hosts we connect to. If mode is "onetry" -then the host will be connected to once only, otherwise the node will be retried -upon disconnection.`, - - "backupwallet": `backupwallet "destination" -Safely copies the wallet file to the destination provided, either a directory or -a filename.`, - - "createmultisig": `createmultisig nrequired ["key", ...] -Creates a multi-signature address with m keys where "nrequired" signatures are -required from those m. A JSON object is returned containing the address and -redemption script: -{ - "address":"address", # the value of the new address. - redeemScript":"script" # The stringified hex-encoded redemption script. -}`, - - "createrawtransaction": `createrawtransaction [{"txid":"id", "vout":n},...] {"address":amount,...} -Creates a transaction spending the given inputs and outputting to the -given addresses. The return is a hex encoded string of the raw -transaction with *unsigned* inputs. The transaction is not stored in any -wallet.`, - - // TODO(oga) this should be external since it is nonstandard. - "debuglevel": `debuglevel "levelspec" -Dynamically changes the debug logging level. Levelspec must be either a debug -level, one of the following: -trace, -debug, -info, -warn, -error, -critical. -Alternatively levelspec may be a specification of the form: -=,= -Where the valid subsystem names are: -AMGR, -ADXR, -BCDB, -BMGR, -BTCD, -CHAN, -DISC, -PEER, -RPCS, -SCRP, -SRVR, -TXMP. -Finally the keyword "show" will return a list of the available subsystems. -The command returns a string which will be "Done." if the command was sucessful, -or the list of subsystems if "show" was specified.`, - - "decoderawtransaction": `decoderawtransaction "hexstring" -Decodes the seralized, hex-encoded transaction in hexstring and returns a JSON -object representing it: -{ - "hex":"hex", # String of the hex encoded transaction provided. - "txid":"id", # The sha id of the transaction as a hex string - "version":n, # The version of the transaction as a number. - "locktime":t, # Locktime of the tx (number). - "vin": [ # Array of objects for inputs. - { - "txid":"id", # Txid that is spent. - "vout":n, # Output number. - "scriptSig": { - "asm":"asm", # Disasembled script as a string. - "hex":"hex", # Hex string of script. - }, - "sequence":n, # Sequence number of script. - } - ], - "vout": [ # Array of objects for outputs. - { - "value":x.xxx, # Value in BTC. - "n":n, # Numeric index. - "scriptPubkey": { # Object representing script. - "asm":"asm", # Disassembled script as string. - "hex":"hex", # Hex string of script. - "reqSigs":n, # Number of required signatures. - "type":"type" # Type as string, e.g. pubkeyhash. - }, - } - ] - "blockhash":"hash", # The block hash. as a string. - "confirmations":n # Number of confirmations in blockchain. - "time":t, # Transaction time in seconds since the epoch. - "blocktime":t, # Block time in seconds since the epoch. -}`, - - "decodescript": `decodescript "hex" -Decodes the hex encoded script passed as a string and returns a JSON object: -{ - "asm":"asm", # disassembled string of the script. - "hex":"hex", # hex string of the script. - "type":"type", # type of script as a string. - "reqSigs":n, # number of required signatures. - "addresses": [ # JSON array of address strings. - "address", # bitcoin address as a string. - ], - "p2sh","address" # script address as a string. -}`, - - "dumpprivkey": `dumpprivkey "bitcoinaddress" -Returns the private key corresponding to the provided address in a format -compatible with importprivkey.`, - - "dumpwallet": `dumpwallet "filename" -Dumps all wallet keys into "filename" in a human readable format.`, - - "encryptwallet": `encryptwallet "passphrase" -Encrypts the wallet with "passphrase". This command is for the initial -encryption of an otherwise unencrypted wallet, changing a passphrase -should use walletpassphrasechange.`, - - "estimatefee": `estimatefee "numblocks" -Estimates the approximate fee per kilobyte needed for a transaction to -get confirmed within 'numblocks' blocks.`, - - "estimatepriority": `estimatepriority "numblocks" -Estimates the approximate priority a zero-fee transaction needs to get -confirmed within 'numblocks' blocks.`, - - "getaccount": `getaccount "address" -Returns the account associated with the given "address" as a string.`, - - "getaccountaddress": `getaccountaddress "account" -Returns the current address used for receiving payments in this given account.`, - - "getaddednodeinfo": `getaddednodeinfo dns ( "node" ) -Returns a list of JSON objects with information about the local list of -permanent nodes. If dns is false, only a list of permanent nodes will -be provided, otherwise connected information will also be provided. If -node is not provided then all nodes will be detailed. The JSON return -format is as follows: -[ - { - "addednode":"1.2.3.4", # node ip address as a string - "connected":true|false # boolean connectionstate. - "addresses": [ - "address":"1.2.3.4:5678" # Bitcoin server host and port as a string. - "connected":"inbound", # The string "inbound" or "outbound". - ], - }, - ... -]`, - - "getaddressesbyaccount": `getaddressesbyaccount "account" -Returns the list of addresses for the given account: -[ - "address", # Bitcoin address associated with the given account. - ... -]`, - - "getbalance": `getbalance ("account" "minconf") -Returns the balance for an account. If "account" is not specified this is the -total balance for the server. if "minconf" is provided then only transactions -with at least "minconf" confirmations will be counted for the balance. The -result is a JSON numeric type.`, - - "getbestblockhash": `getbestblockhash -Returns the hash of the last block in the longest blockchain known to -the server as a hex encoded string.`, - - "getblock": `getblock "hash" ( verbose verbosetx=false) -Returns data about the block with hash "hash". If verbose is false a -string of hex-encoded data for the block is returned. If verbose is true -a JSON object is provided with the following: -{ - "hash":"hash", # The block hash (same as argument). - "confirmations":n, # Number of confirmations as numeric. - "size":n, # Block size as numeric. - "height":n, # Block height as numeric. - "version":n, # Block version as numeric. - "merkelroot":"...", # The merkle root of the block. - "tx" : [ # the transactions in the block as an array of strings. - "transactionid", - ... - ], - "time":t, # The block time in seconds since the epoch. - "nonce":n, # The nonce of the block as a number. - "bits":"1d00ffff", # the compact representation of the difficulty as bits. - "difficulty":n, # the difficulty of the block as a number. - "previousblockhash":"hash", # hash of the previous block as a string. - "nextblockhash":""hash", # hash of the next block as a string. -} -If "verbosetx" is true, the returned object will contain a "rawtx" member -instead of the "tx" member; It will contain objects representing the -transactions in the block in format used by getrawtransaction. -Please note that verbosetx is a btcd/btcjson extension.`, - - "getblockcount": `getblockcount -Returns a numeric for the number of blocks in the longest block chain.`, - - "getblockhash": `getblockhash index -Returns the hash of the block (as a string) at the given index in the -current blockchain.`, - - "getblocktemplate": `getblocktemplate ( jsonrequestobject ) -Returns a block template for external mining purposes. The optional -request object follows the following format: -{ - "mode":"template" # Optional, "template" or omitted. - "capabilities": [ # List of strings, optional. - "support", # Client side features supported. one of: - ... # "longpoll", "coinbasetxn", "coinbasevalue", - ... # "proposal", "serverlist", "workid". - ] -} -The result object is of the following format: -{ - "version":n, # Numeric block version. - "previousblockhash":"string" # Hash of the current tip of the blocktrain. - "transactions":[ - "data" # String of hex-encoded serialized transaction. - "hash" # Hex encoded hash of the tx. - "depends": [ # Array of numbers representing the transactions - n, # that must be included in the final block if - ..., # this one is. A 1 based index into the - ..., # transactions list. - ] - "fee":n # Numeric transaction fee in satoshi. This is calculated by the diffrence between the sum of inputs and outputs. For coinbase transaction this is a negative number of total collected block fees. If not present fee is unknown; clients must not assume that there is no fee in this case. - "sigops":n # Number of total signature operations calculated for purposes of block limits. If not present the count is unknown but clients must not assume it is zero. - "required":true|false # If provided and true this transaction *must* be in the final block. - ], - "coinbaseaux": { # Object of data to be included in coinbase's scriptSig. - "flags":"flags" # String of flags. - } - "coinbasevalue" # Numeric value in satoshi for maximum allowable input to coinbase transaction, including transaction fees and mining aware. - "coinbasetxn":{} # Object contining information for coinbase transaction. - "target":"target", # The hash target as a string. - "mintime":t, # Minimum timestamp appropriate for next block in seconds since the epoch. - "mutable":[ # Array of ways the template may be modified. - "value" # e.g. "time", "transactions", "prevblock", etc - ] - "noncerange":"00000000ffffffff" # Wtring representing the range of valid nonces. - "sigopliit" # Numeric limit for max sigops in block. - "sizelimit" # Numeric limit of block size. - "curtime":t # Current timestamp in seconds since the epoch. - "bits":"xxx", # Compressed target for next block as string. - "height":n, # Numeric height of the next block. -}`, - - "getconnectioncount": `getconnectioncount -Returns the number of connections to other nodes currently active as a JSON -number.`, - - "getdifficulty": `getdifficulty -Returns the proof-of-work difficulty as a JSON number. The result is a -multiple of the minimum difficulty.`, - - "getgenerate": `getgenerate -Returns JSON boolean whether or not the server is set to "mine" coins or not.`, - - "gethashespersec": `gethashespersec -Returns a JSON number representing a recent measurement of hashes-per-second -during mining.`, - - "getinfo": `getinfo -Returns a JSON object containing state information about the service: -{ - "version":n, # Numeric server version. - "protocolversion":n, # Numeric protocol version. - "walletversion":n, # Numeric wallet version. - "balance":n, # Total balance in the wallet as a number. - "blocks":n, # Numeric detailing current number of blocks. - "timeoffset":n, # Numeric server time offset. - "proxy":"host:port" # Optional string detailing the proxy in use. - "difficulty":n, # Current blockchain difficulty as a number. - "testnet":true|false # Boolean if the server is testnet. - "keypoololdest":t, # Oldest timstamp for pre generated keys. (in seconds since the epoch). - "keypoolsize":n, # Numeric size of the wallet keypool. - "paytxfee":n, # Numeric transaction fee that has been set. - "unlocked_until":t, # Numeric time the wallet is unlocked for in seconds since epoch. - "errors":"..." # Any error messages as a string. -}`, - - "getmininginfo": `getmininginfo -Returns a JSON object containing information related to mining: -{ - "blocks":n, # Numeric current block - "currentblocksize":n, # Numeric last block size. - currentblocktx":n, # Numeric last block transaction - "difficulty":n, # Numeric current difficulty. - "errors":"...", # Current error string. -}`, - - "getnettotals": `getnettotals -Returns JSON object containing network traffic statistics: -{ - "totalbytesrecv":n, # Numeric total bytes received. - "totalbytessent":n, # Numeric total bytes sent. - "timemilis",t, # Total numeric of milliseconds since epoch. -}`, - - "getnetworkhashps": `getnetworkhashps ( blocks=120 height=-1 ) -Returns the estimated network hash rate per second based on the last -"blocks" blocks. If "blocks" is -1 then the number of blocks since the -last difficulty change will be used. If "height" is set then the -calculation will be carried out for the given block height instead of -the block tip. A JSON number is returned with the hashes per second -estimate.`, - - "getnewaddress": `getnewaddress ( "account" ) -Returns a string for a new Bitcoin address for receiving payments. In the case -that "account" is specified then the address will be for "account", else the -default account will be used.`, - - "getpeerinfo": `getpeerinfo -Returns a list of JSON objects containing information about each connected -network node. The objects have the following format: -[ - { - "id":n, # Unique node ID. - "addr":"host:port" # IP and port of the peer as a string. - "addrlocal":"ip:port" # Local address as a string. - "services":"00000001", # Services bitmask as a string. - "lastsend":t, # Time in seconds since epoch since last send. - "lastrecv":t, # Time in seconds since epoch since last received message. - "bytessent":n, # Total number of bytes sent. - "bytesrecv":n, # Total number of bytes received. - "conntime":t, # Connection time in seconds since epoch. - "timeoffset":n, # Peer time offset. - "pingtime":n, # Ping time - "pingwait":n, # Ping wait. - "version":n, # The numeric peer version. - "subver":"/btcd:0.1/" # The peer useragent string. - "inbound":true|false, # True or false whether peer is inbound. - "startingheight":n, # Numeric block heght of peer at connect time. - "banscore":n, # The numeric ban score. - "syncnode":true|false, # Boolean if the peer is the current sync node. - } -]`, - "getrawchangeaddress": `getrawchangeaddress -Returns a string containing a new Bitcoin addres for receiving change. -This rpc call is for use with raw transactions only.`, - - "getrawmempool": `getrawmempool ( verbose ) -Returns the contents of the transaction memory pool as a JSON array. If -verbose is false just the transaction ids will be returned as strings. -If it is true then objects in the following format will be returned: -[ - "transactionid": { - "size":n, # Numeric transaction size in bytes. - "fee":n, # Numeric transqaction fee in btc. - "time":t, # Time transaction entered pool in seconds since the epoch. - "height":n, # Numeric block height when the transaction entered pool. - "startingpriority:n, # Numeric transaction priority when it entered the pool. - "currentpriority":n, # Numeric transaction priority. - "depends":[ # Unconfirmed transactions used as inputs for this one. As an array of strings. - "transactionid", # Parent transaction id. - ] - }, - ... -]`, - - "getrawtransaction": `getrawtransaction "txid" ( verbose ) -Returns raw data related to "txid". If verbose is false, a string containing -hex-encoded serialized data for txid. If verbose is true a JSON object with the -following information about txid is returned: -{ - "hex":"data", # String of serialized, hex encoded data for txid. - "txid":"id", # String containing the transaction id (same as "txid" parameter) - "version":n # Numeric tx version number. - "locktime":t, # Transaction locktime. - "vin":[ # Array of objects representing transaction inputs. - { - "txid":"id", # Spent transaction id as a string. - "vout""n, # Spent transaction output no. - "scriptSig":{ # Signature script as an object. - "asm":"asm", # Disassembled script string. - "hex":"hex", # Hex serialized string. - }, - "sequence":n, # Script sequence number. - }, - ... - ], - vout:[ # Array of objects representing transaction outputs. - { - "value":n, # Numeric value of output in btc. - "n", n, # Numeric output index. - "scriptPubKey":{ # Object representing pubkey script. - "asm":"asm" # Disassembled string of script. - "hex":"hex" # Hex serialized string. - "reqSigs":n, # Number of required signatures. - "type":"pubkey", # Type of scirpt. e.g. pubkeyhash" or "pubkey". - "addresses":[ # Array of address strings. - "address", # Bitcoin address. - ... - ], - } - } - ], - "blockhash":"hash" # Hash of the block the transaction is part of. - "confirmations":n, # Number of numeric confirmations of block. - "time":t, # Transaction time in seconds since the epoch. - "blocktime":t, # Block time in seconds since the epoch. -}`, - - "getreceivedbyaccount": `getreceivedbyaccount "account" ( minconf=1 ) -Returns the total amount of BTC received by addresses related to "account". -Only transactions with at least "minconf" confirmations are considered.`, - - "getreceivedbyaddress": `getreceivedbyaddress "address" ( minconf=1 ) -Returns the total amount of BTC received by the given address. Only transactions -with "minconf" confirmations will be used for the total.`, - - "gettransaction": `gettransaction "txid" -Returns a JSON object containing detailed information about the in-wallet -transaction "txid". The object follows the following format: -{ - "amount":n, # Transaction amount in BTC. - "confirmations":n, # Number of confirmations for transaction. - "blockhash":"hash", # Hash of block transaction is part of. - "blockindex":n, # Index of block transaction is part of. - "blocktime":t, # Time of block transaction is part of. - "txid":"id", # Transaction id. - "time":t, # Transaction time in seconds since epoch. - "timereceived":t, # Time transaction was received in seconds since epoch. - "details":[ - { - "account":"name", # The acount name involvedi n the transaction. "" means the default. - "address":"address", # The address involved in the transaction as a string. - "category":"send|receive", # Category - either send or receive. - "amount":n, # numeric amount in BTC. - } - ... - ] -}`, - - "gettxout": `gettxout "txid" n ( includemempool ) -Returns an object containing detauls about an unspent transaction output -the "n"th output of "txid": -{ - "bestblock":"hash", # Block has containing transaction. - "confirmations":n, # Number of confirmations for block. - "value":n # Transaction value in BTC. - scriptPubkey" { - "asm":"asm", # Disassembled string of script. - "hex":"hex", # String script serialized and hex encoded. - "reqSigs" # Numeric required signatures. - "type":"pubkeyhash" # Type of transaction. e.g. pubkeyhas - "addresses":[ # Array of strings containing addresses. - "address", - ... - ] - }, -}`, - - "gettxoutsetinfo": `gettxoutsetinfo -Returns an object containing startstics about the unspent transaction -output set: -{ - "height":n, # Numeric current block height. - "bestblock":"hex" # Hex string of best block hash. - "transactions":n, # Numeric count of transactions. - "txouts":n # Numeric count of transaction outputs. - "bytes_serialized":n # Numeric serialized size. - "hash_serialized" # String of serialized hash. - "total_amount":n, # Numeric total amount in BTC. -}`, - - "getwork": `getwork ( "data" ) -If "data" is present it is a hex encoded block datastruture that has been byte -reversed, if this is the case then the server will try to solve the -block and return true upon success, false upon failure. If data is not -specified the following object is returned to describe the work to be -solved: -{ - "midstate":"xxx", # String of precomputed hash state for the first half of the data (deprecated). - "data":"...", # Block data as string. - "hash1":"..." # Hash buffer for second hash as string. (deprecated). - "target":"...", # Byte reversed hash target. -}`, - - "help": `help ( "command" ) -With no arguemnts, lists the supported commands. If "command" is -specified then help text for that command is returned as a string.`, - - "importprivkey": `importprivkey "privkey" ( "label" rescan=true ) -Adds a private key (in the same format as dumpprivkey) to the wallet. If label -is provided this is used as a label for the key. If rescan is true then the -blockchain will be scanned for transaction.`, - - "importwallet": `importwallet "filename" -Imports keys from the wallet dump file in "filename".`, - - "invalidateblock": `invalidateblock "hash" -Mark block specified by "hash" as invalid.`, - - "keypoolrefill": `keypoolrefill ( newsize=100 ) -Refills the wallet pregenerated key pool to a size of "newsize"`, - - "listaccounts": `listaccounts ( minconf=1) -Returns a JSON object mapping account names to account balances: -{ - "accountname": n # Account name to numeric balance in BTC. - ... -}`, - - "listaddressgroupings": `listaddressgroupings -Returns a JSON array of array of addreses which have had their relation to each -other made public by common use as inputs or in the change address. The data -takes the following format: -[ - [ - [ - "address", # Bitcoin address. - amount, # Amount in BTC. - "account" # Optional account name string. - ], - ... - ], - ... -]`, - - "listlockunspent": `listlockunspent -Returns a JSON array of objects detailing transaction outputs that are -temporarily unspendable due to being processed by the lockunspent call. -[ - { - "txid":"txid" # Id of locked transaction as a string. - "vout":n, # Numeric index of locked output. - }, - ... -]`, - - "listreceivedbyaccount": `listreceivedbyaccount ( minconf=1 includeempty=false ) -Returns a JSON array containing objects for each account detailing their -balances. Only transaction with at least "minconf" confirmations will be -included. If "includeempty" is true then accounts who have received no payments -will also be included, else they will be elided. The format is as follows: -[ - { - "account":"name", # Name of the receiving account. - "amount":n, # Total received amount in BTC. - "confirmations":n, # Total confirmations for most recent transaction. - } -]`, - - "listreceivedbyaddress": `listreceivedbyaddress ( minconf=1 includeempty=false ) -Returns a JSON array containing objects for each address detailing their -balances. Only transaction with at least "minconf" confirmations will be -included. If "includeempty" is true then adresses who have received no payments -will also be included, else they will be elided. The format is as follows: -[ - { - "account":"name", # Name of the receiving account. - "amount":n, # Total received amount in BTC. - "confirmations":n, # Total confirmations for most recent transaction. - } -]`, - - "listsinceblock": `listsinceblock ("blockhash" minconf=1) -Gets all wallet transactions in block since "blockhash", if blockhash is -omitted then all transactions are provided. If present the only transactions -with "minconf" confirmations are listed. -{ - "transactions":[ - "account" # String of account related to the transaction. - "address" # String of related address of transaction. - "category":"send|receive" # String detailing whether transaction was a send or receive of funds. - "amount":n, # Numeric value of transaction. Negative if transaction category was "send" - "fee":n, # Numeric value of transaction fee in BTC. - "confirmations":n, # Number of transaction confirmations - "blockhash":"hash" # String of hash of block transaction is part of. - "blockindex":n, # Numeric index of block transaction is part of. - "blocktime":t, # Block time in seconds since the epoch. - "txid":"id", # Transaction id. - "time":t, # Transaction time in second since the epoch. - "timereceived":t, # Time transaction received in seconds since the epoch. - "comment":"...", # String of the comment associated with the transaction. - "to":"...", # String of "to" comment of the transaction. - ] - "lastblock":"lastblockhash" # Hash of the last block as a string. -}`, - - "listtransactions": `listtransactions ( "account" count=10 from=0 ) -Returns up to "count" most recent wallet transactions for "account" (or all -accounts if none specified) skipping the first "from" transactions. -{ - "transactions":[ - "account" # String of account related to the transaction. - "address" # String of related address of transaction. - "category":"send|receive|move" # String detailing whether transaction was a send or receive of funds.Move is a local move between accounts and doesnt touch the blockchain. - "amount":n, # Numeric value of transaction. Negative if transaction category was "send" - "fee":n, # Numeric value of transaction fee in BTC. - "confirmations":n, # Number of transaction confirmations - "blockhash":"hash" # String of hash of block transaction is part of. - "blockindex":n, # Numeric index of block transaction is part of. - "blocktime":t, # Block time in seconds since the epoch. - "txid":"id", # Transaction id. - "time":t, # Transaction time in second since the epoch. - "timereceived":t, # Time transaction received in seconds since the epoch. - "comment":"...", # String of the comment associated with the transaction. - "to":"...", # String of "to" comment of the transaction. - ] - "lastblock":"lastblockhash" # Hash of the last block as a string. -}`, - - "listunspent": `listunspent (minconf=1 maxconf=9999999 ["address",...] -Returns a JSON array of objects representing unspent transaction outputs with -between minconf and maxconf confirmations (inclusive). If the array of addresses -is present then only txouts paid to the addresses listed will be considered. The -objects take the following format: -[ - { - "txid":"id", # The transaction id as a string. - "vout":n, # The output number of the tx. - "address":"add", # String of the transaction address. - "account":"acc", # The associated account, "" for default. - "scriptPubkey":"key" # The pubkeyscript as a string. - "amount":n, # The value of the transaction in BTC. - "confirmations":n, # The numer of confirmations. - }, - ... -]`, - - "lockunspent": `lockunspent unlock [{"txid":id", "vout":n},...] -Changes the llist of temporarily unspendable transaction outputs. The -transacion outputs in the list of objects provided will be marked as -locked (if unlock is false) or unlocked (unlock is true). A locked -transaction will not be chosen automatically to be spent when a -tranaction is created. Boolean is returned whether the command succeeded.`, - - "move": `move "fromaccount" "toaccount" amount ( minconf=1 "comment" ) -Moves a specifies amount from "fromaccount" to "toaccount". Only funds -with minconf confirmations are used. If comment is present this comment -will be stored in the wallet with the transaction. Boolean is returned -to denode success.`, - - "ping": `ping -Queues a ping to be sent to each connected peer. Ping times are provided in -getpeerinfo.`, - - "reconsiderblock": `reconsiderblock "hash" -Remove invalid mark from block specified by "hash" so it is considered again.`, - - "searchrawtransactions": `searchrawtransactions "address" (verbose=1 skip=0 count=100) -Returns raw tx data related to credits or debits to "address". Skip indicates -the number of leading transactions to leave out of the final result. Count -represents the max number of transactions to return. If verbose is false, a -string containing hex-encoded serialized data for txid. If verbose is true a -JSON object with the following information about txid is returned: -{ - "hex":"data", # String of serialized, hex encoded data for txid. - "txid":"id", # String containing the transaction id (same as "txid" parameter) - "version":n # Numeric tx version number. - "locktime":t, # Transaction locktime. - "vin":[ # Array of objects representing transaction inputs. - { - "txid":"id", # Spent transaction id as a string. - "vout""n, # Spent transaction output no. - "scriptSig":{ # Signature script as an object. - "asm":"asm", # Disassembled script string. - "hex":"hex", # Hex serialized string. - }, - "sequence":n, # Script sequence number. - }, - ... - ], - vout:[ # Array of objects representing transaction outputs. - { - "value":n, # Numeric value of output in btc. - "n", n, # Numeric output index. - "scriptPubKey":{ # Object representing pubkey script. - "asm":"asm" # Disassembled string of script. - "hex":"hex" # Hex serialized string. - "reqSigs":n, # Number of required signatures. - "type":"pubkey", # Type of scirpt. e.g. pubkeyhash" or "pubkey". - "addresses":[ # Array of address strings. - "address", # Bitcoin address. - ... - ], - } - } - ], - "blockhash":"hash" # Hash of the block the transaction is part of. - "confirmations":n, # Number of numeric confirmations of block. - "time":t, # Transaction time in seconds since the epoch. - "blocktime":t, # Block time in seconds since the epoch. -}`, - - "sendfrom": `sendfrom "fromaccount" "tobitcoinaddress" amount ( minconf=1 "comment" "comment-to" ) -Sends "amount" (rounded to the nearest 0.00000001) to -"tobitcoindaddress" from "fromaccount". Only funds with at least -"minconf" confirmations will be considered. If "comment" is present this -will be store the purpose of the transaction. If "comment-to" is present -this comment will be recorded locally to store the recipient of the -transaction.`, - - "sendmany": `sendmany "fromaccount" {"address":amount,...} ( minconf=1 "comment" ) -Sends funds to multiple recipients. Funds from "fromaccount" are send to the -address/amount pairs specified. Only funds with minconf confirmations are -considered. "comment" if present is recorded locally as the purpose of the -transaction.`, - - "sendrawtransaction": `sendrawtransaction "hexstring" (allowhighfees=false) -Submits the hex-encoded transaction in "hexstring" to the bitcoin network via -the local node. If allowhighfees is true then high fees will be allowed.`, - - "sendtoaddress": `sendtoaddress "bitcoindaddress" amount ( "comment" "comment-to") -Send "amount" BTC (rounded to the nearest 0.00000001) to "bitcoinaddress". If -comment is set, it will be stored locally to describe the purpose of the -transaction. If comment-to" is set it will be stored locally to describe the -recipient of the transaction. A string containing the transaction id is -returned if successful.`, - - "setaccount": `setaccount "address" "account" -Sets the account associated with "address" to "account".`, - - "setgenerate": `setgenerate generate ( genproclimit ) -Sets the current mining state to "generate". Up to "genproclimit" processors -will be used, if genproclimit is -1 then it is unlimited.`, - - "settxfee": `settxfee amount -Sets the current transaction fee.`, - - "signmessage": `signmessage "address" "message" -Returns a signature for "message" with the private key of "address"`, - - "signrawtransaction": `signrawtransaction "hexstring" ( prevtxs ["privatekey",...] sighashtype="ALL" ) -Signs the inputs for the serialized and hex encoded transaction in -"hexstring". "prevtxs" optionally is an is an array of objects -representing the previous tx outputs that are spent here but may not yet -be in the blockchain, it takes the following format: -[ - { - "txid":id:, # String of transaction id. - "vout":n, # Output number. - "scriptPubKey":"hex", # Hex encoded string of pubkey script from transaction. - "redemScript":"hex" # Hex encoded redemption script. - }, - ... -] -If the third argument is provided these base58-encoded private keys in -the list will be the only keys used to sign the transaction. sighashtype -optionally denoes the signature hash type to be used. is must be one of the -following: - "ALL", - "NONE", - "SINGLE", - "ALL|ANYONECANPAY", - "NONE|ANYONECANPAY", - "SINGLE|ANYONECANPAY". -The return value takes the following format: -{ - "hex":"value" # Hex string of raw transactino with signatures applied. - "complete":n, # If the transaction has a complete set of signatures. 0 if false. -}`, - - "stop": `stop -Stop the server.`, - - "submitblock": `submitblock "data" ( optionalparameterobject ) -Will attempt to submit the block serialized in "data" to the bitcoin network. -optionalparametersobject takes the following format: -{ - "workid":"id" # If getblocktemplate provided a workid it must be included with submissions. -}`, - - "validateaddress": `validateaddress "address -Returns a JSON objects containing information about the provided "address". -Format: -{ - "isvalid":true|false, # If the address is valid. If false this is the only property returned. - "address:"address", # The address that was validated. - "ismine":true|false, # If the address belongs to the server. - "isscript:true|false, # If the address is a script address. - "pubkey":"pk", # The hex value of the public key associated with the address. - "iscompressed":true|false, # If the address is compresssed. - "account":"account", # The related account. "" is the default. -}`, - - "verifychain": `verifychain ( checklevel=3 numblocks=288 ) -Verifies the stored blockchain database. "checklevel" denotes how thorough the -check is and "numblocks" how many blocks from the tip will be verified.`, - - "verifymessage": `verifymessage "bitcoinaddress" "signature" "message" -Verifies the signature "signature" for "message" from the key related -to "bitcoinaddress". The return is true or false if the signature -verified correctly.`, - - "walletlock": `walletlock -Removes any encryption key for the wallet from memory, unlocking the wallet. -In order to use wallet functionality again the wallet must be unlocked via -walletpassphrase.`, - - "walletpassphrase": `walletpassphrase "passphrase" timeout -Decrypts the wallet for "timeout" seconds with "passphrase". This is required -before using wallet functionality.`, - - "walletpassphrasechange": `walletpassphrasechange "oldpassphrase" "newpassphrase" -Changes the wallet passphrase from "oldpassphrase" to "newpassphrase".`, -} - -// GetHelpString returns a string containing help text for "cmdName". If -// cmdName is unknown to btcjson - either via the default command list or those -// registered using RegisterCustomCmd - an error will be returned. -func GetHelpString(cmdName string) (string, error) { - helpstr := "" - - if help, ok := defaultHelpStrings[cmdName]; ok { - return help, nil - } - if c, ok := customCmds[cmdName]; ok { - return c.helpString, nil - } - return helpstr, errors.New("invalid command specified") -} diff --git a/btcjson/v2/btcjson/cmdinfo.go b/btcjson/cmdinfo.go similarity index 100% rename from btcjson/v2/btcjson/cmdinfo.go rename to btcjson/cmdinfo.go diff --git a/btcjson/v2/btcjson/cmdinfo_test.go b/btcjson/cmdinfo_test.go similarity index 99% rename from btcjson/v2/btcjson/cmdinfo_test.go rename to btcjson/cmdinfo_test.go index 3e082d88..cab0c81c 100644 --- a/btcjson/v2/btcjson/cmdinfo_test.go +++ b/btcjson/cmdinfo_test.go @@ -8,7 +8,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestCmdMethod tests the CmdMethod function to ensure it retuns the expected diff --git a/btcjson/v2/btcjson/cmdparse.go b/btcjson/cmdparse.go similarity index 100% rename from btcjson/v2/btcjson/cmdparse.go rename to btcjson/cmdparse.go diff --git a/btcjson/v2/btcjson/cmdparse_test.go b/btcjson/cmdparse_test.go similarity index 99% rename from btcjson/v2/btcjson/cmdparse_test.go rename to btcjson/cmdparse_test.go index 84123995..83a823bf 100644 --- a/btcjson/v2/btcjson/cmdparse_test.go +++ b/btcjson/cmdparse_test.go @@ -10,7 +10,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestAssignField tests the assignField function handles supported combinations diff --git a/btcjson/doc.go b/btcjson/doc.go index bab66104..6370fd75 100644 --- a/btcjson/doc.go +++ b/btcjson/doc.go @@ -1,116 +1,146 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. +// Copyright (c) 2015 Conformal Systems LLC. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. /* -Package btcjson implements the bitcoin JSON-RPC API. +Package btcjson provides primitives for working with the bitcoin JSON-RPC API. -A complete description of the JSON-RPC protocol as used by bitcoin can -be found on the official wiki at -https://en.bitcoin.it/wiki/API_reference_%28JSON-RPC%29 with a list of -all the supported calls at -https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list. +Overview -This package provides data structures and code for marshalling and -unmarshalling json for communicating with a running instance of btcd -or bitcoind/bitcoin-qt. It also provides code for sending those -messages. It does not provide any code for the client to actually deal -with the messages. Although it is meant primarily for btcd, it is -possible to use this code elsewhere for interacting with a bitcoin -client programatically. +When communicating via the JSON-RPC protocol, all of the commands need to be +marshalled to and from the the wire in the appropriate format. This package +provides data structures and primitives to ease this process. -Protocol +In addition, it also provides some additional features such as custom command +registration, command categorization, and reflection-based help generation. -All messages to bitcoin are of the form: +JSON-RPC Protocol Overview - {"jsonrpc":"1.0","id":"SOMEID","method":"SOMEMETHOD","params":SOMEPARAMS} +This information is not necessary in order to use this package, but it does +provide some intuition into what the marshalling and unmarshalling that is +discussed below is doing under the hood. -The params field can vary in what it contains depending on the -different method (or command) being sent. +As defined by the JSON-RPC spec, there are effectively two forms of messages on +the wire: -Replies will vary in form for the different commands. The basic form is: + - Request Objects + {"jsonrpc":"1.0","id":"SOMEID","method":"SOMEMETHOD","params":[SOMEPARAMS]} + NOTE: Notifications are the same format except the id field is null. - {"result":SOMETHING,"error":null,"id":"SOMEID"} + - Response Objects + {"result":SOMETHING,"error":null,"id":"SOMEID"} + {"result":null,"error":{"code":SOMEINT,"message":SOMESTRING},"id":"SOMEID"} -The result field can be as simple as an int, or a complex structure -containing many nested fields. For cases where we have already worked -out the possible types of reply, result is unmarshalled into a -structure that matches the command. For others, an interface is -returned. An interface is not as convenient as one needs to do a type -assertion first before using the value, but it means we can handle -arbitrary replies. +For requests, the params field can vary in what it contains depending on the +method (a.k.a. command) being sent. Each parameter can be as simple as an int +or a complex structure containing many nested fields. The id field is used to +identify a request and will be included in the associated response. -The error field is null when there is no error. When there is an -error it will return a numeric error code as well as a message -describing the error. +When working with asynchronous transports, such as websockets, spontaneous +notifications are also possible. As indicated, they are the same as a request +object, except they have the id field set to null. Therefore, servers will +ignore requests with the id field set to null, while clients can choose to +consume or ignore them. -id is simply the id of the requester. +Unfortunately, the original Bitcoin JSON-RPC API (and hence anything compatible +with it) doesn't always follow the spec and will sometimes return an error +string in the result field with a null error for certain commands. However, +for the most part, the error field will be set as described on failure. -RPC Server Authentication +Marshalling and Unmarshalling -All RPC calls must be authenticated with a username and password. The specifics -on how to configure the RPC server varies depending on the specific bitcoin -implementation. For bitcoind, this is accomplished by setting rpcuser and -rpcpassword in the file ~/.bitcoin/bitcoin.conf. For btcd, this is accomplished -by setting rpcuser and rpcpass in the file ~/.btcd/btcd.conf. The default local -address of bitcoind is 127.0.0.1:8332 and the default local address of btcd is -127.0.0.1:8334 +Based upon the discussion above, it should be easy to see how the types of this +package map into the required parts of the protocol -Usage + - Request Objects (type Request) + - Commands (type Cmd) + - Notifications (type Ntfn) + - Response Objects (type Response) + - Result (type Result) -The general pattern to use this package consists of generating a message (see -the full list on the official bitcoin wiki), sending the message, and handling -the result after asserting its type. +To simplify the marshalling of the requests and responses, the MarshalCmd and +MarshalResponse functions are provided. They return the raw bytes ready to be +sent across the wire. -For commands where the reply structure is known, such as getinfo, one can -directly access the fields in the Reply structure by type asserting the -reply to the appropriate concrete type. +Unmarshalling a received Request object is a two step process: + 1) Unmarshal the raw bytes into a Request struct instance via json.Unmarshal + 2) Use UnmarshalCmd on the Result field of the unmarshalled Request to create + a concrete command or notification instance with all struct fields set + accordingly - // Create a getinfo command. - id := 1 - cmd, err := btcjson.NewGetInfoCmd(id) - if err != nil { - // Log and handle error. - } +This approach is used since it provides the caller with access to the additional +fields in the request that are not part of the command such as the ID. - // Send the message to server using the appropriate username and - // password. - reply, err := btcjson.RpcSend(user, password, server, cmd) - if err != nil { - fmt.Println(err) - // Log and handle error. - } +Unmarshalling a received Response object is also a two step process: + 1) Unmarhsal the raw bytes into a Response struct instance via json.Unmarshal + 2) Depending on the ID, unmarshal the Result field of the unmarshalled + Response to create a concrete type instance - // Ensure there is a result and type assert it to a btcjson.InfoResult. - if reply.Result != nil { - if info, ok := reply.Result.(*btcjson.InfoResult); ok { - fmt.Println("balance =", info.Balance) - } - } +As above, this approach is used since it provides the caller with access to the +fields in the response such as the ID and Error. -For other commands where this package does not yet provide a concrete -implementation for the reply, such as getrawmempool, the reply uses a generic -interface so one can access individual items as follows: +Command Creation - // Create a getrawmempool command. - id := 1 - cmd, err := btcjson.NewGetRawMempoolCmd(id) - if err != nil { - // Log and handle error. - } +This package provides two approaches for creating a new command. This first, +and preferred, method is to use one of the NewCmd functions. This allows +static compile-time checking to help ensure the parameters stay in sync with +the struct definitions. - // Send the message to server using the appropriate username and - // password. - reply, err := btcjson.RpcSend(user, password, server, cmd) - if err != nil { - // Log and handle error. - } +The second approach is the NewCmd function which takes a method (command) name +and variable arguments. The function includes full checking to ensure the +parameters are accurate according to provided method, however these checks are, +obviously, run-time which means any mistakes won't be found until the code is +actually executed. However, it is quite useful for user-supplied commands +that are intentionally dynamic. - // Ensure there is a result and type assert it to a string slice. - if reply.Result != nil { - if mempool, ok := reply.Result.([]string); ok { - fmt.Println("num mempool entries =", len(mempool)) - } - } +Custom Command Registration + +The command handling of this package is built around the concept of registered +commands. This is true for the wide variety of commands already provided by the +package, but it also means caller can easily provide custom commands with all +of the same functionality as the built-in commands. Use the RegisterCmd +function for this purpose. + +A list of all registered methods can be obtained with the RegisteredCmdMethods +function. + +Command Inspection + +All registered commands are registered with flags that identify information such +as whether the command applies to a chain server, wallet server, or is a +notification along with the method name to use. These flags can be obtained +with the MethodUsageFlags flags, and the method can be obtained with the +CmdMethod function. + +Help Generation + +To facilitate providing consistent help to users of the RPC server, this package +exposes the GenerateHelp and function which uses reflection on registered +commands or notifications, as well as the provided expected result types, to +generate the final help text. + +In addition, the MethodUsageText function is provided to generate consistent +one-line usage for registered commands and notifications using reflection. + +Errors + +There are 2 distinct type of errors supported by this package: + + - General errors related to marshalling or unmarshalling or improper use of + the package (type Error) + - RPC errors which are intended to be returned across the wire as a part of + the JSON-RPC response (type RPCError) + +The first category of errors (type Error) typically indicates a programmer error +and can be avoided by properly using the API. Errors of this type will be +returned from the various functions available in this package. They identify +issues such as unsupported field types, attempts to register malformed commands, +and attempting to create a new command with an improper number of parameters. +The specific reason for the error can be detected by type asserting it to a +*btcjson.Error and accessing the ErrorCode field. + +The second category of errors (type RPCError), on the other hand, are useful for +returning errors to RPC clients. Consequently, they are used in the previously +described Response type. */ package btcjson diff --git a/btcjson/v2/btcjson/error.go b/btcjson/error.go similarity index 100% rename from btcjson/v2/btcjson/error.go rename to btcjson/error.go diff --git a/btcjson/v2/btcjson/error_test.go b/btcjson/error_test.go similarity index 97% rename from btcjson/v2/btcjson/error_test.go rename to btcjson/error_test.go index 12d9bdf2..22721003 100644 --- a/btcjson/v2/btcjson/error_test.go +++ b/btcjson/error_test.go @@ -7,7 +7,7 @@ package btcjson_test import ( "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestErrorCodeStringer tests the stringized output for the ErrorCode type. diff --git a/btcjson/v2/btcjson/example_test.go b/btcjson/example_test.go similarity index 99% rename from btcjson/v2/btcjson/example_test.go rename to btcjson/example_test.go index 793f574c..5e058d6d 100644 --- a/btcjson/v2/btcjson/example_test.go +++ b/btcjson/example_test.go @@ -8,7 +8,7 @@ import ( "encoding/json" "fmt" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // This example demonstrates how to create and marshal a command into a JSON-RPC diff --git a/btcjson/v2/btcjson/export_test.go b/btcjson/export_test.go similarity index 100% rename from btcjson/v2/btcjson/export_test.go rename to btcjson/export_test.go diff --git a/btcjson/v2/btcjson/help.go b/btcjson/help.go similarity index 100% rename from btcjson/v2/btcjson/help.go rename to btcjson/help.go diff --git a/btcjson/v2/btcjson/help_test.go b/btcjson/help_test.go similarity index 99% rename from btcjson/v2/btcjson/help_test.go rename to btcjson/help_test.go index 1756c5bb..0a731623 100644 --- a/btcjson/v2/btcjson/help_test.go +++ b/btcjson/help_test.go @@ -8,7 +8,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestHelpReflectInternals ensures the various help functions which deal with diff --git a/btcjson/v2/btcjson/helpers.go b/btcjson/helpers.go similarity index 100% rename from btcjson/v2/btcjson/helpers.go rename to btcjson/helpers.go diff --git a/btcjson/v2/btcjson/helpers_test.go b/btcjson/helpers_test.go similarity index 97% rename from btcjson/v2/btcjson/helpers_test.go rename to btcjson/helpers_test.go index cb55a9b2..60ab5cdd 100644 --- a/btcjson/v2/btcjson/helpers_test.go +++ b/btcjson/helpers_test.go @@ -8,7 +8,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestHelpers tests the various helper functions which create pointers to diff --git a/btcjson/internal_test.go b/btcjson/internal_test.go deleted file mode 100644 index 3116ec28..00000000 --- a/btcjson/internal_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson - -import ( - "encoding/json" - "testing" -) - -/* -This test file is part of the btcjson package rather than than the -btcjson_test package so it can bridge access to the internals to properly test -cases which are either not possible or can't reliably be tested via the public -interface. The functions are only exported while the tests are being run. -*/ - -// TestJsonWIthArgs tests jsonWithArgs to ensure that it can generate a json -// command as well as sending it something that cannot be marshalled to json -// (a channel) to test the failure paths. -func TestJsonWithArgs(t *testing.T) { - cmd := "list" - var args interface{} - _, err := jsonWithArgs(cmd, "test", args) - if err != nil { - t.Errorf("Could not make json with no args. %v", err) - } - - channel := make(chan int) - _, err = jsonWithArgs(cmd, "test", channel) - if _, ok := err.(*json.UnsupportedTypeError); !ok { - t.Errorf("Message with channel should fail. %v", err) - } - - var comp complex128 - _, err = jsonWithArgs(cmd, "test", comp) - if _, ok := err.(*json.UnsupportedTypeError); !ok { - t.Errorf("Message with complex part should fail. %v", err) - } - - return -} - -// TestJsonRPCSend tests jsonRPCSend which actually send the rpc command. -// This currently a negative test only until we setup a fake http server to -// test the actually connection code. -func TestJsonRPCSend(t *testing.T) { - // Just negative test right now. - user := "something" - password := "something" - server := "invalid" - var message []byte - _, err := jsonRPCSend(user, password, server, message, false, nil, false) - if err == nil { - t.Errorf("Should fail when it cannot connect.") - } - return -} diff --git a/btcjson/jsonapi.go b/btcjson/jsonapi.go deleted file mode 100644 index 7d4693c9..00000000 --- a/btcjson/jsonapi.go +++ /dev/null @@ -1,821 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" -) - -// BadStatusCode describes a HTTP error when a response has non-200 status code -type BadStatusCode int - -func (e BadStatusCode) Error() string { - status := int(e) - return fmt.Sprintf("http bad status: %d %s", status, http.StatusText(status)) -} - -// ErrIncorrectArgTypes describes an error where the wrong argument types -// are present. -var ErrIncorrectArgTypes = errors.New("incorrect arguement types") - -// Message contains a message to be sent to the bitcoin client. -type Message struct { - Jsonrpc string `json:"jsonrpc"` - Id interface{} `json:"id,omitempty"` - Method string `json:"method"` - Params interface{} `json:"params"` -} - -// Reply is the general form of the reply from the bitcoin client. -// The form of the Result part varies from one command to the next so it -// is currently implemented as an interface. -type Reply struct { - Result interface{} `json:"result"` - Error *Error `json:"error"` - // This has to be a pointer for go to put a null in it when empty. - Id *interface{} `json:"id"` -} - -// Error models the error field of the json returned by a bitcoin client. When -// there is no error, this should be a nil pointer to produce the null in the -// json that bitcoind produces. -type Error struct { - Code int `json:"code,omitempty"` - Message string `json:"message,omitempty"` -} - -// Guarantee Error satisifies the builtin error interface -var _, _ error = Error{}, &Error{} - -// Error returns a string describing the btcjson error. This -// satisifies the builtin error interface. -func (e Error) Error() string { - return fmt.Sprintf("%d: %s", e.Code, e.Message) -} - -// jsonWithArgs takes a command, an id, and an interface which contains an -// array of the arguments for that command. It knows NOTHING about the commands -// so all error checking of the arguments must happen before it is called. -func jsonWithArgs(command string, id interface{}, args interface{}) ([]byte, error) { - rawMessage := Message{"1.0", id, command, args} - finalMessage, err := json.Marshal(rawMessage) - if err != nil { - return nil, err - } - return finalMessage, nil -} - -// CreateMessage takes a string and the optional arguments for it. Then, -// if it is a recognized bitcoin json message, generates the json message ready -// to send off to the daemon or server. -// It is capable of handeling all of the commands from the standard client, -// described at: -// https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list -// -// WARNING: This method is deprecated and may be removed in a future version. -// Do NOT use this as it does not work for all commands. Instead, use one of -// the NewCmd functions to create a specific command. -func CreateMessage(message string, args ...interface{}) ([]byte, error) { - finalMessage, err := CreateMessageWithId(message, "btcd", args...) - return finalMessage, err -} - -// CreateMessageWithId takes a string, an id, and the optional arguments for -// it. Then, if it is a recognized bitcoin json message, generates the json -// message ready to send off to the daemon or server. It is capable of handling -// all of the commands from the standard client, described at: -// https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list -// -// WARNING: This method is deprecated and may be removed in a future version. -// Do NOT use this as it does not work for all commands. Instead, use one of -// the NewCmd functions to create a specific command. -func CreateMessageWithId(message string, id interface{}, args ...interface{}) ([]byte, error) { - var finalMessage []byte - var err error - // Different commands have different required and optional arguments. - // Need to handle them based on that. - switch message { - // No args - case "getblockcount", "getblocknumber", "getconnectioncount", - "getdifficulty", "getgenerate", "gethashespersec", "getinfo", - "getmininginfo", "getpeerinfo", "getrawmempool", - "keypoolrefill", "listaddressgroupings", "listlockunspent", - "stop", "walletlock", "getbestblockhash", "getblockchaininfo", - "getnetworkinfo": - if len(args) > 0 { - err = fmt.Errorf("too many arguments for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One optional int - case "listaccounts": - if len(args) > 1 { - err = fmt.Errorf("too many arguments for %s", message) - return finalMessage, err - } - if len(args) == 1 { - _, ok := args[0].(int) - if !ok { - err = fmt.Errorf("argument must be int for %s", message) - return finalMessage, err - } - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required int - case "getblockhash", "estimatefee", "estimatepriority": - if len(args) != 1 { - err = fmt.Errorf("missing argument for %s", message) - return finalMessage, err - } - _, ok := args[0].(int) - if !ok { - err = fmt.Errorf("argument must be int for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required float - case "settxfee": - if len(args) != 1 { - err = fmt.Errorf("missing argument for %s", message) - return finalMessage, err - } - _, ok := args[0].(float64) - if !ok { - err = fmt.Errorf("argument must be float64 for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One optional string - case "getmemorypool", "getnewaddress", "getwork", "help", - "getrawchangeaddress": - if len(args) > 1 { - err = fmt.Errorf("too many arguments for %s", message) - return finalMessage, err - } - if len(args) == 1 { - _, ok := args[0].(string) - if !ok { - err = fmt.Errorf("optional argument must be string for %s", message) - return finalMessage, err - } - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required string - case "backupwallet", "decoderawtransaction", "dumpprivkey", - "encryptwallet", "getaccount", "getaccountaddress", - "getaddressesbyaccount", "getblock", - "gettransaction", "sendrawtransaction", "validateaddress", - "invalidateblock", "reconsiderblock": - if len(args) != 1 { - err = fmt.Errorf("%s requires one argument", message) - return finalMessage, err - } - _, ok := args[0].(string) - if !ok { - err = fmt.Errorf("argument must be string for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // Two required strings - case "setaccount", "signmessage", "walletpassphrasechange", "addnode": - if len(args) != 2 { - err = fmt.Errorf("missing arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - _, ok2 := args[1].(string) - if !ok1 || !ok2 { - err = fmt.Errorf("arguments must be string for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required string, one required int - case "walletpassphrase": - if len(args) != 2 { - err = fmt.Errorf("missing arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - _, ok2 := args[1].(int) - if !ok1 || !ok2 { - err = fmt.Errorf("arguments must be string and int for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // Three required strings - case "verifymessage": - if len(args) != 3 { - err = fmt.Errorf("three arguments required for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - _, ok2 := args[1].(string) - _, ok3 := args[2].(string) - if !ok1 || !ok2 || !ok3 { - err = fmt.Errorf("arguments must be string for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required bool, one optional string - case "getaddednodeinfo": - if len(args) > 2 || len(args) == 0 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(bool) - ok2 := true - if len(args) == 2 { - _, ok2 = args[1].(string) - } - if !ok1 || !ok2 { - err = fmt.Errorf("arguments must be bool and optionally string for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required bool, one optional int - case "setgenerate": - if len(args) > 2 || len(args) == 0 { - err = fmt.Errorf("wrong number of argument for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(bool) - ok2 := true - if len(args) == 2 { - _, ok2 = args[1].(int) - } - if !ok1 || !ok2 { - err = fmt.Errorf("arguments must be bool and optionally int for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One optional string, one optional int - case "getbalance", "getreceivedbyaccount": - if len(args) > 2 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - ok1 := true - ok2 := true - if len(args) >= 1 { - _, ok1 = args[0].(string) - } - if len(args) == 2 { - _, ok2 = args[1].(int) - } - if !ok1 || !ok2 { - err = fmt.Errorf("optional arguments must be string and int for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required string, one optional int - case "getrawtransaction", "getreceivedbyaddress": - if len(args) > 2 || len(args) == 0 { - err = fmt.Errorf("wrong number of argument for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - ok2 := true - if len(args) == 2 { - _, ok2 = args[1].(int) - } - if !ok1 || !ok2 { - err = fmt.Errorf("arguments must be string and optionally int for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required string, one optional string - // Strictly, the optional arg for submit block is an object, but - // bitcoind ignores it for now, so best to just allow string until - // support for it is complete. - case "submitblock": - if len(args) > 2 || len(args) == 0 { - err = fmt.Errorf("wrong number of argument for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - ok2 := true - if len(args) == 2 { - _, ok2 = args[1].(string) - } - if !ok1 || !ok2 { - err = fmt.Errorf("arguments must be string and optionally string for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One optional int, one optional bool - case "listreceivedbyaccount", "listreceivedbyaddress": - if len(args) > 2 { - err = fmt.Errorf("wrong number of argument for %s", message) - return finalMessage, err - } - ok1 := true - ok2 := true - if len(args) >= 1 { - _, ok1 = args[0].(int) - } - if len(args) == 2 { - _, ok2 = args[1].(bool) - } - if !ok1 || !ok2 { - err = fmt.Errorf("optional arguments must be int and bool for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One optional string, two optional ints - case "listtransactions": - if len(args) > 3 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - ok1 := true - ok2 := true - ok3 := true - if len(args) >= 1 { - _, ok1 = args[0].(string) - } - if len(args) > 1 { - _, ok2 = args[1].(int) - } - if len(args) == 3 { - _, ok3 = args[2].(int) - } - if !ok1 || !ok2 || !ok3 { - err = fmt.Errorf("optional arguments must be string and up to two ints for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required string, one optional string, one optional bool - case "importprivkey": - if len(args) > 3 || len(args) == 0 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - ok2 := true - ok3 := true - if len(args) > 1 { - _, ok2 = args[1].(string) - } - if len(args) == 3 { - _, ok3 = args[2].(bool) - } - if !ok1 || !ok2 || !ok3 { - err = fmt.Errorf("arguments must be string and optionally string and bool for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // Two optional ints - case "listunspent": - if len(args) > 2 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - ok1 := true - ok2 := true - if len(args) >= 1 { - _, ok1 = args[0].(int) - } - if len(args) == 2 { - _, ok2 = args[1].(int) - } - if !ok1 || !ok2 { - err = fmt.Errorf("optional arguments must be ints for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // Two optional strings - case "listsinceblock": - if len(args) > 2 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - ok1 := true - ok2 := true - if len(args) >= 1 { - _, ok1 = args[0].(string) - } - if len(args) == 2 { - _, ok2 = args[1].(string) - } - if !ok1 || !ok2 { - err = fmt.Errorf("optional arguments must be strings for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - - // Two required strings, one required float, one optional int, - // two optional strings. - case "sendfrom": - if len(args) > 6 || len(args) < 3 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - _, ok2 := args[1].(string) - _, ok3 := args[2].(float64) - ok4 := true - ok5 := true - ok6 := true - if len(args) >= 4 { - _, ok4 = args[3].(int) - } - if len(args) >= 5 { - _, ok5 = args[4].(string) - } - if len(args) == 6 { - _, ok6 = args[5].(string) - } - if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 || !ok6 { - err = fmt.Errorf("arguments must be string, string, float64 and optionally int and two strings for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // Two required strings, one required float, one optional int, - // one optional string. - case "move": - if len(args) > 5 || len(args) < 3 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - _, ok2 := args[1].(string) - _, ok3 := args[2].(float64) - ok4 := true - ok5 := true - if len(args) >= 4 { - _, ok4 = args[3].(int) - } - if len(args) == 5 { - _, ok5 = args[4].(string) - } - if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 { - err = fmt.Errorf("arguments must be string, string, float64 and optionally int and string for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // One required strings, one required float, two optional strings - case "sendtoaddress": - if len(args) > 4 || len(args) < 2 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - _, ok2 := args[1].(float64) - ok3 := true - ok4 := true - if len(args) >= 3 { - _, ok3 = args[2].(string) - } - if len(args) == 4 { - _, ok4 = args[3].(string) - } - if !ok1 || !ok2 || !ok3 || !ok4 { - err = fmt.Errorf("arguments must be string, float64 and optionally two strings for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // required int, required pair of keys (string), optional string - case "addmultisignaddress": - if len(args) > 4 || len(args) < 3 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(int) - _, ok2 := args[1].(string) - _, ok3 := args[2].(string) - ok4 := true - if len(args) == 4 { - _, ok4 = args[2].(string) - } - if !ok1 || !ok2 || !ok3 || !ok4 { - err = fmt.Errorf("arguments must be int, two string and optionally one for %s", message) - return finalMessage, err - } - finalMessage, err = jsonWithArgs(message, id, args) - // Must be a set of string, int, string, float (any number of those). - case "createrawtransaction": - if len(args)%4 != 0 || len(args) == 0 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - type vlist struct { - Txid string `json:"txid"` - Vout uint32 `json:"vout"` - } - vList := make([]vlist, len(args)/4) - addresses := make(map[string]float64) - for i := 0; i < len(args)/4; i++ { - txid, ok1 := args[(i*4)+0].(string) - vout, ok2 := args[(i*4)+1].(uint32) - add, ok3 := args[(i*4)+2].(string) - amt, ok4 := args[(i*4)+3].(float64) - if !ok1 || !ok2 || !ok3 || !ok4 { - return finalMessage, ErrIncorrectArgTypes - } - vList[i].Txid = txid - vList[i].Vout = vout - addresses[add] = amt - } - finalMessage, err = jsonWithArgs(message, id, []interface{}{vList, addresses}) - // string, string/float pairs, optional int, and string - case "sendmany": - if len(args) < 3 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - var minconf int - var comment string - _, ok1 := args[0].(string) - if !ok1 { - return finalMessage, ErrIncorrectArgTypes - } - addresses := make(map[string]float64) - for i := 1; i < len(args); i += 2 { - add, ok1 := args[i].(string) - if ok1 { - if len(args) > i+1 { - amt, ok2 := args[i+1].(float64) - if !ok2 { - return finalMessage, ErrIncorrectArgTypes - } - // Put a single pair into addresses - addresses[add] = amt - } else { - comment = add - } - } else { - if _, ok := args[i].(int); ok { - minconf = args[i].(int) - } - if len(args)-1 > i { - if _, ok := args[i+1].(string); ok { - comment = args[i+1].(string) - } - } - } - } - finalMessage, err = jsonWithArgs(message, id, []interface{}{args[0].(string), addresses, minconf, comment}) - // bool and an array of stuff - case "lockunspent": - if len(args) < 2 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(bool) - if !ok1 { - return finalMessage, ErrIncorrectArgTypes - } - finalMessage, err = jsonWithArgs(message, id, args) - // one required string (hex) and optional sets of one string, one int, - // and one string along with another optional string. - case "signrawtransaction": - if len(args) < 1 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - if !ok1 { - return finalMessage, ErrIncorrectArgTypes - } - type txlist struct { - Txid string `json:"txid"` - Vout uint32 `json:"vout"` - ScriptPubKey string `json:"scriptPubKey"` - } - txList := make([]txlist, 1) - - if len(args) > 1 { - txid, ok2 := args[1].(string) - vout, ok3 := args[2].(uint32) - spkey, ok4 := args[3].(string) - if !ok1 || !ok2 || !ok3 || !ok4 { - return finalMessage, ErrIncorrectArgTypes - } - txList[0].Txid = txid - txList[0].Vout = vout - txList[0].ScriptPubKey = spkey - } - /* - pkeyList := make([]string, (len(args)-1)/4) - for i := 0; i < len(args)/4; i += 1 { - fmt.Println(args[(i*4)+4]) - txid, ok1 := args[(i*4)+1].(string) - vout, ok2 := args[(i*4)+2].(int) - spkey, ok3 := args[(i*4)+3].(string) - pkey, ok4 := args[(i*4)+4].(string) - if !ok1 || !ok2 || !ok3 || !ok4 { - return finalMessage, ErrIncorrectArgTypes - } - txList[i].Txid = txid - txList[i].Vout = vout - txList[i].ScriptPubKey = spkey - pkeyList[i] = pkey - } - */ - finalMessage, err = jsonWithArgs(message, id, []interface{}{args[0].(string), txList}) - // one required string (address), one optional bool, two optional ints. - case "searchrawtransactions": - if len(args) > 4 || len(args) == 0 { - err = fmt.Errorf("wrong number of arguments for %s", message) - return finalMessage, err - } - _, ok1 := args[0].(string) - ok2 := true - ok3 := true - ok4 := true - if len(args) >= 2 { - _, ok2 = args[1].(int) - } - if len(args) >= 3 { - _, ok3 = args[2].(int) - } - if len(args) == 4 { - _, ok4 = args[3].(int) - } - if !ok1 || !ok2 || !ok3 || !ok4 { - err = fmt.Errorf("arguments must be string, one optional "+ - "bool, and two optional ints for %s", message) - return finalMessage, err - } - // Any other message - default: - err = fmt.Errorf("not a valid command: %s", message) - } - return finalMessage, err -} - -// JSONGetMethod takes a message and tries to find the bitcoin command that it -// is in reply to so it can be processed further. -func JSONGetMethod(message []byte) (string, error) { - var obj struct { - Method string `json:"method"` - } - err := json.Unmarshal(message, &obj) - return obj.Method, err -} - -// TlsRpcCommand takes a message generated from one of the routines above -// along with the login/server information and any relavent PEM encoded -// certificates chains. It sends the command via https and returns a go struct -// with the result. -func TlsRpcCommand(user string, password string, server string, message []byte, - certificates []byte, skipverify bool) (Reply, error) { - return rpcCommand(user, password, server, message, true, certificates, - skipverify) -} - -// RpcCommand takes a message generated from one of the routines above -// along with the login/server info, sends it, and gets a reply, returning -// a go struct with the result. -func RpcCommand(user string, password string, server string, message []byte) (Reply, error) { - return rpcCommand(user, password, server, message, false, nil, false) -} - -func rpcCommand(user string, password string, server string, message []byte, - https bool, certificates []byte, skipverify bool) (Reply, error) { - var result Reply - method, err := JSONGetMethod(message) - if err != nil { - return result, err - } - body, err := rpcRawCommand(user, password, server, message, https, - certificates, skipverify) - if err != nil { - err := fmt.Errorf("error getting json reply: %v", err) - return result, err - } - result, err = ReadResultCmd(method, body) - if err != nil { - err := fmt.Errorf("error reading json message: %v", err) - return result, err - } - return result, err -} - -// TlsRpcRawCommand takes a message generated from one of the routines above -// along with the login,server info and PEM encoded certificate chains for the -// server sends it, and gets a reply, returning -// the raw []byte response for use with ReadResultCmd. -func TlsRpcRawCommand(user string, password string, server string, - message []byte, certificates []byte, skipverify bool) ([]byte, error) { - return rpcRawCommand(user, password, server, message, true, - certificates, skipverify) -} - -// RpcRawCommand takes a message generated from one of the routines above -// along with the login/server info, sends it, and gets a reply, returning -// the raw []byte response for use with ReadResultCmd. -func RpcRawCommand(user string, password string, server string, message []byte) ([]byte, error) { - return rpcRawCommand(user, password, server, message, false, nil, false) -} - -// rpcRawCommand is a helper function for the above two functions. -func rpcRawCommand(user string, password string, server string, - message []byte, https bool, certificates []byte, skipverify bool) ([]byte, error) { - var result []byte - var msg interface{} - err := json.Unmarshal(message, &msg) - if err != nil { - err := fmt.Errorf("error, message does not appear to be valid json: %v", err) - return result, err - } - resp, err := jsonRPCSend(user, password, server, message, https, - certificates, skipverify) - if err != nil { - err := fmt.Errorf("error sending json message: " + err.Error()) - return result, err - } - if resp.StatusCode != http.StatusOK { - return nil, BadStatusCode(resp.StatusCode) - } - result, err = GetRaw(resp.Body) - if err != nil { - err := fmt.Errorf("error getting json reply: %v", err) - return result, err - } - return result, err -} - -// RpcSend sends the passed command to the provided server using the provided -// authentication details, waits for a reply, and returns a Go struct with the -// result. -func RpcSend(user string, password string, server string, cmd Cmd) (Reply, error) { - msg, err := cmd.MarshalJSON() - if err != nil { - return Reply{}, err - } - - return RpcCommand(user, password, server, msg) -} - -// TlsRpcSend sends the passed command to the provided server using the provided -// authentication details and PEM encoded certificate chain, waits for a reply, -// and returns a Go struct with the result. -func TlsRpcSend(user string, password string, server string, cmd Cmd, - certificates []byte, skipVerify bool) (Reply, error) { - - msg, err := cmd.MarshalJSON() - if err != nil { - return Reply{}, err - } - - return TlsRpcCommand(user, password, server, msg, certificates, - skipVerify) -} - -// IsValidIdType checks that the Id field (which can go in any of the json -// messages) is valid. json rpc 1.0 allows any (json) type, but we still need -// to prevent values that cannot be marshalled from going in. json rpc 2.0 -// (which bitcoind follows for some parts) only allows string, number, or null, -// so we restrict to that list. Ths is only necessary if you manually marshal -// a message. The normal btcjson functions only use string ids. -func IsValidIdType(id interface{}) bool { - switch id.(type) { - case int, int8, int16, int32, int64, - uint, uint8, uint16, uint32, uint64, - float32, float64, - string, - nil: - return true - default: - return false - } -} - -// JSONToAmount Safely converts a floating point value to an int. -// Clearly not all floating point numbers can be converted to ints (there -// is no one-to-one mapping), but bitcoin's json api returns most numbers as -// floats which are not safe to use when handling money. Since bitcoins can -// only be divided in a limited way, this methods works for the amounts returned -// by the json api. It is not for general use. -// This follows the method described at: -// https://en.bitcoin.it/wiki/Proper_Money_Handling_%28JSON-RPC%29 -func JSONToAmount(jsonAmount float64) (int64, error) { - var amount int64 - var err error - if jsonAmount > 1.797693134862315708145274237317043567981e+300 { - err := fmt.Errorf("error %v is too large to convert", jsonAmount) - return amount, err - } - if jsonAmount < -1.797693134862315708145274237317043567981e+300 { - err := fmt.Errorf("error %v is too small to convert", jsonAmount) - return amount, err - } - tempVal := 1e8 * jsonAmount - // So we round properly. float won't == 0 and if it did, that - // would be converted fine anyway. - if tempVal < 0 { - tempVal = tempVal - 0.5 - } - if tempVal > 0 { - tempVal = tempVal + 0.5 - } - // Then just rely on the integer truncating - amount = int64(tempVal) - return amount, err -} diff --git a/btcjson/jsonapi_test.go b/btcjson/jsonapi_test.go deleted file mode 100644 index 05800370..00000000 --- a/btcjson/jsonapi_test.go +++ /dev/null @@ -1,395 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson_test - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "testing" - - "github.com/btcsuite/btcd/btcjson" -) - -// cmdtests is a table of all the possible commands and a list of inputs, -// some of which should work, some of which should not (indicated by the -// pass variable). This mainly checks the type and number of the arguments, -// it does not actually check to make sure the values are correct (i.e., that -// addresses are reasonable) as the bitcoin client must be able to deal with -// that. -var cmdtests = []struct { - cmd string - args []interface{} - pass bool -}{ - {"createmultisig", nil, false}, - {"createmultisig", []interface{}{1}, false}, - {"getinfo", nil, true}, - {"getinfo", []interface{}{1}, false}, - {"listaccounts", nil, true}, - {"listaccounts", []interface{}{1}, true}, - {"listaccounts", []interface{}{"test"}, false}, - {"listaccounts", []interface{}{1, 2}, false}, - {"estimatefee", nil, false}, - {"estimatefee", []interface{}{1}, true}, - {"estimatefee", []interface{}{1, 2}, false}, - {"estimatefee", []interface{}{1.3}, false}, - {"estimatepriority", nil, false}, - {"estimatepriority", []interface{}{1}, true}, - {"estimatepriority", []interface{}{1, 2}, false}, - {"estimatepriority", []interface{}{1.3}, false}, - {"getblockhash", nil, false}, - {"getblockhash", []interface{}{1}, true}, - {"getblockhash", []interface{}{1, 2}, false}, - {"getblockhash", []interface{}{1.1}, false}, - {"settxfee", nil, false}, - {"settxfee", []interface{}{1.0}, true}, - {"settxfee", []interface{}{1.0, 2.0}, false}, - {"settxfee", []interface{}{1}, false}, - {"getmemorypool", nil, true}, - {"getmemorypool", []interface{}{"test"}, true}, - {"getmemorypool", []interface{}{1}, false}, - {"getmemorypool", []interface{}{"test", 2}, false}, - {"backupwallet", nil, false}, - {"backupwallet", []interface{}{1, 2}, false}, - {"backupwallet", []interface{}{1}, false}, - {"backupwallet", []interface{}{"testpath"}, true}, - {"invalidateblock", nil, false}, - {"invalidateblock", []interface{}{1, 2}, false}, - {"invalidateblock", []interface{}{1}, false}, - {"invalidateblock", []interface{}{"testhash"}, true}, - {"reconsiderblock", nil, false}, - {"reconsiderblock", []interface{}{1, 2}, false}, - {"reconsiderblock", []interface{}{1}, false}, - {"reconsiderblock", []interface{}{"testhash"}, true}, - {"setaccount", nil, false}, - {"setaccount", []interface{}{1}, false}, - {"setaccount", []interface{}{1, 2, 3}, false}, - {"setaccount", []interface{}{1, "test"}, false}, - {"setaccount", []interface{}{"test", "test"}, true}, - {"verifymessage", nil, false}, - {"verifymessage", []interface{}{1}, false}, - {"verifymessage", []interface{}{1, 2}, false}, - {"verifymessage", []interface{}{1, 2, 3, 4}, false}, - {"verifymessage", []interface{}{"test", "test", "test"}, true}, - {"verifymessage", []interface{}{"test", "test", 1}, false}, - {"getaddednodeinfo", nil, false}, - {"getaddednodeinfo", []interface{}{1}, false}, - {"getaddednodeinfo", []interface{}{true}, true}, - {"getaddednodeinfo", []interface{}{true, 1}, false}, - {"getaddednodeinfo", []interface{}{true, "test"}, true}, - {"setgenerate", nil, false}, - {"setgenerate", []interface{}{1, 2, 3}, false}, - {"setgenerate", []interface{}{true}, true}, - {"setgenerate", []interface{}{true, 1}, true}, - {"setgenerate", []interface{}{true, 1.1}, false}, - {"setgenerate", []interface{}{"true", 1}, false}, - {"getbalance", nil, true}, - {"getbalance", []interface{}{"test"}, true}, - {"getbalance", []interface{}{"test", 1}, true}, - {"getbalance", []interface{}{"test", 1.0}, false}, - {"getbalance", []interface{}{1, 1}, false}, - {"getbalance", []interface{}{"test", 1, 2}, false}, - {"getbalance", []interface{}{1}, false}, - {"addnode", nil, false}, - {"addnode", []interface{}{1, 2, 3}, false}, - {"addnode", []interface{}{"test", "test"}, true}, - {"addnode", []interface{}{1}, false}, - {"addnode", []interface{}{"test", 1}, false}, - {"addnode", []interface{}{"test", 1.0}, false}, - {"listreceivedbyaccount", nil, true}, - {"listreceivedbyaccount", []interface{}{1, 2, 3}, false}, - {"listreceivedbyaccount", []interface{}{1}, true}, - {"listreceivedbyaccount", []interface{}{1.0}, false}, - {"listreceivedbyaccount", []interface{}{1, false}, true}, - {"listreceivedbyaccount", []interface{}{1, "false"}, false}, - {"listtransactions", nil, true}, - {"listtransactions", []interface{}{"test"}, true}, - {"listtransactions", []interface{}{"test", 1}, true}, - {"listtransactions", []interface{}{"test", 1, 2}, true}, - {"listtransactions", []interface{}{"test", 1, 2, 3}, false}, - {"listtransactions", []interface{}{1}, false}, - {"listtransactions", []interface{}{"test", 1.0}, false}, - {"listtransactions", []interface{}{"test", 1, "test"}, false}, - {"importprivkey", nil, false}, - {"importprivkey", []interface{}{"test"}, true}, - {"importprivkey", []interface{}{1}, false}, - {"importprivkey", []interface{}{"test", "test"}, true}, - {"importprivkey", []interface{}{"test", "test", true}, true}, - {"importprivkey", []interface{}{"test", "test", true, 1}, false}, - {"importprivkey", []interface{}{"test", 1.0, true}, false}, - {"importprivkey", []interface{}{"test", "test", "true"}, false}, - {"listunspent", nil, true}, - {"listunspent", []interface{}{1}, true}, - {"listunspent", []interface{}{1, 2}, true}, - {"listunspent", []interface{}{1, 2, 3}, false}, - {"listunspent", []interface{}{1.0}, false}, - {"listunspent", []interface{}{1, 2.0}, false}, - {"sendfrom", nil, false}, - {"sendfrom", []interface{}{"test"}, false}, - {"sendfrom", []interface{}{"test", "test"}, false}, - {"sendfrom", []interface{}{"test", "test", 1.0}, true}, - {"sendfrom", []interface{}{"test", 1, 1.0}, false}, - {"sendfrom", []interface{}{1, "test", 1.0}, false}, - {"sendfrom", []interface{}{"test", "test", 1}, false}, - {"sendfrom", []interface{}{"test", "test", 1.0, 1}, true}, - {"sendfrom", []interface{}{"test", "test", 1.0, 1, "test"}, true}, - {"sendfrom", []interface{}{"test", "test", 1.0, 1, "test", "test"}, true}, - {"move", nil, false}, - {"move", []interface{}{1, 2, 3, 4, 5, 6}, false}, - {"move", []interface{}{1, 2}, false}, - {"move", []interface{}{"test", "test", 1.0}, true}, - {"move", []interface{}{"test", "test", 1.0, 1, "test"}, true}, - {"move", []interface{}{"test", "test", 1.0, 1}, true}, - {"move", []interface{}{1, "test", 1.0}, false}, - {"move", []interface{}{"test", 1, 1.0}, false}, - {"move", []interface{}{"test", "test", 1}, false}, - {"move", []interface{}{"test", "test", 1.0, 1.0, "test"}, false}, - {"move", []interface{}{"test", "test", 1.0, 1, true}, false}, - {"sendtoaddress", nil, false}, - {"sendtoaddress", []interface{}{"test"}, false}, - {"sendtoaddress", []interface{}{"test", 1.0}, true}, - {"sendtoaddress", []interface{}{"test", 1.0, "test"}, true}, - {"sendtoaddress", []interface{}{"test", 1.0, "test", "test"}, true}, - {"sendtoaddress", []interface{}{1, 1.0, "test", "test"}, false}, - {"sendtoaddress", []interface{}{"test", 1, "test", "test"}, false}, - {"sendtoaddress", []interface{}{"test", 1.0, 1.0, "test"}, false}, - {"sendtoaddress", []interface{}{"test", 1.0, "test", 1.0}, false}, - {"sendtoaddress", []interface{}{"test", 1.0, "test", "test", 1}, false}, - {"addmultisignaddress", []interface{}{1, "test", "test"}, true}, - {"addmultisignaddress", []interface{}{1, "test"}, false}, - {"addmultisignaddress", []interface{}{1, 1.0, "test"}, false}, - {"addmultisignaddress", []interface{}{1, "test", "test", "test"}, true}, - {"createrawtransaction", []interface{}{"in1", uint32(0), "a1", 1.0}, true}, - {"createrawtransaction", []interface{}{"in1", "out1", "a1", 1.0, "test"}, false}, - {"createrawtransaction", []interface{}{}, false}, - {"createrawtransaction", []interface{}{"in1", 1.0, "a1", 1.0}, false}, - {"sendmany", []interface{}{"in1", "out1", 1.0, 1, "comment"}, true}, - {"sendmany", []interface{}{"in1", "out1", 1.0, "comment"}, true}, - {"sendmany", []interface{}{"in1", "out1"}, false}, - {"sendmany", []interface{}{true, "out1", 1.0, 1, "comment"}, false}, - {"sendmany", []interface{}{"in1", "out1", "test", 1, "comment"}, false}, - {"lockunspent", []interface{}{true, "something"}, true}, - {"lockunspent", []interface{}{true}, false}, - {"lockunspent", []interface{}{1.0, "something"}, false}, - {"signrawtransaction", []interface{}{"hexstring", "test", uint32(1), "test"}, true}, - {"signrawtransaction", []interface{}{"hexstring", "test", "test2", "test3", "test4"}, false}, - {"signrawtransaction", []interface{}{"hexstring", "test", "test2", "test3"}, false}, - {"signrawtransaction", []interface{}{1.2, "test", "test2", "test3", "test4"}, false}, - {"signrawtransaction", []interface{}{"hexstring", 1, "test2", "test3", "test4"}, false}, - {"signrawtransaction", []interface{}{"hexstring", "test", "test2", 3, "test4"}, false}, - {"searchrawtransactions", []interface{}{"someaddr"}, true}, - {"searchrawtransactions", []interface{}{"someaddr", 1}, true}, - {"searchrawtransactions", []interface{}{"someaddr", 0, 1}, true}, - {"searchrawtransactions", []interface{}{"someaddr", 1, 5, 500}, true}, - {"searchrawtransactions", []interface{}{"someaddr", 1, 5, "test"}, false}, - {"searchrawtransactions", []interface{}{}, false}, - {"listsinceblock", []interface{}{"test", "test"}, true}, - {"listsinceblock", []interface{}{"test", "test", "test"}, false}, - {"listsinceblock", []interface{}{"test"}, true}, - {"listsinceblock", []interface{}{}, true}, - {"listsinceblock", []interface{}{1, "test"}, false}, - {"walletpassphrase", []interface{}{"test", 1}, true}, - {"walletpassphrase", []interface{}{"test"}, false}, - {"walletpassphrase", []interface{}{"test", "test"}, false}, - {"getrawchangeaddress", []interface{}{}, true}, - {"getrawchangeaddress", []interface{}{"something"}, true}, - {"getrawchangeaddress", []interface{}{"something", "test"}, false}, - {"getbestblockhash", []interface{}{}, true}, - {"getbestblockhash", []interface{}{"something"}, false}, - {"getblockchaininfo", []interface{}{}, true}, - {"getblockchaininfo", []interface{}{"something"}, false}, - {"getnetworkinfo", []interface{}{}, true}, - {"getnetworkinfo", []interface{}{"something"}, false}, - {"submitblock", []interface{}{}, false}, - {"submitblock", []interface{}{"something"}, true}, - {"submitblock", []interface{}{"something", "something else"}, true}, - {"submitblock", []interface{}{"something", "something else", "more"}, false}, - {"submitblock", []interface{}{"something", 1}, false}, - {"fakecommand", nil, false}, -} - -// TestRpcCreateMessage tests CreateMessage using the table of messages -// in cmdtests. -func TestRpcCreateMessage(t *testing.T) { - var err error - for i, tt := range cmdtests { - if tt.args == nil { - _, err = btcjson.CreateMessage(tt.cmd) - } else { - _, err = btcjson.CreateMessage(tt.cmd, tt.args...) - } - if tt.pass { - if err != nil { - t.Errorf("Could not create command %d: %s %v.", i, tt.cmd, err) - } - } else { - if err == nil { - t.Errorf("Should create command. %d: %s", i, tt.cmd) - } - } - } - return -} - -// TestRpcCommand tests RpcCommand by generating some commands and -// trying to send them off. -func TestRpcCommand(t *testing.T) { - user := "something" - pass := "something" - server := "invalid" - var msg []byte - _, err := btcjson.RpcCommand(user, pass, server, msg) - if err == nil { - t.Errorf("Should fail.") - } - msg, err = btcjson.CreateMessage("getinfo") - if err != nil { - t.Errorf("Cannot create valid json message") - } - _, err = btcjson.RpcCommand(user, pass, server, msg) - if err == nil { - t.Errorf("Should not connect to server.") - } - - badMsg := []byte("{\"jsonrpc\":\"1.0\",\"id\":\"btcd\",\"method\":\"\"}") - _, err = btcjson.RpcCommand(user, pass, server, badMsg) - if err == nil { - t.Errorf("Cannot have no method in msg..") - } - return -} - -// FailingReadClose is a type used for testing so we can get something that -// fails past Go's type system. -type FailingReadCloser struct{} - -func (f *FailingReadCloser) Close() error { - return io.ErrUnexpectedEOF -} - -func (f *FailingReadCloser) Read(p []byte) (n int, err error) { - return 0, io.ErrUnexpectedEOF -} - -// TestRpcReply tests JsonGetRaw by sending both a good and a bad buffer -// to it. -func TestRpcReply(t *testing.T) { - buffer := new(bytes.Buffer) - buffer2 := ioutil.NopCloser(buffer) - _, err := btcjson.GetRaw(buffer2) - if err != nil { - t.Errorf("Error reading rpc reply.") - } - failBuf := &FailingReadCloser{} - _, err = btcjson.GetRaw(failBuf) - if err == nil { - t.Errorf("Error, this should fail.") - } - return -} - -var idtests = []struct { - testID []interface{} - pass bool -}{ - {[]interface{}{"string test"}, true}, - {[]interface{}{1}, true}, - {[]interface{}{1.0}, true}, - {[]interface{}{nil}, true}, - {[]interface{}{make(chan int)}, false}, -} - -// TestIsValidIdType tests that IsValidIdType allows (and disallows the correct -// types). -func TestIsValidIdType(t *testing.T) { - for _, tt := range idtests { - res := btcjson.IsValidIdType(tt.testID[0]) - if res != tt.pass { - t.Errorf("Incorrect type result %v.", tt) - } - } - return -} - -var floattests = []struct { - in float64 - out int64 - pass bool -}{ - {1.0, 100000000, true}, - {-1.0, -100000000, true}, - {0.0, 0, true}, - {0.00000001, 1, true}, - {-0.00000001, -1, true}, - {-1.0e307, 0, false}, - {1.0e307, 0, false}, -} - -// TestJSONtoAmount tests that JSONtoAmount returns the proper values. -func TestJSONtoAmount(t *testing.T) { - for _, tt := range floattests { - res, err := btcjson.JSONToAmount(tt.in) - if tt.pass { - if res != tt.out || err != nil { - t.Errorf("Should not fail: %v", tt.in) - } - } else { - if err == nil { - t.Errorf("Should not pass: %v", tt.in) - } - } - } - return -} - -// TestErrorInterface tests that the Error type satisifies the builtin -// error interface and tests that the error string is created in the form -// "code: message". -func TestErrorInterface(t *testing.T) { - codes := []int{ - -1, - 0, - 1, - } - messages := []string{ - "parse error", - "error getting field", - "method not found", - } - - // Create an Error and check that both Error and *Error can be used - // as an error. - var jsonError btcjson.Error - var iface interface{} = jsonError - var ifacep interface{} = &jsonError - if _, ok := iface.(error); !ok { - t.Error("cannot type assert Error as error") - return - } - if _, ok := ifacep.(error); !ok { - t.Error("cannot type assert *Error as error") - return - } - - // Verify jsonError is converted to the expected string using a few - // combinations of codes and messages. - for _, code := range codes { - for _, message := range messages { - // Create Error - jsonError := btcjson.Error{ - Code: code, - Message: message, - } - - exp := fmt.Sprintf("%d: %s", jsonError.Code, jsonError.Message) - res := fmt.Sprintf("%v", jsonError) - if exp != res { - t.Errorf("error string '%s' differs from expected '%v'", res, exp) - } - } - } -} diff --git a/btcjson/jsoncmd.go b/btcjson/jsoncmd.go deleted file mode 100644 index e1812a22..00000000 --- a/btcjson/jsoncmd.go +++ /dev/null @@ -1,7283 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson - -import ( - "encoding/json" - "errors" - "fmt" -) - -// ErrTooManyOptArgs describes an error where too many optional -// arguments were passed when creating a new Cmd. -var ErrTooManyOptArgs = errors.New("too many optional arguments") - -// ErrWrongNumberOfParams describes an error where an incorrect number of -// parameters are found in an unmarshalled command. -var ErrWrongNumberOfParams = errors.New("incorrect number of parameters") - -// Cmd is an interface for all Bitcoin JSON API commands to marshal -// and unmarshal as a JSON object. -type Cmd interface { - json.Marshaler - json.Unmarshaler - Id() interface{} - Method() string -} - -// RawCmd is a type for unmarshaling raw commands into before the -// custom command type is set. Other packages may register their -// own RawCmd to Cmd converters by calling RegisterCustomCmd. -type RawCmd struct { - Jsonrpc string `json:"jsonrpc"` - Id interface{} `json:"id"` - Method string `json:"method"` - Params []json.RawMessage `json:"params"` -} - -// NewRawCmd returns a new raw command given the provided id, method, and -// parameters. The parameters are marshalled into a json.RawMessage for the -// Params field of the returned raw command. -func NewRawCmd(id interface{}, method string, params []interface{}) (*RawCmd, error) { - rawParams := make([]json.RawMessage, 0, len(params)) - for _, param := range params { - marshalledParam, err := json.Marshal(param) - if err != nil { - return nil, err - } - rawMessage := json.RawMessage(marshalledParam) - rawParams = append(rawParams, rawMessage) - } - - return &RawCmd{ - Jsonrpc: "1.0", - Id: id, - Method: method, - Params: rawParams, - }, nil -} - -// RawCmdParser is a function to create a custom Cmd from a RawCmd. -type RawCmdParser func(*RawCmd) (Cmd, error) - -// ReplyParser is a function a custom Cmd can use to unmarshal the results of a -// reply into a concrete struct. -type ReplyParser func(json.RawMessage) (interface{}, error) - -type cmd struct { - parser RawCmdParser - replyParser ReplyParser - helpString string -} - -var customCmds = make(map[string]cmd) - -// RegisterCustomCmd registers a custom RawCmd parsing func, reply parsing func, -// and help text for a non-standard Bitcoin command. -func RegisterCustomCmd(method string, parser RawCmdParser, replyParser ReplyParser, helpString string) { - customCmds[method] = cmd{ - parser: parser, - replyParser: replyParser, - helpString: helpString, - } -} - -// ParseMarshaledCmd parses a raw command and unmarshals as a Cmd. -// Code that reads and handles commands should switch on the type and -// type assert as the particular commands supported by the program. -// -// In all cases where b is a valid JSON-RPC message, and unmarshalling -// succeeds, a non-nil Cmd will always be returned. This even -// includes error cases where parsing the message into a concrete Cmd -// type fails. This behavior allows RPC server code to reply back with -// a detailed error using the Id and Method functions of the Cmd -// interface. -func ParseMarshaledCmd(b []byte) (Cmd, error) { - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return nil, err - } - - // Return a custom command type for recognized - var cmd Cmd - switch r.Method { - case "addmultisigaddress": - cmd = new(AddMultisigAddressCmd) - - case "addnode": - cmd = new(AddNodeCmd) - - case "backupwallet": - cmd = new(BackupWalletCmd) - - case "createmultisig": - cmd = new(CreateMultisigCmd) - - case "createrawtransaction": - cmd = new(CreateRawTransactionCmd) - - case "debuglevel": - cmd = new(DebugLevelCmd) - - case "decoderawtransaction": - cmd = new(DecodeRawTransactionCmd) - - case "decodescript": - cmd = new(DecodeScriptCmd) - - case "dumpprivkey": - cmd = new(DumpPrivKeyCmd) - - case "dumpwallet": - cmd = new(DumpWalletCmd) - - case "encryptwallet": - cmd = new(EncryptWalletCmd) - - case "estimatefee": - cmd = new(EstimateFeeCmd) - - case "estimatepriority": - cmd = new(EstimatePriorityCmd) - - case "getaccount": - cmd = new(GetAccountCmd) - - case "getaccountaddress": - cmd = new(GetAccountAddressCmd) - - case "getaddednodeinfo": - cmd = new(GetAddedNodeInfoCmd) - - case "getaddressesbyaccount": - cmd = new(GetAddressesByAccountCmd) - - case "getbalance": - cmd = new(GetBalanceCmd) - - case "getbestblockhash": - cmd = new(GetBestBlockHashCmd) - - case "getblock": - cmd = new(GetBlockCmd) - - case "getblockchaininfo": - cmd = new(GetBlockChainInfoCmd) - - case "getblockcount": - cmd = new(GetBlockCountCmd) - - case "getblockhash": - cmd = new(GetBlockHashCmd) - - case "getblocktemplate": - cmd = new(GetBlockTemplateCmd) - - case "getconnectioncount": - cmd = new(GetConnectionCountCmd) - - case "getdifficulty": - cmd = new(GetDifficultyCmd) - - case "getgenerate": - cmd = new(GetGenerateCmd) - - case "gethashespersec": - cmd = new(GetHashesPerSecCmd) - - case "getinfo": - cmd = new(GetInfoCmd) - - case "getmininginfo": - cmd = new(GetMiningInfoCmd) - - case "getnettotals": - cmd = new(GetNetTotalsCmd) - - case "getnetworkhashps": - cmd = new(GetNetworkHashPSCmd) - - case "getnetworkinfo": - cmd = new(GetNetworkInfoCmd) - - case "getnewaddress": - cmd = new(GetNewAddressCmd) - - case "getpeerinfo": - cmd = new(GetPeerInfoCmd) - - case "getrawchangeaddress": - cmd = new(GetRawChangeAddressCmd) - - case "getrawmempool": - cmd = new(GetRawMempoolCmd) - - case "getrawtransaction": - cmd = new(GetRawTransactionCmd) - - case "getreceivedbyaccount": - cmd = new(GetReceivedByAccountCmd) - - case "getreceivedbyaddress": - cmd = new(GetReceivedByAddressCmd) - - case "gettransaction": - cmd = new(GetTransactionCmd) - - case "gettxout": - cmd = new(GetTxOutCmd) - - case "gettxoutsetinfo": - cmd = new(GetTxOutSetInfoCmd) - - case "getwork": - cmd = new(GetWorkCmd) - - case "help": - cmd = new(HelpCmd) - - case "importaddress": - cmd = new(ImportAddressCmd) - - case "importpubkey": - cmd = new(ImportPubKeyCmd) - - case "importprivkey": - cmd = new(ImportPrivKeyCmd) - - case "importwallet": - cmd = new(ImportWalletCmd) - - case "invalidateblock": - cmd = new(InvalidateBlockCmd) - - case "keypoolrefill": - cmd = new(KeyPoolRefillCmd) - - case "listaccounts": - cmd = new(ListAccountsCmd) - - case "listaddressgroupings": - cmd = new(ListAddressGroupingsCmd) - - case "listlockunspent": - cmd = new(ListLockUnspentCmd) - - case "listreceivedbyaccount": - cmd = new(ListReceivedByAccountCmd) - - case "listreceivedbyaddress": - cmd = new(ListReceivedByAddressCmd) - - case "listsinceblock": - cmd = new(ListSinceBlockCmd) - - case "listtransactions": - cmd = new(ListTransactionsCmd) - - case "listunspent": - cmd = new(ListUnspentCmd) - - case "lockunspent": - cmd = new(LockUnspentCmd) - - case "move": - cmd = new(MoveCmd) - - case "ping": - cmd = new(PingCmd) - - case "reconsiderblock": - cmd = new(ReconsiderBlockCmd) - - case "searchrawtransactions": - cmd = new(SearchRawTransactionsCmd) - - case "sendfrom": - cmd = new(SendFromCmd) - - case "sendmany": - cmd = new(SendManyCmd) - - case "sendrawtransaction": - cmd = new(SendRawTransactionCmd) - - case "sendtoaddress": - cmd = new(SendToAddressCmd) - - case "setaccount": - cmd = new(SetAccountCmd) - - case "setgenerate": - cmd = new(SetGenerateCmd) - - case "settxfee": - cmd = new(SetTxFeeCmd) - - case "signmessage": - cmd = new(SignMessageCmd) - - case "signrawtransaction": - cmd = new(SignRawTransactionCmd) - - case "stop": - cmd = new(StopCmd) - - case "submitblock": - cmd = new(SubmitBlockCmd) - - case "validateaddress": - cmd = new(ValidateAddressCmd) - - case "verifychain": - cmd = new(VerifyChainCmd) - - case "verifymessage": - cmd = new(VerifyMessageCmd) - - case "walletlock": - cmd = new(WalletLockCmd) - - case "walletpassphrase": - cmd = new(WalletPassphraseCmd) - - case "walletpassphrasechange": - cmd = new(WalletPassphraseChangeCmd) - - default: - // None of the standard Bitcoin RPC methods matched. Try - // registered custom commands. - if c, ok := customCmds[r.Method]; ok { - cmd, err := c.parser(&r) - if err != nil { - cmd = newUnparsableCmd(r.Id, r.Method) - return cmd, err - } - return cmd, nil - } - } - - if cmd == nil { - cmd = newUnparsableCmd(r.Id, r.Method) - return cmd, ErrMethodNotFound - } - - // If we get here we have a cmd that can unmarshal itself. - if err := cmd.UnmarshalJSON(b); err != nil { - cmd = newUnparsableCmd(r.Id, r.Method) - return cmd, err - } - return cmd, nil -} - -// unparsableCmd is a type representing a valid unmarshalled JSON-RPC -// request, but is used for cases where parsing the RPC request into a -// concrete Cmd type failed, either due to an unknown method, or trying -// to parse incorrect arguments for a known method. -type unparsableCmd struct { - id interface{} - method string -} - -// Enforce that unparsableCmd satisifies the Cmd interface. -var _ Cmd = &unparsableCmd{} - -func newUnparsableCmd(id interface{}, method string) *unparsableCmd { - return &unparsableCmd{ - id: id, - method: method, - } -} - -// Id satisifies the Cmd interface by returning the id of the command. -func (cmd *unparsableCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *unparsableCmd) Method() string { - return cmd.method -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *unparsableCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.method, nil) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *unparsableCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - cmd.id = r.Id - cmd.method = r.Method - return nil -} - -// AddMultisigAddressCmd is a type handling custom marshaling and -// unmarshaling of addmultisigaddress JSON RPC commands. -type AddMultisigAddressCmd struct { - id interface{} - NRequired int - Keys []string - Account string -} - -// Enforce that AddMultisigAddress satisifies the Cmd interface. -var _ Cmd = &AddMultisigAddressCmd{} - -// NewAddMultisigAddressCmd creates a new AddMultisigAddressCmd, -// parsing the optional arguments optArgs which may be either empty or an -// optional account name. -func NewAddMultisigAddressCmd(id interface{}, nRequired int, keys []string, - optArgs ...string) (*AddMultisigAddressCmd, error) { - // Optional parameters set to their defaults. - var account string - - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - account = optArgs[0] - } - - return &AddMultisigAddressCmd{ - id: id, - NRequired: nRequired, - Keys: keys, - Account: account, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *AddMultisigAddressCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *AddMultisigAddressCmd) Method() string { - return "addmultisigaddress" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *AddMultisigAddressCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 2, 3) - params[0] = cmd.NRequired - params[1] = cmd.Keys - if cmd.Account != "" { - params = append(params, cmd.Account) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *AddMultisigAddressCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) < 2 || len(r.Params) > 3 { - return ErrWrongNumberOfParams - } - - var nRequired int - if err := json.Unmarshal(r.Params[0], &nRequired); err != nil { - return fmt.Errorf("first parameter 'nrequired' must be an integer: %v", err) - } - - var keys []string - if err := json.Unmarshal(r.Params[1], &keys); err != nil { - return fmt.Errorf("second parameter 'keys' must be an array of strings: %v", err) - } - - var account string - if len(r.Params) > 2 { - if err := json.Unmarshal(r.Params[2], &account); err != nil { - return fmt.Errorf("third optional parameter 'account' must be a string: %v", err) - } - } - newCmd, err := NewAddMultisigAddressCmd(r.Id, nRequired, keys, account) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// AddNodeCmd is a type handling custom marshaling and -// unmarshaling of addmultisigaddress JSON RPC commands. -type AddNodeCmd struct { - id interface{} - Addr string - SubCmd string // One of "add","remove","onetry". TODO(oga) enum? -} - -// Enforce that AddNodeCmd satisifies the Cmd interface. -var _ Cmd = &AddNodeCmd{} - -// NewAddNodeCmd creates a new AddNodeCmd for the given address and subcommand. -func NewAddNodeCmd(id interface{}, addr string, subcmd string) ( - *AddNodeCmd, error) { - - switch subcmd { - case "add": - // fine - case "remove": - // fine - case "onetry": - // fine - default: - return nil, errors.New("invalid subcommand for addnode") - } - - return &AddNodeCmd{ - id: id, - Addr: addr, - SubCmd: subcmd, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *AddNodeCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *AddNodeCmd) Method() string { - return "addnode" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *AddNodeCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Addr, - cmd.SubCmd, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *AddNodeCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 2 { - return ErrWrongNumberOfParams - } - - var addr string - if err := json.Unmarshal(r.Params[0], &addr); err != nil { - return fmt.Errorf("first parameter 'addr' must be a string: %v", err) - } - - var subcmd string - if err := json.Unmarshal(r.Params[1], &subcmd); err != nil { - return fmt.Errorf("second parameter 'subcmd' must be a string: %v", err) - } - - newCmd, err := NewAddNodeCmd(r.Id, addr, subcmd) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// BackupWalletCmd is a type handling custom marshaling and -// unmarshaling of backupwallet JSON RPC commands. -type BackupWalletCmd struct { - id interface{} - Destination string -} - -// Enforce that BackupWalletCmd satisifies the Cmd interface. -var _ Cmd = &BackupWalletCmd{} - -// NewBackupWalletCmd creates a new BackupWalletCmd. -func NewBackupWalletCmd(id interface{}, path string) (*BackupWalletCmd, error) { - - return &BackupWalletCmd{ - id: id, - Destination: path, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *BackupWalletCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *BackupWalletCmd) Method() string { - return "backupwallet" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *BackupWalletCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Destination, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *BackupWalletCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var destination string - if err := json.Unmarshal(r.Params[0], &destination); err != nil { - return fmt.Errorf("first parameter 'destination' must be a string: %v", err) - } - - newCmd, err := NewBackupWalletCmd(r.Id, destination) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// CreateMultisigCmd is a type handling custom marshaling and -// unmarshaling of createmultisig JSON RPC commands. -type CreateMultisigCmd struct { - id interface{} - NRequired int - Keys []string -} - -// Enforce that AddMultisigAddress satisifies the Cmd interface. -var _ Cmd = &CreateMultisigCmd{} - -// NewCreateMultisigCmd creates a new CreateMultisigCmd, -// parsing the optional arguments optArgs. -func NewCreateMultisigCmd(id interface{}, nRequired int, keys []string) (*CreateMultisigCmd, error) { - return &CreateMultisigCmd{ - id: id, - NRequired: nRequired, - Keys: keys, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *CreateMultisigCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *CreateMultisigCmd) Method() string { - return "createmultisig" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *CreateMultisigCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.NRequired, - cmd.Keys, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *CreateMultisigCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 2 { - return ErrWrongNumberOfParams - } - - var nRequired int - if err := json.Unmarshal(r.Params[0], &nRequired); err != nil { - return fmt.Errorf("first parameter 'nrequired' must be an integer: %v", err) - } - - var keys []string - if err := json.Unmarshal(r.Params[1], &keys); err != nil { - return fmt.Errorf("second parameter 'keys' must be an array of strings: %v", err) - } - - newCmd, err := NewCreateMultisigCmd(r.Id, nRequired, keys) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// TransactionInput represents the inputs to a transaction. Specifically a -// transactionsha and output number pair. -type TransactionInput struct { - Txid string `json:"txid"` - Vout uint32 `json:"vout"` -} - -// CreateRawTransactionCmd is a type handling custom marshaling and -// unmarshaling of createrawtransaction JSON RPC commands. -type CreateRawTransactionCmd struct { - id interface{} - Inputs []TransactionInput - Amounts map[string]int64 -} - -// Enforce that CreateRawTransactionCmd satisifies the Cmd interface. -var _ Cmd = &CreateRawTransactionCmd{} - -// NewCreateRawTransactionCmd creates a new CreateRawTransactionCmd. -func NewCreateRawTransactionCmd(id interface{}, inputs []TransactionInput, amounts map[string]int64) (*CreateRawTransactionCmd, error) { - return &CreateRawTransactionCmd{ - id: id, - Inputs: inputs, - Amounts: amounts, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *CreateRawTransactionCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *CreateRawTransactionCmd) Method() string { - return "createrawtransaction" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *CreateRawTransactionCmd) MarshalJSON() ([]byte, error) { - floatAmounts := make(map[string]float64) - for k, v := range cmd.Amounts { - floatAmounts[k] = float64(v) / 1e8 - } - - params := []interface{}{ - cmd.Inputs, - floatAmounts, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *CreateRawTransactionCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 2 { - return ErrWrongNumberOfParams - } - - var inputs []TransactionInput - if err := json.Unmarshal(r.Params[0], &inputs); err != nil { - return fmt.Errorf("first parameter 'inputs' must be a JSON array "+ - "of transaction input JSON objects: %v", err) - } - - var amounts map[string]float64 - if err := json.Unmarshal(r.Params[1], &amounts); err != nil { - return fmt.Errorf("second parameter 'amounts' must be a JSON object: %v", err) - } - - intAmounts := make(map[string]int64, len(amounts)) - for k, v := range amounts { - amount, err := JSONToAmount(v) - if err != nil { - return err - } - intAmounts[k] = amount - } - - newCmd, err := NewCreateRawTransactionCmd(r.Id, inputs, intAmounts) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// DebugLevelCmd is a type handling custom marshaling and unmarshaling of -// debuglevel JSON RPC commands. This command is not a standard Bitcoin -// command. It is an extension for btcd. -type DebugLevelCmd struct { - id interface{} - LevelSpec string -} - -// Enforce that DebugLevelCmd satisifies the Cmd interface. -var _ Cmd = &DebugLevelCmd{} - -// NewDebugLevelCmd creates a new DebugLevelCmd. This command is not a standard -// Bitcoin command. It is an extension for btcd. -func NewDebugLevelCmd(id interface{}, levelSpec string) (*DebugLevelCmd, error) { - return &DebugLevelCmd{ - id: id, - LevelSpec: levelSpec, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *DebugLevelCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *DebugLevelCmd) Method() string { - return "debuglevel" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *DebugLevelCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.LevelSpec, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *DebugLevelCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var levelSpec string - if err := json.Unmarshal(r.Params[0], &levelSpec); err != nil { - return fmt.Errorf("first parameter 'levelspec' must be a string: %v", err) - } - - newCmd, err := NewDebugLevelCmd(r.Id, levelSpec) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// DecodeRawTransactionCmd is a type handling custom marshaling and -// unmarshaling of decoderawtransaction JSON RPC commands. -type DecodeRawTransactionCmd struct { - id interface{} - HexTx string -} - -// Enforce that DecodeRawTransactionCmd satisifies the Cmd interface. -var _ Cmd = &DecodeRawTransactionCmd{} - -// NewDecodeRawTransactionCmd creates a new DecodeRawTransactionCmd. -func NewDecodeRawTransactionCmd(id interface{}, hextx string) (*DecodeRawTransactionCmd, error) { - return &DecodeRawTransactionCmd{ - id: id, - HexTx: hextx, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *DecodeRawTransactionCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *DecodeRawTransactionCmd) Method() string { - return "decoderawtransaction" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *DecodeRawTransactionCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.HexTx, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *DecodeRawTransactionCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var hextx string - if err := json.Unmarshal(r.Params[0], &hextx); err != nil { - return fmt.Errorf("first parameter 'hextx' must be a string: %v", err) - } - - newCmd, err := NewDecodeRawTransactionCmd(r.Id, hextx) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// DecodeScriptCmd is a type handling custom marshaling and -// unmarshaling of decodescript JSON RPC commands. -type DecodeScriptCmd struct { - id interface{} - HexScript string -} - -// Enforce that DecodeScriptCmd satisifies the Cmd interface. -var _ Cmd = &DecodeScriptCmd{} - -// NewDecodeScriptCmd creates a new DecodeScriptCmd. -func NewDecodeScriptCmd(id interface{}, hexscript string) (*DecodeScriptCmd, error) { - return &DecodeScriptCmd{ - id: id, - HexScript: hexscript, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *DecodeScriptCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *DecodeScriptCmd) Method() string { - return "decodescript" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *DecodeScriptCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.HexScript, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *DecodeScriptCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var hexscript string - if err := json.Unmarshal(r.Params[0], &hexscript); err != nil { - return fmt.Errorf("first parameter 'hexscript' must be a string: %v", err) - } - - newCmd, err := NewDecodeScriptCmd(r.Id, hexscript) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// DumpPrivKeyCmd is a type handling custom marshaling and -// unmarshaling of dumpprivkey JSON RPC commands. -type DumpPrivKeyCmd struct { - id interface{} - Address string -} - -// Enforce that DumpPrivKeyCmd satisifies the Cmd interface. -var _ Cmd = &DumpPrivKeyCmd{} - -// NewDumpPrivKeyCmd creates a new DumpPrivkeyCmd. -func NewDumpPrivKeyCmd(id interface{}, address string) (*DumpPrivKeyCmd, error) { - return &DumpPrivKeyCmd{ - id: id, - Address: address, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *DumpPrivKeyCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *DumpPrivKeyCmd) Method() string { - return "dumpprivkey" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *DumpPrivKeyCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Address, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *DumpPrivKeyCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - newCmd, err := NewDumpPrivKeyCmd(r.Id, address) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// DumpWalletCmd is a type handling custom marshaling and -// unmarshaling of dumpwallet JSON RPC commands. -type DumpWalletCmd struct { - id interface{} - Filename string -} - -// Enforce that DumpWalletCmd satisifies the Cmd interface. -var _ Cmd = &DumpWalletCmd{} - -// NewDumpWalletCmd creates a new DumpPrivkeyCmd. -func NewDumpWalletCmd(id interface{}, filename string) (*DumpWalletCmd, error) { - return &DumpWalletCmd{ - id: id, - Filename: filename, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *DumpWalletCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *DumpWalletCmd) Method() string { - return "dumpwallet" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *DumpWalletCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Filename, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *DumpWalletCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var filename string - if err := json.Unmarshal(r.Params[0], &filename); err != nil { - return fmt.Errorf("first parameter 'filename' must be a string: %v", err) - } - - newCmd, err := NewDumpWalletCmd(r.Id, filename) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// EncryptWalletCmd is a type handling custom marshaling and -// unmarshaling of encryptwallet JSON RPC commands. -type EncryptWalletCmd struct { - id interface{} - Passphrase string -} - -// Enforce that EncryptWalletCmd satisifies the Cmd interface. -var _ Cmd = &EncryptWalletCmd{} - -// NewEncryptWalletCmd creates a new EncryptWalletCmd. -func NewEncryptWalletCmd(id interface{}, passphrase string) (*EncryptWalletCmd, error) { - return &EncryptWalletCmd{ - id: id, - Passphrase: passphrase, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *EncryptWalletCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *EncryptWalletCmd) Method() string { - return "encryptwallet" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *EncryptWalletCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Passphrase, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *EncryptWalletCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var passphrase string - if err := json.Unmarshal(r.Params[0], &passphrase); err != nil { - return fmt.Errorf("first parameter 'passphrase' must be a string: %v", err) - } - - newCmd, err := NewEncryptWalletCmd(r.Id, passphrase) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// EstimateFeeCmd is a type handling custom marshaling and -// unmarshaling of estimatefee JSON RPC commands. -type EstimateFeeCmd struct { - id interface{} - NumBlocks int64 -} - -// Enforce that EstimateFeeCmd satisifies the Cmd interface. -var _ Cmd = &EstimateFeeCmd{} - -// NewEstimateFeeCmd creates a new EstimateFeeCmd. -func NewEstimateFeeCmd(id interface{}, numblocks int64) (*EstimateFeeCmd, error) { - return &EstimateFeeCmd{ - id: id, - NumBlocks: numblocks, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *EstimateFeeCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *EstimateFeeCmd) Method() string { - return "estimatefee" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *EstimateFeeCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.NumBlocks, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *EstimateFeeCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var numblocks int64 - if err := json.Unmarshal(r.Params[0], &numblocks); err != nil { - return fmt.Errorf("first parameter 'numblocks' must be an integer: %v", err) - } - - newCmd, err := NewEstimateFeeCmd(r.Id, numblocks) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// EstimatePriorityCmd is a type handling custom marshaling and -// unmarshaling of estimatepriority JSON RPC commands. -type EstimatePriorityCmd struct { - id interface{} - NumBlocks int64 -} - -// Enforce that EstimatePriorityCmd satisifies the Cmd interface. -var _ Cmd = &EstimatePriorityCmd{} - -// NewEstimatePriorityCmd creates a new EstimatePriorityCmd. -func NewEstimatePriorityCmd(id interface{}, numblocks int64) (*EstimatePriorityCmd, error) { - return &EstimatePriorityCmd{ - id: id, - NumBlocks: numblocks, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *EstimatePriorityCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *EstimatePriorityCmd) Method() string { - return "estimatepriority" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *EstimatePriorityCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.NumBlocks, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *EstimatePriorityCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var numblocks int64 - if err := json.Unmarshal(r.Params[0], &numblocks); err != nil { - return fmt.Errorf("first parameter 'numblocks' must be an integer: %v", err) - } - - newCmd, err := NewEstimatePriorityCmd(r.Id, numblocks) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetAccountCmd is a type handling custom marshaling and -// unmarshaling of getaccount JSON RPC commands. -type GetAccountCmd struct { - id interface{} - Address string -} - -// Enforce that GetAccountCmd satisifies the Cmd interface. -var _ Cmd = &GetAccountCmd{} - -// NewGetAccountCmd creates a new GetAccountCmd. -func NewGetAccountCmd(id interface{}, address string) (*GetAccountCmd, error) { - return &GetAccountCmd{ - id: id, - Address: address, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetAccountCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetAccountCmd) Method() string { - return "getaccount" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetAccountCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Address, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetAccountCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - newCmd, err := NewGetAccountCmd(r.Id, address) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetAccountAddressCmd is a type handling custom marshaling and -// unmarshaling of getaccountaddress JSON RPC commands. -type GetAccountAddressCmd struct { - id interface{} - Account string -} - -// Enforce that GetAccountAddressCmd satisifies the Cmd interface. -var _ Cmd = &GetAccountAddressCmd{} - -// NewGetAccountAddressCmd creates a new GetAccountAddressCmd. -func NewGetAccountAddressCmd(id interface{}, account string) (*GetAccountAddressCmd, error) { - return &GetAccountAddressCmd{ - id: id, - Account: account, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetAccountAddressCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetAccountAddressCmd) Method() string { - return "getaccountaddress" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetAccountAddressCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Account, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetAccountAddressCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return fmt.Errorf("first parameter 'account' must be a string: %v", err) - } - - newCmd, err := NewGetAccountAddressCmd(r.Id, account) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetAddedNodeInfoCmd is a type handling custom marshaling and -// unmarshaling of getaddednodeinfo JSON RPC commands. -type GetAddedNodeInfoCmd struct { - id interface{} - Dns bool - Node string -} - -// Enforce that GetAddedNodeInfoCmd satisifies the Cmd interface. -var _ Cmd = &GetAddedNodeInfoCmd{} - -// NewGetAddedNodeInfoCmd creates a new GetAddedNodeInfoCmd. Optionally the -// node to be queried may be provided. More than one optonal argument is an -// error. -func NewGetAddedNodeInfoCmd(id interface{}, dns bool, optArgs ...string) (*GetAddedNodeInfoCmd, error) { - var node string - - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - node = optArgs[0] - } - return &GetAddedNodeInfoCmd{ - id: id, - Dns: dns, - Node: node, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetAddedNodeInfoCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetAddedNodeInfoCmd) Method() string { - return "getaddednodeinfo" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetAddedNodeInfoCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Dns, - } - - if cmd.Node != "" { - params = append(params, cmd.Node) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetAddedNodeInfoCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) < 1 || len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - var dns bool - if err := json.Unmarshal(r.Params[0], &dns); err != nil { - return fmt.Errorf("first parameter 'dns' must be a bool: %v", err) - } - - var node string - if len(r.Params) > 1 { - if err := json.Unmarshal(r.Params[1], &node); err != nil { - return fmt.Errorf("second optional parameter 'node' must be a string: %v", err) - } - } - - newCmd, err := NewGetAddedNodeInfoCmd(r.Id, dns, node) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetAddressesByAccountCmd is a type handling custom marshaling and -// unmarshaling of getaddressesbyaccount JSON RPC commands. -type GetAddressesByAccountCmd struct { - id interface{} - Account string -} - -// Enforce that GetAddressesByAccountCmd satisifies the Cmd interface. -var _ Cmd = &GetAddressesByAccountCmd{} - -// NewGetAddressesByAccountCmd creates a new GetAddressesByAccountCmd. -func NewGetAddressesByAccountCmd(id interface{}, account string) (*GetAddressesByAccountCmd, error) { - return &GetAddressesByAccountCmd{ - id: id, - Account: account, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetAddressesByAccountCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetAddressesByAccountCmd) Method() string { - return "getaddressesbyaccount" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetAddressesByAccountCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Account, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetAddressesByAccountCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return fmt.Errorf("first parameter 'account' must be a string: %v", err) - } - - newCmd, err := NewGetAddressesByAccountCmd(r.Id, account) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetBalanceCmd is a type handling custom marshaling and -// unmarshaling of getbalance JSON RPC commands. -type GetBalanceCmd struct { - id interface{} - Account *string - MinConf int -} - -// Enforce that GetBalanceCmd satisifies the Cmd interface. -var _ Cmd = &GetBalanceCmd{} - -// NewGetBalanceCmd creates a new GetBalanceCmd. Optionally a string for account -// and an int for minconf may be provided as arguments. -func NewGetBalanceCmd(id interface{}, optArgs ...interface{}) (*GetBalanceCmd, error) { - var account *string - var minconf = 1 - - if len(optArgs) > 2 { - return nil, ErrWrongNumberOfParams - } - if len(optArgs) > 0 { - a, ok := optArgs[0].(string) - if !ok { - return nil, errors.New("first optional argument account is not a string") - } - account = &a - } - - if len(optArgs) > 1 { - m, ok := optArgs[1].(int) - if !ok { - return nil, errors.New("second optional argument minconf is not a int") - } - minconf = m - } - - return &GetBalanceCmd{ - id: id, - Account: account, - MinConf: minconf, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetBalanceCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetBalanceCmd) Method() string { - return "getbalance" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetBalanceCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 2) - if cmd.Account != nil { - params = append(params, cmd.Account) - } - if cmd.MinConf != 1 { - params = append(params, cmd.MinConf) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetBalanceCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - optArgs := make([]interface{}, 0, 2) - if len(r.Params) > 0 { - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return fmt.Errorf("first optional parameter 'account' must be a string: %v", err) - } - optArgs = append(optArgs, account) - } - - if len(r.Params) > 1 { - var minconf int - if err := json.Unmarshal(r.Params[1], &minconf); err != nil { - return fmt.Errorf("second optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - - newCmd, err := NewGetBalanceCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetBestBlockHashCmd is a type handling custom marshaling and -// unmarshaling of getbestblockhash JSON RPC commands. -type GetBestBlockHashCmd struct { - id interface{} -} - -// Enforce that GetBestBlockHashCmd satisifies the Cmd interface. -var _ Cmd = &GetBestBlockHashCmd{} - -// NewGetBestBlockHashCmd creates a new GetBestBlockHashCmd. -func NewGetBestBlockHashCmd(id interface{}) (*GetBestBlockHashCmd, error) { - return &GetBestBlockHashCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetBestBlockHashCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetBestBlockHashCmd) Method() string { - return "getbestblockhash" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetBestBlockHashCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetBestBlockHashCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetBestBlockHashCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetBlockCmd is a type handling custom marshaling and -// unmarshaling of getblock JSON RPC commands. -type GetBlockCmd struct { - id interface{} - Hash string - Verbose bool - VerboseTx bool -} - -// Enforce that GetBlockCmd satisifies the Cmd interface. -var _ Cmd = &GetBlockCmd{} - -// NewGetBlockCmd creates a new GetBlockCmd. -func NewGetBlockCmd(id interface{}, hash string, optArgs ...bool) (*GetBlockCmd, error) { - // default verbose is set to true to match old behavior - verbose, verboseTx := true, false - - optArgsLen := len(optArgs) - if optArgsLen > 0 { - if optArgsLen > 2 { - return nil, ErrTooManyOptArgs - } - verbose = optArgs[0] - if optArgsLen > 1 { - verboseTx = optArgs[1] - - if !verbose && verboseTx { - return nil, ErrInvalidParams - } - } - } - - return &GetBlockCmd{ - id: id, - Hash: hash, - Verbose: verbose, - VerboseTx: verboseTx, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetBlockCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetBlockCmd) Method() string { - return "getblock" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetBlockCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 3) - params[0] = cmd.Hash - if !cmd.Verbose { - // set optional verbose argument to false - params = append(params, false) - } else if cmd.VerboseTx { - // set optional verbose argument to true - params = append(params, true) - // set optional verboseTx argument to true - params = append(params, true) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetBlockCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 3 || len(r.Params) < 1 { - return ErrWrongNumberOfParams - } - - var hash string - if err := json.Unmarshal(r.Params[0], &hash); err != nil { - return fmt.Errorf("first parameter 'hash' must be a string: %v", err) - } - - optArgs := make([]bool, 0, 2) - if len(r.Params) > 1 { - var verbose bool - if err := json.Unmarshal(r.Params[1], &verbose); err != nil { - return fmt.Errorf("second optional parameter 'verbose' must be a bool: %v", err) - } - optArgs = append(optArgs, verbose) - } - if len(r.Params) > 2 { - var verboseTx bool - if err := json.Unmarshal(r.Params[2], &verboseTx); err != nil { - return fmt.Errorf("third optional parameter 'verboseTx' must be a bool: %v", err) - } - optArgs = append(optArgs, verboseTx) - } - - newCmd, err := NewGetBlockCmd(r.Id, hash, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetBlockChainInfoCmd is a type handling custom marshaling and -// unmarshaling of getblockchaininfo JSON RPC commands. -type GetBlockChainInfoCmd struct { - id interface{} -} - -// Enforce that GetBlockChainInfoCmd satisifies the Cmd interface. -var _ Cmd = &GetBlockChainInfoCmd{} - -// NewGetBlockChainInfoCmd creates a new GetBlockChainInfoCmd. -func NewGetBlockChainInfoCmd(id interface{}) (*GetBlockChainInfoCmd, error) { - return &GetBlockChainInfoCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetBlockChainInfoCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetBlockChainInfoCmd) Method() string { - return "getblockchaininfo" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetBlockChainInfoCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetBlockChainInfoCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetBlockChainInfoCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetBlockCountCmd is a type handling custom marshaling and -// unmarshaling of getblockcount JSON RPC commands. -type GetBlockCountCmd struct { - id interface{} -} - -// Enforce that GetBlockCountCmd satisifies the Cmd interface. -var _ Cmd = &GetBlockCountCmd{} - -// NewGetBlockCountCmd creates a new GetBlockCountCmd. -func NewGetBlockCountCmd(id interface{}) (*GetBlockCountCmd, error) { - return &GetBlockCountCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetBlockCountCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetBlockCountCmd) Method() string { - return "getblockcount" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetBlockCountCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetBlockCountCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetBlockCountCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetBlockHashCmd is a type handling custom marshaling and -// unmarshaling of getblockhash JSON RPC commands. -type GetBlockHashCmd struct { - id interface{} - Index int64 -} - -// Enforce that GetBlockHashCmd satisifies the Cmd interface. -var _ Cmd = &GetBlockHashCmd{} - -// NewGetBlockHashCmd creates a new GetBlockHashCmd. -func NewGetBlockHashCmd(id interface{}, index int64) (*GetBlockHashCmd, error) { - return &GetBlockHashCmd{ - id: id, - Index: index, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetBlockHashCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetBlockHashCmd) Method() string { - return "getblockhash" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetBlockHashCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Index, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetBlockHashCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var index int64 - if err := json.Unmarshal(r.Params[0], &index); err != nil { - return fmt.Errorf("first parameter 'index' must be an integer: %v", err) - } - - newCmd, err := NewGetBlockHashCmd(r.Id, index) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// TemplateRequest is a request object as defined in BIP22 -// (https://en.bitcoin.it/wiki/BIP_0022), it is optionally provided as an -// pointer argument to GetBlockTemplateCmd. -type TemplateRequest struct { - Mode string `json:"mode,omitempty"` - Capabilities []string `json:"capabilities,omitempty"` - - // Optional long polling. - LongPollID string `json:"longpollid,omitempty"` - - // Optional template tweaking. SigOpLimit and SizeLimit can be int64 - // or bool. - SigOpLimit interface{} `json:"sigoplimit,omitempty"` - SizeLimit interface{} `json:"sizelimit,omitempty"` - MaxVersion uint32 `json:"maxversion,omitempty"` - - // Basic pool extension from BIP 0023. - Target string `json:"target,omitempty"` - - // Block proposal from BIP 0023. Data is only provided when Mode is - // "proposal". - Data string `json:"data,omitempty"` - WorkID string `json:"workid,omitempty"` -} - -// isFloatInt64 returns whether the passed float64 is a whole number that safely -// fits into a 64-bit integer. -func isFloatInt64(a float64) bool { - return a == float64(int64(a)) -} - -// GetBlockTemplateCmd is a type handling custom marshaling and -// unmarshaling of getblocktemplate JSON RPC commands. -type GetBlockTemplateCmd struct { - id interface{} - Request *TemplateRequest -} - -// Enforce that GetBlockTemplateCmd satisifies the Cmd interface. -var _ Cmd = &GetBlockTemplateCmd{} - -// NewGetBlockTemplateCmd creates a new GetBlockTemplateCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewGetBlockTemplateCmd(id interface{}, optArgs ...*TemplateRequest) (*GetBlockTemplateCmd, error) { - var request *TemplateRequest - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - request = optArgs[0] - switch val := request.SigOpLimit.(type) { - case nil: - case bool: - case int64: - case float64: - if !isFloatInt64(val) { - return nil, errors.New("the sigoplimit field " + - "must be unspecified, a boolean, or a " + - "64-bit integer") - } - request.SigOpLimit = int64(val) - default: - return nil, errors.New("the sigoplimit field " + - "must be unspecified, a boolean, or a 64-bit " + - "integer") - } - switch val := request.SizeLimit.(type) { - case nil: - case bool: - case int64: - case float64: - if !isFloatInt64(val) { - return nil, errors.New("the sizelimit field " + - "must be unspecified, a boolean, or a " + - "64-bit integer") - } - request.SizeLimit = int64(val) - default: - return nil, errors.New("the sizelimit field " + - "must be unspecified, a boolean, or a 64-bit " + - "integer") - } - } - return &GetBlockTemplateCmd{ - id: id, - Request: request, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetBlockTemplateCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetBlockTemplateCmd) Method() string { - return "getblocktemplate" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetBlockTemplateCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.Request != nil { - params = append(params, cmd.Request) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetBlockTemplateCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 1 { - return ErrWrongNumberOfParams - } - - optArgs := make([]*TemplateRequest, 0, 1) - if len(r.Params) > 0 { - var template TemplateRequest - if err := json.Unmarshal(r.Params[0], &template); err != nil { - return fmt.Errorf("first optional parameter 'template' must be a template request JSON object: %v", err) - } - optArgs = append(optArgs, &template) - } - - newCmd, err := NewGetBlockTemplateCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetConnectionCountCmd is a type handling custom marshaling and -// unmarshaling of getconnectioncount JSON RPC commands. -type GetConnectionCountCmd struct { - id interface{} -} - -// Enforce that GetConnectionCountCmd satisifies the Cmd interface. -var _ Cmd = &GetConnectionCountCmd{} - -// NewGetConnectionCountCmd creates a new GetConnectionCountCmd. -func NewGetConnectionCountCmd(id interface{}) (*GetConnectionCountCmd, error) { - return &GetConnectionCountCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetConnectionCountCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetConnectionCountCmd) Method() string { - return "getconnectioncount" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetConnectionCountCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetConnectionCountCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetConnectionCountCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetDifficultyCmd is a type handling custom marshaling and -// unmarshaling of getdifficulty JSON RPC commands. -type GetDifficultyCmd struct { - id interface{} -} - -// Enforce that GetDifficultyCmd satisifies the Cmd interface. -var _ Cmd = &GetDifficultyCmd{} - -// NewGetDifficultyCmd creates a new GetDifficultyCmd. -func NewGetDifficultyCmd(id interface{}) (*GetDifficultyCmd, error) { - return &GetDifficultyCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetDifficultyCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetDifficultyCmd) Method() string { - return "getdifficulty" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetDifficultyCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetDifficultyCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetDifficultyCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetGenerateCmd is a type handling custom marshaling and -// unmarshaling of getgenerate JSON RPC commands. -type GetGenerateCmd struct { - id interface{} -} - -// Enforce that GetGenerateCmd satisifies the Cmd interface. -var _ Cmd = &GetGenerateCmd{} - -// NewGetGenerateCmd creates a new GetGenerateCmd. -func NewGetGenerateCmd(id interface{}) (*GetGenerateCmd, error) { - return &GetGenerateCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetGenerateCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetGenerateCmd) Method() string { - return "getgenerate" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetGenerateCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetGenerateCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetGenerateCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetHashesPerSecCmd is a type handling custom marshaling and -// unmarshaling of gethashespersec JSON RPC commands. -type GetHashesPerSecCmd struct { - id interface{} -} - -// Enforce that GetHashesPerSecCmd satisifies the Cmd interface. -var _ Cmd = &GetHashesPerSecCmd{} - -// NewGetHashesPerSecCmd creates a new GetHashesPerSecCmd. -func NewGetHashesPerSecCmd(id interface{}) (*GetHashesPerSecCmd, error) { - return &GetHashesPerSecCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetHashesPerSecCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetHashesPerSecCmd) Method() string { - return "gethashespersec" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetHashesPerSecCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetHashesPerSecCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetHashesPerSecCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetInfoCmd is a type handling custom marshaling and -// unmarshaling of getinfo JSON RPC commands. -type GetInfoCmd struct { - id interface{} -} - -// Enforce that GetInfoCmd satisifies the Cmd interface. -var _ Cmd = &GetInfoCmd{} - -// NewGetInfoCmd creates a new GetInfoCmd. -func NewGetInfoCmd(id interface{}) (*GetInfoCmd, error) { - return &GetInfoCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetInfoCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetInfoCmd) Method() string { - return "getinfo" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetInfoCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetInfoCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetInfoCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetMiningInfoCmd is a type handling custom marshaling and -// unmarshaling of getmininginfo JSON RPC commands. -type GetMiningInfoCmd struct { - id interface{} -} - -// Enforce that GetMiningInfoCmd satisifies the Cmd interface. -var _ Cmd = &GetMiningInfoCmd{} - -// NewGetMiningInfoCmd creates a new GetMiningInfoCmd. -func NewGetMiningInfoCmd(id interface{}) (*GetMiningInfoCmd, error) { - return &GetMiningInfoCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetMiningInfoCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetMiningInfoCmd) Method() string { - return "getmininginfo" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetMiningInfoCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetMiningInfoCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetMiningInfoCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetNetworkInfoCmd is a type handling custom marshaling and -// unmarshaling of getnetworkinfo JSON RPC commands. -type GetNetworkInfoCmd struct { - id interface{} -} - -// Enforce that GetNetworkInfoCmd satisifies the Cmd interface. -var _ Cmd = &GetNetworkInfoCmd{} - -// NewGetNetworkInfoCmd creates a new GetNetworkInfoCmd. -func NewGetNetworkInfoCmd(id interface{}) (*GetNetworkInfoCmd, error) { - return &GetNetworkInfoCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetNetworkInfoCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetNetworkInfoCmd) Method() string { - return "getnetworkinfo" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetNetworkInfoCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetNetworkInfoCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetNetworkInfoCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetNetTotalsCmd is a type handling custom marshaling and -// unmarshaling of getnettotals JSON RPC commands. -type GetNetTotalsCmd struct { - id interface{} -} - -// Enforce that GetNetTotalsCmd satisifies the Cmd interface. -var _ Cmd = &GetNetTotalsCmd{} - -// NewGetNetTotalsCmd creates a new GetNetTotalsCmd. -func NewGetNetTotalsCmd(id interface{}) (*GetNetTotalsCmd, error) { - return &GetNetTotalsCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetNetTotalsCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetNetTotalsCmd) Method() string { - return "getnettotals" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetNetTotalsCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetNetTotalsCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetNetTotalsCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetNetworkHashPSCmd is a type handling custom marshaling and -// unmarshaling of getnetworkhashps JSON RPC commands. -type GetNetworkHashPSCmd struct { - id interface{} - Blocks int - Height int -} - -// Enforce that GetNetworkHashPSCmd satisifies the Cmd interface. -var _ Cmd = &GetNetworkHashPSCmd{} - -// NewGetNetworkHashPSCmd creates a new GetNetworkHashPSCmd. -func NewGetNetworkHashPSCmd(id interface{}, optArgs ...int) (*GetNetworkHashPSCmd, error) { - blocks := 120 - height := -1 - - if len(optArgs) > 0 { - if len(optArgs) > 2 { - return nil, ErrTooManyOptArgs - } - - blocks = optArgs[0] - - if len(optArgs) > 1 { - height = optArgs[1] - } - } - return &GetNetworkHashPSCmd{ - id: id, - Blocks: blocks, - Height: height, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetNetworkHashPSCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetNetworkHashPSCmd) Method() string { - return "getnetworkhashps" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetNetworkHashPSCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 2) - if cmd.Blocks != 120 || cmd.Height != -1 { - params = append(params, cmd.Blocks) - } - if cmd.Height != -1 { - params = append(params, cmd.Height) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetNetworkHashPSCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - optArgs := make([]int, 0, 2) - if len(r.Params) > 0 { - var blocks int - if err := json.Unmarshal(r.Params[0], &blocks); err != nil { - return fmt.Errorf("first optional parameter 'blocks' must be an integer: %v", err) - } - optArgs = append(optArgs, blocks) - } - - if len(r.Params) > 1 { - var height int - if err := json.Unmarshal(r.Params[1], &height); err != nil { - return fmt.Errorf("second optional parameter 'height' must be an integer: %v", err) - } - optArgs = append(optArgs, height) - } - newCmd, err := NewGetNetworkHashPSCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetNewAddressCmd is a type handling custom marshaling and -// unmarshaling of getnewaddress JSON RPC commands. -type GetNewAddressCmd struct { - id interface{} - Account string -} - -// Enforce that GetNewAddressCmd satisifies the Cmd interface. -var _ Cmd = &GetNewAddressCmd{} - -// NewGetNewAddressCmd creates a new GetNewAddressCmd. -func NewGetNewAddressCmd(id interface{}, optArgs ...string) (*GetNewAddressCmd, error) { - var account string - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - account = optArgs[0] - - } - return &GetNewAddressCmd{ - id: id, - Account: account, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetNewAddressCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetNewAddressCmd) Method() string { - return "getnewaddress" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetNewAddressCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.Account != "" { - params = append(params, cmd.Account) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetNewAddressCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 1 { - return ErrWrongNumberOfParams - } - - optArgs := make([]string, 0, 1) - if len(r.Params) > 0 { - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return fmt.Errorf("first optional parameter 'account' must be a string: %v", err) - } - optArgs = append(optArgs, account) - } - - newCmd, err := NewGetNewAddressCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetPeerInfoCmd is a type handling custom marshaling and -// unmarshaling of getpeerinfo JSON RPC commands. -type GetPeerInfoCmd struct { - id interface{} -} - -// Enforce that GetPeerInfoCmd satisifies the Cmd interface. -var _ Cmd = &GetPeerInfoCmd{} - -// NewGetPeerInfoCmd creates a new GetPeerInfoCmd. -func NewGetPeerInfoCmd(id interface{}) (*GetPeerInfoCmd, error) { - return &GetPeerInfoCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetPeerInfoCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetPeerInfoCmd) Method() string { - return "getpeerinfo" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetPeerInfoCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetPeerInfoCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetPeerInfoCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetRawChangeAddressCmd is a type handling custom marshaling and -// unmarshaling of getrawchangeaddress JSON RPC commands. -type GetRawChangeAddressCmd struct { - id interface{} - Account string -} - -// Enforce that GetRawChangeAddressCmd satisifies the Cmd interface. -var _ Cmd = &GetRawChangeAddressCmd{} - -// NewGetRawChangeAddressCmd creates a new GetRawChangeAddressCmd. -func NewGetRawChangeAddressCmd(id interface{}, optArgs ...string) (*GetRawChangeAddressCmd, error) { - var account string - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - account = optArgs[0] - - } - return &GetRawChangeAddressCmd{ - id: id, - Account: account, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetRawChangeAddressCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetRawChangeAddressCmd) Method() string { - return "getrawchangeaddress" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetRawChangeAddressCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.Account != "" { - params = append(params, cmd.Account) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetRawChangeAddressCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 1 { - return ErrWrongNumberOfParams - } - - optArgs := make([]string, 0, 1) - if len(r.Params) > 0 { - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return fmt.Errorf("first optional parameter 'account' must be a string: %v", err) - } - optArgs = append(optArgs, account) - } - - newCmd, err := NewGetRawChangeAddressCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetRawMempoolCmd is a type handling custom marshaling and -// unmarshaling of getrawmempool JSON RPC commands. -type GetRawMempoolCmd struct { - id interface{} - Verbose bool -} - -// Enforce that GetRawMempoolCmd satisifies the Cmd interface. -var _ Cmd = &GetRawMempoolCmd{} - -// NewGetRawMempoolCmd creates a new GetRawMempoolCmd. -func NewGetRawMempoolCmd(id interface{}, optArgs ...bool) (*GetRawMempoolCmd, error) { - verbose := false - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - verbose = optArgs[0] - } - return &GetRawMempoolCmd{ - id: id, - Verbose: verbose, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetRawMempoolCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetRawMempoolCmd) Method() string { - return "getrawmempool" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetRawMempoolCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.Verbose { - params = append(params, cmd.Verbose) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetRawMempoolCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 1 { - return ErrWrongNumberOfParams - } - - optArgs := make([]bool, 0, 1) - if len(r.Params) > 0 { - var verbose bool - if err := json.Unmarshal(r.Params[0], &verbose); err != nil { - return fmt.Errorf("first optional parameter 'verbose' must be a bool: %v", err) - } - optArgs = append(optArgs, verbose) - } - - newCmd, err := NewGetRawMempoolCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetRawTransactionCmd is a type handling custom marshaling and -// unmarshaling of getrawtransaction JSON RPC commands. -type GetRawTransactionCmd struct { - id interface{} - Txid string - Verbose int -} - -// Enforce that GetRawTransactionCmd satisifies the Cmd interface. -var _ Cmd = &GetRawTransactionCmd{} - -// NewGetRawTransactionCmd creates a new GetRawTransactionCmd. -func NewGetRawTransactionCmd(id interface{}, txid string, optArgs ...int) (*GetRawTransactionCmd, error) { - var verbose int - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - verbose = optArgs[0] - - } - return &GetRawTransactionCmd{ - id: id, - Txid: txid, - Verbose: verbose, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetRawTransactionCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetRawTransactionCmd) Method() string { - return "getrawtransaction" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetRawTransactionCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.Txid - if cmd.Verbose != 0 { - params = append(params, cmd.Verbose) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetRawTransactionCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 || len(r.Params) < 1 { - return ErrWrongNumberOfParams - } - - var txid string - if err := json.Unmarshal(r.Params[0], &txid); err != nil { - return fmt.Errorf("first parameter 'txid' must be a string: %v", err) - } - - optArgs := make([]int, 0, 1) - if len(r.Params) > 1 { - var verbose int - if err := json.Unmarshal(r.Params[1], &verbose); err != nil { - return fmt.Errorf("second optional parameter 'verbose' must be an integer: %v", err) - } - optArgs = append(optArgs, verbose) - } - - newCmd, err := NewGetRawTransactionCmd(r.Id, txid, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetReceivedByAccountCmd is a type handling custom marshaling and -// unmarshaling of getreceivedbyaccount JSON RPC commands. -type GetReceivedByAccountCmd struct { - id interface{} - Account string - MinConf int -} - -// Enforce that GetReceivedByAccountCmd satisifies the Cmd interface. -var _ Cmd = &GetReceivedByAccountCmd{} - -// NewGetReceivedByAccountCmd creates a new GetReceivedByAccountCmd. -func NewGetReceivedByAccountCmd(id interface{}, account string, optArgs ...int) (*GetReceivedByAccountCmd, error) { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - var minconf = 1 - if len(optArgs) > 0 { - minconf = optArgs[0] - } - return &GetReceivedByAccountCmd{ - id: id, - Account: account, - MinConf: minconf, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetReceivedByAccountCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetReceivedByAccountCmd) Method() string { - return "getreceivedbyaccount" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetReceivedByAccountCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.Account - if cmd.MinConf != 1 { - params = append(params, cmd.MinConf) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetReceivedByAccountCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return fmt.Errorf("first parameter 'account' must be a string: %v", err) - } - - optArgs := make([]int, 0, 1) - if len(r.Params) > 1 { - var minconf int - if err := json.Unmarshal(r.Params[1], &minconf); err != nil { - return fmt.Errorf("second optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - - newCmd, err := NewGetReceivedByAccountCmd(r.Id, account, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetReceivedByAddressCmd is a type handling custom marshaling and -// unmarshaling of getreceivedbyaddress JSON RPC commands. -type GetReceivedByAddressCmd struct { - id interface{} - Address string - MinConf int -} - -// Enforce that GetReceivedByAddressCmd satisifies the Cmd interface. -var _ Cmd = &GetReceivedByAddressCmd{} - -// NewGetReceivedByAddressCmd creates a new GetReceivedByAddressCmd. -func NewGetReceivedByAddressCmd(id interface{}, address string, optArgs ...int) (*GetReceivedByAddressCmd, error) { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - var minconf = 1 - if len(optArgs) > 0 { - minconf = optArgs[0] - } - return &GetReceivedByAddressCmd{ - id: id, - Address: address, - MinConf: minconf, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetReceivedByAddressCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetReceivedByAddressCmd) Method() string { - return "getreceivedbyaddress" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetReceivedByAddressCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.Address - if cmd.MinConf != 1 { - params = append(params, cmd.MinConf) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetReceivedByAddressCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - optArgs := make([]int, 0, 1) - if len(r.Params) > 1 { - var minconf int - if err := json.Unmarshal(r.Params[1], &minconf); err != nil { - return fmt.Errorf("second optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - - newCmd, err := NewGetReceivedByAddressCmd(r.Id, address, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetTransactionCmd is a type handling custom marshaling and -// unmarshaling of gettransaction JSON RPC commands. -type GetTransactionCmd struct { - id interface{} - Txid string -} - -// Enforce that GetTransactionCmd satisifies the Cmd interface. -var _ Cmd = &GetTransactionCmd{} - -// NewGetTransactionCmd creates a new GetTransactionCmd. -func NewGetTransactionCmd(id interface{}, txid string) (*GetTransactionCmd, error) { - return &GetTransactionCmd{ - id: id, - Txid: txid, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetTransactionCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetTransactionCmd) Method() string { - return "gettransaction" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetTransactionCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Txid, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetTransactionCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var txid string - if err := json.Unmarshal(r.Params[0], &txid); err != nil { - return fmt.Errorf("first parameter 'txid' must be a string: %v", err) - } - - newCmd, err := NewGetTransactionCmd(r.Id, txid) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetTxOutCmd is a type handling custom marshaling and -// unmarshaling of gettxout JSON RPC commands. -type GetTxOutCmd struct { - id interface{} - Txid string - Output int - IncludeMempool bool -} - -// Enforce that GetTxOutCmd satisifies the Cmd interface. -var _ Cmd = &GetTxOutCmd{} - -// NewGetTxOutCmd creates a new GetTxOutCmd. -func NewGetTxOutCmd(id interface{}, txid string, output int, optArgs ...bool) (*GetTxOutCmd, error) { - mempool := true - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - mempool = optArgs[0] - } - return &GetTxOutCmd{ - id: id, - Txid: txid, - Output: output, - IncludeMempool: mempool, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetTxOutCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetTxOutCmd) Method() string { - return "gettxout" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetTxOutCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 2, 3) - params[0] = cmd.Txid - params[1] = cmd.Output - if !cmd.IncludeMempool { - params = append(params, cmd.IncludeMempool) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetTxOutCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 3 || len(r.Params) < 2 { - return ErrWrongNumberOfParams - } - - var txid string - if err := json.Unmarshal(r.Params[0], &txid); err != nil { - return fmt.Errorf("first parameter 'txid' must be a string: %v", err) - } - - var output int - if err := json.Unmarshal(r.Params[1], &output); err != nil { - return fmt.Errorf("second parameter 'output' must be an integer: %v", err) - } - - optArgs := make([]bool, 0, 1) - if len(r.Params) > 2 { - var mempool bool - if err := json.Unmarshal(r.Params[2], &mempool); err != nil { - return fmt.Errorf("third optional parameter 'includemempool' must be a bool: %v", err) - } - optArgs = append(optArgs, mempool) - } - - newCmd, err := NewGetTxOutCmd(r.Id, txid, int(output), optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetTxOutSetInfoCmd is a type handling custom marshaling and -// unmarshaling of gettxoutsetinfo JSON RPC commands. -type GetTxOutSetInfoCmd struct { - id interface{} -} - -// Enforce that GetTxOutSetInfoCmd satisifies the Cmd interface. -var _ Cmd = &GetTxOutSetInfoCmd{} - -// NewGetTxOutSetInfoCmd creates a new GetTxOutSetInfoCmd. -func NewGetTxOutSetInfoCmd(id interface{}) (*GetTxOutSetInfoCmd, error) { - return &GetTxOutSetInfoCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetTxOutSetInfoCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetTxOutSetInfoCmd) Method() string { - return "gettxoutsetinfo" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetTxOutSetInfoCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetTxOutSetInfoCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewGetTxOutSetInfoCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// GetWorkCmd is a type handling custom marshaling and -// unmarshaling of getwork JSON RPC commands. -type GetWorkCmd struct { - id interface{} - Data string `json:"data,omitempty"` -} - -// Enforce that GetWorkCmd satisifies the Cmd interface. -var _ Cmd = &GetWorkCmd{} - -// NewGetWorkCmd creates a new GetWorkCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewGetWorkCmd(id interface{}, optArgs ...string) (*GetWorkCmd, error) { - var data string - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - data = optArgs[0] - } - return &GetWorkCmd{ - id: id, - Data: data, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *GetWorkCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *GetWorkCmd) Method() string { - return "getwork" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *GetWorkCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.Data != "" { - params = append(params, cmd.Data) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *GetWorkCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - if len(r.Params) > 1 { - return ErrWrongNumberOfParams - } - - var data string - if len(r.Params) > 0 { - if err := json.Unmarshal(r.Params[0], &data); err != nil { - return fmt.Errorf("first optional parameter 'data' must be a string: %v", err) - } - } - - newCmd, err := NewGetWorkCmd(r.Id, data) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// HelpCmd is a type handling custom marshaling and -// unmarshaling of help JSON RPC commands. -type HelpCmd struct { - id interface{} - Command string -} - -// Enforce that HelpCmd satisifies the Cmd interface. -var _ Cmd = &HelpCmd{} - -// NewHelpCmd creates a new HelpCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewHelpCmd(id interface{}, optArgs ...string) (*HelpCmd, error) { - - var command string - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - command = optArgs[0] - } - return &HelpCmd{ - id: id, - Command: command, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *HelpCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *HelpCmd) Method() string { - return "help" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *HelpCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.Command != "" { - params = append(params, cmd.Command) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *HelpCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 1 { - return ErrWrongNumberOfParams - } - - optArgs := make([]string, 0, 1) - if len(r.Params) > 0 { - var command string - if err := json.Unmarshal(r.Params[0], &command); err != nil { - return fmt.Errorf("first optional parameter 'command' must be a string: %v", err) - } - optArgs = append(optArgs, command) - } - - newCmd, err := NewHelpCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ImportAddressCmd is a type handling custom marshaling and -// unmarshaling of importaddress JSON RPC commands. -type ImportAddressCmd struct { - id interface{} - Address string - Rescan bool -} - -// Enforce that ImportAddressCmd satisifies the Cmd interface. -var _ Cmd = &ImportAddressCmd{} - -// NewImportAddressCmd creates a new ImportAddressCmd. -func NewImportAddressCmd(id interface{}, address string, optArgs ...interface{}) (*ImportAddressCmd, error) { - rescan := true - var ok bool - - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - if len(optArgs) > 0 { - rescan, ok = optArgs[0].(bool) - if !ok { - return nil, errors.New("first optional argument rescan is not a bool") - } - } - return &ImportAddressCmd{ - id: id, - Address: address, - Rescan: rescan, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ImportAddressCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ImportAddressCmd) Method() string { - return "importaddress" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ImportAddressCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.Address - if !cmd.Rescan { - params = append(params, cmd.Rescan) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ImportAddressCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) == 0 || len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - var optArgs []interface{} - if len(r.Params) > 1 { - var rescan bool - if err := json.Unmarshal(r.Params[1], &rescan); err != nil { - return fmt.Errorf("first optional parameter 'rescan' must be a bool: %v", err) - } - optArgs = append(optArgs, rescan) - } - - newCmd, err := NewImportAddressCmd(r.Id, address, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ImportPubKeyCmd is a type handling custom marshaling and -// unmarshaling of importpubkey JSON RPC commands. -type ImportPubKeyCmd struct { - id interface{} - PubKey string - Rescan bool -} - -// Enforce that ImportPubKeyCmd satisifies the Cmd interface. -var _ Cmd = &ImportPubKeyCmd{} - -// NewImportPubKeyCmd creates a new ImportPubKeyCmd. -func NewImportPubKeyCmd(id interface{}, pubkey string, optArgs ...interface{}) (*ImportPubKeyCmd, error) { - rescan := true - var ok bool - - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - if len(optArgs) > 0 { - rescan, ok = optArgs[0].(bool) - if !ok { - return nil, errors.New("first optional argument rescan is not a bool") - } - } - return &ImportPubKeyCmd{ - id: id, - PubKey: pubkey, - Rescan: rescan, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ImportPubKeyCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ImportPubKeyCmd) Method() string { - return "importpubkey" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ImportPubKeyCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.PubKey - if !cmd.Rescan { - params = append(params, cmd.Rescan) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ImportPubKeyCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) == 0 || len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - var pubkey string - if err := json.Unmarshal(r.Params[0], &pubkey); err != nil { - return fmt.Errorf("first parameter 'pubkey' must be a string: %v", err) - } - - var optArgs []interface{} - if len(r.Params) > 1 { - var rescan bool - if err := json.Unmarshal(r.Params[1], &rescan); err != nil { - return fmt.Errorf("first optional parameter 'rescan' must be a bool: %v", err) - } - optArgs = append(optArgs, rescan) - } - - newCmd, err := NewImportPubKeyCmd(r.Id, pubkey, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ImportPrivKeyCmd is a type handling custom marshaling and -// unmarshaling of importprivkey JSON RPC commands. -type ImportPrivKeyCmd struct { - id interface{} - PrivKey string - Label string - Rescan bool -} - -// Enforce that ImportPrivKeyCmd satisifies the Cmd interface. -var _ Cmd = &ImportPrivKeyCmd{} - -// NewImportPrivKeyCmd creates a new ImportPrivKeyCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewImportPrivKeyCmd(id interface{}, privkey string, optArgs ...interface{}) (*ImportPrivKeyCmd, error) { - var label string - rescan := true - var ok bool - - if len(optArgs) > 2 { - return nil, ErrTooManyOptArgs - } - if len(optArgs) > 0 { - label, ok = optArgs[0].(string) - if !ok { - return nil, errors.New("first optional argument label is not a string") - } - } - if len(optArgs) > 1 { - rescan, ok = optArgs[1].(bool) - if !ok { - return nil, errors.New("first optional argument rescan is not a bool") - } - } - return &ImportPrivKeyCmd{ - id: id, - PrivKey: privkey, - Label: label, - Rescan: rescan, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ImportPrivKeyCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ImportPrivKeyCmd) Method() string { - return "importprivkey" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ImportPrivKeyCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 3) - params[0] = cmd.PrivKey - if cmd.Label != "" || !cmd.Rescan { - params = append(params, cmd.Label) - } - if !cmd.Rescan { - params = append(params, cmd.Rescan) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ImportPrivKeyCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) == 0 || len(r.Params) > 3 { - return ErrWrongNumberOfParams - } - - var privkey string - if err := json.Unmarshal(r.Params[0], &privkey); err != nil { - return fmt.Errorf("first parameter 'privkey' must be a string: %v", err) - } - - optArgs := make([]interface{}, 0, 2) - if len(r.Params) > 1 { - var label string - if err := json.Unmarshal(r.Params[1], &label); err != nil { - return fmt.Errorf("second optional parameter 'label' must be a string: %v", err) - } - optArgs = append(optArgs, label) - } - - if len(r.Params) > 2 { - var rescan bool - if err := json.Unmarshal(r.Params[2], &rescan); err != nil { - return fmt.Errorf("third optional parameter 'rescan' must be a bool: %v", err) - } - optArgs = append(optArgs, rescan) - } - - newCmd, err := NewImportPrivKeyCmd(r.Id, privkey, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ImportWalletCmd is a type handling custom marshaling and -// unmarshaling of importwallet JSON RPC commands. -type ImportWalletCmd struct { - id interface{} - Filename string -} - -// Enforce that ImportWalletCmd satisifies the Cmd interface. -var _ Cmd = &ImportWalletCmd{} - -// NewImportWalletCmd creates a new ImportWalletCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewImportWalletCmd(id interface{}, filename string) (*ImportWalletCmd, error) { - return &ImportWalletCmd{ - id: id, - Filename: filename, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ImportWalletCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ImportWalletCmd) Method() string { - return "importwallet" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ImportWalletCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Filename, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ImportWalletCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var filename string - if err := json.Unmarshal(r.Params[0], &filename); err != nil { - return fmt.Errorf("first parameter 'filename' must be a string: %v", err) - } - - newCmd, err := NewImportWalletCmd(r.Id, filename) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// InvalidateBlockCmd is a type handling custom marshaling and -// unmarshaling of invalidateblock JSON RPC commands. -type InvalidateBlockCmd struct { - id interface{} - BlockHash string -} - -// Enforce that InvalidateBlockCmd satisifies the Cmd interface. -var _ Cmd = &InvalidateBlockCmd{} - -// NewInvalidateBlockCmd creates a new InvalidateBlockCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewInvalidateBlockCmd(id interface{}, blockhash string) (*InvalidateBlockCmd, error) { - return &InvalidateBlockCmd{ - id: id, - BlockHash: blockhash, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *InvalidateBlockCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *InvalidateBlockCmd) Method() string { - return "invalidateblock" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *InvalidateBlockCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.BlockHash, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *InvalidateBlockCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var blockhash string - if err := json.Unmarshal(r.Params[0], &blockhash); err != nil { - return fmt.Errorf("first parameter 'hash' must be a string: %v", err) - } - - newCmd, err := NewInvalidateBlockCmd(r.Id, blockhash) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// KeyPoolRefillCmd is a type handling custom marshaling and -// unmarshaling of keypoolrefill JSON RPC commands. -type KeyPoolRefillCmd struct { - id interface{} - NewSize uint -} - -// Enforce that KeyPoolRefillCmd satisifies the Cmd interface. -var _ Cmd = &KeyPoolRefillCmd{} - -// NewKeyPoolRefillCmd creates a new KeyPoolRefillCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewKeyPoolRefillCmd(id interface{}, optArgs ...uint) (*KeyPoolRefillCmd, error) { - newSize := uint(0) - - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - newSize = optArgs[0] - } - - return &KeyPoolRefillCmd{ - id: id, - NewSize: newSize, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *KeyPoolRefillCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *KeyPoolRefillCmd) Method() string { - return "keypoolrefill" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *KeyPoolRefillCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.NewSize != 0 { - params = append(params, cmd.NewSize) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *KeyPoolRefillCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 1 { - return ErrWrongNumberOfParams - } - - optArgs := make([]uint, 0, 1) - if len(r.Params) > 0 { - var newsize uint - if err := json.Unmarshal(r.Params[0], &newsize); err != nil { - return fmt.Errorf("first optional parameter 'newsize' must be an unsigned integer: %v", err) - } - optArgs = append(optArgs, newsize) - } - - newCmd, err := NewKeyPoolRefillCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ListAccountsCmd is a type handling custom marshaling and -// unmarshaling of listaccounts JSON RPC commands. -type ListAccountsCmd struct { - id interface{} - MinConf int -} - -// Enforce that ListAccountsCmd satisifies the Cmd interface. -var _ Cmd = &ListAccountsCmd{} - -// NewListAccountsCmd creates a new ListAccountsCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewListAccountsCmd(id interface{}, optArgs ...int) (*ListAccountsCmd, error) { - var minconf = 1 - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - minconf = optArgs[0] - } - return &ListAccountsCmd{ - id: id, - MinConf: minconf, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ListAccountsCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ListAccountsCmd) Method() string { - return "listaccounts" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListAccountsCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 1) - if cmd.MinConf != 1 { - params = append(params, cmd.MinConf) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListAccountsCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 1 { - return ErrWrongNumberOfParams - } - - optArgs := make([]int, 0, 1) - if len(r.Params) == 1 { - var minconf int - if err := json.Unmarshal(r.Params[0], &minconf); err != nil { - return fmt.Errorf("first optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - - newCmd, err := NewListAccountsCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ListAddressGroupingsCmd is a type handling custom marshaling and -// unmarshaling of listaddressgroupings JSON RPC commands. -type ListAddressGroupingsCmd struct { - id interface{} -} - -// Enforce that ListAddressGroupingsCmd satisifies the Cmd interface. -var _ Cmd = &ListAddressGroupingsCmd{} - -// NewListAddressGroupingsCmd creates a new ListAddressGroupingsCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewListAddressGroupingsCmd(id interface{}) (*ListAddressGroupingsCmd, error) { - return &ListAddressGroupingsCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ListAddressGroupingsCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ListAddressGroupingsCmd) Method() string { - return "listaddressgroupings" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListAddressGroupingsCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListAddressGroupingsCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewListAddressGroupingsCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ListLockUnspentCmd is a type handling custom marshaling and -// unmarshaling of listlockunspent JSON RPC commands. -type ListLockUnspentCmd struct { - id interface{} -} - -// Enforce that ListLockUnspentCmd satisifies the Cmd interface. -var _ Cmd = &ListLockUnspentCmd{} - -// NewListLockUnspentCmd creates a new ListLockUnspentCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewListLockUnspentCmd(id interface{}) (*ListLockUnspentCmd, error) { - return &ListLockUnspentCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ListLockUnspentCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ListLockUnspentCmd) Method() string { - return "listlockunspent" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListLockUnspentCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListLockUnspentCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewListLockUnspentCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ListReceivedByAccountCmd is a type handling custom marshaling and -// unmarshaling of listreceivedbyaccount JSON RPC commands. -type ListReceivedByAccountCmd struct { - id interface{} - MinConf int - IncludeEmpty bool -} - -// Enforce that ListReceivedByAccountCmd satisifies the Cmd interface. -var _ Cmd = &ListReceivedByAccountCmd{} - -// NewListReceivedByAccountCmd creates a new ListReceivedByAccountCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewListReceivedByAccountCmd(id interface{}, optArgs ...interface{}) (*ListReceivedByAccountCmd, error) { - minconf := 1 - includeempty := false - - if len(optArgs) > 2 { - return nil, ErrWrongNumberOfParams - } - if len(optArgs) > 0 { - m, ok := optArgs[0].(int) - if !ok { - return nil, errors.New("first optional argument minconf is not an int") - } - minconf = m - } - if len(optArgs) > 1 { - ie, ok := optArgs[1].(bool) - if !ok { - return nil, errors.New("second optional argument includeempty is not a bool") - } - - includeempty = ie - } - return &ListReceivedByAccountCmd{ - id: id, - MinConf: minconf, - IncludeEmpty: includeempty, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ListReceivedByAccountCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ListReceivedByAccountCmd) Method() string { - return "listreceivedbyaccount" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListReceivedByAccountCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 2) - if cmd.MinConf != 1 || cmd.IncludeEmpty != false { - params = append(params, cmd.MinConf) - } - if cmd.IncludeEmpty != false { - params = append(params, cmd.IncludeEmpty) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListReceivedByAccountCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - optArgs := make([]interface{}, 0, 2) - if len(r.Params) > 0 { - var minconf int - if err := json.Unmarshal(r.Params[0], &minconf); err != nil { - return fmt.Errorf("first optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - if len(r.Params) > 1 { - var includeempty bool - if err := json.Unmarshal(r.Params[1], &includeempty); err != nil { - return fmt.Errorf("second optional parameter 'includeempty' must be a bool: %v", err) - } - optArgs = append(optArgs, includeempty) - } - - newCmd, err := NewListReceivedByAccountCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ListReceivedByAddressCmd is a type handling custom marshaling and -// unmarshaling of listreceivedbyaddress JSON RPC commands. -type ListReceivedByAddressCmd struct { - id interface{} - MinConf int - IncludeEmpty bool -} - -// Enforce that ListReceivedByAddressCmd satisifies the Cmd interface. -var _ Cmd = &ListReceivedByAddressCmd{} - -// NewListReceivedByAddressCmd creates a new ListReceivedByAddressCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewListReceivedByAddressCmd(id interface{}, optArgs ...interface{}) (*ListReceivedByAddressCmd, error) { - minconf := 1 - includeempty := false - - if len(optArgs) > 2 { - return nil, ErrWrongNumberOfParams - } - if len(optArgs) > 0 { - m, ok := optArgs[0].(int) - if !ok { - return nil, errors.New("first optional argument minconf is not an int") - } - minconf = m - } - if len(optArgs) > 1 { - ie, ok := optArgs[1].(bool) - if !ok { - return nil, errors.New("second optional argument includeempty is not a bool") - } - - includeempty = ie - } - return &ListReceivedByAddressCmd{ - id: id, - MinConf: minconf, - IncludeEmpty: includeempty, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ListReceivedByAddressCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ListReceivedByAddressCmd) Method() string { - return "listreceivedbyaddress" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListReceivedByAddressCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 2) - if cmd.MinConf != 1 || cmd.IncludeEmpty != false { - params = append(params, cmd.MinConf) - } - if cmd.IncludeEmpty != false { - params = append(params, cmd.IncludeEmpty) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListReceivedByAddressCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - optArgs := make([]interface{}, 0, 2) - if len(r.Params) > 0 { - var minconf int - if err := json.Unmarshal(r.Params[0], &minconf); err != nil { - return fmt.Errorf("first optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - if len(r.Params) > 1 { - var includeempty bool - if err := json.Unmarshal(r.Params[1], &includeempty); err != nil { - return fmt.Errorf("second optional parameter 'includeempty' must be a bool: %v", err) - } - optArgs = append(optArgs, includeempty) - } - - newCmd, err := NewListReceivedByAddressCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ListSinceBlockCmd is a type handling custom marshaling and -// unmarshaling of listsinceblock JSON RPC commands. -type ListSinceBlockCmd struct { - id interface{} - BlockHash string - TargetConfirmations int -} - -// Enforce that ListSinceBlockCmd satisifies the Cmd interface. -var _ Cmd = &ListSinceBlockCmd{} - -// NewListSinceBlockCmd creates a new ListSinceBlockCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewListSinceBlockCmd(id interface{}, optArgs ...interface{}) (*ListSinceBlockCmd, error) { - blockhash := "" - targetconfirmations := 1 - - if len(optArgs) > 2 { - return nil, ErrWrongNumberOfParams - } - if len(optArgs) > 0 { - bh, ok := optArgs[0].(string) - if !ok { - return nil, errors.New("first optional argument blockhash is not a string") - } - blockhash = bh - } - if len(optArgs) > 1 { - tc, ok := optArgs[1].(int) - if !ok { - return nil, errors.New("second optional argument targetconfirmations is not an int") - } - - targetconfirmations = tc - } - return &ListSinceBlockCmd{ - id: id, - BlockHash: blockhash, - TargetConfirmations: targetconfirmations, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ListSinceBlockCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ListSinceBlockCmd) Method() string { - return "listsinceblock" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListSinceBlockCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 2) - if cmd.BlockHash != "" || cmd.TargetConfirmations != 1 { - params = append(params, cmd.BlockHash) - } - if cmd.TargetConfirmations != 1 { - params = append(params, cmd.TargetConfirmations) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListSinceBlockCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - optArgs := make([]interface{}, 0, 2) - if len(r.Params) > 0 { - var blockhash string - if err := json.Unmarshal(r.Params[0], &blockhash); err != nil { - return fmt.Errorf("first optional parameter 'blockhash' must be a string: %v", err) - } - optArgs = append(optArgs, blockhash) - } - if len(r.Params) > 1 { - var targetconfirmations int - if err := json.Unmarshal(r.Params[1], &targetconfirmations); err != nil { - return fmt.Errorf("second optional parameter 'targetconfirmations' must be an integer: %v", err) - } - optArgs = append(optArgs, targetconfirmations) - } - - newCmd, err := NewListSinceBlockCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ListTransactionsCmd is a type handling custom marshaling and -// unmarshaling of listtransactions JSON RPC commands. -type ListTransactionsCmd struct { - id interface{} - Account *string - Count int - From int -} - -// Enforce that ListTransactionsCmd satisifies the Cmd interface. -var _ Cmd = &ListTransactionsCmd{} - -// NewListTransactionsCmd creates a new ListTransactionsCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewListTransactionsCmd(id interface{}, optArgs ...interface{}) (*ListTransactionsCmd, error) { - var account *string - count := 10 - from := 0 - - if len(optArgs) > 3 { - return nil, ErrWrongNumberOfParams - } - if len(optArgs) > 0 { - ac, ok := optArgs[0].(string) - if !ok { - return nil, errors.New("first optional argument account is not a string") - } - account = &ac - } - if len(optArgs) > 1 { - cnt, ok := optArgs[1].(int) - if !ok { - return nil, errors.New("second optional argument count is not an int") - } - - count = cnt - } - if len(optArgs) > 2 { - frm, ok := optArgs[2].(int) - if !ok { - return nil, errors.New("third optional argument from is not an int") - } - - from = frm - } - return &ListTransactionsCmd{ - id: id, - Account: account, - Count: count, - From: from, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ListTransactionsCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ListTransactionsCmd) Method() string { - return "listtransactions" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListTransactionsCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 3) - if cmd.Account != nil { - params = append(params, cmd.Account) - } - if cmd.Count != 10 || cmd.From != 0 { - params = append(params, cmd.Count) - } - if cmd.From != 0 { - params = append(params, cmd.From) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListTransactionsCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 3 { - return ErrWrongNumberOfParams - } - - optArgs := make([]interface{}, 0, 3) - if len(r.Params) > 0 { - var account string - if err := json.Unmarshal(r.Params[0], &account); err != nil { - return fmt.Errorf("first optional parameter 'account' must be a string: %v", err) - } - optArgs = append(optArgs, account) - } - if len(r.Params) > 1 { - var count int - if err := json.Unmarshal(r.Params[1], &count); err != nil { - return fmt.Errorf("second optional parameter 'count' must be an integer: %v", err) - } - optArgs = append(optArgs, count) - } - if len(r.Params) > 2 { - var from int - if err := json.Unmarshal(r.Params[2], &from); err != nil { - return fmt.Errorf("third optional parameter 'from' must be an integer: %v", err) - } - optArgs = append(optArgs, from) - } - - newCmd, err := NewListTransactionsCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ListUnspentCmd is a type handling custom marshaling and -// unmarshaling of listunspent JSON RPC commands. -type ListUnspentCmd struct { - id interface{} - MinConf int - MaxConf int - Addresses []string -} - -// Enforce that ListUnspentCmd satisifies the Cmd interface. -var _ Cmd = &ListUnspentCmd{} - -// NewListUnspentCmd creates a new ListUnspentCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewListUnspentCmd(id interface{}, optArgs ...interface{}) (*ListUnspentCmd, error) { - minconf := 1 - maxconf := 999999 - var addresses []string - - if len(optArgs) > 3 { - return nil, ErrWrongNumberOfParams - } - if len(optArgs) > 0 { - m, ok := optArgs[0].(int) - if !ok { - return nil, errors.New("first optional argument minconf is not an int") - } - minconf = m - } - if len(optArgs) > 1 { - m, ok := optArgs[1].(int) - if !ok { - return nil, errors.New("second optional argument maxconf is not an int") - } - maxconf = m - } - if len(optArgs) > 2 { - a, ok := optArgs[2].([]string) - if !ok { - return nil, errors.New("third optional argument addresses is not an array of strings") - } - addresses = a - } - return &ListUnspentCmd{ - id: id, - MinConf: minconf, - MaxConf: maxconf, - Addresses: addresses, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ListUnspentCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ListUnspentCmd) Method() string { - return "listunspent" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ListUnspentCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 0, 3) - if cmd.MinConf != 1 || cmd.MaxConf != 99999 || len(cmd.Addresses) != 0 { - params = append(params, cmd.MinConf) - } - if cmd.MaxConf != 99999 || len(cmd.Addresses) != 0 { - params = append(params, cmd.MaxConf) - } - if len(cmd.Addresses) != 0 { - params = append(params, cmd.Addresses) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ListUnspentCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 3 { - return ErrWrongNumberOfParams - } - - optArgs := make([]interface{}, 0, 3) - if len(r.Params) > 0 { - var minconf int - if err := json.Unmarshal(r.Params[0], &minconf); err != nil { - return fmt.Errorf("first optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - if len(r.Params) > 1 { - var maxconf int - if err := json.Unmarshal(r.Params[1], &maxconf); err != nil { - return fmt.Errorf("second optional parameter 'maxconf' must be an integer: %v", err) - } - optArgs = append(optArgs, maxconf) - } - if len(r.Params) > 2 { - var addrs []string - if err := json.Unmarshal(r.Params[2], &addrs); err != nil { - return fmt.Errorf("third optional parameter 'addresses' must be an array of strings: %v", err) - } - optArgs = append(optArgs, addrs) - } - - newCmd, err := NewListUnspentCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// LockUnspentCmd is a type handling custom marshaling and -// unmarshaling of lockunspent JSON RPC commands. -type LockUnspentCmd struct { - id interface{} - Unlock bool - Transactions []TransactionInput -} - -// Enforce that LockUnspentCmd satisifies the Cmd interface. -var _ Cmd = &LockUnspentCmd{} - -// NewLockUnspentCmd creates a new LockUnspentCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewLockUnspentCmd(id interface{}, unlock bool, optArgs ...[]TransactionInput) (*LockUnspentCmd, error) { - var transactions []TransactionInput - - if len(optArgs) > 1 { - return nil, ErrWrongNumberOfParams - } - - if len(optArgs) > 0 { - transactions = optArgs[0] - } - - return &LockUnspentCmd{ - id: id, - Unlock: unlock, - Transactions: transactions, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *LockUnspentCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *LockUnspentCmd) Method() string { - return "lockunspent" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *LockUnspentCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.Unlock - if len(cmd.Transactions) > 0 { - params = append(params, cmd.Transactions) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *LockUnspentCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 || len(r.Params) < 1 { - return ErrWrongNumberOfParams - } - - var unlock bool - if err := json.Unmarshal(r.Params[0], &unlock); err != nil { - return fmt.Errorf("first parameter 'unlock' must be a bool: %v", err) - } - - optArgs := make([][]TransactionInput, 0, 1) - if len(r.Params) > 1 { - var transactions []TransactionInput - if err := json.Unmarshal(r.Params[1], &transactions); err != nil { - return fmt.Errorf("second optional parameter 'transactions' "+ - "must be a JSON array of transaction input JSON objects: %v", err) - } - optArgs = append(optArgs, transactions) - } - - newCmd, err := NewLockUnspentCmd(r.Id, unlock, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// MoveCmd is a type handling custom marshaling and -// unmarshaling of move JSON RPC commands. -type MoveCmd struct { - id interface{} - FromAccount string - ToAccount string - Amount int64 - MinConf int - Comment string -} - -// Enforce that MoveCmd satisifies the Cmd interface. -var _ Cmd = &MoveCmd{} - -// NewMoveCmd creates a new MoveCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewMoveCmd(id interface{}, fromaccount string, toaccount string, amount int64, optArgs ...interface{}) (*MoveCmd, error) { - minconf := 1 - comment := "" - - if len(optArgs) > 2 { - return nil, ErrWrongNumberOfParams - } - - if len(optArgs) > 0 { - m, ok := optArgs[0].(int) - if !ok { - return nil, errors.New("first optional parameter minconf is not a int64") - } - minconf = m - } - if len(optArgs) > 1 { - c, ok := optArgs[1].(string) - if !ok { - return nil, errors.New("second optional parameter comment is not a string") - } - comment = c - } - - return &MoveCmd{ - id: id, - FromAccount: fromaccount, - ToAccount: toaccount, - Amount: amount, - MinConf: minconf, - Comment: comment, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *MoveCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *MoveCmd) Method() string { - return "move" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *MoveCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 3, 5) - params[0] = cmd.FromAccount - params[1] = cmd.ToAccount - params[2] = float64(cmd.Amount) / 1e8 //convert to BTC - if cmd.MinConf != 1 || cmd.Comment != "" { - params = append(params, cmd.MinConf) - } - if cmd.Comment != "" { - params = append(params, cmd.Comment) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *MoveCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 5 || len(r.Params) < 3 { - return ErrWrongNumberOfParams - } - - var fromaccount string - if err := json.Unmarshal(r.Params[0], &fromaccount); err != nil { - return fmt.Errorf("first parameter 'fromaccount' must be a string: %v", err) - } - - var toaccount string - if err := json.Unmarshal(r.Params[1], &toaccount); err != nil { - return fmt.Errorf("second parameter 'toaccount' must be a string: %v", err) - } - - var famount float64 - if err := json.Unmarshal(r.Params[2], &famount); err != nil { - return fmt.Errorf("third parameter 'amount' must be a number: %v", err) - } - amount, err := JSONToAmount(famount) - if err != nil { - return err - } - - optArgs := make([]interface{}, 0, 2) - if len(r.Params) > 3 { - var minconf int - if err := json.Unmarshal(r.Params[3], &minconf); err != nil { - return fmt.Errorf("fourth optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - if len(r.Params) > 4 { - var comment string - if err := json.Unmarshal(r.Params[4], &comment); err != nil { - return fmt.Errorf("fifth optional parameter 'comment' must be a string: %v", err) - } - optArgs = append(optArgs, comment) - } - - newCmd, err := NewMoveCmd(r.Id, fromaccount, toaccount, amount, - optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// PingCmd is a type handling custom marshaling and -// unmarshaling of ping JSON RPC commands. -type PingCmd struct { - id interface{} -} - -// Enforce that PingCmd satisifies the Cmd interface. -var _ Cmd = &PingCmd{} - -// NewPingCmd creates a new PingCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewPingCmd(id interface{}) (*PingCmd, error) { - return &PingCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *PingCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *PingCmd) Method() string { - return "ping" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *PingCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *PingCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewPingCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ReconsiderBlockCmd is a type handling custom marshaling and -// unmarshaling of reconsiderblock JSON RPC commands. -type ReconsiderBlockCmd struct { - id interface{} - BlockHash string -} - -// Enforce that ReconsiderBlockCmd satisifies the Cmd interface. -var _ Cmd = &ReconsiderBlockCmd{} - -// NewReconsiderBlockCmd creates a new ReconsiderBlockCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewReconsiderBlockCmd(id interface{}, blockhash string) (*ReconsiderBlockCmd, error) { - return &ReconsiderBlockCmd{ - id: id, - BlockHash: blockhash, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ReconsiderBlockCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ReconsiderBlockCmd) Method() string { - return "reconsiderblock" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ReconsiderBlockCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.BlockHash, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ReconsiderBlockCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var blockhash string - if err := json.Unmarshal(r.Params[0], &blockhash); err != nil { - return fmt.Errorf("first parameter 'hash' must be a string: %v", err) - } - - newCmd, err := NewReconsiderBlockCmd(r.Id, blockhash) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// SearchRawTransactionsCmd is a type handling custom marshaling and -// unmarshaling of sendrawtransactions JSON RPC commands. -type SearchRawTransactionsCmd struct { - id interface{} - Address string - Verbose int - Skip int - Count int -} - -// NewSearchRawTransactionsCmd creates a new SearchRawTransactionsCmd. -func NewSearchRawTransactionsCmd(id interface{}, address string, - optArgs ...interface{}) (*SearchRawTransactionsCmd, error) { - var skip int - verbose := 1 - count := 100 - - if len(optArgs) > 3 { - return nil, ErrTooManyOptArgs - } - - if len(optArgs) > 0 { - v, ok := optArgs[0].(int) - if !ok { - return nil, errors.New("first optional argument verbose is not a int") - } - - verbose = v - } - if len(optArgs) > 1 { - s, ok := optArgs[1].(int) - if !ok { - return nil, errors.New("second optional argument skip is not an int") - } - skip = s - } - if len(optArgs) > 2 { - c, ok := optArgs[2].(int) - if !ok { - return nil, errors.New("third optional argument count is not an int") - } - - count = c - } - - return &SearchRawTransactionsCmd{ - id: id, - Address: address, - Verbose: verbose, - Skip: skip, - Count: count, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SearchRawTransactionsCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SearchRawTransactionsCmd) Method() string { - return "searchrawtransactions" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SearchRawTransactionsCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 4) - params[0] = cmd.Address - if cmd.Verbose != 1 || cmd.Skip != 0 || cmd.Count != 100 { - params = append(params, cmd.Verbose) - } - if cmd.Skip != 0 || cmd.Count != 100 { - params = append(params, cmd.Skip) - } - if cmd.Count != 100 { - params = append(params, cmd.Count) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SearchRawTransactionsCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) == 0 || len(r.Params) > 4 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - optArgs := make([]interface{}, 0, 3) - if len(r.Params) > 1 { - var verbose int - if err := json.Unmarshal(r.Params[1], &verbose); err != nil { - return fmt.Errorf("second optional parameter 'verbose' must be an int: %v", err) - } - optArgs = append(optArgs, verbose) - } - if len(r.Params) > 2 { - var skip int - if err := json.Unmarshal(r.Params[2], &skip); err != nil { - return fmt.Errorf("third optional parameter 'skip' must be an int: %v", err) - } - optArgs = append(optArgs, skip) - } - if len(r.Params) > 3 { - var count int - if err := json.Unmarshal(r.Params[3], &count); err != nil { - return fmt.Errorf("fourth optional parameter 'count' must be an int: %v", err) - } - optArgs = append(optArgs, count) - } - - newCmd, err := NewSearchRawTransactionsCmd(r.Id, address, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// Enforce that SearchRawTransactionsCmd satisifies the Cmd interface. -var _ Cmd = &SearchRawTransactionsCmd{} - -// SendFromCmd is a type handling custom marshaling and -// unmarshaling of sendfrom JSON RPC commands. -type SendFromCmd struct { - id interface{} - FromAccount string - ToAddress string - Amount int64 - MinConf int - Comment string - CommentTo string -} - -// Enforce that SendFromCmd satisifies the Cmd interface. -var _ Cmd = &SendFromCmd{} - -// NewSendFromCmd creates a new SendFromCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSendFromCmd(id interface{}, fromaccount string, toaddress string, amount int64, optArgs ...interface{}) (*SendFromCmd, error) { - minconf := 1 - comment := "" - commentto := "" - - if len(optArgs) > 3 { - return nil, ErrWrongNumberOfParams - } - - if len(optArgs) > 0 { - m, ok := optArgs[0].(int) - if !ok { - return nil, errors.New("first optional parameter minconf is not a int64") - } - minconf = m - } - if len(optArgs) > 1 { - c, ok := optArgs[1].(string) - if !ok { - return nil, errors.New("second optional parameter comment is not a string") - } - comment = c - } - - if len(optArgs) > 2 { - cto, ok := optArgs[2].(string) - if !ok { - return nil, errors.New("third optional parameter commentto is not a string") - } - commentto = cto - } - - return &SendFromCmd{ - id: id, - FromAccount: fromaccount, - ToAddress: toaddress, - Amount: amount, - MinConf: minconf, - Comment: comment, - CommentTo: commentto, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SendFromCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SendFromCmd) Method() string { - return "sendfrom" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SendFromCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 3, 6) - params[0] = cmd.FromAccount - params[1] = cmd.ToAddress - params[2] = float64(cmd.Amount) / 1e8 //convert to BTC - if cmd.MinConf != 1 || cmd.Comment != "" || cmd.CommentTo != "" { - params = append(params, cmd.MinConf) - } - if cmd.Comment != "" || cmd.CommentTo != "" { - params = append(params, cmd.Comment) - } - if cmd.CommentTo != "" { - params = append(params, cmd.CommentTo) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SendFromCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 6 || len(r.Params) < 3 { - return ErrWrongNumberOfParams - } - - var fromaccount string - if err := json.Unmarshal(r.Params[0], &fromaccount); err != nil { - return fmt.Errorf("first parameter 'fromaccount' must be a string: %v", err) - } - - var toaddress string - if err := json.Unmarshal(r.Params[1], &toaddress); err != nil { - return fmt.Errorf("second parameter 'toaddress' must be a string: %v", err) - } - - var famount float64 - if err := json.Unmarshal(r.Params[2], &famount); err != nil { - return fmt.Errorf("third parameter 'amount' must be a number: %v", err) - } - amount, err := JSONToAmount(famount) - if err != nil { - return err - } - - optArgs := make([]interface{}, 0, 3) - if len(r.Params) > 3 { - var minconf int - if err := json.Unmarshal(r.Params[3], &minconf); err != nil { - return fmt.Errorf("fourth optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - if len(r.Params) > 4 { - var comment string - if err := json.Unmarshal(r.Params[4], &comment); err != nil { - return fmt.Errorf("fifth optional parameter 'comment' must be a string: %v", err) - } - optArgs = append(optArgs, comment) - } - if len(r.Params) > 5 { - var commentto string - if err := json.Unmarshal(r.Params[5], &commentto); err != nil { - return fmt.Errorf("sixth optional parameter 'commentto' must be a string: %v", err) - } - optArgs = append(optArgs, commentto) - } - - newCmd, err := NewSendFromCmd(r.Id, fromaccount, toaddress, amount, - optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// SendManyCmd is a type handling custom marshaling and -// unmarshaling of sendmany JSON RPC commands. -type SendManyCmd struct { - id interface{} - FromAccount string - Amounts map[string]int64 - MinConf int - Comment string -} - -// Enforce that SendManyCmd satisifies the Cmd interface. -var _ Cmd = &SendManyCmd{} - -// NewSendManyCmd creates a new SendManyCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSendManyCmd(id interface{}, fromaccount string, amounts map[string]int64, optArgs ...interface{}) (*SendManyCmd, error) { - minconf := 1 - comment := "" - - if len(optArgs) > 2 { - return nil, ErrWrongNumberOfParams - } - - if len(optArgs) > 0 { - m, ok := optArgs[0].(int) - if !ok { - return nil, errors.New("first optional parameter minconf is not a int64") - } - minconf = m - } - if len(optArgs) > 1 { - c, ok := optArgs[1].(string) - if !ok { - return nil, errors.New("second optional parameter comment is not a string") - } - comment = c - } - - return &SendManyCmd{ - id: id, - FromAccount: fromaccount, - Amounts: amounts, - MinConf: minconf, - Comment: comment, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SendManyCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SendManyCmd) Method() string { - return "sendmany" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SendManyCmd) MarshalJSON() ([]byte, error) { - floatAmounts := make(map[string]float64, len(cmd.Amounts)) - for k, v := range cmd.Amounts { - floatAmounts[k] = float64(v) / 1e8 - } - - params := make([]interface{}, 2, 4) - params[0] = cmd.FromAccount - params[1] = floatAmounts - if cmd.MinConf != 1 || cmd.Comment != "" { - params = append(params, cmd.MinConf) - } - if cmd.Comment != "" { - params = append(params, cmd.Comment) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SendManyCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 4 || len(r.Params) < 2 { - return ErrWrongNumberOfParams - } - - var fromaccount string - if err := json.Unmarshal(r.Params[0], &fromaccount); err != nil { - return fmt.Errorf("first parameter 'fromaccount' must be a string: %v", err) - } - - var famounts map[string]float64 - if err := json.Unmarshal(r.Params[1], &famounts); err != nil { - return fmt.Errorf("second parameter 'amounts' must be a JSON object of address to amount mappings: %v", err) - } - amounts := make(map[string]int64, len(famounts)) - for k, v := range famounts { - amount, err := JSONToAmount(v) - if err != nil { - return err - } - amounts[k] = amount - } - - optArgs := make([]interface{}, 0, 2) - if len(r.Params) > 2 { - var minconf int - if err := json.Unmarshal(r.Params[2], &minconf); err != nil { - return fmt.Errorf("third optional parameter 'minconf' must be an integer: %v", err) - } - optArgs = append(optArgs, minconf) - } - if len(r.Params) > 3 { - var comment string - if err := json.Unmarshal(r.Params[3], &comment); err != nil { - return fmt.Errorf("fourth optional parameter 'comment' must be a string: %v", err) - } - optArgs = append(optArgs, comment) - } - - newCmd, err := NewSendManyCmd(r.Id, fromaccount, amounts, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// SendRawTransactionCmd is a type handling custom marshaling and -// unmarshaling of sendrawtransaction JSON RPC commands. -type SendRawTransactionCmd struct { - id interface{} - HexTx string - AllowHighFees bool -} - -// Enforce that SendRawTransactionCmd satisifies the Cmd interface. -var _ Cmd = &SendRawTransactionCmd{} - -// NewSendRawTransactionCmd creates a new SendRawTransactionCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSendRawTransactionCmd(id interface{}, hextx string, optArgs ...bool) (*SendRawTransactionCmd, error) { - allowHighFees := false - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - if len(optArgs) == 1 { - allowHighFees = optArgs[0] - } - - return &SendRawTransactionCmd{ - id: id, - HexTx: hextx, - AllowHighFees: allowHighFees, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SendRawTransactionCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SendRawTransactionCmd) Method() string { - return "sendrawtransaction" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SendRawTransactionCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.HexTx - if cmd.AllowHighFees { - params = append(params, cmd.AllowHighFees) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SendRawTransactionCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 || len(r.Params) < 1 { - return ErrWrongNumberOfParams - } - - var hextx string - if err := json.Unmarshal(r.Params[0], &hextx); err != nil { - return fmt.Errorf("first parameter 'hextx' must be a string: %v", err) - } - - optArgs := make([]bool, 0, 1) - if len(r.Params) > 1 { - var allowHighFees bool - if err := json.Unmarshal(r.Params[1], &allowHighFees); err != nil { - return fmt.Errorf("second optional parameter 'allowhighfees' must be a bool: %v", err) - } - optArgs = append(optArgs, allowHighFees) - } - - newCmd, err := NewSendRawTransactionCmd(r.Id, hextx, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// SendToAddressCmd is a type handling custom marshaling and -// unmarshaling of sendtoaddress JSON RPC commands. -type SendToAddressCmd struct { - id interface{} - Address string - Amount int64 - Comment string - CommentTo string -} - -// Enforce that SendToAddressCmd satisifies the Cmd interface. -var _ Cmd = &SendToAddressCmd{} - -// NewSendToAddressCmd creates a new SendToAddressCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSendToAddressCmd(id interface{}, address string, amount int64, optArgs ...interface{}) (*SendToAddressCmd, error) { - comment := "" - commentto := "" - - if len(optArgs) > 2 { - return nil, ErrWrongNumberOfParams - } - - if len(optArgs) > 0 { - c, ok := optArgs[0].(string) - if !ok { - return nil, errors.New("first optional parameter comment is not a string") - } - comment = c - } - if len(optArgs) > 1 { - cto, ok := optArgs[1].(string) - if !ok { - return nil, errors.New("second optional parameter commentto is not a string") - } - commentto = cto - } - - return &SendToAddressCmd{ - id: id, - Address: address, - Amount: amount, - Comment: comment, - CommentTo: commentto, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SendToAddressCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SendToAddressCmd) Method() string { - return "sendtoaddress" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SendToAddressCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 2, 4) - params[0] = cmd.Address - params[1] = float64(cmd.Amount) / 1e8 //convert to BTC - if cmd.Comment != "" || cmd.CommentTo != "" { - params = append(params, cmd.Comment) - } - if cmd.CommentTo != "" { - params = append(params, cmd.CommentTo) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SendToAddressCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 4 || len(r.Params) < 2 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - var famount float64 - if err := json.Unmarshal(r.Params[1], &famount); err != nil { - return fmt.Errorf("second parameter 'amount' must be a number: %v", err) - } - amount, err := JSONToAmount(famount) - if err != nil { - return err - } - - optArgs := make([]interface{}, 0, 2) - if len(r.Params) > 2 { - var comment string - if err := json.Unmarshal(r.Params[2], &comment); err != nil { - return fmt.Errorf("third optional parameter 'comment' must be a string: %v", err) - } - optArgs = append(optArgs, comment) - } - if len(r.Params) > 3 { - var commentto string - if err := json.Unmarshal(r.Params[3], &commentto); err != nil { - return fmt.Errorf("fourth optional parameter 'commentto' must be a string: %v", err) - } - optArgs = append(optArgs, commentto) - } - - newCmd, err := NewSendToAddressCmd(r.Id, address, amount, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// SetAccountCmd is a type handling custom marshaling and -// unmarshaling of setaccount JSON RPC commands. -type SetAccountCmd struct { - id interface{} - Address string - Account string -} - -// Enforce that SetAccountCmd satisifies the Cmd interface. -var _ Cmd = &SetAccountCmd{} - -// NewSetAccountCmd creates a new SetAccountCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSetAccountCmd(id interface{}, address string, account string) (*SetAccountCmd, error) { - - return &SetAccountCmd{ - id: id, - Address: address, - Account: account, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SetAccountCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SetAccountCmd) Method() string { - return "setaccount" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SetAccountCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Address, - cmd.Account, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SetAccountCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 2 || len(r.Params) < 2 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - var account string - if err := json.Unmarshal(r.Params[1], &account); err != nil { - return fmt.Errorf("second parameter 'account' must be a string: %v", err) - } - - newCmd, err := NewSetAccountCmd(r.Id, address, account) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// SetGenerateCmd is a type handling custom marshaling and -// unmarshaling of setgenerate JSON RPC commands. -type SetGenerateCmd struct { - id interface{} - Generate bool - GenProcLimit int -} - -// Enforce that SetGenerateCmd satisifies the Cmd interface. -var _ Cmd = &SetGenerateCmd{} - -// NewSetGenerateCmd creates a new SetGenerateCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSetGenerateCmd(id interface{}, generate bool, optArgs ...int) (*SetGenerateCmd, error) { - genproclimit := -1 - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - if len(optArgs) == 1 { - genproclimit = optArgs[0] - } - - return &SetGenerateCmd{ - id: id, - Generate: generate, - GenProcLimit: genproclimit, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SetGenerateCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SetGenerateCmd) Method() string { - return "setgenerate" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SetGenerateCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.Generate - if cmd.GenProcLimit != -1 { - params = append(params, cmd.GenProcLimit) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SetGenerateCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 || len(r.Params) < 1 { - return ErrWrongNumberOfParams - } - - var generate bool - if err := json.Unmarshal(r.Params[0], &generate); err != nil { - return fmt.Errorf("first parameter 'generate' must be a bool: %v", err) - } - - optArgs := make([]int, 0, 1) - if len(r.Params) > 1 { - var genproclimit int - if err := json.Unmarshal(r.Params[1], &genproclimit); err != nil { - return fmt.Errorf("second optional parameter 'genproclimit' must be an integer: %v", err) - } - optArgs = append(optArgs, genproclimit) - } - - newCmd, err := NewSetGenerateCmd(r.Id, generate, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// SetTxFeeCmd is a type handling custom marshaling and -// unmarshaling of settxfee JSON RPC commands. -type SetTxFeeCmd struct { - id interface{} - Amount int64 -} - -// Enforce that SetTxFeeCmd satisifies the Cmd interface. -var _ Cmd = &SetTxFeeCmd{} - -// NewSetTxFeeCmd creates a new SetTxFeeCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSetTxFeeCmd(id interface{}, amount int64) (*SetTxFeeCmd, error) { - return &SetTxFeeCmd{ - id: id, - Amount: amount, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SetTxFeeCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SetTxFeeCmd) Method() string { - return "settxfee" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SetTxFeeCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - float64(cmd.Amount) / 1e8, //convert to BTC - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SetTxFeeCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var famount float64 - if err := json.Unmarshal(r.Params[0], &famount); err != nil { - return fmt.Errorf("first parameter 'amount' must be a number: %v", err) - } - amount, err := JSONToAmount(famount) - if err != nil { - return err - } - - newCmd, err := NewSetTxFeeCmd(r.Id, amount) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// SignMessageCmd is a type handling custom marshaling and -// unmarshaling of signmessage JSON RPC commands. -type SignMessageCmd struct { - id interface{} - Address string - Message string -} - -// Enforce that SignMessageCmd satisifies the Cmd interface. -var _ Cmd = &SignMessageCmd{} - -// NewSignMessageCmd creates a new SignMessageCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSignMessageCmd(id interface{}, address string, message string) (*SignMessageCmd, error) { - return &SignMessageCmd{ - id: id, - Address: address, - Message: message, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SignMessageCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SignMessageCmd) Method() string { - return "signmessage" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SignMessageCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Address, - cmd.Message, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SignMessageCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 2 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - var message string - if err := json.Unmarshal(r.Params[1], &message); err != nil { - return fmt.Errorf("second parameter 'message' must be a string: %v", err) - } - - newCmd, err := NewSignMessageCmd(r.Id, address, message) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// RawTxInput models the data needed for a raw tx input. -type RawTxInput struct { - Txid string `json:"txid"` - Vout uint32 `json:"vout"` - ScriptPubKey string `json:"scriptPubKey"` - RedeemScript string `json:"redeemScript"` -} - -// SignRawTransactionCmd is a type handling custom marshaling and -// unmarshaling of signrawtransaction JSON RPC commands. -type SignRawTransactionCmd struct { - id interface{} - RawTx string - Inputs []RawTxInput - PrivKeys []string - Flags string -} - -// Enforce that SignRawTransactionCmd satisifies the Cmd interface. -var _ Cmd = &SignRawTransactionCmd{} - -// NewSignRawTransactionCmd creates a new SignRawTransactionCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSignRawTransactionCmd(id interface{}, rawTx string, optArgs ...interface{}) (*SignRawTransactionCmd, error) { - var inputs []RawTxInput - var privkeys []string - var flags string - if len(optArgs) > 3 { - return nil, ErrTooManyOptArgs - } - if len(optArgs) > 0 { - ip, ok := optArgs[0].([]RawTxInput) - if !ok { - return nil, errors.New("first optional parameter inputs should be an array of RawTxInput") - } - - inputs = ip - } - if len(optArgs) > 1 { - pk, ok := optArgs[1].([]string) - if !ok { - return nil, errors.New("second optional parameter inputs should be an array of string") - } - - privkeys = pk - } - if len(optArgs) > 2 { - fl, ok := optArgs[2].(string) - if !ok { - return nil, errors.New("third optional parameter flags should be a string") - } - - flags = fl - } - return &SignRawTransactionCmd{ - id: id, - RawTx: rawTx, - Inputs: inputs, - PrivKeys: privkeys, - Flags: flags, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SignRawTransactionCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SignRawTransactionCmd) Method() string { - return "signrawtransaction" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SignRawTransactionCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 4) - params[0] = cmd.RawTx - if len(cmd.Inputs) > 0 || len(cmd.PrivKeys) > 0 || cmd.Flags != "" { - params = append(params, cmd.Inputs) - } - if len(cmd.PrivKeys) > 0 || cmd.Flags != "" { - params = append(params, cmd.PrivKeys) - } - if cmd.Flags != "" { - params = append(params, cmd.Flags) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SignRawTransactionCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 4 || len(r.Params) < 1 { - return ErrWrongNumberOfParams - } - - var rawtx string - if err := json.Unmarshal(r.Params[0], &rawtx); err != nil { - return fmt.Errorf("first parameter 'rawtx' must be a string: %v", err) - } - - optArgs := make([]interface{}, 0, 3) - if len(r.Params) > 1 { - var inputs []RawTxInput - if err := json.Unmarshal(r.Params[1], &inputs); err != nil { - return fmt.Errorf("second optional parameter 'inputs' "+ - "must be a JSON array of raw transaction input JSON objects: %v", err) - } - optArgs = append(optArgs, inputs) - } - - if len(r.Params) > 2 { - var privkeys []string - if err := json.Unmarshal(r.Params[2], &privkeys); err != nil { - return fmt.Errorf("third optional parameter 'privkeys' must be an array of strings: %v", err) - } - optArgs = append(optArgs, privkeys) - } - if len(r.Params) > 3 { - var flags string - if err := json.Unmarshal(r.Params[3], &flags); err != nil { - return fmt.Errorf("fourth optional parameter 'flags' must be a string: %v", err) - } - optArgs = append(optArgs, flags) - } - - newCmd, err := NewSignRawTransactionCmd(r.Id, rawtx, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// StopCmd is a type handling custom marshaling and -// unmarshaling of stop JSON RPC commands. -type StopCmd struct { - id interface{} -} - -// Enforce that StopCmd satisifies the Cmd interface. -var _ Cmd = &StopCmd{} - -// NewStopCmd creates a new StopCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewStopCmd(id interface{}) (*StopCmd, error) { - - return &StopCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *StopCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *StopCmd) Method() string { - return "stop" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *StopCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *StopCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewStopCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// SubmitBlockOptions represents the optional options struct provided with -// a SubmitBlockCmd command. -type SubmitBlockOptions struct { - // must be provided if server provided a workid with template. - WorkID string `json:"workid,omitempty"` -} - -// SubmitBlockCmd is a type handling custom marshaling and -// unmarshaling of submitblock JSON RPC commands. -type SubmitBlockCmd struct { - id interface{} - HexBlock string - Options *SubmitBlockOptions -} - -// Enforce that SubmitBlockCmd satisifies the Cmd interface. -var _ Cmd = &SubmitBlockCmd{} - -// NewSubmitBlockCmd creates a new SubmitBlockCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewSubmitBlockCmd(id interface{}, hexblock string, optArgs ...*SubmitBlockOptions) (*SubmitBlockCmd, error) { - var options *SubmitBlockOptions - if len(optArgs) > 0 { - if len(optArgs) > 1 { - return nil, ErrTooManyOptArgs - } - options = optArgs[0] - } - - return &SubmitBlockCmd{ - id: id, - HexBlock: hexblock, - Options: options, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *SubmitBlockCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *SubmitBlockCmd) Method() string { - return "submitblock" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *SubmitBlockCmd) MarshalJSON() ([]byte, error) { - params := make([]interface{}, 1, 2) - params[0] = cmd.HexBlock - if cmd.Options != nil { - params = append(params, cmd.Options) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *SubmitBlockCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 || len(r.Params) < 1 { - return ErrWrongNumberOfParams - } - - var hexblock string - if err := json.Unmarshal(r.Params[0], &hexblock); err != nil { - return fmt.Errorf("first parameter 'hexblock' must be a string: %v", err) - } - - optArgs := make([]*SubmitBlockOptions, 0, 1) - if len(r.Params) == 2 { - var options SubmitBlockOptions - if err := json.Unmarshal(r.Params[1], &options); err != nil { - return fmt.Errorf("second optional parameter 'options' must "+ - "be a JSON object of submit block options: %v", err) - } - optArgs = append(optArgs, &options) - } - - newCmd, err := NewSubmitBlockCmd(r.Id, hexblock, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// ValidateAddressCmd is a type handling custom marshaling and -// unmarshaling of validateaddress JSON RPC commands. -type ValidateAddressCmd struct { - id interface{} - Address string -} - -// Enforce that ValidateAddressCmd satisifies the Cmd interface. -var _ Cmd = &ValidateAddressCmd{} - -// NewValidateAddressCmd creates a new ValidateAddressCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewValidateAddressCmd(id interface{}, address string) (*ValidateAddressCmd, error) { - - return &ValidateAddressCmd{ - id: id, - Address: address, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *ValidateAddressCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *ValidateAddressCmd) Method() string { - return "validateaddress" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *ValidateAddressCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Address, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *ValidateAddressCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 1 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - newCmd, err := NewValidateAddressCmd(r.Id, address) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// VerifyChainCmd is a type handling custom marshaling and -// unmarshaling of verifychain JSON RPC commands. -type VerifyChainCmd struct { - id interface{} - CheckLevel int32 - CheckDepth int32 -} - -// Enforce that VerifyChainCmd satisifies the Cmd interface. -var _ Cmd = &VerifyChainCmd{} - -// NewVerifyChainCmd creates a new VerifyChainCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewVerifyChainCmd(id interface{}, optArgs ...int32) (*VerifyChainCmd, error) { - // bitcoind default, but they do vary it based on cli args. - var checklevel int32 = 3 - var checkdepth int32 = 288 - - if len(optArgs) > 0 { - if len(optArgs) > 2 { - return nil, ErrTooManyOptArgs - } - checklevel = optArgs[0] - - if len(optArgs) > 1 { - checkdepth = optArgs[1] - } - } - - return &VerifyChainCmd{ - id: id, - CheckLevel: checklevel, - CheckDepth: checkdepth, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *VerifyChainCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *VerifyChainCmd) Method() string { - return "verifychain" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *VerifyChainCmd) MarshalJSON() ([]byte, error) { - // XXX(oga) magic numbers - params := make([]interface{}, 0, 2) - if cmd.CheckLevel != 3 || cmd.CheckDepth != 288 { - params = append(params, cmd.CheckLevel) - } - if cmd.CheckDepth != 288 { - params = append(params, cmd.CheckDepth) - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *VerifyChainCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) > 2 { - return ErrWrongNumberOfParams - } - - optArgs := make([]int32, 0, 2) - if len(r.Params) > 0 { - var checklevel int32 - if err := json.Unmarshal(r.Params[0], &checklevel); err != nil { - return fmt.Errorf("first optional parameter 'checklevel' must be a 32-bit integer: %v", err) - } - optArgs = append(optArgs, checklevel) - } - - if len(r.Params) > 1 { - var checkdepth int32 - if err := json.Unmarshal(r.Params[1], &checkdepth); err != nil { - return fmt.Errorf("second optional parameter 'checkdepth' must be a 32-bit integer: %v", err) - } - optArgs = append(optArgs, checkdepth) - } - - newCmd, err := NewVerifyChainCmd(r.Id, optArgs...) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// VerifyMessageCmd is a type handling custom marshaling and -// unmarshaling of verifymessage JSON RPC commands. -type VerifyMessageCmd struct { - id interface{} - Address string - Signature string - Message string -} - -// Enforce that VerifyMessageCmd satisifies the Cmd interface. -var _ Cmd = &VerifyMessageCmd{} - -// NewVerifyMessageCmd creates a new VerifyMessageCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewVerifyMessageCmd(id interface{}, address string, signature string, - message string) (*VerifyMessageCmd, error) { - - return &VerifyMessageCmd{ - id: id, - Address: address, - Signature: signature, - Message: message, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *VerifyMessageCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *VerifyMessageCmd) Method() string { - return "verifymessage" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *VerifyMessageCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Address, - cmd.Signature, - cmd.Message, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *VerifyMessageCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 3 { - return ErrWrongNumberOfParams - } - - var address string - if err := json.Unmarshal(r.Params[0], &address); err != nil { - return fmt.Errorf("first parameter 'address' must be a string: %v", err) - } - - var signature string - if err := json.Unmarshal(r.Params[1], &signature); err != nil { - return fmt.Errorf("second parameter 'signature' must be a string: %v", err) - } - - var message string - if err := json.Unmarshal(r.Params[2], &message); err != nil { - return fmt.Errorf("third parameter 'message' must be a string: %v", err) - } - - newCmd, err := NewVerifyMessageCmd(r.Id, address, signature, message) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// WalletLockCmd is a type handling custom marshaling and -// unmarshaling of walletlock JSON RPC commands. -type WalletLockCmd struct { - id interface{} -} - -// Enforce that WalletLockCmd satisifies the Cmd interface. -var _ Cmd = &WalletLockCmd{} - -// NewWalletLockCmd creates a new WalletLockCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewWalletLockCmd(id interface{}) (*WalletLockCmd, error) { - - return &WalletLockCmd{ - id: id, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *WalletLockCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *WalletLockCmd) Method() string { - return "walletlock" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *WalletLockCmd) MarshalJSON() ([]byte, error) { - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), []interface{}{}) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *WalletLockCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 0 { - return ErrWrongNumberOfParams - } - - newCmd, err := NewWalletLockCmd(r.Id) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// WalletPassphraseCmd is a type handling custom marshaling and -// unmarshaling of walletpassphrase JSON RPC commands. -type WalletPassphraseCmd struct { - id interface{} - Passphrase string - Timeout int64 -} - -// Enforce that WalletPassphraseCmd satisifies the Cmd interface. -var _ Cmd = &WalletPassphraseCmd{} - -// NewWalletPassphraseCmd creates a new WalletPassphraseCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewWalletPassphraseCmd(id interface{}, passphrase string, timeout int64) (*WalletPassphraseCmd, error) { - - return &WalletPassphraseCmd{ - id: id, - Passphrase: passphrase, - Timeout: timeout, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *WalletPassphraseCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *WalletPassphraseCmd) Method() string { - return "walletpassphrase" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *WalletPassphraseCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.Passphrase, - cmd.Timeout, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *WalletPassphraseCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 2 { - return ErrWrongNumberOfParams - } - - var passphrase string - if err := json.Unmarshal(r.Params[0], &passphrase); err != nil { - return fmt.Errorf("first parameter 'passphrase' must be a string: %v", err) - } - - var timeout int64 - if err := json.Unmarshal(r.Params[1], &timeout); err != nil { - return fmt.Errorf("second parameter 'timeout' must be an integer: %v", err) - } - - newCmd, err := NewWalletPassphraseCmd(r.Id, passphrase, timeout) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} - -// WalletPassphraseChangeCmd is a type handling custom marshaling and -// unmarshaling of walletpassphrasechange JSON RPC commands. -type WalletPassphraseChangeCmd struct { - id interface{} - OldPassphrase string - NewPassphrase string -} - -// Enforce that WalletPassphraseChangeCmd satisifies the Cmd interface. -var _ Cmd = &WalletPassphraseChangeCmd{} - -// NewWalletPassphraseChangeCmd creates a new WalletPassphraseChangeCmd. Optionally a -// pointer to a TemplateRequest may be provided. -func NewWalletPassphraseChangeCmd(id interface{}, oldpassphrase, newpassphrase string) (*WalletPassphraseChangeCmd, error) { - - return &WalletPassphraseChangeCmd{ - id: id, - OldPassphrase: oldpassphrase, - NewPassphrase: newpassphrase, - }, nil -} - -// Id satisfies the Cmd interface by returning the id of the command. -func (cmd *WalletPassphraseChangeCmd) Id() interface{} { - return cmd.id -} - -// Method satisfies the Cmd interface by returning the json method. -func (cmd *WalletPassphraseChangeCmd) Method() string { - return "walletpassphrasechange" -} - -// MarshalJSON returns the JSON encoding of cmd. Part of the Cmd interface. -func (cmd *WalletPassphraseChangeCmd) MarshalJSON() ([]byte, error) { - params := []interface{}{ - cmd.OldPassphrase, - cmd.NewPassphrase, - } - - // Fill and marshal a RawCmd. - raw, err := NewRawCmd(cmd.id, cmd.Method(), params) - if err != nil { - return nil, err - } - return json.Marshal(raw) -} - -// UnmarshalJSON unmarshals the JSON encoding of cmd into cmd. Part of -// the Cmd interface. -func (cmd *WalletPassphraseChangeCmd) UnmarshalJSON(b []byte) error { - // Unmarshal into a RawCmd - var r RawCmd - if err := json.Unmarshal(b, &r); err != nil { - return err - } - - if len(r.Params) != 2 { - return ErrWrongNumberOfParams - } - - var oldpassphrase string - if err := json.Unmarshal(r.Params[0], &oldpassphrase); err != nil { - return fmt.Errorf("first parameter 'oldpassphrase' must be a string: %v", err) - } - - var newpassphrase string - if err := json.Unmarshal(r.Params[1], &newpassphrase); err != nil { - return fmt.Errorf("second parameter 'newpassphrase' must be a string: %v", err) - } - - newCmd, err := NewWalletPassphraseChangeCmd(r.Id, oldpassphrase, newpassphrase) - if err != nil { - return err - } - - *cmd = *newCmd - return nil -} diff --git a/btcjson/jsoncmd_test.go b/btcjson/jsoncmd_test.go deleted file mode 100644 index c8e9fdca..00000000 --- a/btcjson/jsoncmd_test.go +++ /dev/null @@ -1,1814 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -// this has to be in the real json subpackage so we can mock up structs -package btcjson - -import ( - "encoding/json" - "reflect" - "strings" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -var testID = float64(1) - -var defaultAccount = "" -var testAccount = "account" - -var jsoncmdtests = []struct { - name string - cmd string - f func() (Cmd, error) - result Cmd // after marshal and unmarshal -}{ - { - name: "basic", - cmd: "addmultisigaddress", - f: func() (Cmd, error) { - return NewAddMultisigAddressCmd(testID, 1, - []string{"foo", "bar"}) - }, - result: &AddMultisigAddressCmd{ - id: testID, - NRequired: 1, - Keys: []string{"foo", "bar"}, - Account: defaultAccount, - }, - }, - { - name: "+ optional", - cmd: "addmultisigaddress", - f: func() (Cmd, error) { - return NewAddMultisigAddressCmd(testID, 1, - []string{"foo", "bar"}, "address") - }, - result: &AddMultisigAddressCmd{ - id: testID, - NRequired: 1, - Keys: []string{"foo", "bar"}, - Account: "address", - }, - }, - // TODO(oga) Too many arguments to newaddmultisigaddress - { - name: "basic add", - cmd: "addnode", - f: func() (Cmd, error) { - return NewAddNodeCmd(testID, "address", - "add") - }, - result: &AddNodeCmd{ - id: testID, - Addr: "address", - SubCmd: "add", - }, - }, - { - name: "basic remove", - cmd: "addnode", - f: func() (Cmd, error) { - return NewAddNodeCmd(testID, "address", - "remove") - }, - result: &AddNodeCmd{ - id: testID, - Addr: "address", - SubCmd: "remove", - }, - }, - { - name: "basic onetry", - cmd: "addnode", - f: func() (Cmd, error) { - return NewAddNodeCmd(testID, "address", - "onetry") - }, - result: &AddNodeCmd{ - id: testID, - Addr: "address", - SubCmd: "onetry", - }, - }, - // TODO(oga) try invalid subcmds - { - name: "basic", - cmd: "backupwallet", - f: func() (Cmd, error) { - return NewBackupWalletCmd(testID, "destination") - }, - result: &BackupWalletCmd{ - id: testID, - Destination: "destination", - }, - }, - { - name: "basic", - cmd: "createmultisig", - f: func() (Cmd, error) { - return NewCreateMultisigCmd(testID, 1, - []string{"key1", "key2", "key3"}) - }, - result: &CreateMultisigCmd{ - id: testID, - NRequired: 1, - Keys: []string{"key1", "key2", "key3"}, - }, - }, - { - name: "basic", - cmd: "createrawtransaction", - f: func() (Cmd, error) { - return NewCreateRawTransactionCmd(testID, - []TransactionInput{ - {Txid: "tx1", Vout: 1}, - {Txid: "tx2", Vout: 3}}, - map[string]int64{"bob": 1, "bill": 2}) - }, - result: &CreateRawTransactionCmd{ - id: testID, - Inputs: []TransactionInput{ - {Txid: "tx1", Vout: 1}, - {Txid: "tx2", Vout: 3}, - }, - Amounts: map[string]int64{ - "bob": 1, - "bill": 2, - }, - }, - }, - { - name: "basic", - cmd: "debuglevel", - f: func() (Cmd, error) { - return NewDebugLevelCmd(testID, "debug") - }, - result: &DebugLevelCmd{ - id: testID, - LevelSpec: "debug", - }, - }, - { - name: "basic", - cmd: "decoderawtransaction", - f: func() (Cmd, error) { - return NewDecodeRawTransactionCmd(testID, - "thisisahexidecimaltransaction") - }, - result: &DecodeRawTransactionCmd{ - id: testID, - HexTx: "thisisahexidecimaltransaction", - }, - }, - { - name: "basic", - cmd: "decodescript", - f: func() (Cmd, error) { - return NewDecodeScriptCmd(testID, - "a bunch of hex") - }, - result: &DecodeScriptCmd{ - id: testID, - HexScript: "a bunch of hex", - }, - }, - { - name: "basic", - cmd: "dumpprivkey", - f: func() (Cmd, error) { - return NewDumpPrivKeyCmd(testID, - "address") - }, - result: &DumpPrivKeyCmd{ - id: testID, - Address: "address", - }, - }, - { - name: "basic", - cmd: "dumpwallet", - f: func() (Cmd, error) { - return NewDumpWalletCmd(testID, - "filename") - }, - result: &DumpWalletCmd{ - id: testID, - Filename: "filename", - }, - }, - { - name: "basic", - cmd: "encryptwallet", - f: func() (Cmd, error) { - return NewEncryptWalletCmd(testID, - "passphrase") - }, - result: &EncryptWalletCmd{ - id: testID, - Passphrase: "passphrase", - }, - }, - { - name: "basic", - cmd: "estimatefee", - f: func() (Cmd, error) { - return NewEstimateFeeCmd(testID, 1234) - }, - result: &EstimateFeeCmd{ - id: testID, - NumBlocks: 1234, - }, - }, - { - name: "basic", - cmd: "estimatepriority", - f: func() (Cmd, error) { - return NewEstimatePriorityCmd(testID, 1234) - }, - result: &EstimatePriorityCmd{ - id: testID, - NumBlocks: 1234, - }, - }, - { - name: "basic", - cmd: "getaccount", - f: func() (Cmd, error) { - return NewGetAccountCmd(testID, - "address") - }, - result: &GetAccountCmd{ - id: testID, - Address: "address", - }, - }, - { - name: "basic", - cmd: "getaccountaddress", - f: func() (Cmd, error) { - return NewGetAccountAddressCmd(testID, - testAccount) - }, - result: &GetAccountAddressCmd{ - id: testID, - Account: testAccount, - }, - }, - { - name: "basic true", - cmd: "getaddednodeinfo", - f: func() (Cmd, error) { - return NewGetAddedNodeInfoCmd(testID, true) - }, - result: &GetAddedNodeInfoCmd{ - id: testID, - Dns: true, - }, - }, - { - name: "basic false", - cmd: "getaddednodeinfo", - f: func() (Cmd, error) { - return NewGetAddedNodeInfoCmd(testID, false) - }, - result: &GetAddedNodeInfoCmd{ - id: testID, - Dns: false, - }, - }, - { - name: "basic withnode", - cmd: "getaddednodeinfo", - f: func() (Cmd, error) { - return NewGetAddedNodeInfoCmd(testID, true, - "thisisanode") - }, - result: &GetAddedNodeInfoCmd{ - id: testID, - Dns: true, - Node: "thisisanode", - }, - }, - { - name: "basic", - cmd: "getaddressesbyaccount", - f: func() (Cmd, error) { - return NewGetAddressesByAccountCmd(testID, - testAccount) - }, - result: &GetAddressesByAccountCmd{ - id: testID, - Account: testAccount, - }, - }, - { - name: "basic", - cmd: "getbalance", - f: func() (Cmd, error) { - return NewGetBalanceCmd(testID) - }, - result: &GetBalanceCmd{ - id: testID, - MinConf: 1, // the default - }, - }, - { - name: "basic + account", - cmd: "getbalance", - f: func() (Cmd, error) { - return NewGetBalanceCmd(testID, testAccount) - }, - result: &GetBalanceCmd{ - id: testID, - Account: &testAccount, - MinConf: 1, // the default - }, - }, - { - name: "basic + minconf", - cmd: "getbalance", - f: func() (Cmd, error) { - return NewGetBalanceCmd(testID, defaultAccount, 2) - }, - result: &GetBalanceCmd{ - id: testID, - Account: &defaultAccount, - MinConf: 2, - }, - }, - { - name: "basic + account + minconf", - cmd: "getbalance", - f: func() (Cmd, error) { - return NewGetBalanceCmd(testID, testAccount, 2) - }, - result: &GetBalanceCmd{ - id: testID, - Account: &testAccount, - MinConf: 2, - }, - }, - { - name: "basic", - cmd: "getbestblockhash", - f: func() (Cmd, error) { - return NewGetBestBlockHashCmd(testID) - }, - result: &GetBestBlockHashCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getblock", - f: func() (Cmd, error) { - return NewGetBlockCmd(testID, - "somehash") - }, - result: &GetBlockCmd{ - id: testID, - Hash: "somehash", - Verbose: true, - }, - }, - { - name: "basic", - cmd: "getblockchaininfo", - f: func() (Cmd, error) { - return NewGetBlockChainInfoCmd(testID) - }, - result: &GetBlockChainInfoCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getblockcount", - f: func() (Cmd, error) { - return NewGetBlockCountCmd(testID) - }, - result: &GetBlockCountCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getblockhash", - f: func() (Cmd, error) { - return NewGetBlockHashCmd(testID, 1234) - }, - result: &GetBlockHashCmd{ - id: testID, - Index: 1234, - }, - }, - { - name: "basic", - cmd: "getblocktemplate", - f: func() (Cmd, error) { - return NewGetBlockTemplateCmd(testID) - }, - result: &GetBlockTemplateCmd{ - id: testID, - }, - }, - { - name: "basic + request", - cmd: "getblocktemplate", - f: func() (Cmd, error) { - return NewGetBlockTemplateCmd(testID, - &TemplateRequest{Mode: "mode", - Capabilities: []string{"one", "two", "three"}}) - }, - result: &GetBlockTemplateCmd{ - id: testID, - Request: &TemplateRequest{ - Mode: "mode", - Capabilities: []string{ - "one", - "two", - "three", - }, - }, - }, - }, - { - name: "basic + request no mode", - cmd: "getblocktemplate", - f: func() (Cmd, error) { - return NewGetBlockTemplateCmd(testID, - &TemplateRequest{ - Capabilities: []string{"one", "two", "three"}}) - }, - result: &GetBlockTemplateCmd{ - id: testID, - Request: &TemplateRequest{ - Capabilities: []string{ - "one", - "two", - "three", - }, - }, - }, - }, - { - name: "basic", - cmd: "getconnectioncount", - f: func() (Cmd, error) { - return NewGetConnectionCountCmd(testID) - }, - result: &GetConnectionCountCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getdifficulty", - f: func() (Cmd, error) { - return NewGetDifficultyCmd(testID) - }, - result: &GetDifficultyCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getgenerate", - f: func() (Cmd, error) { - return NewGetGenerateCmd(testID) - }, - result: &GetGenerateCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "gethashespersec", - f: func() (Cmd, error) { - return NewGetHashesPerSecCmd(testID) - }, - result: &GetHashesPerSecCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getinfo", - f: func() (Cmd, error) { - return NewGetInfoCmd(testID) - }, - result: &GetInfoCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getmininginfo", - f: func() (Cmd, error) { - return NewGetMiningInfoCmd(testID) - }, - result: &GetMiningInfoCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getnettotals", - f: func() (Cmd, error) { - return NewGetNetTotalsCmd(testID) - }, - result: &GetNetTotalsCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getnetworkhashps", - f: func() (Cmd, error) { - return NewGetNetworkHashPSCmd(testID) - }, - result: &GetNetworkHashPSCmd{ - id: testID, - Blocks: 120, - Height: -1, - }, - }, - { - name: "basic + blocks", - cmd: "getnetworkhashps", - f: func() (Cmd, error) { - return NewGetNetworkHashPSCmd(testID, 5000) - }, - result: &GetNetworkHashPSCmd{ - id: testID, - Blocks: 5000, - Height: -1, - }, - }, - { - name: "basic + blocks + height", - cmd: "getnetworkhashps", - f: func() (Cmd, error) { - return NewGetNetworkHashPSCmd(testID, 5000, 1000) - }, - result: &GetNetworkHashPSCmd{ - id: testID, - Blocks: 5000, - Height: 1000, - }, - }, - { - name: "basic", - cmd: "getnetworkinfo", - f: func() (Cmd, error) { - return NewGetNetworkInfoCmd(testID) - }, - result: &GetNetworkInfoCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getnewaddress", - f: func() (Cmd, error) { - return NewGetNewAddressCmd(testID, testAccount) - }, - result: &GetNewAddressCmd{ - id: testID, - Account: testAccount, - }, - }, - { - name: "basic", - cmd: "getpeerinfo", - f: func() (Cmd, error) { - return NewGetPeerInfoCmd(testID) - }, - result: &GetPeerInfoCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getrawchangeaddress", - f: func() (Cmd, error) { - return NewGetRawChangeAddressCmd(testID) - }, - result: &GetRawChangeAddressCmd{ - id: testID, - }, - }, - { - name: "basic + account", - cmd: "getrawchangeaddress", - f: func() (Cmd, error) { - return NewGetRawChangeAddressCmd(testID, - "accountname") - }, - result: &GetRawChangeAddressCmd{ - id: testID, - Account: "accountname", - }, - }, - { - name: "basic", - cmd: "getrawmempool", - f: func() (Cmd, error) { - return NewGetRawMempoolCmd(testID) - }, - result: &GetRawMempoolCmd{ - id: testID, - }, - }, - { - name: "basic noverbose", - cmd: "getrawmempool", - f: func() (Cmd, error) { - return NewGetRawMempoolCmd(testID, false) - }, - result: &GetRawMempoolCmd{ - id: testID, - }, - }, - { - name: "basic verbose", - cmd: "getrawmempool", - f: func() (Cmd, error) { - return NewGetRawMempoolCmd(testID, true) - }, - result: &GetRawMempoolCmd{ - id: testID, - Verbose: true, - }, - }, - { - name: "basic", - cmd: "getrawtransaction", - f: func() (Cmd, error) { - return NewGetRawTransactionCmd(testID, - "sometxid") - }, - result: &GetRawTransactionCmd{ - id: testID, - Txid: "sometxid", - }, - }, - { - name: "basic + verbose", - cmd: "getrawtransaction", - f: func() (Cmd, error) { - return NewGetRawTransactionCmd(testID, - "sometxid", - 1) - }, - result: &GetRawTransactionCmd{ - id: testID, - Txid: "sometxid", - Verbose: 1, - }, - }, - { - name: "basic", - cmd: "getreceivedbyaccount", - f: func() (Cmd, error) { - return NewGetReceivedByAccountCmd(testID, - "abtcaccount", - 1) - }, - result: &GetReceivedByAccountCmd{ - id: testID, - Account: "abtcaccount", - MinConf: 1, - }, - }, - { - name: "basic + opt", - cmd: "getreceivedbyaccount", - f: func() (Cmd, error) { - return NewGetReceivedByAccountCmd(testID, - "abtcaccount", - 2) - }, - result: &GetReceivedByAccountCmd{ - id: testID, - Account: "abtcaccount", - MinConf: 2, - }, - }, - { - name: "basic", - cmd: "getreceivedbyaddress", - f: func() (Cmd, error) { - return NewGetReceivedByAddressCmd(testID, - "abtcaddress", - 1) - }, - result: &GetReceivedByAddressCmd{ - id: testID, - Address: "abtcaddress", - MinConf: 1, - }, - }, - { - name: "basic + opt", - cmd: "getreceivedbyaddress", - f: func() (Cmd, error) { - return NewGetReceivedByAddressCmd(testID, - "abtcaddress", - 2) - }, - result: &GetReceivedByAddressCmd{ - id: testID, - Address: "abtcaddress", - MinConf: 2, - }, - }, - { - name: "basic", - cmd: "gettransaction", - f: func() (Cmd, error) { - return NewGetTransactionCmd(testID, - "atxid") - }, - result: &GetTransactionCmd{ - id: testID, - Txid: "atxid", - }, - }, - { - name: "basic", - cmd: "gettxout", - f: func() (Cmd, error) { - return NewGetTxOutCmd(testID, - "sometx", - 10) - }, - result: &GetTxOutCmd{ - id: testID, - Txid: "sometx", - Output: 10, - IncludeMempool: true, - }, - }, - { - name: "basic + optional", - cmd: "gettxout", - f: func() (Cmd, error) { - return NewGetTxOutCmd(testID, - "sometx", - 10, - false) - }, - result: &GetTxOutCmd{ - id: testID, - Txid: "sometx", - Output: 10, - IncludeMempool: false, - }, - }, - { - name: "basic", - cmd: "gettxoutsetinfo", - f: func() (Cmd, error) { - return NewGetTxOutSetInfoCmd(testID) - }, - result: &GetTxOutSetInfoCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "getwork", - f: func() (Cmd, error) { - return NewGetWorkCmd(testID, "some data") - }, - result: &GetWorkCmd{ - id: testID, - Data: "some data", - }, - }, - { - name: "basic", - cmd: "help", - f: func() (Cmd, error) { - return NewHelpCmd(testID) - }, - result: &HelpCmd{ - id: testID, - }, - }, - { - name: "basic + optional cmd", - cmd: "help", - f: func() (Cmd, error) { - return NewHelpCmd(testID, - "getinfo") - }, - result: &HelpCmd{ - id: testID, - Command: "getinfo", - }, - }, - { - name: "basic", - cmd: "importaddress", - f: func() (Cmd, error) { - return NewImportAddressCmd(testID, - "address") - }, - result: &ImportAddressCmd{ - id: testID, - Address: "address", - Rescan: true, - }, - }, - { - name: "basic + optional cmd", - cmd: "importaddress", - f: func() (Cmd, error) { - return NewImportAddressCmd(testID, - "address", false) - }, - result: &ImportAddressCmd{ - id: testID, - Address: "address", - Rescan: false, - }, - }, - { - name: "basic", - cmd: "importpubkey", - f: func() (Cmd, error) { - return NewImportPubKeyCmd(testID, - "pubkey") - }, - result: &ImportPubKeyCmd{ - id: testID, - PubKey: "pubkey", - Rescan: true, - }, - }, - { - name: "basic + optional cmd", - cmd: "importpubkey", - f: func() (Cmd, error) { - return NewImportPubKeyCmd(testID, - "pubkey", false) - }, - result: &ImportPubKeyCmd{ - id: testID, - PubKey: "pubkey", - Rescan: false, - }, - }, - { - name: "basic", - cmd: "importprivkey", - f: func() (Cmd, error) { - return NewImportPrivKeyCmd(testID, - "somereallongprivatekey") - }, - result: &ImportPrivKeyCmd{ - id: testID, - PrivKey: "somereallongprivatekey", - Rescan: true, - }, - }, - { - name: "basic + 1 opt", - cmd: "importprivkey", - f: func() (Cmd, error) { - return NewImportPrivKeyCmd(testID, - "somereallongprivatekey", - "some text") - }, - result: &ImportPrivKeyCmd{ - id: testID, - PrivKey: "somereallongprivatekey", - Label: "some text", - Rescan: true, - }, - }, - { - name: "basic + 2 opts", - cmd: "importprivkey", - f: func() (Cmd, error) { - return NewImportPrivKeyCmd(testID, - "somereallongprivatekey", - "some text", - false) - }, - result: &ImportPrivKeyCmd{ - id: testID, - PrivKey: "somereallongprivatekey", - Label: "some text", - Rescan: false, - }, - }, - { - name: "basic", - cmd: "importwallet", - f: func() (Cmd, error) { - return NewImportWalletCmd(testID, - "walletfilename.dat") - }, - result: &ImportWalletCmd{ - id: testID, - Filename: "walletfilename.dat", - }, - }, - { - name: "basic", - cmd: "invalidateblock", - f: func() (Cmd, error) { - return NewInvalidateBlockCmd(testID, - "lotsofhex") - }, - result: &InvalidateBlockCmd{ - id: testID, - BlockHash: "lotsofhex", - }, - }, - { - name: "basic", - cmd: "keypoolrefill", - f: func() (Cmd, error) { - return NewKeyPoolRefillCmd(testID) - }, - result: &KeyPoolRefillCmd{ - id: testID, - }, - }, - { - name: "newsize", - cmd: "keypoolrefill", - f: func() (Cmd, error) { - return NewKeyPoolRefillCmd(testID, 1000000) - }, - result: &KeyPoolRefillCmd{ - id: testID, - NewSize: 1000000, - }, - }, - { - name: "basic", - cmd: "listaccounts", - f: func() (Cmd, error) { - return NewListAccountsCmd(testID, 1) - }, - result: &ListAccountsCmd{ - id: testID, - MinConf: 1, - }, - }, - { - name: "basic + opt", - cmd: "listaccounts", - f: func() (Cmd, error) { - return NewListAccountsCmd(testID, 2) - }, - result: &ListAccountsCmd{ - id: testID, - MinConf: 2, - }, - }, - { - name: "basic", - cmd: "listaddressgroupings", - f: func() (Cmd, error) { - return NewListAddressGroupingsCmd(testID) - }, - result: &ListAddressGroupingsCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "listlockunspent", - f: func() (Cmd, error) { - return NewListLockUnspentCmd(testID) - }, - result: &ListLockUnspentCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "listreceivedbyaccount", - f: func() (Cmd, error) { - return NewListReceivedByAccountCmd(testID) - }, - result: &ListReceivedByAccountCmd{ - id: testID, - MinConf: 1, - }, - }, - { - name: "basic + 1 opt", - cmd: "listreceivedbyaccount", - f: func() (Cmd, error) { - return NewListReceivedByAccountCmd(testID, 2) - }, - result: &ListReceivedByAccountCmd{ - id: testID, - MinConf: 2, - }, - }, - { - name: "basic + 2 opt", - cmd: "listreceivedbyaccount", - f: func() (Cmd, error) { - return NewListReceivedByAccountCmd(testID, 2, true) - }, - result: &ListReceivedByAccountCmd{ - id: testID, - MinConf: 2, - IncludeEmpty: true, - }, - }, - { - name: "basic", - cmd: "listreceivedbyaddress", - f: func() (Cmd, error) { - return NewListReceivedByAddressCmd(testID) - }, - result: &ListReceivedByAddressCmd{ - id: testID, - MinConf: 1, - }, - }, - { - name: "basic + 1 opt", - cmd: "listreceivedbyaddress", - f: func() (Cmd, error) { - return NewListReceivedByAddressCmd(testID, 2) - }, - result: &ListReceivedByAddressCmd{ - id: testID, - MinConf: 2, - }, - }, - { - name: "basic + 2 opt", - cmd: "listreceivedbyaddress", - f: func() (Cmd, error) { - return NewListReceivedByAddressCmd(testID, 2, true) - }, - result: &ListReceivedByAddressCmd{ - id: testID, - MinConf: 2, - IncludeEmpty: true, - }, - }, - { - name: "basic", - cmd: "listsinceblock", - f: func() (Cmd, error) { - return NewListSinceBlockCmd(testID) - }, - result: &ListSinceBlockCmd{ - id: testID, - TargetConfirmations: 1, - }, - }, - { - name: "basic + 1 ops", - cmd: "listsinceblock", - f: func() (Cmd, error) { - return NewListSinceBlockCmd(testID, "someblockhash") - }, - result: &ListSinceBlockCmd{ - id: testID, - BlockHash: "someblockhash", - TargetConfirmations: 1, - }, - }, - { - name: "basic + 2 ops", - cmd: "listsinceblock", - f: func() (Cmd, error) { - return NewListSinceBlockCmd(testID, "someblockhash", 3) - }, - result: &ListSinceBlockCmd{ - id: testID, - BlockHash: "someblockhash", - TargetConfirmations: 3, - }, - }, - { - name: "basic", - cmd: "listtransactions", - f: func() (Cmd, error) { - return NewListTransactionsCmd(testID) - }, - result: &ListTransactionsCmd{ - id: testID, - Account: nil, - Count: 10, - From: 0, - }, - }, - { - name: "+ 1 optarg", - cmd: "listtransactions", - f: func() (Cmd, error) { - return NewListTransactionsCmd(testID, testAccount) - }, - result: &ListTransactionsCmd{ - id: testID, - Account: &testAccount, - Count: 10, - From: 0, - }, - }, - { - name: "+ 2 optargs", - cmd: "listtransactions", - f: func() (Cmd, error) { - return NewListTransactionsCmd(testID, testAccount, 123) - }, - result: &ListTransactionsCmd{ - id: testID, - Account: &testAccount, - Count: 123, - From: 0, - }, - }, - { - name: "+ 3 optargs", - cmd: "listtransactions", - f: func() (Cmd, error) { - return NewListTransactionsCmd(testID, testAccount, 123, 456) - }, - result: &ListTransactionsCmd{ - id: testID, - Account: &testAccount, - Count: 123, - From: 456, - }, - }, - { - name: "basic", - cmd: "listunspent", - f: func() (Cmd, error) { - return NewListUnspentCmd(testID) - }, - result: &ListUnspentCmd{ - id: testID, - MinConf: 1, - MaxConf: 999999, - }, - }, - { - name: "basic + opts", - cmd: "listunspent", - f: func() (Cmd, error) { - return NewListUnspentCmd(testID, 0, 6) - }, - result: &ListUnspentCmd{ - id: testID, - MinConf: 0, - MaxConf: 6, - }, - }, - { - name: "basic + opts + addresses", - cmd: "listunspent", - f: func() (Cmd, error) { - return NewListUnspentCmd(testID, 0, 6, []string{ - "a", "b", "c", - }) - }, - result: &ListUnspentCmd{ - id: testID, - MinConf: 0, - MaxConf: 6, - Addresses: []string{"a", "b", "c"}, - }, - }, - { - name: "basic", - cmd: "lockunspent", - f: func() (Cmd, error) { - return NewLockUnspentCmd(testID, true) - }, - result: &LockUnspentCmd{ - id: testID, - Unlock: true, - }, - }, - { - name: "basic", - cmd: "move", - f: func() (Cmd, error) { - return NewMoveCmd(testID, - "account1", - "account2", - 12, - 1) - }, - result: &MoveCmd{ - id: testID, - FromAccount: "account1", - ToAccount: "account2", - Amount: 12, - MinConf: 1, // the default - }, - }, - { - name: "basic + optionals", - cmd: "move", - f: func() (Cmd, error) { - return NewMoveCmd(testID, - "account1", - "account2", - 12, - 1, - "some comment") - }, - result: &MoveCmd{ - id: testID, - FromAccount: "account1", - ToAccount: "account2", - Amount: 12, - MinConf: 1, // the default - Comment: "some comment", - }, - }, - { - name: "basic", - cmd: "ping", - f: func() (Cmd, error) { - return NewPingCmd(testID) - }, - result: &PingCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "reconsiderblock", - f: func() (Cmd, error) { - return NewReconsiderBlockCmd(testID, - "lotsofhex") - }, - result: &ReconsiderBlockCmd{ - id: testID, - BlockHash: "lotsofhex", - }, - }, - { - name: "basic + optionals", - cmd: "searchrawtransactions", - f: func() (Cmd, error) { - return NewSearchRawTransactionsCmd(testID, - "someaddr", 1, 5, 200) - }, - result: &SearchRawTransactionsCmd{ - id: testID, - Address: "someaddr", - Verbose: 1, - Skip: 5, - Count: 200, - }, - }, - { - name: "basic", - cmd: "sendfrom", - f: func() (Cmd, error) { - return NewSendFromCmd(testID, - testAccount, - "address", - 12, - 1) - }, - result: &SendFromCmd{ - id: testID, - FromAccount: testAccount, - ToAddress: "address", - Amount: 12, - MinConf: 1, // the default - }, - }, - { - name: "basic + options", - cmd: "sendfrom", - f: func() (Cmd, error) { - return NewSendFromCmd(testID, - testAccount, - "address", - 12, - 1, - "a comment", - "comment to") - }, - result: &SendFromCmd{ - id: testID, - FromAccount: testAccount, - ToAddress: "address", - Amount: 12, - MinConf: 1, // the default - Comment: "a comment", - CommentTo: "comment to", - }, - }, - { - name: "basic", - cmd: "sendmany", - f: func() (Cmd, error) { - pairs := map[string]int64{ - "address A": 1000, - "address B": 2000, - "address C": 3000, - } - return NewSendManyCmd(testID, - testAccount, - pairs) - }, - result: &SendManyCmd{ - id: testID, - FromAccount: testAccount, - Amounts: map[string]int64{ - "address A": 1000, - "address B": 2000, - "address C": 3000, - }, - MinConf: 1, // the default - }, - }, - { - name: "+ options", - cmd: "sendmany", - f: func() (Cmd, error) { - pairs := map[string]int64{ - "address A": 1000, - "address B": 2000, - "address C": 3000, - } - return NewSendManyCmd(testID, - testAccount, - pairs, - 10, - "comment") - }, - result: &SendManyCmd{ - id: testID, - FromAccount: testAccount, - Amounts: map[string]int64{ - "address A": 1000, - "address B": 2000, - "address C": 3000, - }, - MinConf: 10, - Comment: "comment", - }, - }, - { - name: "basic", - cmd: "sendrawtransaction", - f: func() (Cmd, error) { - return NewSendRawTransactionCmd(testID, - "hexstringofatx") - }, - result: &SendRawTransactionCmd{ - id: testID, - HexTx: "hexstringofatx", - }, - }, - { - name: "allowhighfees: false", - cmd: "sendrawtransaction", - f: func() (Cmd, error) { - return NewSendRawTransactionCmd(testID, - "hexstringofatx", false) - }, - result: &SendRawTransactionCmd{ - id: testID, - HexTx: "hexstringofatx", - }, - }, - { - name: "allowhighfees: true", - cmd: "sendrawtransaction", - f: func() (Cmd, error) { - return NewSendRawTransactionCmd(testID, - "hexstringofatx", true) - }, - result: &SendRawTransactionCmd{ - id: testID, - HexTx: "hexstringofatx", - AllowHighFees: true, - }, - }, - { - name: "basic", - cmd: "sendtoaddress", - f: func() (Cmd, error) { - return NewSendToAddressCmd(testID, - "somebtcaddress", - 1) - }, - result: &SendToAddressCmd{ - id: testID, - Address: "somebtcaddress", - Amount: 1, - }, - }, - { - name: "basic + optional", - cmd: "sendtoaddress", - f: func() (Cmd, error) { - return NewSendToAddressCmd(testID, - "somebtcaddress", - 1, - "a comment", - "comment to") - }, - result: &SendToAddressCmd{ - id: testID, - Address: "somebtcaddress", - Amount: 1, - Comment: "a comment", - CommentTo: "comment to", - }, - }, - { - name: "basic", - cmd: "setaccount", - f: func() (Cmd, error) { - return NewSetAccountCmd(testID, - "somebtcaddress", - "account name") - }, - result: &SetAccountCmd{ - id: testID, - Address: "somebtcaddress", - Account: "account name", - }, - }, - { - name: "basic", - cmd: "setgenerate", - f: func() (Cmd, error) { - return NewSetGenerateCmd(testID, true) - }, - result: &SetGenerateCmd{ - id: testID, - Generate: true, - GenProcLimit: -1, - }, - }, - { - name: "basic + optional", - cmd: "setgenerate", - f: func() (Cmd, error) { - return NewSetGenerateCmd(testID, true, 10) - }, - result: &SetGenerateCmd{ - id: testID, - Generate: true, - GenProcLimit: 10, - }, - }, - { - name: "basic", - cmd: "settxfee", - f: func() (Cmd, error) { - return NewSetTxFeeCmd(testID, 10) - }, - result: &SetTxFeeCmd{ - id: testID, - Amount: 10, - }, - }, - { - name: "basic", - cmd: "signmessage", - f: func() (Cmd, error) { - return NewSignMessageCmd(testID, - "btcaddress", - "a message") - }, - result: &SignMessageCmd{ - id: testID, - Address: "btcaddress", - Message: "a message", - }, - }, - { - name: "basic", - cmd: "signrawtransaction", - f: func() (Cmd, error) { - return NewSignRawTransactionCmd(testID, - "sometxstring") - }, - result: &SignRawTransactionCmd{ - id: testID, - RawTx: "sometxstring", - }, - }, - /* { - name: "basic + optional", - cmd: "signrawtransaction", - f: func() (Cmd, error) { - return NewSignRawTransactionCmd(testID, - "sometxstring", - []RawTxInput{ - RawTxInput{ - Txid: "test", - Vout: 1, - ScriptPubKey: "test", - RedeemScript: "test", - }, - }, - []string{"aprivatekey", "privkey2"}, - "flags") - }, - result: &SignRawTransactionCmd{ - id: testID, - RawTx: "sometxstring", - Inputs: []RawTxInput{ - RawTxInput{ - Txid: "test", - Vout: 1, - ScriptPubKey: "test", - RedeemScript: "test", - }, - }, - PrivKeys: []string{"aprivatekey", "privkey2"}, - Flags: "flags", - }, - },*/ - { - name: "basic", - cmd: "stop", - f: func() (Cmd, error) { - return NewStopCmd(testID) - }, - result: &StopCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "submitblock", - f: func() (Cmd, error) { - return NewSubmitBlockCmd(testID, - "lotsofhex") - }, - result: &SubmitBlockCmd{ - id: testID, - HexBlock: "lotsofhex", - }, - }, - { - name: "+ optional object", - cmd: "submitblock", - f: func() (Cmd, error) { - return NewSubmitBlockCmd(testID, - "lotsofhex", - &SubmitBlockOptions{WorkID: "otherstuff"}) - }, - result: &SubmitBlockCmd{ - id: testID, - HexBlock: "lotsofhex", - Options: &SubmitBlockOptions{WorkID: "otherstuff"}, - }, - }, - { - name: "basic", - cmd: "validateaddress", - f: func() (Cmd, error) { - return NewValidateAddressCmd(testID, - "somebtcaddress") - }, - result: &ValidateAddressCmd{ - id: testID, - Address: "somebtcaddress", - }, - }, - { - name: "basic", - cmd: "verifychain", - f: func() (Cmd, error) { - return NewVerifyChainCmd(testID) - }, - result: &VerifyChainCmd{ - id: testID, - CheckLevel: 3, - CheckDepth: 288, - }, - }, - { - name: "basic + optional", - cmd: "verifychain", - f: func() (Cmd, error) { - return NewVerifyChainCmd(testID, 4, 1) - }, - result: &VerifyChainCmd{ - id: testID, - CheckLevel: 4, - CheckDepth: 1, - }, - }, - { - name: "basic", - cmd: "verifymessage", - f: func() (Cmd, error) { - return NewVerifyMessageCmd(testID, - "someaddress", - "somesig", - "a message") - }, - result: &VerifyMessageCmd{ - id: testID, - Address: "someaddress", - Signature: "somesig", - Message: "a message", - }, - }, - { - name: "basic", - cmd: "walletlock", - f: func() (Cmd, error) { - return NewWalletLockCmd(testID) - }, - result: &WalletLockCmd{ - id: testID, - }, - }, - { - name: "basic", - cmd: "walletpassphrase", - f: func() (Cmd, error) { - return NewWalletPassphraseCmd(testID, - "phrase1", - 10) - }, - result: &WalletPassphraseCmd{ - id: testID, - Passphrase: "phrase1", - Timeout: 10, - }, - }, - { - name: "basic", - cmd: "walletpassphrasechange", - f: func() (Cmd, error) { - return NewWalletPassphraseChangeCmd(testID, - "phrase1", "phrase2") - }, - result: &WalletPassphraseChangeCmd{ - id: testID, - OldPassphrase: "phrase1", - NewPassphrase: "phrase2", - }, - }, -} - -func TestCmds(t *testing.T) { - for _, test := range jsoncmdtests { - c, err := test.f() - name := test.cmd + " " + test.name - if err != nil { - t.Errorf("%s: failed to run func: %v", - name, err) - continue - } - - msg, err := json.Marshal(c) - if err != nil { - t.Errorf("%s: failed to marshal cmd: %v", - name, err) - continue - } - - c2, err := ParseMarshaledCmd(msg) - if err != nil { - t.Errorf("%s: failed to ummarshal cmd: %v", - name, err) - continue - } - - id, ok := (c.Id()).(float64) - if !ok || id != testID { - t.Errorf("%s: id not returned properly", name) - } - - if c.Method() != test.cmd { - t.Errorf("%s: Method name not returned properly: "+ - "%s vs. %s", name, c.Method(), test.cmd) - } - - if !reflect.DeepEqual(test.result, c2) { - t.Errorf("%s: unmarshal not as expected. "+ - "got %v wanted %v", name, spew.Sdump(c2), - spew.Sdump(test.result)) - } - if !reflect.DeepEqual(c, c2) { - t.Errorf("%s: unmarshal not as we started with. "+ - "got %v wanted %v", name, spew.Sdump(c2), - spew.Sdump(c)) - } - } -} - -func TestHelps(t *testing.T) { - helpTests := []string{ - "addmultisigaddress", - "addnode", - "backupwallet", - "createmultisig", - "createrawtransaction", - "debuglevel", - "decoderawtransaction", - "decodescript", - "dumpprivkey", - "dumpwallet", - "encryptwallet", - "estimatefee", - "estimatepriority", - "getaccount", - "getaccountaddress", - "getaddednodeinfo", - "getaddressesbyaccount", - "getbalance", - "getbestblockhash", - "getblock", - "getblockcount", - "getblockhash", - "getblocktemplate", - "getconnectioncount", - "getdifficulty", - "getgenerate", - "gethashespersec", - "getinfo", - "getmininginfo", - "getnettotals", - "getnetworkhashps", - "getnewaddress", - "getpeerinfo", - "getrawchangeaddress", - "getrawmempool", - "getrawtransaction", - "getreceivedbyaccount", - "getreceivedbyaddress", - "gettransaction", - "gettxout", - "gettxoutsetinfo", - "getwork", - "help", - "importprivkey", - "importwallet", - "invalidateblock", - "keypoolrefill", - "listaccounts", - "listaddressgroupings", - "listlockunspent", - "listreceivedbyaccount", - "listreceivedbyaddress", - "listsinceblock", - "listtransactions", - "listunspent", - "lockunspent", - "move", - "ping", - "reconsiderblock", - "searchrawtransactions", - "sendfrom", - "sendmany", - "sendrawtransaction", - "sendtoaddress", - "setaccount", - "setgenerate", - "settxfee", - "signmessage", - "signrawtransaction", - "stop", - "submitblock", - "validateaddress", - "verifychain", - "verifymessage", - "walletlock", - "walletpassphrase", - "walletpassphrasechange", - } - - for _, test := range helpTests { - helpStr, err := GetHelpString(test) - if err != nil { - t.Errorf("%s: failed to get help string: %v", - test, err) - continue - } - - if !strings.HasPrefix(helpStr, test) { - t.Errorf("%s: help string doesn't begin with command "+ - "name: \"%s\"", test, helpStr) - continue - } - } -} diff --git a/btcjson/jsonerr.go b/btcjson/jsonerr.go deleted file mode 100644 index 87c07f1e..00000000 --- a/btcjson/jsonerr.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson - -// Standard JSON-RPC 2.0 errors -var ( - ErrInvalidRequest = Error{ - Code: -32600, - Message: "Invalid request", - } - ErrMethodNotFound = Error{ - Code: -32601, - Message: "Method not found", - } - ErrInvalidParams = Error{ - Code: -32602, - Message: "Invalid paramaters", - } - ErrInternal = Error{ - Code: -32603, - Message: "Internal error", - } - ErrParse = Error{ - Code: -32700, - Message: "Parse error", - } -) - -// General application defined JSON errors -var ( - ErrMisc = Error{ - Code: -1, - Message: "Miscellaneous error", - } - ErrForbiddenBySafeMode = Error{ - Code: -2, - Message: "Server is in safe mode, and command is not allowed in safe mode", - } - ErrType = Error{ - Code: -3, - Message: "Unexpected type was passed as parameter", - } - ErrInvalidAddressOrKey = Error{ - Code: -5, - Message: "Invalid address or key", - } - ErrOutOfMemory = Error{ - Code: -7, - Message: "Ran out of memory during operation", - } - ErrInvalidParameter = Error{ - Code: -8, - Message: "Invalid, missing or duplicate parameter", - } - ErrDatabase = Error{ - Code: -20, - Message: "Database error", - } - ErrDeserialization = Error{ - Code: -22, - Message: "Error parsing or validating structure in raw format", - } -) - -// Peer-to-peer client errors -var ( - ErrClientNotConnected = Error{ - Code: -9, - Message: "Bitcoin is not connected", - } - ErrClientInInitialDownload = Error{ - Code: -10, - Message: "Bitcoin is downloading blocks...", - } -) - -// Wallet JSON errors -var ( - ErrWallet = Error{ - Code: -4, - Message: "Unspecified problem with wallet", - } - ErrWalletInsufficientFunds = Error{ - Code: -6, - Message: "Not enough funds in wallet or account", - } - ErrWalletInvalidAccountName = Error{ - Code: -11, - Message: "Invalid account name", - } - ErrWalletKeypoolRanOut = Error{ - Code: -12, - Message: "Keypool ran out, call keypoolrefill first", - } - ErrWalletUnlockNeeded = Error{ - Code: -13, - Message: "Enter the wallet passphrase with walletpassphrase first", - } - ErrWalletPassphraseIncorrect = Error{ - Code: -14, - Message: "The wallet passphrase entered was incorrect", - } - ErrWalletWrongEncState = Error{ - Code: -15, - Message: "Command given in wrong wallet encryption state", - } - ErrWalletEncryptionFailed = Error{ - Code: -16, - Message: "Failed to encrypt the wallet", - } - ErrWalletAlreadyUnlocked = Error{ - Code: -17, - Message: "Wallet is already unlocked", - } -) - -// Specific Errors related to commands. These are the ones a user of the rpc -// server are most likely to see. Generally, the codes should match one of the -// more general errors above. -var ( - ErrBlockNotFound = Error{ - Code: -5, - Message: "Block not found", - } - ErrBlockCount = Error{ - Code: -5, - Message: "Error getting block count", - } - ErrBestBlockHash = Error{ - Code: -5, - Message: "Error getting best block hash", - } - ErrDifficulty = Error{ - Code: -5, - Message: "Error getting difficulty", - } - ErrOutOfRange = Error{ - Code: -1, - Message: "Block number out of range", - } - ErrNoTxInfo = Error{ - Code: -5, - Message: "No information available about transaction", - } - ErrNoNewestBlockInfo = Error{ - Code: -5, - Message: "No information about newest block", - } - ErrInvalidTxVout = Error{ - Code: -5, - Message: "Ouput index number (vout) does not exist for transaction.", - } - ErrRawTxString = Error{ - Code: -32602, - Message: "Raw tx is not a string", - } - ErrDecodeHexString = Error{ - Code: -22, - Message: "Unable to decode hex string", - } -) - -// Errors that are specific to btcd. -var ( - ErrNoWallet = Error{ - Code: -1, - Message: "This implementation does not implement wallet commands", - } - ErrUnimplemented = Error{ - Code: -1, - Message: "Command unimplemented", - } -) diff --git a/btcjson/jsonfxns.go b/btcjson/jsonfxns.go deleted file mode 100644 index baa45b65..00000000 --- a/btcjson/jsonfxns.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson - -import ( - "bytes" - // Need to import this size it registers hash we need. - _ "crypto/sha512" - "crypto/tls" - "crypto/x509" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "strings" -) - -// MarshallAndSend takes the reply structure, marshalls it to json, and -// sends it back to the io.Writer (most likely an http.ResponseWriter). -// returning a log message and an error if there is one. -func MarshallAndSend(rawReply Reply, w io.Writer) (string, error) { - finalReply, err := json.Marshal(rawReply) - if err != nil { - msg := fmt.Sprintf("[RPCS] Error Marshalling reply: %v", err) - return msg, err - } - fmt.Fprintf(w, "%s\n", finalReply) - msg := fmt.Sprintf("[RPCS] reply: %v", rawReply) - return msg, nil -} - -// jsonRPCSend connects to the daemon with the specified username, password, -// and ip/port and then send the supplied message. This uses net/http rather -// than net/rpc/jsonrpc since that one doesn't support http connections and is -// therefore useless. -func jsonRPCSend(user string, password string, server string, message []byte, - https bool, certificates []byte, skipverify bool) (*http.Response, error) { - client := &http.Client{} - protocol := "http" - if https { - pool := x509.NewCertPool() - pool.AppendCertsFromPEM(certificates) - - config := &tls.Config{ - InsecureSkipVerify: skipverify, - RootCAs: pool, - } - transport := &http.Transport{TLSClientConfig: config} - client.Transport = transport - protocol = "https" - } - credentials := url.UserPassword(user, password).String() - resp, err := client.Post(protocol+"://"+credentials+"@"+server, - "application/json", bytes.NewReader(message)) - if err != nil { - // We do not want to log the username/password in the errors. - replaceStr := ":" - str := strings.Replace(err.Error(), credentials, replaceStr, -1) - err = fmt.Errorf("%v", str) - } - return resp, err -} - -// GetRaw should be called after JsonRpcSend. It reads and returns -// the reply (which you can then call ReadResultCmd() on) and closes the -// connection. -func GetRaw(resp io.ReadCloser) ([]byte, error) { - body, err := ioutil.ReadAll(resp) - resp.Close() - if err != nil { - err = fmt.Errorf("error reading json reply: %v", err) - return body, err - } - return body, nil -} diff --git a/btcjson/jsonfxns_test.go b/btcjson/jsonfxns_test.go deleted file mode 100644 index 0398b312..00000000 --- a/btcjson/jsonfxns_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson_test - -import ( - "bytes" - "fmt" - "testing" - - "github.com/btcsuite/btcd/btcjson" -) - -// TestMarshallAndSend tests the MarshallAndSend function to make sure it can -// create a json message to write to the io.Writerr and to make sure -// it fails properly in cases where it cannot generate json. -func TestMarshallAndSend(t *testing.T) { - jsonError := btcjson.Error{ - Code: -32700, - Message: "Parse error", - } - // json.Marshal cannot handle channels so this is a good way to get a - // marshal failure. - badRes := make(chan interface{}) - rawReply := btcjson.Reply{ - Result: badRes, - Error: &jsonError, - Id: nil, - } - var w bytes.Buffer - - msg, err := btcjson.MarshallAndSend(rawReply, &w) - if fmt.Sprintf("%s", err) != "json: unsupported type: chan interface {}" { - t.Error("Should not be able to unmarshall channel") - } - - // Use something simple so we can compare the reply. - rawReply = btcjson.Reply{ - Result: nil, - Error: nil, - Id: nil, - } - - msg, err = btcjson.MarshallAndSend(rawReply, &w) - if msg != "[RPCS] reply: { }" { - t.Error("Incorrect reply:", msg) - } - - expBuf := "{\"result\":null,\"error\":null,\"id\":null}\n" - - if w.String() != expBuf { - t.Error("Incorrect data in buffer:", w.String()) - } - return -} diff --git a/btcjson/jsonresults.go b/btcjson/jsonresults.go deleted file mode 100644 index 21de6c6e..00000000 --- a/btcjson/jsonresults.go +++ /dev/null @@ -1,750 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson - -import ( - "bytes" - "encoding/json" - "fmt" -) - -// BlockResult models the data from the getblock command when the verbose flag -// is set. When the verbose flag is not set, getblock return a hex-encoded -// string. -type BlockResult struct { - Hash string `json:"hash"` - Confirmations uint64 `json:"confirmations"` - Size int32 `json:"size"` - Height int64 `json:"height"` - Version int32 `json:"version"` - MerkleRoot string `json:"merkleroot"` - Tx []string `json:"tx,omitempty"` - RawTx []TxRawResult `json:"rawtx,omitempty"` - Time int64 `json:"time"` - Nonce uint32 `json:"nonce"` - Bits string `json:"bits"` - Difficulty float64 `json:"difficulty"` - PreviousHash string `json:"previousblockhash"` - NextHash string `json:"nextblockhash"` -} - -// CreateMultiSigResult models the data returned from the createmultisig command. -type CreateMultiSigResult struct { - Address string `json:"address"` - RedeemScript string `json:"redeemScript"` -} - -// DecodeScriptResult models the data returned from the decodescript command. -type DecodeScriptResult struct { - Asm string `json:"asm"` - ReqSigs int32 `json:"reqSigs,omitempty"` - Type string `json:"type"` - Addresses []string `json:"addresses,omitempty"` - P2sh string `json:"p2sh"` -} - -// GetAddedNodeInfoResultAddr models the data of the addresses portion of the -// getaddednodeinfo command. -type GetAddedNodeInfoResultAddr struct { - Address string `json:"address"` - Connected string `json:"connected"` -} - -// GetAddedNodeInfoResult models the data from the getaddednodeinfo command. -type GetAddedNodeInfoResult struct { - AddedNode string `json:"addednode"` - Connected *bool `json:"connected,omitempty"` - Addresses *[]GetAddedNodeInfoResultAddr `json:"addresses,omitempty"` -} - -// GetBlockChainInfoResult models the data returned from the getblockchaininfo -// command. -type GetBlockChainInfoResult struct { - Chain string `json:"chain"` - Blocks int32 `json:"blocks"` - BestBlockHash string `json:"bestblockhash"` - Difficulty float64 `json:"difficulty"` - VerificationProgress float64 `json:"verificationprogress"` - ChainWork string `json:"chainwork"` -} - -// GetBlockTemplateResultTx models the transactions field of the -// getblocktemplate command. -type GetBlockTemplateResultTx struct { - Data string `json:"data"` - Hash string `json:"hash"` - Depends []int64 `json:"depends"` - Fee int64 `json:"fee"` - SigOps int64 `json:"sigops"` -} - -// GetBlockTemplateResultAux models the coinbaseaux field of the -// getblocktemplate command. -type GetBlockTemplateResultAux struct { - Flags string `json:"flags"` -} - -// GetBlockTemplateResult models the data returned from the getblocktemplate -// command. -type GetBlockTemplateResult struct { - // Base fields from BIP 0022. CoinbaseAux is optional. One of - // CoinbaseTxn or CoinbaseValue must be specified, but not both. - Bits string `json:"bits"` - CurTime int64 `json:"curtime"` - Height int64 `json:"height"` - PreviousHash string `json:"previousblockhash"` - SigOpLimit int64 `json:"sigoplimit,omitempty"` - SizeLimit int64 `json:"sizelimit,omitempty"` - Transactions []GetBlockTemplateResultTx `json:"transactions"` - Version int32 `json:"version"` - CoinbaseAux *GetBlockTemplateResultAux `json:"coinbaseaux,omitempty"` - CoinbaseTxn *GetBlockTemplateResultTx `json:"coinbasetxn,omitempty"` - CoinbaseValue *int64 `json:"coinbasevalue,omitempty"` - WorkID string `json:"workid,omitempty"` - - // Optional long polling from BIP 0022. - LongPollID string `json:"longpollid,omitempty"` - LongPollURI string `json:"longpolluri,omitempty"` - SubmitOld *bool `json:"submitold,omitempty"` - - // Basic pool extension from BIP 0023. - Target string `json:"target,omitempty"` - Expires int64 `json:"expires,omitempty"` - - // Mutations from BIP 0023. - MaxTime int64 `json:"maxtime,omitempty"` - MinTime int64 `json:"mintime,omitempty"` - Mutable []string `json:"mutable,omitempty"` - NonceRange string `json:"noncerange,omitempty"` - - // Block proposal from BIP 0023. - Capabilities []string `json:"capabilities,omitempty"` - RejectReasion string `json:"reject-reason,omitempty"` -} - -// GetNetworkInfoResult models the data returned from the getnetworkinfo command. -type GetNetworkInfoResult struct { - Version int32 `json:"version"` - ProtocolVersion int32 `json:"protocolversion"` - TimeOffset int64 `json:"timeoffset"` - Connections int32 `json:"connections"` - Networks []NetworksResult `json:"networks"` - RelayFee float64 `json:"relayfee"` - LocalAddresses []LocalAddressesResult `json:"localaddresses"` -} - -// GetPeerInfoResult models the data returned from the getpeerinfo command. -type GetPeerInfoResult struct { - ID string `json:"id"` - Addr string `json:"addr"` - AddrLocal string `json:"addrlocal,omitempty"` - Services string `json:"services"` - LastSend int64 `json:"lastsend"` - LastRecv int64 `json:"lastrecv"` - BytesSent uint64 `json:"bytessent"` - BytesRecv uint64 `json:"bytesrecv"` - ConnTime int64 `json:"conntime"` - TimeOffset int64 `json:"timeoffset"` - PingTime float64 `json:"pingtime"` - PingWait float64 `json:"pingwait,omitempty"` - Version uint32 `json:"version"` - SubVer string `json:"subver"` - Inbound bool `json:"inbound"` - StartingHeight int32 `json:"startingheight"` - CurrentHeight int32 `json:"currentheight,omitempty"` - BanScore int32 `json:"banscore,omitempty"` - SyncNode bool `json:"syncnode"` -} - -// GetRawMempoolResult models the data returned from the getrawmempool command. -type GetRawMempoolResult struct { - Size int32 `json:"size"` - Fee float64 `json:"fee"` - Time int64 `json:"time"` - Height int64 `json:"height"` - StartingPriority float64 `json:"startingpriority"` - CurrentPriority float64 `json:"currentpriority"` - Depends []string `json:"depends"` -} - -// GetTransactionDetailsResult models the details data from the gettransaction command. -type GetTransactionDetailsResult struct { - Account string `json:"account"` - Address string `json:"address,omitempty"` - Category string `json:"category"` - Amount float64 `json:"amount"` - Fee float64 `json:"fee,omitempty"` -} - -// GetTransactionResult models the data from the gettransaction command. -type GetTransactionResult struct { - Amount float64 `json:"amount"` - Fee float64 `json:"fee,omitempty"` - Confirmations int64 `json:"confirmations"` - BlockHash string `json:"blockhash"` - BlockIndex int64 `json:"blockindex"` - BlockTime int64 `json:"blocktime"` - TxID string `json:"txid"` - WalletConflicts []string `json:"walletconflicts"` - Time int64 `json:"time"` - TimeReceived int64 `json:"timereceived"` - Details []GetTransactionDetailsResult `json:"details"` - Hex string `json:"hex"` -} - -// GetTxOutResult models the data from the gettxout command. -type GetTxOutResult struct { - BestBlock string `json:"bestblock"` - Confirmations int64 `json:"confirmations"` - Value float64 `json:"value"` - ScriptPubKey ScriptPubKeyResult `json:"scriptPubKey"` - Version int32 `json:"version"` - Coinbase bool `json:"coinbase"` -} - -// GetNetTotalsResult models the data returned from the getnettotals command. -type GetNetTotalsResult struct { - TotalBytesRecv uint64 `json:"totalbytesrecv"` - TotalBytesSent uint64 `json:"totalbytessent"` - TimeMillis int64 `json:"timemillis"` -} - -// ScriptSig models a signature script. It is defined seperately since it only -// applies to non-coinbase. Therefore the field in the Vin structure needs -// to be a pointer. -type ScriptSig struct { - Asm string `json:"asm"` - Hex string `json:"hex"` -} - -// Vin models parts of the tx data. It is defined seperately since both -// getrawtransaction, sendrawtransaction, and decoderawtransaction use the -// same structure. -type Vin struct { - Coinbase string `json:"coinbase"` - Txid string `json:"txid"` - Vout uint32 `json:"vout"` - ScriptSig *ScriptSig `json:"scriptSig"` - Sequence uint32 `json:"sequence"` -} - -// IsCoinBase returns a bool to show if a Vin is a Coinbase one or not. -func (v *Vin) IsCoinBase() bool { - return len(v.Coinbase) > 0 -} - -// MarshalJSON provides a custom Marshal method for Vin. -func (v *Vin) MarshalJSON() ([]byte, error) { - if v.IsCoinBase() { - coinbaseStruct := struct { - Coinbase string `json:"coinbase"` - Sequence uint32 `json:"sequence"` - }{ - Coinbase: v.Coinbase, - Sequence: v.Sequence, - } - return json.Marshal(coinbaseStruct) - } - - txStruct := struct { - Txid string `json:"txid"` - Vout uint32 `json:"vout"` - ScriptSig *ScriptSig `json:"scriptSig"` - Sequence uint32 `json:"sequence"` - }{ - Txid: v.Txid, - Vout: v.Vout, - ScriptSig: v.ScriptSig, - Sequence: v.Sequence, - } - return json.Marshal(txStruct) -} - -// ScriptPubKeyResult models the scriptPubKey data of a tx script. It is -// defined separately since it is used by multiple commands. -type ScriptPubKeyResult struct { - Asm string `json:"asm"` - Hex string `json:"hex,omitempty"` - ReqSigs int32 `json:"reqSigs,omitempty"` - Type string `json:"type"` - Addresses []string `json:"addresses,omitempty"` -} - -// Vout models parts of the tx data. It is defined seperately since both -// getrawtransaction, sendrawtransaction, and decoderawtransaction use the same -// structure. -type Vout struct { - Value float64 `json:"value"` - N uint32 `json:"n"` - ScriptPubKey ScriptPubKeyResult `json:"scriptPubKey"` -} - -// GetMiningInfoResult models the data from the getmininginfo command. -type GetMiningInfoResult struct { - Blocks int64 `json:"blocks"` - CurrentBlockSize uint64 `json:"currentblocksize"` - CurrentBlockTx uint64 `json:"currentblocktx"` - Difficulty float64 `json:"difficulty"` - Errors string `json:"errors"` - Generate bool `json:"generate"` - GenProcLimit int32 `json:"genproclimit"` - HashesPerSec int64 `json:"hashespersec"` - NetworkHashPS int64 `json:"networkhashps"` - PooledTx uint64 `json:"pooledtx"` - TestNet bool `json:"testnet"` -} - -// GetWorkResult models the data from the getwork command. -type GetWorkResult struct { - Data string `json:"data"` - Hash1 string `json:"hash1"` - Midstate string `json:"midstate"` - Target string `json:"target"` -} - -// InfoResult contains the data returned by the getinfo command. -type InfoResult struct { - Version int32 `json:"version"` - ProtocolVersion int32 `json:"protocolversion"` - WalletVersion int32 `json:"walletversion,omitempty"` - Balance float64 `json:"balance,omitempty"` - Blocks int32 `json:"blocks"` - TimeOffset int64 `json:"timeoffset"` - Connections int32 `json:"connections"` - Proxy string `json:"proxy"` - Difficulty float64 `json:"difficulty"` - TestNet bool `json:"testnet"` - KeypoolOldest int64 `json:"keypoololdest,omitempty"` - KeypoolSize int32 `json:"keypoolsize,omitempty"` - UnlockedUntil int64 `json:"unlocked_until,omitempty"` - PaytxFee float64 `json:"paytxfee,omitempty"` - RelayFee float64 `json:"relayfee"` - Errors string `json:"errors"` -} - -// ListTransactionsResult models the data from the listtransactions command. -type ListTransactionsResult struct { - Account string `json:"account"` - Address string `json:"address,omitempty"` - Category string `json:"category"` - Amount float64 `json:"amount"` - Fee float64 `json:"fee"` - Confirmations int64 `json:"confirmations"` - Generated bool `json:"generated,omitempty"` - BlockHash string `json:"blockhash,omitempty"` - BlockIndex int64 `json:"blockindex,omitempty"` - BlockTime int64 `json:"blocktime,omitempty"` - TxID string `json:"txid"` - WalletConflicts []string `json:"walletconflicts"` - Time int64 `json:"time"` - TimeReceived int64 `json:"timereceived"` - Comment string `json:"comment,omitempty"` - OtherAccount string `json:"otheraccount"` -} - -// LocalAddressesResult models the localaddresses data from the getnetworkinfo command. -type LocalAddressesResult struct { - Address string `json:"address"` - Port uint16 `json:"port"` - Score int32 `json:"score"` -} - -// ListReceivedByAccountResult models the data from the listreceivedbyaccount -// command. -type ListReceivedByAccountResult struct { - Account string `json:"account"` - Amount float64 `json:"amount"` - Confirmations uint64 `json:"confirmations"` -} - -// ListReceivedByAddressResult models the data from the listreceivedbyaddress -// command. -type ListReceivedByAddressResult struct { - Account string `json:"account"` - Address string `json:"address"` - Amount float64 `json:"amount"` - Confirmations uint64 `json:"confirmations"` - TxIDs []string `json:"txids,omitempty"` - InvolvesWatchonly bool `json:"involvesWatchonly,omitempty"` -} - -// ListSinceBlockResult models the data from the listsinceblock command. -type ListSinceBlockResult struct { - Transactions []ListTransactionsResult `json:"transactions"` - LastBlock string `json:"lastblock"` -} - -// ListUnspentResult models a successful response from the listunspent request. -type ListUnspentResult struct { - TxId string `json:"txid"` - Vout uint32 `json:"vout"` - Address string `json:"address"` - Account string `json:"account"` - ScriptPubKey string `json:"scriptPubKey"` - RedeemScript string `json:"redeemScript,omitempty"` - Amount float64 `json:"amount"` - Confirmations int64 `json:"confirmations"` -} - -// NetworksResult models the networks data from the getnetworkinfo command. -type NetworksResult struct { - Name string `json:"name"` - Limited bool `json:"limited"` - Reachable bool `json:"reachable"` - Proxy string `json:"proxy"` -} - -// SignRawTransactionResult models the data from the signrawtransaction -// command. -type SignRawTransactionResult struct { - Hex string `json:"hex"` - Complete bool `json:"complete"` -} - -// TxRawResult models the data from the getrawtransaction and sendrawtransaction -// commands -type TxRawResult struct { - Hex string `json:"hex"` - Txid string `json:"txid"` - Version int32 `json:"version"` - LockTime uint32 `json:"locktime"` - Vin []Vin `json:"vin"` - Vout []Vout `json:"vout"` - BlockHash string `json:"blockhash,omitempty"` - Confirmations uint64 `json:"confirmations"` - Time int64 `json:"time,omitempty"` - Blocktime int64 `json:"blocktime,omitempty"` -} - -// TxRawDecodeResult models the data from the decoderawtransaction command. -type TxRawDecodeResult struct { - Txid string `json:"txid"` - Version int32 `json:"version"` - Locktime uint32 `json:"locktime"` - Vin []Vin `json:"vin"` - Vout []Vout `json:"vout"` -} - -// ValidateAddressResult models the data from the validateaddress command. -type ValidateAddressResult struct { - IsValid bool `json:"isvalid"` - Address string `json:"address,omitempty"` - IsMine bool `json:"ismine,omitempty"` - IsWatchOnly bool `json:"iswatchonly,omitempty"` - IsScript bool `json:"isscript,omitempty"` - PubKey string `json:"pubkey,omitempty"` - IsCompressed bool `json:"iscompressed,omitempty"` - Account string `json:"account,omitempty"` - Addresses []string `json:"addresses,omitempty"` - Hex string `json:"hex,omitempty"` - Script string `json:"script,omitempty"` - SigsRequired int32 `json:"sigsrequired,omitempty"` -} - -// ReadResultCmd unmarshalls the json reply with data struct for specific -// commands or an interface if it is not a command where we already have a -// struct ready. -func ReadResultCmd(cmd string, message []byte) (Reply, error) { - var result Reply - var err error - var objmap map[string]json.RawMessage - err = json.Unmarshal(message, &objmap) - if err != nil { - return result, err - } - // Take care of the parts that are the same for all replies. - var jsonErr Error - var id interface{} - err = json.Unmarshal(objmap["error"], &jsonErr) - if err != nil { - err = fmt.Errorf("error unmarshalling json reply: %v", err) - return result, err - } - err = json.Unmarshal(objmap["id"], &id) - if err != nil { - err = fmt.Errorf("error unmarshalling json reply: %v", err) - return result, err - } - - // If it is a command where we have already worked out the reply, - // generate put the results in the proper structure. - // We handle the error condition after the switch statement. - switch cmd { - case "createmultisig": - var res *CreateMultiSigResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "decodescript": - var res *DecodeScriptResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "getaddednodeinfo": - // getaddednodeinfo can either return a JSON object or a - // slice of strings depending on the verbose flag. Choose the - // right form accordingly. - if bytes.IndexByte(objmap["result"], '{') > -1 { - var res []GetAddedNodeInfoResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } else { - var res []string - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } - case "getinfo": - var res *InfoResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "getblock": - // getblock can either return a JSON object or a hex-encoded - // string depending on the verbose flag. Choose the right form - // accordingly. - if bytes.IndexByte(objmap["result"], '{') > -1 { - var res *BlockResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } else { - var res string - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } - case "getblockchaininfo": - var res *GetBlockChainInfoResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "getnettotals": - var res *GetNetTotalsResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "getnetworkhashps": - var res int64 - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "getpeerinfo": - var res []GetPeerInfoResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "getrawtransaction": - // getrawtransaction can either return a JSON object or a - // hex-encoded string depending on the verbose flag. Choose the - // right form accordingly. - if bytes.IndexByte(objmap["result"], '{') > -1 { - var res *TxRawResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } else { - var res string - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } - case "decoderawtransaction": - var res *TxRawDecodeResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "getaddressesbyaccount": - var res []string - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "getmininginfo": - var res *GetMiningInfoResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "getnetworkinfo": - var res *GetNetworkInfoResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - if res != nil && res.LocalAddresses == nil { - res.LocalAddresses = []LocalAddressesResult{} - } - result.Result = res - } - case "getrawmempool": - // getrawmempool can either return a map of JSON objects or - // an array of strings depending on the verbose flag. Choose - // the right form accordingly. - if bytes.IndexByte(objmap["result"], '{') > -1 { - var res map[string]GetRawMempoolResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } else { - var res []string - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } - case "gettransaction": - var res *GetTransactionResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "gettxout": - var res *GetTxOutResult - err = json.Unmarshal(objmap["result"], &res) - if res != nil && err == nil { - if res.ScriptPubKey.Addresses == nil { - res.ScriptPubKey.Addresses = []string{} - } - result.Result = res - } - case "getwork": - // getwork can either return a JSON object or a boolean - // depending on whether or not data was provided. Choose the - // right form accordingly. - if bytes.IndexByte(objmap["result"], '{') > -1 { - var res *GetWorkResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } else { - var res bool - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } - case "validateaddress": - var res *ValidateAddressResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "signrawtransaction": - var res *SignRawTransactionResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "listaccounts": - var res map[string]float64 - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "listreceivedbyaccount": - var res []ListReceivedByAccountResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "listreceivedbyaddress": - var res []ListReceivedByAddressResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "listsinceblock": - var res *ListSinceBlockResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - if res.Transactions == nil { - res.Transactions = []ListTransactionsResult{} - } - result.Result = res - } - case "listtransactions": - var res []ListTransactionsResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - case "listunspent": - var res []ListUnspentResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - - case "searchrawtransactions": - // searchrawtransactions can either return a list of JSON objects - // or a list of hex-encoded strings depending on the verbose flag. - // Choose the right form accordingly. - if bytes.IndexByte(objmap["result"], '{') > -1 { - var res []*TxRawResult - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } else { - var res []string - err = json.Unmarshal(objmap["result"], &res) - if err == nil { - result.Result = res - } - } - // For commands that return a single item (or no items), we get it with - // the correct concrete type for free (but treat them separately - // for clarity). - case "getblockcount", "getbalance", "getblockhash", "getgenerate", - "getconnectioncount", "getdifficulty", "gethashespersec", - "setgenerate", "stop", "settxfee", "getaccount", - "getnewaddress", "sendtoaddress", "createrawtransaction", - "sendrawtransaction", "getbestblockhash", "getrawchangeaddress", - "sendfrom", "sendmany", "addmultisigaddress", "getunconfirmedbalance", - "getaccountaddress", "estimatefee", "estimatepriority": - err = json.Unmarshal(message, &result) - default: - // None of the standard Bitcoin RPC methods matched. Try - // registered custom command reply parsers. - if c, ok := customCmds[cmd]; ok && c.replyParser != nil { - var res interface{} - res, err = c.replyParser(objmap["result"]) - if err == nil { - result.Result = res - } - } else { - // For anything else put it in an interface. All the - // data is still there, just a little less convenient - // to deal with. - err = json.Unmarshal(message, &result) - } - } - if err != nil { - err = fmt.Errorf("error unmarshalling json reply: %v", err) - return result, err - } - // Only want the error field when there is an actual error to report. - if jsonErr.Code != 0 { - result.Error = &jsonErr - } - result.Id = &id - return result, err -} diff --git a/btcjson/jsonresults_test.go b/btcjson/jsonresults_test.go deleted file mode 100644 index f80b2d18..00000000 --- a/btcjson/jsonresults_test.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2013-2014 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson_test - -import ( - "bytes" - "encoding/json" - "testing" - - "github.com/btcsuite/btcd/btcjson" -) - -var resulttests = []struct { - cmd string - msg []byte - comp bool - pass bool -}{ - // Generate a fake message to make sure we can encode and decode it and - // get the same thing back. - {"getblockcount", - []byte(`{"result":226790,"error":{"code":1,"message":"No Error"},"id":"btcd"}`), - true, true}, - // Generate a fake message to make sure we don't make a command from it. - {"anycommand", []byte(`{"result":"test","id":1}`), false, false}, - {"anycommand", []byte(`{some junk}`), false, false}, - {"anycommand", []byte(`{"error":null,"result":null,"id":"test"}`), false, true}, - {"createmultisig", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"createmultisig", []byte(`{"error":null,"id":1,"result":{"address":"something","redeemScript":"else"}}`), false, true}, - {"decodescript", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"decodescript", []byte(`{"error":null,"id":1,"result":{"Asm":"something"}}`), false, true}, - {"getinfo", []byte(`{"error":null,"result":null,"id":"test"}`), false, true}, - {"getinfo", []byte(`{"error":null,"result":null}`), false, false}, - {"getinfo", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"getblock", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"getblock", []byte(`{"result":{"hash":"000000","confirmations":16007,"size":325648},"error":null,"id":1}`), false, true}, - {"getblockchaininfo", []byte(`{"result":{"chain":"hex","blocks":250000,"bestblockhash":"hash"},"error":null,"id":1}`), false, true}, - {"getblockchaininfo", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"getnetworkinfo", []byte(`{"result":{"version":100,"protocolversion":70002},"error":null,"id":1}`), false, true}, - {"getnetworkinfo", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"getrawtransaction", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"getrawtransaction", []byte(`{"error":null,"id":1,"result":{"hex":"somejunk","version":1}}`), false, true}, - {"gettransaction", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"gettransaction", []byte(`{"error":null,"id":1,"result":{"Amount":0.0}}`), false, true}, - {"decoderawtransaction", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"decoderawtransaction", []byte(`{"error":null,"id":1,"result":{"Txid":"something"}}`), false, true}, - {"getaddressesbyaccount", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"getaddressesbyaccount", []byte(`{"error":null,"id":1,"result":["test"]}`), false, true}, - {"getmininginfo", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"getmininginfo", []byte(`{"error":null,"id":1,"result":{"generate":true}}`), false, true}, - {"gettxout", []byte(`{"error":null,"id":1,"result":{"bestblock":"a","value":1.0}}`), false, true}, - {"listreceivedbyaddress", []byte(`{"error":null,"id":1,"result":[{"a"}]}`), false, false}, - {"listreceivedbyaddress", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, true}, - {"listsinceblock", []byte(`{"error":null,"id":1,"result":[{"a":"b"}]}`), false, false}, - {"listsinceblock", []byte(`{"error":null,"id":1,"result":{"lastblock":"something"}}`), false, true}, - {"validateaddress", []byte(`{"error":null,"id":1,"result":{"isvalid":false}}`), false, true}, - {"validateaddress", []byte(`{"error":null,"id":1,"result":{false}}`), false, false}, - {"signrawtransaction", []byte(`{"error":null,"id":1,"result":{"hex":"something","complete":false}}`), false, true}, - {"signrawtransaction", []byte(`{"error":null,"id":1,"result":{false}}`), false, false}, - {"listunspent", []byte(`{"error":null,"id":1,"result":[{"txid":"something"}]}`), false, true}, - {"listunspent", []byte(`{"error":null,"id":1,"result":[{"txid"}]}`), false, false}, - {"searchrawtransactions", []byte(`{"error":null,"id":1,"result":{"a":"b"}}`), false, false}, - {"searchrawtransactions", []byte(`{"error":null,"id":1,"result":["sometxhex"]}`), false, true}, - {"searchrawtransactions", []byte(`{"error":null,"id":1,"result":[{"hex":"somejunk","version":1}]}`), false, true}, -} - -// TestReadResultCmd tests that readResultCmd can properly unmarshall the -// returned []byte that contains a json reply for both known and unknown -// messages. -func TestReadResultCmd(t *testing.T) { - for i, tt := range resulttests { - result, err := btcjson.ReadResultCmd(tt.cmd, tt.msg) - if tt.pass { - if err != nil { - t.Errorf("Should read result: %d %v", i, err) - } - // Due to the pointer for the Error and other structs, - // we can't always guarantee byte for byte comparison. - if tt.comp { - msg2, err := json.Marshal(result) - if err != nil { - t.Errorf("Should unmarshal result: %d %v", i, err) - } - if !bytes.Equal(tt.msg, msg2) { - t.Errorf("json byte arrays differ. %d %v %v", i, tt.msg, msg2) - } - } - - } else { - if err == nil { - t.Errorf("Should fail: %d, %s", i, tt.msg) - } - } - } - - return -} diff --git a/btcjson/v2/btcjson/jsonrpc.go b/btcjson/jsonrpc.go similarity index 100% rename from btcjson/v2/btcjson/jsonrpc.go rename to btcjson/jsonrpc.go diff --git a/btcjson/v2/btcjson/jsonrpc_test.go b/btcjson/jsonrpc_test.go similarity index 98% rename from btcjson/v2/btcjson/jsonrpc_test.go rename to btcjson/jsonrpc_test.go index 8a48462e..061d462d 100644 --- a/btcjson/v2/btcjson/jsonrpc_test.go +++ b/btcjson/jsonrpc_test.go @@ -9,7 +9,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestIsValidIDType ensures the IsValidIDType function behaves as expected. diff --git a/btcjson/v2/btcjson/jsonrpcerr.go b/btcjson/jsonrpcerr.go similarity index 100% rename from btcjson/v2/btcjson/jsonrpcerr.go rename to btcjson/jsonrpcerr.go diff --git a/btcjson/v2/btcjson/register.go b/btcjson/register.go similarity index 100% rename from btcjson/v2/btcjson/register.go rename to btcjson/register.go diff --git a/btcjson/v2/btcjson/register_test.go b/btcjson/register_test.go similarity index 99% rename from btcjson/v2/btcjson/register_test.go rename to btcjson/register_test.go index f0131075..bce32b37 100644 --- a/btcjson/v2/btcjson/register_test.go +++ b/btcjson/register_test.go @@ -9,7 +9,7 @@ import ( "sort" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestUsageFlagStringer tests the stringized output for the UsageFlag type. diff --git a/btcjson/v2/btcjson/README.md b/btcjson/v2/btcjson/README.md deleted file mode 100644 index 4d6b27d9..00000000 --- a/btcjson/v2/btcjson/README.md +++ /dev/null @@ -1,87 +0,0 @@ -btcjson -======= - -[![Build Status](https://travis-ci.org/btcsuite/btcd.png?branch=master)] -(https://travis-ci.org/btcsuite/btcd) [![ISC License] -(http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) - -Package btcjson implements concrete types for marshalling to and from the -bitcoin JSON-RPC API. A comprehensive suite of tests is provided to ensure -proper functionality. - -Although this package was primarily written for the btcsuite, it has -intentionally been designed so it can be used as a standalone package for any -projects needing to marshal to and from bitcoin JSON-RPC requests and responses. - -Note that although it's possible to use this package directly to implement an -RPC client, it is not recommended since it is only intended as an infrastructure -package. Instead, RPC clients should use the -[btcrpcclient](https://github.com/btcsuite/btcrpcclient) package which provides -a full blown RPC client with many features such as automatic connection -management, websocket support, automatic notification re-registration on -reconnect, and conversion from the raw underlying RPC types (strings, floats, -ints, etc) to higher-level types with many nice and useful properties. - -## Documentation - -[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)] -(http://godoc.org/github.com/btcsuite/btcd/btcjson/v2/btcjson) - -Full `go doc` style documentation for the project can be viewed online without -installing this package by using the GoDoc site -[here](http://godoc.org/github.com/btcsuite/btcd/btcjson/v2/btcjson). - -You can also view the documentation locally once the package is installed with -the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to -http://localhost:6060/pkg/github.com/btcsuite/btcd/btcjson/v2/btcjson - -## Installation - -```bash -$ go get github.com/btcsuite/btcd/btcjson/v2/btcjson -``` - -## Examples - -* [Marshal Command] - (http://godoc.org/github.com/btcsuite/btcd/btcjson/v2/btcjson#example-MarshalCmd) - Demonstrates how to create and marshal a command into a JSON-RPC request. - -* [Unmarshal Command] - (http://godoc.org/github.com/btcsuite/btcd/btcjson/v2/btcjson#example-UnmarshalCmd) - Demonstrates how to unmarshal a JSON-RPC request and then unmarshal the - concrete request into a concrete command. - -* [Marshal Response] - (http://godoc.org/github.com/btcsuite/btcd/btcjson/v2/btcjson#example-MarshalResponse) - Demonstrates how to marshal a JSON-RPC response. - -* [Unmarshal Response] - (http://godoc.org/github.com/btcsuite/btcd/btcjson/v2/btcjson#example-package--UnmarshalResponse) - Demonstrates how to unmarshal a JSON-RPC response and then unmarshal the - result field in the response to a concrete type. - -## GPG Verification Key - -All official release tags are signed by Conformal so users can ensure the code -has not been tampered with and is coming from Conformal. To verify the -signature perform the following: - -- Download the public key from the Conformal website at - https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt - -- Import the public key into your GPG keyring: - ```bash - gpg --import GIT-GPG-KEY-conformal.txt - ``` - -- Verify the release tag with the following command where `TAG_NAME` is a - placeholder for the specific tag: - ```bash - git tag -v TAG_NAME - ``` - -## License - -Package btcjson is licensed under the [copyfree](http://copyfree.org) ISC -License. diff --git a/btcjson/v2/btcjson/doc.go b/btcjson/v2/btcjson/doc.go deleted file mode 100644 index 54f549ea..00000000 --- a/btcjson/v2/btcjson/doc.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) 2015 Conformal Systems LLC. -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -/* -Package btcjson provides primitives for working with the bitcoin JSON-RPC API. - -Overview - -When communicating via the JSON-RPC protocol, all of the commands need to be -marshalled to and from the the wire in the appropriate format. This package -provides data structures and primitives to ease this process. - -In addition, it also provides some additional features such as custom command -registration, command categorization, and reflection-based help generation. - -JSON-RPC Protocol Overview - -This information is not necessary in order to use this package, but it does -provide some intuition into what the marshalling and unmarshalling that is -discussed below is doing under the hood. - -As defined by the JSON-RPC spec, there are effectively two forms of messages on -the wire: - - - Request Objects - {"jsonrpc":"1.0","id":"SOMEID","method":"SOMEMETHOD","params":[SOMEPARAMS]} - NOTE: Notifications are the same format except the id field is null. - - - Response Objects - {"result":SOMETHING,"error":null,"id":"SOMEID"} - {"result":null,"error":{"code":SOMEINT,"message":SOMESTRING},"id":"SOMEID"} - -For requests, the params field can vary in what it contains depending on the -method (a.k.a. command) being sent. Each parameter can be as simple as an int -or a complex structure containing many nested fields. The id field is used to -identify a request and will be included in the associated response. - -When working with asynchronous transports, such as websockets, spontaneous -notifications are also possible. As indicated, they are the same as a request -object, except they have the id field set to null. Therefore, servers will -ignore requests with the id field set to null, while clients can choose to -consume or ignore them. - -Unfortunately, the original Bitcoin JSON-RPC API (and hence anything compatible -with it) doesn't always follow the spec and will sometimes return an error -string in the result field with a null error for certain commands. However, -for the most part, the error field will be set as described on failure. - -Marshalling and Unmarshalling - -Based upon the discussion above, it should be easy to see how the types of this -package map into the required parts of the protocol - - - Request Objects (type Request) - - Commands (type Cmd) - - Notifications (type Ntfn) - - Response Objects (type Response) - - Result (type Result) - -To simplify the marshalling of the requests and responses, the MarshalCmd and -MarshalResponse functions are provided. They return the raw bytes ready to be -sent across the wire. - -Unmarshalling a received Request object is a two step process: - 1) Unmarshal the raw bytes into a Request struct instance via json.Unmarshal - 2) Use UnmarshalCmd on the Result field of the unmarshalled Request to create - a concrete command or notification instance with all struct fields set - accordingly - -This approach is used since it provides the caller with access to the additional -fields in the request that are not part of the command such as the ID. - -Unmarshalling a received Response object is also a two step process: - 1) Unmarshal the raw bytes into a Response struct instance via json.Unmarshal - 2) Depending on the ID, unmarshal the Result field of the unmarshalled - Response to create a concrete type instance - -As above, this approach is used since it provides the caller with access to the -fields in the response such as the ID and Error. - -Command Creation - -This package provides two approaches for creating a new command. This first, -and preferred, method is to use one of the NewCmd functions. This allows -static compile-time checking to help ensure the parameters stay in sync with -the struct definitions. - -The second approach is the NewCmd function which takes a method (command) name -and variable arguments. The function includes full checking to ensure the -parameters are accurate according to provided method, however these checks are, -obviously, run-time which means any mistakes won't be found until the code is -actually executed. However, it is quite useful for user-supplied commands -that are intentionally dynamic. - -Custom Command Registration - -The command handling of this package is built around the concept of registered -commands. This is true for the wide variety of commands already provided by the -package, but it also means caller can easily provide custom commands with all -of the same functionality as the built-in commands. Use the RegisterCmd -function for this purpose. - -A list of all registered methods can be obtained with the RegisteredCmdMethods -function. - -Command Inspection - -All registered commands are registered with flags that identify information such -as whether the command applies to a chain server, wallet server, or is a -notification along with the method name to use. These flags can be obtained -with the MethodUsageFlags flags, and the method can be obtained with the -CmdMethod function. - -Help Generation - -To facilitate providing consistent help to users of the RPC server, this package -exposes the GenerateHelp and function which uses reflection on registered -commands or notifications, as well as the provided expected result types, to -generate the final help text. - -In addition, the MethodUsageText function is provided to generate consistent -one-line usage for registered commands and notifications using reflection. - -Errors - -There are 2 distinct type of errors supported by this package: - - - General errors related to marshalling or unmarshalling or improper use of - the package (type Error) - - RPC errors which are intended to be returned across the wire as a part of - the JSON-RPC response (type RPCError) - -The first category of errors (type Error) typically indicates a programmer error -and can be avoided by properly using the API. Errors of this type will be -returned from the various functions available in this package. They identify -issues such as unsupported field types, attempts to register malformed commands, -and attempting to create a new command with an improper number of parameters. -The specific reason for the error can be detected by type asserting it to a -*btcjson.Error and accessing the ErrorCode field. - -The second category of errors (type RPCError), on the other hand, are useful for -returning errors to RPC clients. Consequently, they are used in the previously -described Response type. -*/ -package btcjson diff --git a/btcjson/v2/btcjson/walletsvrcmds.go b/btcjson/walletsvrcmds.go similarity index 100% rename from btcjson/v2/btcjson/walletsvrcmds.go rename to btcjson/walletsvrcmds.go diff --git a/btcjson/v2/btcjson/walletsvrcmds_test.go b/btcjson/walletsvrcmds_test.go similarity index 99% rename from btcjson/v2/btcjson/walletsvrcmds_test.go rename to btcjson/walletsvrcmds_test.go index 83c19559..6df5a673 100644 --- a/btcjson/v2/btcjson/walletsvrcmds_test.go +++ b/btcjson/walletsvrcmds_test.go @@ -11,7 +11,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestWalletSvrCmds tests all of the wallet server commands marshal and diff --git a/btcjson/v2/btcjson/walletsvrresults.go b/btcjson/walletsvrresults.go similarity index 100% rename from btcjson/v2/btcjson/walletsvrresults.go rename to btcjson/walletsvrresults.go diff --git a/btcjson/v2/btcjson/walletsvrwscmds.go b/btcjson/walletsvrwscmds.go similarity index 100% rename from btcjson/v2/btcjson/walletsvrwscmds.go rename to btcjson/walletsvrwscmds.go diff --git a/btcjson/v2/btcjson/walletsvrwscmds_test.go b/btcjson/walletsvrwscmds_test.go similarity index 99% rename from btcjson/v2/btcjson/walletsvrwscmds_test.go rename to btcjson/walletsvrwscmds_test.go index 6189445f..e2f23575 100644 --- a/btcjson/v2/btcjson/walletsvrwscmds_test.go +++ b/btcjson/walletsvrwscmds_test.go @@ -11,7 +11,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestWalletSvrWsCmds tests all of the wallet server websocket-specific diff --git a/btcjson/v2/btcjson/walletsvrwsntfns.go b/btcjson/walletsvrwsntfns.go similarity index 100% rename from btcjson/v2/btcjson/walletsvrwsntfns.go rename to btcjson/walletsvrwsntfns.go diff --git a/btcjson/v2/btcjson/walletsvrwsntfns_test.go b/btcjson/walletsvrwsntfns_test.go similarity index 99% rename from btcjson/v2/btcjson/walletsvrwsntfns_test.go rename to btcjson/walletsvrwsntfns_test.go index ef8b28ec..883246df 100644 --- a/btcjson/v2/btcjson/walletsvrwsntfns_test.go +++ b/btcjson/walletsvrwsntfns_test.go @@ -11,7 +11,7 @@ import ( "reflect" "testing" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // TestWalletSvrWsNtfns tests all of the chain server websocket-specific diff --git a/cmd/btcctl/btcctl.go b/cmd/btcctl/btcctl.go index 9748045e..5c412f86 100644 --- a/cmd/btcctl/btcctl.go +++ b/cmd/btcctl/btcctl.go @@ -10,7 +10,7 @@ import ( "path/filepath" "strings" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) const ( diff --git a/cmd/btcctl/config.go b/cmd/btcctl/config.go index 77f412e3..45f73d69 100644 --- a/cmd/btcctl/config.go +++ b/cmd/btcctl/config.go @@ -11,7 +11,7 @@ import ( "path/filepath" "strings" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" "github.com/btcsuite/btcutil" flags "github.com/btcsuite/go-flags" ) diff --git a/cmd/btcctl/httpclient.go b/cmd/btcctl/httpclient.go index 1498f684..2a0f6dff 100644 --- a/cmd/btcctl/httpclient.go +++ b/cmd/btcctl/httpclient.go @@ -10,7 +10,7 @@ import ( "net" "net/http" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" "github.com/btcsuite/go-socks/socks" ) diff --git a/rpcserver.go b/rpcserver.go index ff7a84c8..c81c19f4 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -29,8 +29,7 @@ import ( "github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/btcec" - "github.com/btcsuite/btcd/btcjson/btcws" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" "github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/txscript" @@ -880,7 +879,7 @@ func handleGetBestBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{} } } - result := &btcws.GetBestBlockResult{ + result := &btcjson.GetBestBlockResult{ Hash: sha.String(), Height: int32(height), } diff --git a/rpcserverhelp.go b/rpcserverhelp.go index 920e1849..8d8ea431 100644 --- a/rpcserverhelp.go +++ b/rpcserverhelp.go @@ -10,7 +10,7 @@ import ( "strings" "sync" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" ) // helpDescsEnUS defines the English descriptions used for the help strings. diff --git a/rpcwebsocket.go b/rpcwebsocket.go index 2e1c4e4e..f95030b8 100644 --- a/rpcwebsocket.go +++ b/rpcwebsocket.go @@ -17,7 +17,7 @@ import ( "sync" "time" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" "github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/wire" diff --git a/server.go b/server.go index 0d9140bc..2207c88c 100644 --- a/server.go +++ b/server.go @@ -21,7 +21,7 @@ import ( "github.com/btcsuite/btcd/addrmgr" "github.com/btcsuite/btcd/blockchain" - "github.com/btcsuite/btcd/btcjson/v2/btcjson" + "github.com/btcsuite/btcd/btcjson" "github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/wire"