From bb3f23b6dc7dd34feeedef9dedbcd9addfd8e2c5 Mon Sep 17 00:00:00 2001 From: stasatdaglabs <39559713+stasatdaglabs@users.noreply.github.com> Date: Mon, 12 Aug 2019 09:54:07 +0300 Subject: [PATCH] [NOD-240] Get rid of all references for wallet related RPC commands (#361) * [NOD-240] Removed references to the wallet in rpcserver.go. * [NOD-240] Began removing btcwalletxxx.go. * [NOD-240] Got rid of rpcclient/wallet.go and walletsvrcmds.go. * [NOD-240] Moved GetBestBlockResult to dagsvrresults.go. * [NOD-240] Finished removing walletsvrXXX.go. * [NOD-240] Removed wallet stuff from btcctl. * [NOD-240] Removed a few last things that I've missed. --- btcjson/btcdextcmds_test.go | 2 +- btcjson/btcwalletextcmds.go | 104 - btcjson/btcwalletextcmds_test.go | 208 -- btcjson/cmdinfo_test.go | 5 - btcjson/dagsvrresults.go | 6 + btcjson/doc.go | 2 +- btcjson/jsonrpcerr.go | 14 - btcjson/register.go | 9 +- btcjson/register_test.go | 9 +- btcjson/walletsvrcmds.go | 671 ----- btcjson/walletsvrcmds_test.go | 1248 --------- btcjson/walletsvrresults.go | 161 -- btcjson/walletsvrwscmds.go | 128 - btcjson/walletsvrwscmds_test.go | 259 -- btcjson/walletsvrwsntfns.go | 95 - btcjson/walletsvrwsntfns_test.go | 187 -- cmd/btcctl/config.go | 61 +- .../examples/btcwalletwebsockets/README.md | 37 - .../examples/btcwalletwebsockets/main.go | 72 - rpcclient/extensions.go | 153 -- rpcclient/notify.go | 151 -- rpcclient/rawtransactions.go | 242 -- rpcclient/wallet.go | 2240 ----------------- server/rpc/rpcserver.go | 67 - server/rpc/rpcserverhelp.go | 22 +- 25 files changed, 30 insertions(+), 6123 deletions(-) delete mode 100644 btcjson/btcwalletextcmds.go delete mode 100644 btcjson/btcwalletextcmds_test.go delete mode 100644 btcjson/walletsvrcmds.go delete mode 100644 btcjson/walletsvrcmds_test.go delete mode 100644 btcjson/walletsvrresults.go delete mode 100644 btcjson/walletsvrwscmds.go delete mode 100644 btcjson/walletsvrwscmds_test.go delete mode 100644 btcjson/walletsvrwsntfns.go delete mode 100644 btcjson/walletsvrwsntfns_test.go delete mode 100644 rpcclient/examples/btcwalletwebsockets/README.md delete mode 100644 rpcclient/examples/btcwalletwebsockets/main.go delete mode 100644 rpcclient/wallet.go diff --git a/btcjson/btcdextcmds_test.go b/btcjson/btcdextcmds_test.go index b90d03d22..44a763063 100644 --- a/btcjson/btcdextcmds_test.go +++ b/btcjson/btcdextcmds_test.go @@ -22,7 +22,7 @@ import ( func TestBtcdExtCmds(t *testing.T) { t.Parallel() - testID := int(1) + testID := 1 tests := []struct { name string newCmd func() (interface{}, error) diff --git a/btcjson/btcwalletextcmds.go b/btcjson/btcwalletextcmds.go deleted file mode 100644 index 268fe2c1c..000000000 --- a/btcjson/btcwalletextcmds.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) 2015 The btcsuite developers -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -// NOTE: This file is intended to house the RPC commands that are supported by -// a wallet server with btcwallet extensions. - -package btcjson - -// CreateNewAccountCmd defines the createNewAccount JSON-RPC command. -type CreateNewAccountCmd struct { - Account string -} - -// NewCreateNewAccountCmd returns a new instance which can be used to issue a -// createNewAccount JSON-RPC command. -func NewCreateNewAccountCmd(account string) *CreateNewAccountCmd { - return &CreateNewAccountCmd{ - Account: account, - } -} - -// DumpWalletCmd defines the dumpWallet JSON-RPC command. -type DumpWalletCmd struct { - Filename string -} - -// NewDumpWalletCmd returns a new instance which can be used to issue a -// dumpWallet JSON-RPC command. -func NewDumpWalletCmd(filename string) *DumpWalletCmd { - return &DumpWalletCmd{ - Filename: filename, - } -} - -// ImportAddressCmd defines the importAddress JSON-RPC command. -type ImportAddressCmd struct { - Address string - Rescan *bool `jsonrpcdefault:"true"` -} - -// NewImportAddressCmd returns a new instance which can be used to issue an -// importAddress JSON-RPC command. -func NewImportAddressCmd(address string, rescan *bool) *ImportAddressCmd { - return &ImportAddressCmd{ - Address: address, - Rescan: rescan, - } -} - -// ImportPubKeyCmd defines the importPubKey JSON-RPC command. -type ImportPubKeyCmd struct { - PubKey string - Rescan *bool `jsonrpcdefault:"true"` -} - -// NewImportPubKeyCmd returns a new instance which can be used to issue an -// importPubKey JSON-RPC command. -func NewImportPubKeyCmd(pubKey string, rescan *bool) *ImportPubKeyCmd { - return &ImportPubKeyCmd{ - PubKey: pubKey, - Rescan: rescan, - } -} - -// ImportWalletCmd defines the importWallet JSON-RPC command. -type ImportWalletCmd struct { - Filename string -} - -// NewImportWalletCmd returns a new instance which can be used to issue a -// importWallet JSON-RPC command. -func NewImportWalletCmd(filename string) *ImportWalletCmd { - return &ImportWalletCmd{ - Filename: filename, - } -} - -// RenameAccountCmd defines the renameAccount JSON-RPC command. -type RenameAccountCmd struct { - OldAccount string - NewAccount string -} - -// NewRenameAccountCmd returns a new instance which can be used to issue a -// renameAccount JSON-RPC command. -func NewRenameAccountCmd(oldAccount, newAccount string) *RenameAccountCmd { - return &RenameAccountCmd{ - OldAccount: oldAccount, - NewAccount: newAccount, - } -} - -func init() { - // The commands in this file are only usable with a wallet server. - flags := UFWalletOnly - - MustRegisterCmd("createNewAccount", (*CreateNewAccountCmd)(nil), flags) - MustRegisterCmd("dumpWallet", (*DumpWalletCmd)(nil), flags) - MustRegisterCmd("importAddress", (*ImportAddressCmd)(nil), flags) - MustRegisterCmd("importPubKey", (*ImportPubKeyCmd)(nil), flags) - MustRegisterCmd("importWallet", (*ImportWalletCmd)(nil), flags) - MustRegisterCmd("renameAccount", (*RenameAccountCmd)(nil), flags) -} diff --git a/btcjson/btcwalletextcmds_test.go b/btcjson/btcwalletextcmds_test.go deleted file mode 100644 index 3c03c0b6e..000000000 --- a/btcjson/btcwalletextcmds_test.go +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (c) 2014 The btcsuite developers -// 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" - "fmt" - "reflect" - "testing" - - "github.com/daglabs/btcd/btcjson" -) - -// TestBtcWalletExtCmds tests all of the btcwallet extended commands marshal and -// unmarshal into valid results include handling of optional fields being -// omitted in the marshalled command, while optional fields with defaults have -// the default assigned on unmarshalled commands. -func TestBtcWalletExtCmds(t *testing.T) { - t.Parallel() - - testID := int(1) - tests := []struct { - name string - newCmd func() (interface{}, error) - staticCmd func() interface{} - marshalled string - unmarshalled interface{} - }{ - { - name: "createNewAccount", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("createNewAccount", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewCreateNewAccountCmd("acct") - }, - marshalled: `{"jsonrpc":"1.0","method":"createNewAccount","params":["acct"],"id":1}`, - unmarshalled: &btcjson.CreateNewAccountCmd{ - Account: "acct", - }, - }, - { - name: "dumpWallet", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("dumpWallet", "filename") - }, - staticCmd: func() interface{} { - return btcjson.NewDumpWalletCmd("filename") - }, - marshalled: `{"jsonrpc":"1.0","method":"dumpWallet","params":["filename"],"id":1}`, - unmarshalled: &btcjson.DumpWalletCmd{ - Filename: "filename", - }, - }, - { - name: "importAddress", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("importAddress", "1Address") - }, - staticCmd: func() interface{} { - return btcjson.NewImportAddressCmd("1Address", nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"importAddress","params":["1Address"],"id":1}`, - unmarshalled: &btcjson.ImportAddressCmd{ - Address: "1Address", - Rescan: btcjson.Bool(true), - }, - }, - { - name: "importAddress optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("importAddress", "1Address", false) - }, - staticCmd: func() interface{} { - return btcjson.NewImportAddressCmd("1Address", btcjson.Bool(false)) - }, - marshalled: `{"jsonrpc":"1.0","method":"importAddress","params":["1Address",false],"id":1}`, - unmarshalled: &btcjson.ImportAddressCmd{ - Address: "1Address", - Rescan: btcjson.Bool(false), - }, - }, - { - name: "importPubKey", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("importPubKey", "031234") - }, - staticCmd: func() interface{} { - return btcjson.NewImportPubKeyCmd("031234", nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"importPubKey","params":["031234"],"id":1}`, - unmarshalled: &btcjson.ImportPubKeyCmd{ - PubKey: "031234", - Rescan: btcjson.Bool(true), - }, - }, - { - name: "importPubKey optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("importPubKey", "031234", false) - }, - staticCmd: func() interface{} { - return btcjson.NewImportPubKeyCmd("031234", btcjson.Bool(false)) - }, - marshalled: `{"jsonrpc":"1.0","method":"importPubKey","params":["031234",false],"id":1}`, - unmarshalled: &btcjson.ImportPubKeyCmd{ - PubKey: "031234", - Rescan: btcjson.Bool(false), - }, - }, - { - name: "importWallet", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("importWallet", "filename") - }, - staticCmd: func() interface{} { - return btcjson.NewImportWalletCmd("filename") - }, - marshalled: `{"jsonrpc":"1.0","method":"importWallet","params":["filename"],"id":1}`, - unmarshalled: &btcjson.ImportWalletCmd{ - Filename: "filename", - }, - }, - { - name: "renameAccount", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("renameAccount", "oldacct", "newacct") - }, - staticCmd: func() interface{} { - return btcjson.NewRenameAccountCmd("oldacct", "newacct") - }, - marshalled: `{"jsonrpc":"1.0","method":"renameAccount","params":["oldacct","newacct"],"id":1}`, - unmarshalled: &btcjson.RenameAccountCmd{ - OldAccount: "oldacct", - NewAccount: "newacct", - }, - }, - } - - t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - // Marshal the command as created by the new static command - // creation function. - marshalled, err := btcjson.MarshalCmd(testID, test.staticCmd()) - if err != nil { - t.Errorf("MarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !bytes.Equal(marshalled, []byte(test.marshalled)) { - t.Errorf("Test #%d (%s) unexpected marshalled data - "+ - "got %s, want %s", i, test.name, marshalled, - test.marshalled) - continue - } - - // Ensure the command is created without error via the generic - // new command creation function. - cmd, err := test.newCmd() - if err != nil { - t.Errorf("Test #%d (%s) unexpected NewCmd error: %v ", - i, test.name, err) - } - - // Marshal the command as created by the generic new command - // creation function. - marshalled, err = btcjson.MarshalCmd(testID, cmd) - if err != nil { - t.Errorf("MarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !bytes.Equal(marshalled, []byte(test.marshalled)) { - t.Errorf("Test #%d (%s) unexpected marshalled data - "+ - "got %s, want %s", i, test.name, marshalled, - test.marshalled) - continue - } - - var request btcjson.Request - if err := json.Unmarshal(marshalled, &request); err != nil { - t.Errorf("Test #%d (%s) unexpected error while "+ - "unmarshalling JSON-RPC request: %v", i, - test.name, err) - continue - } - - cmd, err = btcjson.UnmarshalCmd(&request) - if err != nil { - t.Errorf("UnmarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !reflect.DeepEqual(cmd, test.unmarshalled) { - t.Errorf("Test #%d (%s) unexpected unmarshalled command "+ - "- got %s, want %s", i, test.name, - fmt.Sprintf("(%T) %+[1]v", cmd), - fmt.Sprintf("(%T) %+[1]v\n", test.unmarshalled)) - continue - } - } -} diff --git a/btcjson/cmdinfo_test.go b/btcjson/cmdinfo_test.go index cd3c1850f..80cafe8f3 100644 --- a/btcjson/cmdinfo_test.go +++ b/btcjson/cmdinfo_test.go @@ -90,11 +90,6 @@ func TestMethodUsageFlags(t *testing.T) { method: "getBlock", flags: 0, }, - { - name: "walletPassphrase", - method: "walletPassphrase", - flags: btcjson.UFWalletOnly, - }, } t.Logf("Running %d tests", len(tests)) diff --git a/btcjson/dagsvrresults.go b/btcjson/dagsvrresults.go index f4e3ecf6a..f4c9c76c1 100644 --- a/btcjson/dagsvrresults.go +++ b/btcjson/dagsvrresults.go @@ -502,3 +502,9 @@ type ValidateAddressResult struct { IsValid bool `json:"isValid"` Address string `json:"address,omitempty"` } + +// GetBestBlockResult models the data from the getbestblock command. +type GetBestBlockResult struct { + Hash string `json:"hash"` + Height uint64 `json:"height"` +} diff --git a/btcjson/doc.go b/btcjson/doc.go index d3b4d22bd..33c32eb77 100644 --- a/btcjson/doc.go +++ b/btcjson/doc.go @@ -107,7 +107,7 @@ function. Command Inspection All registered commands are registered with flags that identify information such -as whether the command applies to a dag server, wallet server, or is a +as whether the command applies to a dag 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. diff --git a/btcjson/jsonrpcerr.go b/btcjson/jsonrpcerr.go index ae2b51de5..641c2b916 100644 --- a/btcjson/jsonrpcerr.go +++ b/btcjson/jsonrpcerr.go @@ -48,19 +48,6 @@ const ( ErrRPCClientNodeNotAdded RPCErrorCode = -24 ) -// Wallet JSON errors -const ( - ErrRPCWallet RPCErrorCode = -4 - ErrRPCWalletInsufficientFunds RPCErrorCode = -6 - ErrRPCWalletInvalidAccountName RPCErrorCode = -11 - ErrRPCWalletKeypoolRanOut RPCErrorCode = -12 - ErrRPCWalletUnlockNeeded RPCErrorCode = -13 - ErrRPCWalletPassphraseIncorrect RPCErrorCode = -14 - ErrRPCWalletWrongEncState RPCErrorCode = -15 - ErrRPCWalletEncryptionFailed RPCErrorCode = -16 - ErrRPCWalletAlreadyUnlocked RPCErrorCode = -17 -) - // 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. @@ -81,6 +68,5 @@ const ( // Errors that are specific to btcd. const ( - ErrRPCNoWallet RPCErrorCode = -1 ErrRPCUnimplemented RPCErrorCode = -1 ) diff --git a/btcjson/register.go b/btcjson/register.go index 8a85e756c..434baeaab 100644 --- a/btcjson/register.go +++ b/btcjson/register.go @@ -19,15 +19,11 @@ import ( type UsageFlag uint32 const ( - // UFWalletOnly indicates that the command can only be used with an RPC - // server that supports wallet commands. - UFWalletOnly UsageFlag = 1 << iota - // UFWebsocketOnly indicates that the command can only be used when // communicating with an RPC server over websockets. This typically // applies to notifications and notification registration functions // since neiher makes since when using a single-shot HTTP-POST request. - UFWebsocketOnly + UFWebsocketOnly UsageFlag = 1 << iota // UFNotification indicates that the command is actually a notification. // This means when it is marshalled, the ID must be nil. @@ -41,7 +37,6 @@ const ( // Map of UsageFlag values back to their constant names for pretty printing. var usageFlagStrings = map[UsageFlag]string{ - UFWalletOnly: "UFWalletOnly", UFWebsocketOnly: "UFWebsocketOnly", UFNotification: "UFNotification", } @@ -55,7 +50,7 @@ func (fl UsageFlag) String() string { // Add individual bit flags. s := "" - for flag := UFWalletOnly; flag < highestUsageFlagBit; flag <<= 1 { + for flag := UFWebsocketOnly; flag < highestUsageFlagBit; flag <<= 1 { if fl&flag == flag { s += usageFlagStrings[flag] + "|" fl -= flag diff --git a/btcjson/register_test.go b/btcjson/register_test.go index 82b14d0bb..671a55a26 100644 --- a/btcjson/register_test.go +++ b/btcjson/register_test.go @@ -21,13 +21,12 @@ func TestUsageFlagStringer(t *testing.T) { want string }{ {0, "0x0"}, - {btcjson.UFWalletOnly, "UFWalletOnly"}, {btcjson.UFWebsocketOnly, "UFWebsocketOnly"}, {btcjson.UFNotification, "UFNotification"}, - {btcjson.UFWalletOnly | btcjson.UFWebsocketOnly, - "UFWalletOnly|UFWebsocketOnly"}, - {btcjson.UFWalletOnly | btcjson.UFWebsocketOnly | (1 << 31), - "UFWalletOnly|UFWebsocketOnly|0x80000000"}, + {btcjson.UFWebsocketOnly | btcjson.UFNotification, + "UFWebsocketOnly|UFNotification"}, + {btcjson.UFWebsocketOnly | btcjson.UFNotification | (1 << 31), + "UFWebsocketOnly|UFNotification|0x80000000"}, } // Detect additional usage flags that don't have the stringer added. diff --git a/btcjson/walletsvrcmds.go b/btcjson/walletsvrcmds.go deleted file mode 100644 index 5431ef51b..000000000 --- a/btcjson/walletsvrcmds.go +++ /dev/null @@ -1,671 +0,0 @@ -// Copyright (c) 2014 The btcsuite developers -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -// NOTE: This file is intended to house the RPC commands that are supported by -// a wallet server. - -package btcjson - -// AddMultisigAddressCmd defines the addmutisigaddress JSON-RPC command. -type AddMultisigAddressCmd struct { - NRequired int - Keys []string - Account *string -} - -// NewAddMultisigAddressCmd returns a new instance which can be used to issue a -// addMultisigAddress JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewAddMultisigAddressCmd(nRequired int, keys []string, account *string) *AddMultisigAddressCmd { - return &AddMultisigAddressCmd{ - NRequired: nRequired, - Keys: keys, - Account: account, - } -} - -// CreateMultisigCmd defines the createMultisig JSON-RPC command. -type CreateMultisigCmd struct { - NRequired int - Keys []string -} - -// NewCreateMultisigCmd returns a new instance which can be used to issue a -// createMultisig JSON-RPC command. -func NewCreateMultisigCmd(nRequired int, keys []string) *CreateMultisigCmd { - return &CreateMultisigCmd{ - NRequired: nRequired, - Keys: keys, - } -} - -// DumpPrivKeyCmd defines the dumpPrivKey JSON-RPC command. -type DumpPrivKeyCmd struct { - Address string -} - -// NewDumpPrivKeyCmd returns a new instance which can be used to issue a -// dumpPrivKey JSON-RPC command. -func NewDumpPrivKeyCmd(address string) *DumpPrivKeyCmd { - return &DumpPrivKeyCmd{ - Address: address, - } -} - -// EncryptWalletCmd defines the encryptWallet JSON-RPC command. -type EncryptWalletCmd struct { - Passphrase string -} - -// NewEncryptWalletCmd returns a new instance which can be used to issue a -// encryptWallet JSON-RPC command. -func NewEncryptWalletCmd(passphrase string) *EncryptWalletCmd { - return &EncryptWalletCmd{ - Passphrase: passphrase, - } -} - -// EstimatePriorityCmd defines the estimatePriority JSON-RPC command. -type EstimatePriorityCmd struct { - NumBlocks int64 -} - -// NewEstimatePriorityCmd returns a new instance which can be used to issue a -// estimatePriority JSON-RPC command. -func NewEstimatePriorityCmd(numBlocks int64) *EstimatePriorityCmd { - return &EstimatePriorityCmd{ - NumBlocks: numBlocks, - } -} - -// GetAccountCmd defines the getAccount JSON-RPC command. -type GetAccountCmd struct { - Address string -} - -// NewGetAccountCmd returns a new instance which can be used to issue a -// getAccount JSON-RPC command. -func NewGetAccountCmd(address string) *GetAccountCmd { - return &GetAccountCmd{ - Address: address, - } -} - -// GetAccountAddressCmd defines the getAccountAddress JSON-RPC command. -type GetAccountAddressCmd struct { - Account string -} - -// NewGetAccountAddressCmd returns a new instance which can be used to issue a -// getAccountAddress JSON-RPC command. -func NewGetAccountAddressCmd(account string) *GetAccountAddressCmd { - return &GetAccountAddressCmd{ - Account: account, - } -} - -// GetAddressesByAccountCmd defines the getAddressesByAccount JSON-RPC command. -type GetAddressesByAccountCmd struct { - Account string -} - -// NewGetAddressesByAccountCmd returns a new instance which can be used to issue -// a getAddressesByAccount JSON-RPC command. -func NewGetAddressesByAccountCmd(account string) *GetAddressesByAccountCmd { - return &GetAddressesByAccountCmd{ - Account: account, - } -} - -// GetBalanceCmd defines the getBalance JSON-RPC command. -type GetBalanceCmd struct { - Account *string - MinConf *int `jsonrpcdefault:"1"` -} - -// NewGetBalanceCmd returns a new instance which can be used to issue a -// getBalance JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewGetBalanceCmd(account *string, minConf *int) *GetBalanceCmd { - return &GetBalanceCmd{ - Account: account, - MinConf: minConf, - } -} - -// GetNewAddressCmd defines the getNewAddress JSON-RPC command. -type GetNewAddressCmd struct { - Account *string -} - -// NewGetNewAddressCmd returns a new instance which can be used to issue a -// getNewAddress JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewGetNewAddressCmd(account *string) *GetNewAddressCmd { - return &GetNewAddressCmd{ - Account: account, - } -} - -// GetRawChangeAddressCmd defines the getRawChangeAddress JSON-RPC command. -type GetRawChangeAddressCmd struct { - Account *string -} - -// NewGetRawChangeAddressCmd returns a new instance which can be used to issue a -// getRawChangeAddress JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewGetRawChangeAddressCmd(account *string) *GetRawChangeAddressCmd { - return &GetRawChangeAddressCmd{ - Account: account, - } -} - -// GetReceivedByAccountCmd defines the getReceivedByAccount JSON-RPC command. -type GetReceivedByAccountCmd struct { - Account string - MinConf *int `jsonrpcdefault:"1"` -} - -// NewGetReceivedByAccountCmd returns a new instance which can be used to issue -// a getReceivedByAccount JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewGetReceivedByAccountCmd(account string, minConf *int) *GetReceivedByAccountCmd { - return &GetReceivedByAccountCmd{ - Account: account, - MinConf: minConf, - } -} - -// GetReceivedByAddressCmd defines the getReceivedByAddress JSON-RPC command. -type GetReceivedByAddressCmd struct { - Address string - MinConf *int `jsonrpcdefault:"1"` -} - -// NewGetReceivedByAddressCmd returns a new instance which can be used to issue -// a getReceivedByAddress JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewGetReceivedByAddressCmd(address string, minConf *int) *GetReceivedByAddressCmd { - return &GetReceivedByAddressCmd{ - Address: address, - MinConf: minConf, - } -} - -// GetTransactionCmd defines the getTransaction JSON-RPC command. -type GetTransactionCmd struct { - TxID string - IncludeWatchOnly *bool `jsonrpcdefault:"false"` -} - -// NewGetTransactionCmd returns a new instance which can be used to issue a -// getTransaction JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewGetTransactionCmd(txHash string, includeWatchOnly *bool) *GetTransactionCmd { - return &GetTransactionCmd{ - TxID: txHash, - IncludeWatchOnly: includeWatchOnly, - } -} - -// GetWalletInfoCmd defines the getWalletInfo JSON-RPC command. -type GetWalletInfoCmd struct{} - -// NewGetWalletInfoCmd returns a new instance which can be used to issue a -// getWalletInfo JSON-RPC command. -func NewGetWalletInfoCmd() *GetWalletInfoCmd { - return &GetWalletInfoCmd{} -} - -// ImportPrivKeyCmd defines the importPrivKey JSON-RPC command. -type ImportPrivKeyCmd struct { - PrivKey string - Label *string - Rescan *bool `jsonrpcdefault:"true"` -} - -// NewImportPrivKeyCmd returns a new instance which can be used to issue a -// importPrivKey JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewImportPrivKeyCmd(privKey string, label *string, rescan *bool) *ImportPrivKeyCmd { - return &ImportPrivKeyCmd{ - PrivKey: privKey, - Label: label, - Rescan: rescan, - } -} - -// KeyPoolRefillCmd defines the keyPoolRefill JSON-RPC command. -type KeyPoolRefillCmd struct { - NewSize *uint `jsonrpcdefault:"100"` -} - -// NewKeyPoolRefillCmd returns a new instance which can be used to issue a -// keyPoolRefill JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewKeyPoolRefillCmd(newSize *uint) *KeyPoolRefillCmd { - return &KeyPoolRefillCmd{ - NewSize: newSize, - } -} - -// ListAccountsCmd defines the listAccounts JSON-RPC command. -type ListAccountsCmd struct { - MinConf *int `jsonrpcdefault:"1"` -} - -// NewListAccountsCmd returns a new instance which can be used to issue a -// listAccounts JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewListAccountsCmd(minConf *int) *ListAccountsCmd { - return &ListAccountsCmd{ - MinConf: minConf, - } -} - -// ListAddressGroupingsCmd defines the listAddressGroupings JSON-RPC command. -type ListAddressGroupingsCmd struct{} - -// NewListAddressGroupingsCmd returns a new instance which can be used to issue -// a listaddressgroupoings JSON-RPC command. -func NewListAddressGroupingsCmd() *ListAddressGroupingsCmd { - return &ListAddressGroupingsCmd{} -} - -// ListLockUnspentCmd defines the listLockUnspent JSON-RPC command. -type ListLockUnspentCmd struct{} - -// NewListLockUnspentCmd returns a new instance which can be used to issue a -// listLockUnspent JSON-RPC command. -func NewListLockUnspentCmd() *ListLockUnspentCmd { - return &ListLockUnspentCmd{} -} - -// ListReceivedByAccountCmd defines the listReceivedByAccount JSON-RPC command. -type ListReceivedByAccountCmd struct { - MinConf *int `jsonrpcdefault:"1"` - IncludeEmpty *bool `jsonrpcdefault:"false"` - IncludeWatchOnly *bool `jsonrpcdefault:"false"` -} - -// NewListReceivedByAccountCmd returns a new instance which can be used to issue -// a listReceivedByAccount JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewListReceivedByAccountCmd(minConf *int, includeEmpty, includeWatchOnly *bool) *ListReceivedByAccountCmd { - return &ListReceivedByAccountCmd{ - MinConf: minConf, - IncludeEmpty: includeEmpty, - IncludeWatchOnly: includeWatchOnly, - } -} - -// ListReceivedByAddressCmd defines the listReceivedByAddress JSON-RPC command. -type ListReceivedByAddressCmd struct { - MinConf *int `jsonrpcdefault:"1"` - IncludeEmpty *bool `jsonrpcdefault:"false"` - IncludeWatchOnly *bool `jsonrpcdefault:"false"` -} - -// NewListReceivedByAddressCmd returns a new instance which can be used to issue -// a listReceivedByAddress JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewListReceivedByAddressCmd(minConf *int, includeEmpty, includeWatchOnly *bool) *ListReceivedByAddressCmd { - return &ListReceivedByAddressCmd{ - MinConf: minConf, - IncludeEmpty: includeEmpty, - IncludeWatchOnly: includeWatchOnly, - } -} - -// ListSinceBlockCmd defines the listSinceBlock JSON-RPC command. -type ListSinceBlockCmd struct { - BlockHash *string - TargetConfirmations *int `jsonrpcdefault:"1"` - IncludeWatchOnly *bool `jsonrpcdefault:"false"` -} - -// NewListSinceBlockCmd returns a new instance which can be used to issue a -// listSinceBlock JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewListSinceBlockCmd(blockHash *string, targetConfirms *int, includeWatchOnly *bool) *ListSinceBlockCmd { - return &ListSinceBlockCmd{ - BlockHash: blockHash, - TargetConfirmations: targetConfirms, - IncludeWatchOnly: includeWatchOnly, - } -} - -// ListTransactionsCmd defines the listTransactions JSON-RPC command. -type ListTransactionsCmd struct { - Account *string - Count *int `jsonrpcdefault:"10"` - From *int `jsonrpcdefault:"0"` - IncludeWatchOnly *bool `jsonrpcdefault:"false"` -} - -// NewListTransactionsCmd returns a new instance which can be used to issue a -// listTransactions JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewListTransactionsCmd(account *string, count, from *int, includeWatchOnly *bool) *ListTransactionsCmd { - return &ListTransactionsCmd{ - Account: account, - Count: count, - From: from, - IncludeWatchOnly: includeWatchOnly, - } -} - -// ListUnspentCmd defines the listUnspent JSON-RPC command. -type ListUnspentCmd struct { - MinConf *int `jsonrpcdefault:"1"` - MaxConf *int `jsonrpcdefault:"9999999"` - Addresses *[]string -} - -// NewListUnspentCmd returns a new instance which can be used to issue a -// listUnspent JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewListUnspentCmd(minConf, maxConf *int, addresses *[]string) *ListUnspentCmd { - return &ListUnspentCmd{ - MinConf: minConf, - MaxConf: maxConf, - Addresses: addresses, - } -} - -// LockUnspentCmd defines the lockUnspent JSON-RPC command. -type LockUnspentCmd struct { - Unlock bool - Transactions []TransactionInput -} - -// NewLockUnspentCmd returns a new instance which can be used to issue a -// lockUnspent JSON-RPC command. -func NewLockUnspentCmd(unlock bool, transactions []TransactionInput) *LockUnspentCmd { - return &LockUnspentCmd{ - Unlock: unlock, - Transactions: transactions, - } -} - -// MoveCmd defines the move JSON-RPC command. -type MoveCmd struct { - FromAccount string - ToAccount string - Amount float64 // In BTC - MinConf *int `jsonrpcdefault:"1"` - Comment *string -} - -// NewMoveCmd returns a new instance which can be used to issue a move JSON-RPC -// command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewMoveCmd(fromAccount, toAccount string, amount float64, minConf *int, comment *string) *MoveCmd { - return &MoveCmd{ - FromAccount: fromAccount, - ToAccount: toAccount, - Amount: amount, - MinConf: minConf, - Comment: comment, - } -} - -// SendFromCmd defines the sendFrom JSON-RPC command. -type SendFromCmd struct { - FromAccount string - ToAddress string - Amount float64 // In BTC - MinConf *int `jsonrpcdefault:"1"` - Comment *string - CommentTo *string -} - -// NewSendFromCmd returns a new instance which can be used to issue a sendFrom -// JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewSendFromCmd(fromAccount, toAddress string, amount float64, minConf *int, comment, commentTo *string) *SendFromCmd { - return &SendFromCmd{ - FromAccount: fromAccount, - ToAddress: toAddress, - Amount: amount, - MinConf: minConf, - Comment: comment, - CommentTo: commentTo, - } -} - -// SendManyCmd defines the sendMany JSON-RPC command. -type SendManyCmd struct { - FromAccount string - Amounts map[string]float64 `jsonrpcusage:"{\"address\":amount,...}"` // In BTC - MinConf *int `jsonrpcdefault:"1"` - Comment *string -} - -// NewSendManyCmd returns a new instance which can be used to issue a sendMany -// JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewSendManyCmd(fromAccount string, amounts map[string]float64, minConf *int, comment *string) *SendManyCmd { - return &SendManyCmd{ - FromAccount: fromAccount, - Amounts: amounts, - MinConf: minConf, - Comment: comment, - } -} - -// SendToAddressCmd defines the sendToAddress JSON-RPC command. -type SendToAddressCmd struct { - Address string - Amount float64 - Comment *string - CommentTo *string -} - -// NewSendToAddressCmd returns a new instance which can be used to issue a -// sendToAddress JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewSendToAddressCmd(address string, amount float64, comment, commentTo *string) *SendToAddressCmd { - return &SendToAddressCmd{ - Address: address, - Amount: amount, - Comment: comment, - CommentTo: commentTo, - } -} - -// SetAccountCmd defines the setAccount JSON-RPC command. -type SetAccountCmd struct { - Address string - Account string -} - -// NewSetAccountCmd returns a new instance which can be used to issue a -// setAccount JSON-RPC command. -func NewSetAccountCmd(address, account string) *SetAccountCmd { - return &SetAccountCmd{ - Address: address, - Account: account, - } -} - -// SetTxFeeCmd defines the setTxFee JSON-RPC command. -type SetTxFeeCmd struct { - Amount float64 // In BTC -} - -// NewSetTxFeeCmd returns a new instance which can be used to issue a setTxFee -// JSON-RPC command. -func NewSetTxFeeCmd(amount float64) *SetTxFeeCmd { - return &SetTxFeeCmd{ - Amount: amount, - } -} - -// SignMessageCmd defines the signMessage JSON-RPC command. -type SignMessageCmd struct { - Address string - Message string -} - -// NewSignMessageCmd returns a new instance which can be used to issue a -// signMessage JSON-RPC command. -func NewSignMessageCmd(address, message string) *SignMessageCmd { - return &SignMessageCmd{ - Address: address, - Message: message, - } -} - -// RawTxInput models the data needed for raw transaction input that is used in -// the SignRawTransactionCmd struct. -type RawTxInput struct { - TxID string `json:"txId"` - Vout uint32 `json:"vout"` - ScriptPubKey string `json:"scriptPubKey"` - RedeemScript string `json:"redeemScript"` -} - -// SignRawTransactionCmd defines the signRawTransaction JSON-RPC command. -type SignRawTransactionCmd struct { - RawTx string - Inputs *[]RawTxInput - PrivKeys *[]string - Flags *string `jsonrpcdefault:"\"ALL\""` -} - -// NewSignRawTransactionCmd returns a new instance which can be used to issue a -// signRawTransaction JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewSignRawTransactionCmd(hexEncodedTx string, inputs *[]RawTxInput, privKeys *[]string, flags *string) *SignRawTransactionCmd { - return &SignRawTransactionCmd{ - RawTx: hexEncodedTx, - Inputs: inputs, - PrivKeys: privKeys, - Flags: flags, - } -} - -// WalletLockCmd defines the walletLock JSON-RPC command. -type WalletLockCmd struct{} - -// NewWalletLockCmd returns a new instance which can be used to issue a -// walletLock JSON-RPC command. -func NewWalletLockCmd() *WalletLockCmd { - return &WalletLockCmd{} -} - -// WalletPassphraseCmd defines the walletPassphrase JSON-RPC command. -type WalletPassphraseCmd struct { - Passphrase string - Timeout int64 -} - -// NewWalletPassphraseCmd returns a new instance which can be used to issue a -// walletPassphrase JSON-RPC command. -func NewWalletPassphraseCmd(passphrase string, timeout int64) *WalletPassphraseCmd { - return &WalletPassphraseCmd{ - Passphrase: passphrase, - Timeout: timeout, - } -} - -// WalletPassphraseChangeCmd defines the walletPassphrase JSON-RPC command. -type WalletPassphraseChangeCmd struct { - OldPassphrase string - NewPassphrase string -} - -// NewWalletPassphraseChangeCmd returns a new instance which can be used to -// issue a walletPassphraseChange JSON-RPC command. -func NewWalletPassphraseChangeCmd(oldPassphrase, newPassphrase string) *WalletPassphraseChangeCmd { - return &WalletPassphraseChangeCmd{ - OldPassphrase: oldPassphrase, - NewPassphrase: newPassphrase, - } -} - -func init() { - // The commands in this file are only usable with a wallet server. - flags := UFWalletOnly - - MustRegisterCmd("addMultisigAddress", (*AddMultisigAddressCmd)(nil), flags) - MustRegisterCmd("createMultisig", (*CreateMultisigCmd)(nil), flags) - MustRegisterCmd("dumpPrivKey", (*DumpPrivKeyCmd)(nil), flags) - MustRegisterCmd("encryptWallet", (*EncryptWalletCmd)(nil), flags) - MustRegisterCmd("estimatePriority", (*EstimatePriorityCmd)(nil), flags) - MustRegisterCmd("getAccount", (*GetAccountCmd)(nil), flags) - MustRegisterCmd("getAccountAddress", (*GetAccountAddressCmd)(nil), flags) - MustRegisterCmd("getAddressesByAccount", (*GetAddressesByAccountCmd)(nil), flags) - MustRegisterCmd("getBalance", (*GetBalanceCmd)(nil), flags) - MustRegisterCmd("getNewAddress", (*GetNewAddressCmd)(nil), flags) - MustRegisterCmd("getRawChangeAddress", (*GetRawChangeAddressCmd)(nil), flags) - MustRegisterCmd("getReceivedByAccount", (*GetReceivedByAccountCmd)(nil), flags) - MustRegisterCmd("getReceivedByAddress", (*GetReceivedByAddressCmd)(nil), flags) - MustRegisterCmd("getTransaction", (*GetTransactionCmd)(nil), flags) - MustRegisterCmd("getWalletInfo", (*GetWalletInfoCmd)(nil), flags) - MustRegisterCmd("importPrivKey", (*ImportPrivKeyCmd)(nil), flags) - MustRegisterCmd("keyPoolRefill", (*KeyPoolRefillCmd)(nil), flags) - MustRegisterCmd("listAccounts", (*ListAccountsCmd)(nil), flags) - MustRegisterCmd("listAddressGroupings", (*ListAddressGroupingsCmd)(nil), flags) - MustRegisterCmd("listLockUnspent", (*ListLockUnspentCmd)(nil), flags) - MustRegisterCmd("listReceivedByAccount", (*ListReceivedByAccountCmd)(nil), flags) - MustRegisterCmd("listReceivedByAddress", (*ListReceivedByAddressCmd)(nil), flags) - MustRegisterCmd("listSinceBlock", (*ListSinceBlockCmd)(nil), flags) - MustRegisterCmd("listTransactions", (*ListTransactionsCmd)(nil), flags) - MustRegisterCmd("listUnspent", (*ListUnspentCmd)(nil), flags) - MustRegisterCmd("lockUnspent", (*LockUnspentCmd)(nil), flags) - MustRegisterCmd("move", (*MoveCmd)(nil), flags) - MustRegisterCmd("sendFrom", (*SendFromCmd)(nil), flags) - MustRegisterCmd("sendMany", (*SendManyCmd)(nil), flags) - MustRegisterCmd("sendToAddress", (*SendToAddressCmd)(nil), flags) - MustRegisterCmd("setAccount", (*SetAccountCmd)(nil), flags) - MustRegisterCmd("setTxFee", (*SetTxFeeCmd)(nil), flags) - MustRegisterCmd("signMessage", (*SignMessageCmd)(nil), flags) - MustRegisterCmd("signRawTransaction", (*SignRawTransactionCmd)(nil), flags) - MustRegisterCmd("walletLock", (*WalletLockCmd)(nil), flags) - MustRegisterCmd("walletPassphrase", (*WalletPassphraseCmd)(nil), flags) - MustRegisterCmd("walletPassphraseChange", (*WalletPassphraseChangeCmd)(nil), flags) -} diff --git a/btcjson/walletsvrcmds_test.go b/btcjson/walletsvrcmds_test.go deleted file mode 100644 index 5e9576ef1..000000000 --- a/btcjson/walletsvrcmds_test.go +++ /dev/null @@ -1,1248 +0,0 @@ -// Copyright (c) 2014 The btcsuite developers -// 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" - "fmt" - "reflect" - "testing" - - "github.com/daglabs/btcd/btcjson" -) - -// TestWalletSvrCmds tests all of the wallet server commands marshal and -// unmarshal into valid results include handling of optional fields being -// omitted in the marshalled command, while optional fields with defaults have -// the default assigned on unmarshalled commands. -func TestWalletSvrCmds(t *testing.T) { - t.Parallel() - - testID := int(1) - tests := []struct { - name string - newCmd func() (interface{}, error) - staticCmd func() interface{} - marshalled string - unmarshalled interface{} - }{ - { - name: "addMultisigAddress", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("addMultisigAddress", 2, []string{"031234", "035678"}) - }, - staticCmd: func() interface{} { - keys := []string{"031234", "035678"} - return btcjson.NewAddMultisigAddressCmd(2, keys, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"addMultisigAddress","params":[2,["031234","035678"]],"id":1}`, - unmarshalled: &btcjson.AddMultisigAddressCmd{ - NRequired: 2, - Keys: []string{"031234", "035678"}, - Account: nil, - }, - }, - { - name: "addMultisigAddress optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("addMultisigAddress", 2, []string{"031234", "035678"}, "test") - }, - staticCmd: func() interface{} { - keys := []string{"031234", "035678"} - return btcjson.NewAddMultisigAddressCmd(2, keys, btcjson.String("test")) - }, - marshalled: `{"jsonrpc":"1.0","method":"addMultisigAddress","params":[2,["031234","035678"],"test"],"id":1}`, - unmarshalled: &btcjson.AddMultisigAddressCmd{ - NRequired: 2, - Keys: []string{"031234", "035678"}, - Account: btcjson.String("test"), - }, - }, - { - name: "createMultisig", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("createMultisig", 2, []string{"031234", "035678"}) - }, - staticCmd: func() interface{} { - keys := []string{"031234", "035678"} - return btcjson.NewCreateMultisigCmd(2, keys) - }, - marshalled: `{"jsonrpc":"1.0","method":"createMultisig","params":[2,["031234","035678"]],"id":1}`, - unmarshalled: &btcjson.CreateMultisigCmd{ - NRequired: 2, - Keys: []string{"031234", "035678"}, - }, - }, - { - name: "dumpPrivKey", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("dumpPrivKey", "1Address") - }, - staticCmd: func() interface{} { - return btcjson.NewDumpPrivKeyCmd("1Address") - }, - marshalled: `{"jsonrpc":"1.0","method":"dumpPrivKey","params":["1Address"],"id":1}`, - unmarshalled: &btcjson.DumpPrivKeyCmd{ - Address: "1Address", - }, - }, - { - name: "encryptWallet", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("encryptWallet", "pass") - }, - staticCmd: func() interface{} { - return btcjson.NewEncryptWalletCmd("pass") - }, - marshalled: `{"jsonrpc":"1.0","method":"encryptWallet","params":["pass"],"id":1}`, - unmarshalled: &btcjson.EncryptWalletCmd{ - Passphrase: "pass", - }, - }, - { - name: "estimatePriority", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("estimatePriority", 6) - }, - staticCmd: func() interface{} { - return btcjson.NewEstimatePriorityCmd(6) - }, - marshalled: `{"jsonrpc":"1.0","method":"estimatePriority","params":[6],"id":1}`, - unmarshalled: &btcjson.EstimatePriorityCmd{ - NumBlocks: 6, - }, - }, - { - name: "getAccount", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getAccount", "1Address") - }, - staticCmd: func() interface{} { - return btcjson.NewGetAccountCmd("1Address") - }, - marshalled: `{"jsonrpc":"1.0","method":"getAccount","params":["1Address"],"id":1}`, - unmarshalled: &btcjson.GetAccountCmd{ - Address: "1Address", - }, - }, - { - name: "getAccountAddress", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getAccountAddress", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewGetAccountAddressCmd("acct") - }, - marshalled: `{"jsonrpc":"1.0","method":"getAccountAddress","params":["acct"],"id":1}`, - unmarshalled: &btcjson.GetAccountAddressCmd{ - Account: "acct", - }, - }, - { - name: "getAddressesByAccount", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getAddressesByAccount", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewGetAddressesByAccountCmd("acct") - }, - marshalled: `{"jsonrpc":"1.0","method":"getAddressesByAccount","params":["acct"],"id":1}`, - unmarshalled: &btcjson.GetAddressesByAccountCmd{ - Account: "acct", - }, - }, - { - name: "getBalance", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getBalance") - }, - staticCmd: func() interface{} { - return btcjson.NewGetBalanceCmd(nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"getBalance","params":[],"id":1}`, - unmarshalled: &btcjson.GetBalanceCmd{ - Account: nil, - MinConf: btcjson.Int(1), - }, - }, - { - name: "getBalance optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getBalance", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewGetBalanceCmd(btcjson.String("acct"), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"getBalance","params":["acct"],"id":1}`, - unmarshalled: &btcjson.GetBalanceCmd{ - Account: btcjson.String("acct"), - MinConf: btcjson.Int(1), - }, - }, - { - name: "getBalance optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getBalance", "acct", 6) - }, - staticCmd: func() interface{} { - return btcjson.NewGetBalanceCmd(btcjson.String("acct"), btcjson.Int(6)) - }, - marshalled: `{"jsonrpc":"1.0","method":"getBalance","params":["acct",6],"id":1}`, - unmarshalled: &btcjson.GetBalanceCmd{ - Account: btcjson.String("acct"), - MinConf: btcjson.Int(6), - }, - }, - { - name: "getNewAddress", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getNewAddress") - }, - staticCmd: func() interface{} { - return btcjson.NewGetNewAddressCmd(nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"getNewAddress","params":[],"id":1}`, - unmarshalled: &btcjson.GetNewAddressCmd{ - Account: nil, - }, - }, - { - name: "getNewAddress optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getNewAddress", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewGetNewAddressCmd(btcjson.String("acct")) - }, - marshalled: `{"jsonrpc":"1.0","method":"getNewAddress","params":["acct"],"id":1}`, - unmarshalled: &btcjson.GetNewAddressCmd{ - Account: btcjson.String("acct"), - }, - }, - { - name: "getRawChangeAddress", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getRawChangeAddress") - }, - staticCmd: func() interface{} { - return btcjson.NewGetRawChangeAddressCmd(nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"getRawChangeAddress","params":[],"id":1}`, - unmarshalled: &btcjson.GetRawChangeAddressCmd{ - Account: nil, - }, - }, - { - name: "getRawChangeAddress optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getRawChangeAddress", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewGetRawChangeAddressCmd(btcjson.String("acct")) - }, - marshalled: `{"jsonrpc":"1.0","method":"getRawChangeAddress","params":["acct"],"id":1}`, - unmarshalled: &btcjson.GetRawChangeAddressCmd{ - Account: btcjson.String("acct"), - }, - }, - { - name: "getReceivedByAccount", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getReceivedByAccount", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewGetReceivedByAccountCmd("acct", nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"getReceivedByAccount","params":["acct"],"id":1}`, - unmarshalled: &btcjson.GetReceivedByAccountCmd{ - Account: "acct", - MinConf: btcjson.Int(1), - }, - }, - { - name: "getReceivedByAccount optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getReceivedByAccount", "acct", 6) - }, - staticCmd: func() interface{} { - return btcjson.NewGetReceivedByAccountCmd("acct", btcjson.Int(6)) - }, - marshalled: `{"jsonrpc":"1.0","method":"getReceivedByAccount","params":["acct",6],"id":1}`, - unmarshalled: &btcjson.GetReceivedByAccountCmd{ - Account: "acct", - MinConf: btcjson.Int(6), - }, - }, - { - name: "getReceivedByAddress", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getReceivedByAddress", "1Address") - }, - staticCmd: func() interface{} { - return btcjson.NewGetReceivedByAddressCmd("1Address", nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"getReceivedByAddress","params":["1Address"],"id":1}`, - unmarshalled: &btcjson.GetReceivedByAddressCmd{ - Address: "1Address", - MinConf: btcjson.Int(1), - }, - }, - { - name: "getReceivedByAddress optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getReceivedByAddress", "1Address", 6) - }, - staticCmd: func() interface{} { - return btcjson.NewGetReceivedByAddressCmd("1Address", btcjson.Int(6)) - }, - marshalled: `{"jsonrpc":"1.0","method":"getReceivedByAddress","params":["1Address",6],"id":1}`, - unmarshalled: &btcjson.GetReceivedByAddressCmd{ - Address: "1Address", - MinConf: btcjson.Int(6), - }, - }, - { - name: "getTransaction", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getTransaction", "123") - }, - staticCmd: func() interface{} { - return btcjson.NewGetTransactionCmd("123", nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"getTransaction","params":["123"],"id":1}`, - unmarshalled: &btcjson.GetTransactionCmd{ - TxID: "123", - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "getTransaction optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getTransaction", "123", true) - }, - staticCmd: func() interface{} { - return btcjson.NewGetTransactionCmd("123", btcjson.Bool(true)) - }, - marshalled: `{"jsonrpc":"1.0","method":"getTransaction","params":["123",true],"id":1}`, - unmarshalled: &btcjson.GetTransactionCmd{ - TxID: "123", - IncludeWatchOnly: btcjson.Bool(true), - }, - }, - { - name: "getWalletInfo", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getWalletInfo") - }, - staticCmd: func() interface{} { - return btcjson.NewGetWalletInfoCmd() - }, - marshalled: `{"jsonrpc":"1.0","method":"getWalletInfo","params":[],"id":1}`, - unmarshalled: &btcjson.GetWalletInfoCmd{}, - }, - { - name: "importPrivKey", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("importPrivKey", "abc") - }, - staticCmd: func() interface{} { - return btcjson.NewImportPrivKeyCmd("abc", nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"importPrivKey","params":["abc"],"id":1}`, - unmarshalled: &btcjson.ImportPrivKeyCmd{ - PrivKey: "abc", - Label: nil, - Rescan: btcjson.Bool(true), - }, - }, - { - name: "importPrivKey optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("importPrivKey", "abc", "label") - }, - staticCmd: func() interface{} { - return btcjson.NewImportPrivKeyCmd("abc", btcjson.String("label"), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"importPrivKey","params":["abc","label"],"id":1}`, - unmarshalled: &btcjson.ImportPrivKeyCmd{ - PrivKey: "abc", - Label: btcjson.String("label"), - Rescan: btcjson.Bool(true), - }, - }, - { - name: "importPrivKey optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("importPrivKey", "abc", "label", false) - }, - staticCmd: func() interface{} { - return btcjson.NewImportPrivKeyCmd("abc", btcjson.String("label"), btcjson.Bool(false)) - }, - marshalled: `{"jsonrpc":"1.0","method":"importPrivKey","params":["abc","label",false],"id":1}`, - unmarshalled: &btcjson.ImportPrivKeyCmd{ - PrivKey: "abc", - Label: btcjson.String("label"), - Rescan: btcjson.Bool(false), - }, - }, - { - name: "keyPoolRefill", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("keyPoolRefill") - }, - staticCmd: func() interface{} { - return btcjson.NewKeyPoolRefillCmd(nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"keyPoolRefill","params":[],"id":1}`, - unmarshalled: &btcjson.KeyPoolRefillCmd{ - NewSize: btcjson.Uint(100), - }, - }, - { - name: "keyPoolRefill optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("keyPoolRefill", 200) - }, - staticCmd: func() interface{} { - return btcjson.NewKeyPoolRefillCmd(btcjson.Uint(200)) - }, - marshalled: `{"jsonrpc":"1.0","method":"keyPoolRefill","params":[200],"id":1}`, - unmarshalled: &btcjson.KeyPoolRefillCmd{ - NewSize: btcjson.Uint(200), - }, - }, - { - name: "listAccounts", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listAccounts") - }, - staticCmd: func() interface{} { - return btcjson.NewListAccountsCmd(nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listAccounts","params":[],"id":1}`, - unmarshalled: &btcjson.ListAccountsCmd{ - MinConf: btcjson.Int(1), - }, - }, - { - name: "listAccounts optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listAccounts", 6) - }, - staticCmd: func() interface{} { - return btcjson.NewListAccountsCmd(btcjson.Int(6)) - }, - marshalled: `{"jsonrpc":"1.0","method":"listAccounts","params":[6],"id":1}`, - unmarshalled: &btcjson.ListAccountsCmd{ - MinConf: btcjson.Int(6), - }, - }, - { - name: "listAddressGroupings", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listAddressGroupings") - }, - staticCmd: func() interface{} { - return btcjson.NewListAddressGroupingsCmd() - }, - marshalled: `{"jsonrpc":"1.0","method":"listAddressGroupings","params":[],"id":1}`, - unmarshalled: &btcjson.ListAddressGroupingsCmd{}, - }, - { - name: "listLockUnspent", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listLockUnspent") - }, - staticCmd: func() interface{} { - return btcjson.NewListLockUnspentCmd() - }, - marshalled: `{"jsonrpc":"1.0","method":"listLockUnspent","params":[],"id":1}`, - unmarshalled: &btcjson.ListLockUnspentCmd{}, - }, - { - name: "listReceivedByAccount", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listReceivedByAccount") - }, - staticCmd: func() interface{} { - return btcjson.NewListReceivedByAccountCmd(nil, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listReceivedByAccount","params":[],"id":1}`, - unmarshalled: &btcjson.ListReceivedByAccountCmd{ - MinConf: btcjson.Int(1), - IncludeEmpty: btcjson.Bool(false), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listReceivedByAccount optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listReceivedByAccount", 6) - }, - staticCmd: func() interface{} { - return btcjson.NewListReceivedByAccountCmd(btcjson.Int(6), nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listReceivedByAccount","params":[6],"id":1}`, - unmarshalled: &btcjson.ListReceivedByAccountCmd{ - MinConf: btcjson.Int(6), - IncludeEmpty: btcjson.Bool(false), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listReceivedByAccount optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listReceivedByAccount", 6, true) - }, - staticCmd: func() interface{} { - return btcjson.NewListReceivedByAccountCmd(btcjson.Int(6), btcjson.Bool(true), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listReceivedByAccount","params":[6,true],"id":1}`, - unmarshalled: &btcjson.ListReceivedByAccountCmd{ - MinConf: btcjson.Int(6), - IncludeEmpty: btcjson.Bool(true), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listReceivedByAccount optional3", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listReceivedByAccount", 6, true, false) - }, - staticCmd: func() interface{} { - return btcjson.NewListReceivedByAccountCmd(btcjson.Int(6), btcjson.Bool(true), btcjson.Bool(false)) - }, - marshalled: `{"jsonrpc":"1.0","method":"listReceivedByAccount","params":[6,true,false],"id":1}`, - unmarshalled: &btcjson.ListReceivedByAccountCmd{ - MinConf: btcjson.Int(6), - IncludeEmpty: btcjson.Bool(true), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listReceivedByAddress", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listReceivedByAddress") - }, - staticCmd: func() interface{} { - return btcjson.NewListReceivedByAddressCmd(nil, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listReceivedByAddress","params":[],"id":1}`, - unmarshalled: &btcjson.ListReceivedByAddressCmd{ - MinConf: btcjson.Int(1), - IncludeEmpty: btcjson.Bool(false), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listReceivedByAddress optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listReceivedByAddress", 6) - }, - staticCmd: func() interface{} { - return btcjson.NewListReceivedByAddressCmd(btcjson.Int(6), nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listReceivedByAddress","params":[6],"id":1}`, - unmarshalled: &btcjson.ListReceivedByAddressCmd{ - MinConf: btcjson.Int(6), - IncludeEmpty: btcjson.Bool(false), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listReceivedByAddress optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listReceivedByAddress", 6, true) - }, - staticCmd: func() interface{} { - return btcjson.NewListReceivedByAddressCmd(btcjson.Int(6), btcjson.Bool(true), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listReceivedByAddress","params":[6,true],"id":1}`, - unmarshalled: &btcjson.ListReceivedByAddressCmd{ - MinConf: btcjson.Int(6), - IncludeEmpty: btcjson.Bool(true), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listReceivedByAddress optional3", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listReceivedByAddress", 6, true, false) - }, - staticCmd: func() interface{} { - return btcjson.NewListReceivedByAddressCmd(btcjson.Int(6), btcjson.Bool(true), btcjson.Bool(false)) - }, - marshalled: `{"jsonrpc":"1.0","method":"listReceivedByAddress","params":[6,true,false],"id":1}`, - unmarshalled: &btcjson.ListReceivedByAddressCmd{ - MinConf: btcjson.Int(6), - IncludeEmpty: btcjson.Bool(true), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listSinceBlock", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listSinceBlock") - }, - staticCmd: func() interface{} { - return btcjson.NewListSinceBlockCmd(nil, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listSinceBlock","params":[],"id":1}`, - unmarshalled: &btcjson.ListSinceBlockCmd{ - BlockHash: nil, - TargetConfirmations: btcjson.Int(1), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listSinceBlock optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listSinceBlock", "123") - }, - staticCmd: func() interface{} { - return btcjson.NewListSinceBlockCmd(btcjson.String("123"), nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listSinceBlock","params":["123"],"id":1}`, - unmarshalled: &btcjson.ListSinceBlockCmd{ - BlockHash: btcjson.String("123"), - TargetConfirmations: btcjson.Int(1), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listSinceBlock optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listSinceBlock", "123", 6) - }, - staticCmd: func() interface{} { - return btcjson.NewListSinceBlockCmd(btcjson.String("123"), btcjson.Int(6), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listSinceBlock","params":["123",6],"id":1}`, - unmarshalled: &btcjson.ListSinceBlockCmd{ - BlockHash: btcjson.String("123"), - TargetConfirmations: btcjson.Int(6), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listSinceBlock optional3", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listSinceBlock", "123", 6, true) - }, - staticCmd: func() interface{} { - return btcjson.NewListSinceBlockCmd(btcjson.String("123"), btcjson.Int(6), btcjson.Bool(true)) - }, - marshalled: `{"jsonrpc":"1.0","method":"listSinceBlock","params":["123",6,true],"id":1}`, - unmarshalled: &btcjson.ListSinceBlockCmd{ - BlockHash: btcjson.String("123"), - TargetConfirmations: btcjson.Int(6), - IncludeWatchOnly: btcjson.Bool(true), - }, - }, - { - name: "listTransactions", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listTransactions") - }, - staticCmd: func() interface{} { - return btcjson.NewListTransactionsCmd(nil, nil, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listTransactions","params":[],"id":1}`, - unmarshalled: &btcjson.ListTransactionsCmd{ - Account: nil, - Count: btcjson.Int(10), - From: btcjson.Int(0), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listTransactions optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listTransactions", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewListTransactionsCmd(btcjson.String("acct"), nil, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listTransactions","params":["acct"],"id":1}`, - unmarshalled: &btcjson.ListTransactionsCmd{ - Account: btcjson.String("acct"), - Count: btcjson.Int(10), - From: btcjson.Int(0), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listTransactions optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listTransactions", "acct", 20) - }, - staticCmd: func() interface{} { - return btcjson.NewListTransactionsCmd(btcjson.String("acct"), btcjson.Int(20), nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listTransactions","params":["acct",20],"id":1}`, - unmarshalled: &btcjson.ListTransactionsCmd{ - Account: btcjson.String("acct"), - Count: btcjson.Int(20), - From: btcjson.Int(0), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listTransactions optional3", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listTransactions", "acct", 20, 1) - }, - staticCmd: func() interface{} { - return btcjson.NewListTransactionsCmd(btcjson.String("acct"), btcjson.Int(20), - btcjson.Int(1), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listTransactions","params":["acct",20,1],"id":1}`, - unmarshalled: &btcjson.ListTransactionsCmd{ - Account: btcjson.String("acct"), - Count: btcjson.Int(20), - From: btcjson.Int(1), - IncludeWatchOnly: btcjson.Bool(false), - }, - }, - { - name: "listTransactions optional4", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listTransactions", "acct", 20, 1, true) - }, - staticCmd: func() interface{} { - return btcjson.NewListTransactionsCmd(btcjson.String("acct"), btcjson.Int(20), - btcjson.Int(1), btcjson.Bool(true)) - }, - marshalled: `{"jsonrpc":"1.0","method":"listTransactions","params":["acct",20,1,true],"id":1}`, - unmarshalled: &btcjson.ListTransactionsCmd{ - Account: btcjson.String("acct"), - Count: btcjson.Int(20), - From: btcjson.Int(1), - IncludeWatchOnly: btcjson.Bool(true), - }, - }, - { - name: "listUnspent", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listUnspent") - }, - staticCmd: func() interface{} { - return btcjson.NewListUnspentCmd(nil, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listUnspent","params":[],"id":1}`, - unmarshalled: &btcjson.ListUnspentCmd{ - MinConf: btcjson.Int(1), - MaxConf: btcjson.Int(9999999), - Addresses: nil, - }, - }, - { - name: "listUnspent optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listUnspent", 6) - }, - staticCmd: func() interface{} { - return btcjson.NewListUnspentCmd(btcjson.Int(6), nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listUnspent","params":[6],"id":1}`, - unmarshalled: &btcjson.ListUnspentCmd{ - MinConf: btcjson.Int(6), - MaxConf: btcjson.Int(9999999), - Addresses: nil, - }, - }, - { - name: "listUnspent optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listUnspent", 6, 100) - }, - staticCmd: func() interface{} { - return btcjson.NewListUnspentCmd(btcjson.Int(6), btcjson.Int(100), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listUnspent","params":[6,100],"id":1}`, - unmarshalled: &btcjson.ListUnspentCmd{ - MinConf: btcjson.Int(6), - MaxConf: btcjson.Int(100), - Addresses: nil, - }, - }, - { - name: "listUnspent optional3", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listUnspent", 6, 100, []string{"1Address", "1Address2"}) - }, - staticCmd: func() interface{} { - return btcjson.NewListUnspentCmd(btcjson.Int(6), btcjson.Int(100), - &[]string{"1Address", "1Address2"}) - }, - marshalled: `{"jsonrpc":"1.0","method":"listUnspent","params":[6,100,["1Address","1Address2"]],"id":1}`, - unmarshalled: &btcjson.ListUnspentCmd{ - MinConf: btcjson.Int(6), - MaxConf: btcjson.Int(100), - Addresses: &[]string{"1Address", "1Address2"}, - }, - }, - { - name: "lockUnspent", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("lockUnspent", true, `[{"txId":"123","vout":1}]`) - }, - staticCmd: func() interface{} { - txInputs := []btcjson.TransactionInput{ - {TxID: "123", Vout: 1}, - } - return btcjson.NewLockUnspentCmd(true, txInputs) - }, - marshalled: `{"jsonrpc":"1.0","method":"lockUnspent","params":[true,[{"txId":"123","vout":1}]],"id":1}`, - unmarshalled: &btcjson.LockUnspentCmd{ - Unlock: true, - Transactions: []btcjson.TransactionInput{ - {TxID: "123", Vout: 1}, - }, - }, - }, - { - name: "move", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("move", "from", "to", 0.5) - }, - staticCmd: func() interface{} { - return btcjson.NewMoveCmd("from", "to", 0.5, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"move","params":["from","to",0.5],"id":1}`, - unmarshalled: &btcjson.MoveCmd{ - FromAccount: "from", - ToAccount: "to", - Amount: 0.5, - MinConf: btcjson.Int(1), - Comment: nil, - }, - }, - { - name: "move optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("move", "from", "to", 0.5, 6) - }, - staticCmd: func() interface{} { - return btcjson.NewMoveCmd("from", "to", 0.5, btcjson.Int(6), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"move","params":["from","to",0.5,6],"id":1}`, - unmarshalled: &btcjson.MoveCmd{ - FromAccount: "from", - ToAccount: "to", - Amount: 0.5, - MinConf: btcjson.Int(6), - Comment: nil, - }, - }, - { - name: "move optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("move", "from", "to", 0.5, 6, "comment") - }, - staticCmd: func() interface{} { - return btcjson.NewMoveCmd("from", "to", 0.5, btcjson.Int(6), btcjson.String("comment")) - }, - marshalled: `{"jsonrpc":"1.0","method":"move","params":["from","to",0.5,6,"comment"],"id":1}`, - unmarshalled: &btcjson.MoveCmd{ - FromAccount: "from", - ToAccount: "to", - Amount: 0.5, - MinConf: btcjson.Int(6), - Comment: btcjson.String("comment"), - }, - }, - { - name: "sendFrom", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("sendFrom", "from", "1Address", 0.5) - }, - staticCmd: func() interface{} { - return btcjson.NewSendFromCmd("from", "1Address", 0.5, nil, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"sendFrom","params":["from","1Address",0.5],"id":1}`, - unmarshalled: &btcjson.SendFromCmd{ - FromAccount: "from", - ToAddress: "1Address", - Amount: 0.5, - MinConf: btcjson.Int(1), - Comment: nil, - CommentTo: nil, - }, - }, - { - name: "sendFrom optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("sendFrom", "from", "1Address", 0.5, 6) - }, - staticCmd: func() interface{} { - return btcjson.NewSendFromCmd("from", "1Address", 0.5, btcjson.Int(6), nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"sendFrom","params":["from","1Address",0.5,6],"id":1}`, - unmarshalled: &btcjson.SendFromCmd{ - FromAccount: "from", - ToAddress: "1Address", - Amount: 0.5, - MinConf: btcjson.Int(6), - Comment: nil, - CommentTo: nil, - }, - }, - { - name: "sendFrom optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("sendFrom", "from", "1Address", 0.5, 6, "comment") - }, - staticCmd: func() interface{} { - return btcjson.NewSendFromCmd("from", "1Address", 0.5, btcjson.Int(6), - btcjson.String("comment"), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"sendFrom","params":["from","1Address",0.5,6,"comment"],"id":1}`, - unmarshalled: &btcjson.SendFromCmd{ - FromAccount: "from", - ToAddress: "1Address", - Amount: 0.5, - MinConf: btcjson.Int(6), - Comment: btcjson.String("comment"), - CommentTo: nil, - }, - }, - { - name: "sendFrom optional3", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("sendFrom", "from", "1Address", 0.5, 6, "comment", "commentto") - }, - staticCmd: func() interface{} { - return btcjson.NewSendFromCmd("from", "1Address", 0.5, btcjson.Int(6), - btcjson.String("comment"), btcjson.String("commentto")) - }, - marshalled: `{"jsonrpc":"1.0","method":"sendFrom","params":["from","1Address",0.5,6,"comment","commentto"],"id":1}`, - unmarshalled: &btcjson.SendFromCmd{ - FromAccount: "from", - ToAddress: "1Address", - Amount: 0.5, - MinConf: btcjson.Int(6), - Comment: btcjson.String("comment"), - CommentTo: btcjson.String("commentto"), - }, - }, - { - name: "sendMany", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("sendMany", "from", `{"1Address":0.5}`) - }, - staticCmd: func() interface{} { - amounts := map[string]float64{"1Address": 0.5} - return btcjson.NewSendManyCmd("from", amounts, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"sendMany","params":["from",{"1Address":0.5}],"id":1}`, - unmarshalled: &btcjson.SendManyCmd{ - FromAccount: "from", - Amounts: map[string]float64{"1Address": 0.5}, - MinConf: btcjson.Int(1), - Comment: nil, - }, - }, - { - name: "sendMany optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("sendMany", "from", `{"1Address":0.5}`, 6) - }, - staticCmd: func() interface{} { - amounts := map[string]float64{"1Address": 0.5} - return btcjson.NewSendManyCmd("from", amounts, btcjson.Int(6), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"sendMany","params":["from",{"1Address":0.5},6],"id":1}`, - unmarshalled: &btcjson.SendManyCmd{ - FromAccount: "from", - Amounts: map[string]float64{"1Address": 0.5}, - MinConf: btcjson.Int(6), - Comment: nil, - }, - }, - { - name: "sendMany optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("sendMany", "from", `{"1Address":0.5}`, 6, "comment") - }, - staticCmd: func() interface{} { - amounts := map[string]float64{"1Address": 0.5} - return btcjson.NewSendManyCmd("from", amounts, btcjson.Int(6), btcjson.String("comment")) - }, - marshalled: `{"jsonrpc":"1.0","method":"sendMany","params":["from",{"1Address":0.5},6,"comment"],"id":1}`, - unmarshalled: &btcjson.SendManyCmd{ - FromAccount: "from", - Amounts: map[string]float64{"1Address": 0.5}, - MinConf: btcjson.Int(6), - Comment: btcjson.String("comment"), - }, - }, - { - name: "sendToAddress", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("sendToAddress", "1Address", 0.5) - }, - staticCmd: func() interface{} { - return btcjson.NewSendToAddressCmd("1Address", 0.5, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"sendToAddress","params":["1Address",0.5],"id":1}`, - unmarshalled: &btcjson.SendToAddressCmd{ - Address: "1Address", - Amount: 0.5, - Comment: nil, - CommentTo: nil, - }, - }, - { - name: "sendToAddress optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("sendToAddress", "1Address", 0.5, "comment", "commentto") - }, - staticCmd: func() interface{} { - return btcjson.NewSendToAddressCmd("1Address", 0.5, btcjson.String("comment"), - btcjson.String("commentto")) - }, - marshalled: `{"jsonrpc":"1.0","method":"sendToAddress","params":["1Address",0.5,"comment","commentto"],"id":1}`, - unmarshalled: &btcjson.SendToAddressCmd{ - Address: "1Address", - Amount: 0.5, - Comment: btcjson.String("comment"), - CommentTo: btcjson.String("commentto"), - }, - }, - { - name: "setAccount", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("setAccount", "1Address", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewSetAccountCmd("1Address", "acct") - }, - marshalled: `{"jsonrpc":"1.0","method":"setAccount","params":["1Address","acct"],"id":1}`, - unmarshalled: &btcjson.SetAccountCmd{ - Address: "1Address", - Account: "acct", - }, - }, - { - name: "setTxFee", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("setTxFee", 0.0001) - }, - staticCmd: func() interface{} { - return btcjson.NewSetTxFeeCmd(0.0001) - }, - marshalled: `{"jsonrpc":"1.0","method":"setTxFee","params":[0.0001],"id":1}`, - unmarshalled: &btcjson.SetTxFeeCmd{ - Amount: 0.0001, - }, - }, - { - name: "signMessage", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("signMessage", "1Address", "message") - }, - staticCmd: func() interface{} { - return btcjson.NewSignMessageCmd("1Address", "message") - }, - marshalled: `{"jsonrpc":"1.0","method":"signMessage","params":["1Address","message"],"id":1}`, - unmarshalled: &btcjson.SignMessageCmd{ - Address: "1Address", - Message: "message", - }, - }, - { - name: "signRawTransaction", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("signRawTransaction", "001122") - }, - staticCmd: func() interface{} { - return btcjson.NewSignRawTransactionCmd("001122", nil, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"signRawTransaction","params":["001122"],"id":1}`, - unmarshalled: &btcjson.SignRawTransactionCmd{ - RawTx: "001122", - Inputs: nil, - PrivKeys: nil, - Flags: btcjson.String("ALL"), - }, - }, - { - name: "signRawTransaction optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("signRawTransaction", "001122", `[{"txId":"123","vout":1,"scriptPubKey":"00","redeemScript":"01"}]`) - }, - staticCmd: func() interface{} { - txInputs := []btcjson.RawTxInput{ - { - TxID: "123", - Vout: 1, - ScriptPubKey: "00", - RedeemScript: "01", - }, - } - - return btcjson.NewSignRawTransactionCmd("001122", &txInputs, nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"signRawTransaction","params":["001122",[{"txId":"123","vout":1,"scriptPubKey":"00","redeemScript":"01"}]],"id":1}`, - unmarshalled: &btcjson.SignRawTransactionCmd{ - RawTx: "001122", - Inputs: &[]btcjson.RawTxInput{ - { - TxID: "123", - Vout: 1, - ScriptPubKey: "00", - RedeemScript: "01", - }, - }, - PrivKeys: nil, - Flags: btcjson.String("ALL"), - }, - }, - { - name: "signRawTransaction optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("signRawTransaction", "001122", `[]`, `["abc"]`) - }, - staticCmd: func() interface{} { - txInputs := []btcjson.RawTxInput{} - privKeys := []string{"abc"} - return btcjson.NewSignRawTransactionCmd("001122", &txInputs, &privKeys, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"signRawTransaction","params":["001122",[],["abc"]],"id":1}`, - unmarshalled: &btcjson.SignRawTransactionCmd{ - RawTx: "001122", - Inputs: &[]btcjson.RawTxInput{}, - PrivKeys: &[]string{"abc"}, - Flags: btcjson.String("ALL"), - }, - }, - { - name: "signRawTransaction optional3", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("signRawTransaction", "001122", `[]`, `[]`, "ALL") - }, - staticCmd: func() interface{} { - txInputs := []btcjson.RawTxInput{} - privKeys := []string{} - return btcjson.NewSignRawTransactionCmd("001122", &txInputs, &privKeys, - btcjson.String("ALL")) - }, - marshalled: `{"jsonrpc":"1.0","method":"signRawTransaction","params":["001122",[],[],"ALL"],"id":1}`, - unmarshalled: &btcjson.SignRawTransactionCmd{ - RawTx: "001122", - Inputs: &[]btcjson.RawTxInput{}, - PrivKeys: &[]string{}, - Flags: btcjson.String("ALL"), - }, - }, - { - name: "walletLock", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("walletLock") - }, - staticCmd: func() interface{} { - return btcjson.NewWalletLockCmd() - }, - marshalled: `{"jsonrpc":"1.0","method":"walletLock","params":[],"id":1}`, - unmarshalled: &btcjson.WalletLockCmd{}, - }, - { - name: "walletPassphrase", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("walletPassphrase", "pass", 60) - }, - staticCmd: func() interface{} { - return btcjson.NewWalletPassphraseCmd("pass", 60) - }, - marshalled: `{"jsonrpc":"1.0","method":"walletPassphrase","params":["pass",60],"id":1}`, - unmarshalled: &btcjson.WalletPassphraseCmd{ - Passphrase: "pass", - Timeout: 60, - }, - }, - { - name: "walletPassphraseChange", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("walletPassphraseChange", "old", "new") - }, - staticCmd: func() interface{} { - return btcjson.NewWalletPassphraseChangeCmd("old", "new") - }, - marshalled: `{"jsonrpc":"1.0","method":"walletPassphraseChange","params":["old","new"],"id":1}`, - unmarshalled: &btcjson.WalletPassphraseChangeCmd{ - OldPassphrase: "old", - NewPassphrase: "new", - }, - }, - } - - t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - // Marshal the command as created by the new static command - // creation function. - marshalled, err := btcjson.MarshalCmd(testID, test.staticCmd()) - if err != nil { - t.Errorf("MarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !bytes.Equal(marshalled, []byte(test.marshalled)) { - t.Errorf("Test #%d (%s) unexpected marshalled data - "+ - "got %s, want %s", i, test.name, marshalled, - test.marshalled) - continue - } - - // Ensure the command is created without error via the generic - // new command creation function. - cmd, err := test.newCmd() - if err != nil { - t.Errorf("Test #%d (%s) unexpected NewCmd error: %v ", - i, test.name, err) - } - - // Marshal the command as created by the generic new command - // creation function. - marshalled, err = btcjson.MarshalCmd(testID, cmd) - if err != nil { - t.Errorf("MarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !bytes.Equal(marshalled, []byte(test.marshalled)) { - t.Errorf("Test #%d (%s) unexpected marshalled data - "+ - "got %s, want %s", i, test.name, marshalled, - test.marshalled) - continue - } - - var request btcjson.Request - if err := json.Unmarshal(marshalled, &request); err != nil { - t.Errorf("Test #%d (%s) unexpected error while "+ - "unmarshalling JSON-RPC request: %v", i, - test.name, err) - continue - } - - cmd, err = btcjson.UnmarshalCmd(&request) - if err != nil { - t.Errorf("UnmarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !reflect.DeepEqual(cmd, test.unmarshalled) { - t.Errorf("Test #%d (%s) unexpected unmarshalled command "+ - "- got %s, want %s", i, test.name, - fmt.Sprintf("(%T) %+[1]v", cmd), - fmt.Sprintf("(%T) %+[1]v\n", test.unmarshalled)) - continue - } - } -} diff --git a/btcjson/walletsvrresults.go b/btcjson/walletsvrresults.go deleted file mode 100644 index 4a9ab4d4e..000000000 --- a/btcjson/walletsvrresults.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) 2014 The btcsuite developers -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson - -// GetTransactionDetailsResult models the details data from the gettransaction command. -// -// This models the "short" version of the ListTransactionsResult type, which -// excludes fields common to the transaction. These common fields are instead -// part of the GetTransactionResult. -type GetTransactionDetailsResult struct { - Account string `json:"account"` - Address string `json:"address,omitempty"` - Amount float64 `json:"amount"` - Category string `json:"category"` - InvolvesWatchOnly bool `json:"involvesWatchOnly,omitempty"` - Fee *float64 `json:"fee,omitempty"` - Vout uint32 `json:"vout"` -} - -// 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 uint64 `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"` -} - -// InfoWalletResult models the data returned by the wallet server getinfo -// command. -type InfoWalletResult struct { - Version int32 `json:"version"` - ProtocolVersion int32 `json:"protocolVersion"` - WalletVersion int32 `json:"walletVersion"` - Balance float64 `json:"balance"` - 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"` - KeypoolSize int32 `json:"keypoolSize"` - UnlockedUntil int64 `json:"unlockedUntil"` - PayTxFee float64 `json:"payTxFee"` - RelayFee float64 `json:"relayFee"` - Errors string `json:"errors"` -} - -// ListTransactionsResult models the data from the listtransactions command. -type ListTransactionsResult struct { - Abandoned bool `json:"abandoned"` - Account string `json:"account"` - Address string `json:"address,omitempty"` - Amount float64 `json:"amount"` - BIP125Replaceable string `json:"bip125Replaceable,omitempty"` - BlockHash string `json:"blockGash,omitempty"` - BlockIndex *int64 `json:"blockIndex,omitempty"` - BlockTime uint64 `json:"blockTime,omitempty"` - Category string `json:"category"` - Confirmations int64 `json:"confirmations"` - Fee *float64 `json:"fee,omitempty"` - Generated bool `json:"generated,omitempty"` - InvolvesWatchOnly bool `json:"involvesWatchOnly,omitempty"` - Time int64 `json:"time"` - TimeReceived int64 `json:"timeReceived"` - Trusted bool `json:"trusted"` - TxID string `json:"txId"` - Vout uint32 `json:"vout"` - WalletConflicts []string `json:"walletConflicts"` - Comment string `json:"comment,omitempty"` - OtherAccount string `json:"otherAccount,omitempty"` -} - -// 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"` - Spendable bool `json:"spendable"` -} - -// SignRawTransactionError models the data that contains script verification -// errors from the signrawtransaction request. -type SignRawTransactionError struct { - TxID string `json:"txId"` - Vout uint32 `json:"vout"` - ScriptSig string `json:"scriptSig"` - Sequence uint64 `json:"sequence"` - Error string `json:"error"` -} - -// SignRawTransactionResult models the data from the signrawtransaction -// command. -type SignRawTransactionResult struct { - Hex string `json:"hex"` - Complete bool `json:"complete"` - Errors []SignRawTransactionError `json:"errors,omitempty"` -} - -// ValidateAddressWalletResult models the data returned by the wallet server -// validateaddress command. -type ValidateAddressWalletResult 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"` -} - -// GetBestBlockResult models the data from the getbestblock command. -type GetBestBlockResult struct { - Hash string `json:"hash"` - Height uint64 `json:"height"` -} diff --git a/btcjson/walletsvrwscmds.go b/btcjson/walletsvrwscmds.go deleted file mode 100644 index b65e646cf..000000000 --- a/btcjson/walletsvrwscmds.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) 2014 The btcsuite developers -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package btcjson - -// NOTE: This file is intended to house the RPC commands that are supported by -// a wallet server, but are only available via websockets. - -// CreateEncryptedWalletCmd defines the createEncryptedWallet JSON-RPC command. -type CreateEncryptedWalletCmd struct { - Passphrase string -} - -// NewCreateEncryptedWalletCmd returns a new instance which can be used to issue -// a createEncryptedWallet JSON-RPC command. -func NewCreateEncryptedWalletCmd(passphrase string) *CreateEncryptedWalletCmd { - return &CreateEncryptedWalletCmd{ - Passphrase: passphrase, - } -} - -// ExportWatchingWalletCmd defines the exportWatchingWallet JSON-RPC command. -type ExportWatchingWalletCmd struct { - Account *string - Download *bool `jsonrpcdefault:"false"` -} - -// NewExportWatchingWalletCmd returns a new instance which can be used to issue -// a exportWatchingWallet JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewExportWatchingWalletCmd(account *string, download *bool) *ExportWatchingWalletCmd { - return &ExportWatchingWalletCmd{ - Account: account, - Download: download, - } -} - -// GetUnconfirmedBalanceCmd defines the getUnconfirmedBalance JSON-RPC command. -type GetUnconfirmedBalanceCmd struct { - Account *string -} - -// NewGetUnconfirmedBalanceCmd returns a new instance which can be used to issue -// a getUnconfirmedBalance JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewGetUnconfirmedBalanceCmd(account *string) *GetUnconfirmedBalanceCmd { - return &GetUnconfirmedBalanceCmd{ - Account: account, - } -} - -// ListAddressTransactionsCmd defines the listAddressTransactions JSON-RPC -// command. -type ListAddressTransactionsCmd struct { - Addresses []string - Account *string -} - -// NewListAddressTransactionsCmd returns a new instance which can be used to -// issue a listAddressTransactions JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewListAddressTransactionsCmd(addresses []string, account *string) *ListAddressTransactionsCmd { - return &ListAddressTransactionsCmd{ - Addresses: addresses, - Account: account, - } -} - -// ListAllTransactionsCmd defines the listAllTransactions JSON-RPC command. -type ListAllTransactionsCmd struct { - Account *string -} - -// NewListAllTransactionsCmd returns a new instance which can be used to issue a -// listAllTransactions JSON-RPC command. -// -// The parameters which are pointers indicate they are optional. Passing nil -// for optional parameters will use the default value. -func NewListAllTransactionsCmd(account *string) *ListAllTransactionsCmd { - return &ListAllTransactionsCmd{ - Account: account, - } -} - -// RecoverAddressesCmd defines the recoverAddresses JSON-RPC command. -type RecoverAddressesCmd struct { - Account string - N int -} - -// NewRecoverAddressesCmd returns a new instance which can be used to issue a -// recoverAddresses JSON-RPC command. -func NewRecoverAddressesCmd(account string, n int) *RecoverAddressesCmd { - return &RecoverAddressesCmd{ - Account: account, - N: n, - } -} - -// WalletIsLockedCmd defines the walletIsLocked JSON-RPC command. -type WalletIsLockedCmd struct{} - -// NewWalletIsLockedCmd returns a new instance which can be used to issue a -// walletIsLocked JSON-RPC command. -func NewWalletIsLockedCmd() *WalletIsLockedCmd { - return &WalletIsLockedCmd{} -} - -func init() { - // The commands in this file are only usable with a wallet server via - // websockets. - flags := UFWalletOnly | UFWebsocketOnly - - MustRegisterCmd("createEncryptedWallet", (*CreateEncryptedWalletCmd)(nil), flags) - MustRegisterCmd("exportWatchingWallet", (*ExportWatchingWalletCmd)(nil), flags) - MustRegisterCmd("getUnconfirmedBalance", (*GetUnconfirmedBalanceCmd)(nil), flags) - MustRegisterCmd("listAddressTransactions", (*ListAddressTransactionsCmd)(nil), flags) - MustRegisterCmd("listAllTransactions", (*ListAllTransactionsCmd)(nil), flags) - MustRegisterCmd("recoverAddresses", (*RecoverAddressesCmd)(nil), flags) - MustRegisterCmd("walletIsLocked", (*WalletIsLockedCmd)(nil), flags) -} diff --git a/btcjson/walletsvrwscmds_test.go b/btcjson/walletsvrwscmds_test.go deleted file mode 100644 index 0989e8d7e..000000000 --- a/btcjson/walletsvrwscmds_test.go +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright (c) 2014 The btcsuite developers -// 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" - "fmt" - "reflect" - "testing" - - "github.com/daglabs/btcd/btcjson" -) - -// TestWalletSvrWsCmds tests all of the wallet server websocket-specific -// commands marshal and unmarshal into valid results include handling of -// optional fields being omitted in the marshalled command, while optional -// fields with defaults have the default assigned on unmarshalled commands. -func TestWalletSvrWsCmds(t *testing.T) { - t.Parallel() - - testID := int(1) - tests := []struct { - name string - newCmd func() (interface{}, error) - staticCmd func() interface{} - marshalled string - unmarshalled interface{} - }{ - { - name: "createEncryptedWallet", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("createEncryptedWallet", "pass") - }, - staticCmd: func() interface{} { - return btcjson.NewCreateEncryptedWalletCmd("pass") - }, - marshalled: `{"jsonrpc":"1.0","method":"createEncryptedWallet","params":["pass"],"id":1}`, - unmarshalled: &btcjson.CreateEncryptedWalletCmd{Passphrase: "pass"}, - }, - { - name: "exportWatchingWallet", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("exportWatchingWallet") - }, - staticCmd: func() interface{} { - return btcjson.NewExportWatchingWalletCmd(nil, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"exportWatchingWallet","params":[],"id":1}`, - unmarshalled: &btcjson.ExportWatchingWalletCmd{ - Account: nil, - Download: btcjson.Bool(false), - }, - }, - { - name: "exportWatchingWallet optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("exportWatchingWallet", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewExportWatchingWalletCmd(btcjson.String("acct"), nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"exportWatchingWallet","params":["acct"],"id":1}`, - unmarshalled: &btcjson.ExportWatchingWalletCmd{ - Account: btcjson.String("acct"), - Download: btcjson.Bool(false), - }, - }, - { - name: "exportWatchingWallet optional2", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("exportWatchingWallet", "acct", true) - }, - staticCmd: func() interface{} { - return btcjson.NewExportWatchingWalletCmd(btcjson.String("acct"), - btcjson.Bool(true)) - }, - marshalled: `{"jsonrpc":"1.0","method":"exportWatchingWallet","params":["acct",true],"id":1}`, - unmarshalled: &btcjson.ExportWatchingWalletCmd{ - Account: btcjson.String("acct"), - Download: btcjson.Bool(true), - }, - }, - { - name: "getUnconfirmedBalance", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getUnconfirmedBalance") - }, - staticCmd: func() interface{} { - return btcjson.NewGetUnconfirmedBalanceCmd(nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"getUnconfirmedBalance","params":[],"id":1}`, - unmarshalled: &btcjson.GetUnconfirmedBalanceCmd{ - Account: nil, - }, - }, - { - name: "getUnconfirmedBalance optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("getUnconfirmedBalance", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewGetUnconfirmedBalanceCmd(btcjson.String("acct")) - }, - marshalled: `{"jsonrpc":"1.0","method":"getUnconfirmedBalance","params":["acct"],"id":1}`, - unmarshalled: &btcjson.GetUnconfirmedBalanceCmd{ - Account: btcjson.String("acct"), - }, - }, - { - name: "listAddressTransactions", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listAddressTransactions", `["1Address"]`) - }, - staticCmd: func() interface{} { - return btcjson.NewListAddressTransactionsCmd([]string{"1Address"}, nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listAddressTransactions","params":[["1Address"]],"id":1}`, - unmarshalled: &btcjson.ListAddressTransactionsCmd{ - Addresses: []string{"1Address"}, - Account: nil, - }, - }, - { - name: "listAddressTransactions optional1", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listAddressTransactions", `["1Address"]`, "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewListAddressTransactionsCmd([]string{"1Address"}, - btcjson.String("acct")) - }, - marshalled: `{"jsonrpc":"1.0","method":"listAddressTransactions","params":[["1Address"],"acct"],"id":1}`, - unmarshalled: &btcjson.ListAddressTransactionsCmd{ - Addresses: []string{"1Address"}, - Account: btcjson.String("acct"), - }, - }, - { - name: "listAllTransactions", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listAllTransactions") - }, - staticCmd: func() interface{} { - return btcjson.NewListAllTransactionsCmd(nil) - }, - marshalled: `{"jsonrpc":"1.0","method":"listAllTransactions","params":[],"id":1}`, - unmarshalled: &btcjson.ListAllTransactionsCmd{ - Account: nil, - }, - }, - { - name: "listAllTransactions optional", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("listAllTransactions", "acct") - }, - staticCmd: func() interface{} { - return btcjson.NewListAllTransactionsCmd(btcjson.String("acct")) - }, - marshalled: `{"jsonrpc":"1.0","method":"listAllTransactions","params":["acct"],"id":1}`, - unmarshalled: &btcjson.ListAllTransactionsCmd{ - Account: btcjson.String("acct"), - }, - }, - { - name: "recoverAddresses", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("recoverAddresses", "acct", 10) - }, - staticCmd: func() interface{} { - return btcjson.NewRecoverAddressesCmd("acct", 10) - }, - marshalled: `{"jsonrpc":"1.0","method":"recoverAddresses","params":["acct",10],"id":1}`, - unmarshalled: &btcjson.RecoverAddressesCmd{ - Account: "acct", - N: 10, - }, - }, - { - name: "walletIsLocked", - newCmd: func() (interface{}, error) { - return btcjson.NewCmd("walletIsLocked") - }, - staticCmd: func() interface{} { - return btcjson.NewWalletIsLockedCmd() - }, - marshalled: `{"jsonrpc":"1.0","method":"walletIsLocked","params":[],"id":1}`, - unmarshalled: &btcjson.WalletIsLockedCmd{}, - }, - } - - t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - // Marshal the command as created by the new static command - // creation function. - marshalled, err := btcjson.MarshalCmd(testID, test.staticCmd()) - if err != nil { - t.Errorf("MarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !bytes.Equal(marshalled, []byte(test.marshalled)) { - t.Errorf("Test #%d (%s) unexpected marshalled data - "+ - "got %s, want %s", i, test.name, marshalled, - test.marshalled) - continue - } - - // Ensure the command is created without error via the generic - // new command creation function. - cmd, err := test.newCmd() - if err != nil { - t.Errorf("Test #%d (%s) unexpected NewCmd error: %v ", - i, test.name, err) - } - - // Marshal the command as created by the generic new command - // creation function. - marshalled, err = btcjson.MarshalCmd(testID, cmd) - if err != nil { - t.Errorf("MarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !bytes.Equal(marshalled, []byte(test.marshalled)) { - t.Errorf("Test #%d (%s) unexpected marshalled data - "+ - "got %s, want %s", i, test.name, marshalled, - test.marshalled) - continue - } - - var request btcjson.Request - if err := json.Unmarshal(marshalled, &request); err != nil { - t.Errorf("Test #%d (%s) unexpected error while "+ - "unmarshalling JSON-RPC request: %v", i, - test.name, err) - continue - } - - cmd, err = btcjson.UnmarshalCmd(&request) - if err != nil { - t.Errorf("UnmarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !reflect.DeepEqual(cmd, test.unmarshalled) { - t.Errorf("Test #%d (%s) unexpected unmarshalled command "+ - "- got %s, want %s", i, test.name, - fmt.Sprintf("(%T) %+[1]v", cmd), - fmt.Sprintf("(%T) %+[1]v\n", test.unmarshalled)) - continue - } - } -} diff --git a/btcjson/walletsvrwsntfns.go b/btcjson/walletsvrwsntfns.go deleted file mode 100644 index 19e6d93cc..000000000 --- a/btcjson/walletsvrwsntfns.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2014 The btcsuite developers -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -// NOTE: This file is intended to house the RPC websocket notifications that are -// supported by a wallet server. - -package btcjson - -const ( - // AccountBalanceNtfnMethod is the method used for account balance - // notifications. - AccountBalanceNtfnMethod = "accountBalance" - - // BtcdConnectedNtfnMethod is the method used for notifications when - // a wallet server is connected to a dag server. - BtcdConnectedNtfnMethod = "btcdConnected" - - // WalletLockStateNtfnMethod is the method used to notify the lock state - // of a wallet has changed. - WalletLockStateNtfnMethod = "walletLockState" - - // NewTxNtfnMethod is the method used to notify that a wallet server has - // added a new transaction to the transaction store. - NewTxNtfnMethod = "newTx" -) - -// AccountBalanceNtfn defines the accountBalance JSON-RPC notification. -type AccountBalanceNtfn struct { - Account string - Balance float64 // In BTC - Confirmed bool // Whether Balance is confirmed or unconfirmed. -} - -// NewAccountBalanceNtfn returns a new instance which can be used to issue an -// accountBalance JSON-RPC notification. -func NewAccountBalanceNtfn(account string, balance float64, confirmed bool) *AccountBalanceNtfn { - return &AccountBalanceNtfn{ - Account: account, - Balance: balance, - Confirmed: confirmed, - } -} - -// BtcdConnectedNtfn defines the btcdConnected JSON-RPC notification. -type BtcdConnectedNtfn struct { - Connected bool -} - -// NewBtcdConnectedNtfn returns a new instance which can be used to issue a -// btcdConnected JSON-RPC notification. -func NewBtcdConnectedNtfn(connected bool) *BtcdConnectedNtfn { - return &BtcdConnectedNtfn{ - Connected: connected, - } -} - -// WalletLockStateNtfn defines the walletLockState JSON-RPC notification. -type WalletLockStateNtfn struct { - Locked bool -} - -// NewWalletLockStateNtfn returns a new instance which can be used to issue a -// walletLockState JSON-RPC notification. -func NewWalletLockStateNtfn(locked bool) *WalletLockStateNtfn { - return &WalletLockStateNtfn{ - Locked: locked, - } -} - -// NewTxNtfn defines the newTx JSON-RPC notification. -type NewTxNtfn struct { - Account string - Details ListTransactionsResult -} - -// NewNewTxNtfn returns a new instance which can be used to issue a newTx -// JSON-RPC notification. -func NewNewTxNtfn(account string, details ListTransactionsResult) *NewTxNtfn { - return &NewTxNtfn{ - Account: account, - Details: details, - } -} - -func init() { - // The commands in this file are only usable with a wallet server via - // websockets and are notifications. - flags := UFWalletOnly | UFWebsocketOnly | UFNotification - - MustRegisterCmd(AccountBalanceNtfnMethod, (*AccountBalanceNtfn)(nil), flags) - MustRegisterCmd(BtcdConnectedNtfnMethod, (*BtcdConnectedNtfn)(nil), flags) - MustRegisterCmd(WalletLockStateNtfnMethod, (*WalletLockStateNtfn)(nil), flags) - MustRegisterCmd(NewTxNtfnMethod, (*NewTxNtfn)(nil), flags) -} diff --git a/btcjson/walletsvrwsntfns_test.go b/btcjson/walletsvrwsntfns_test.go deleted file mode 100644 index a86783e10..000000000 --- a/btcjson/walletsvrwsntfns_test.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) 2014 The btcsuite developers -// 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" - "fmt" - "reflect" - "testing" - - "github.com/daglabs/btcd/btcjson" -) - -// TestWalletSvrWsNtfns tests all of the dag server websocket-specific -// notifications marshal and unmarshal into valid results include handling of -// optional fields being omitted in the marshalled command, while optional -// fields with defaults have the default assigned on unmarshalled commands. -func TestWalletSvrWsNtfns(t *testing.T) { - t.Parallel() - - tests := []struct { - name string - newNtfn func() (interface{}, error) - staticNtfn func() interface{} - marshalled string - unmarshalled interface{} - }{ - { - name: "accountBalance", - newNtfn: func() (interface{}, error) { - return btcjson.NewCmd("accountBalance", "acct", 1.25, true) - }, - staticNtfn: func() interface{} { - return btcjson.NewAccountBalanceNtfn("acct", 1.25, true) - }, - marshalled: `{"jsonrpc":"1.0","method":"accountBalance","params":["acct",1.25,true],"id":null}`, - unmarshalled: &btcjson.AccountBalanceNtfn{ - Account: "acct", - Balance: 1.25, - Confirmed: true, - }, - }, - { - name: "btcdConnected", - newNtfn: func() (interface{}, error) { - return btcjson.NewCmd("btcdConnected", true) - }, - staticNtfn: func() interface{} { - return btcjson.NewBtcdConnectedNtfn(true) - }, - marshalled: `{"jsonrpc":"1.0","method":"btcdConnected","params":[true],"id":null}`, - unmarshalled: &btcjson.BtcdConnectedNtfn{ - Connected: true, - }, - }, - { - name: "walletLockState", - newNtfn: func() (interface{}, error) { - return btcjson.NewCmd("walletLockState", true) - }, - staticNtfn: func() interface{} { - return btcjson.NewWalletLockStateNtfn(true) - }, - marshalled: `{"jsonrpc":"1.0","method":"walletLockState","params":[true],"id":null}`, - unmarshalled: &btcjson.WalletLockStateNtfn{ - Locked: true, - }, - }, - { - name: "newTx", - newNtfn: func() (interface{}, error) { - return btcjson.NewCmd("newTx", "acct", `{"account":"acct","address":"1Address","category":"send","amount":1.5,"bip125Replaceable":"unknown","fee":0.0001,"confirmations":1,"trusted":true,"txId":"456","walletConflicts":[],"time":12345678,"timeReceived":12345876,"vout":789,"otherAccount":"otheracct"}`) - }, - staticNtfn: func() interface{} { - result := btcjson.ListTransactionsResult{ - Abandoned: false, - Account: "acct", - Address: "1Address", - BIP125Replaceable: "unknown", - Category: "send", - Amount: 1.5, - Fee: btcjson.Float64(0.0001), - Confirmations: 1, - TxID: "456", - WalletConflicts: []string{}, - Time: 12345678, - TimeReceived: 12345876, - Trusted: true, - Vout: 789, - OtherAccount: "otheracct", - } - return btcjson.NewNewTxNtfn("acct", result) - }, - marshalled: `{"jsonrpc":"1.0","method":"newTx","params":["acct",{"abandoned":false,"account":"acct","address":"1Address","amount":1.5,"bip125Replaceable":"unknown","category":"send","confirmations":1,"fee":0.0001,"time":12345678,"timeReceived":12345876,"trusted":true,"txId":"456","vout":789,"walletConflicts":[],"otherAccount":"otheracct"}],"id":null}`, - unmarshalled: &btcjson.NewTxNtfn{ - Account: "acct", - Details: btcjson.ListTransactionsResult{ - Abandoned: false, - Account: "acct", - Address: "1Address", - BIP125Replaceable: "unknown", - Category: "send", - Amount: 1.5, - Fee: btcjson.Float64(0.0001), - Confirmations: 1, - TxID: "456", - WalletConflicts: []string{}, - Time: 12345678, - TimeReceived: 12345876, - Trusted: true, - Vout: 789, - OtherAccount: "otheracct", - }, - }, - }, - } - - t.Logf("Running %d tests", len(tests)) - for i, test := range tests { - // Marshal the notification as created by the new static - // creation function. The ID is nil for notifications. - marshalled, err := btcjson.MarshalCmd(nil, test.staticNtfn()) - if err != nil { - t.Errorf("MarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !bytes.Equal(marshalled, []byte(test.marshalled)) { - t.Errorf("Test #%d (%s) unexpected marshalled data - "+ - "got %s, want %s", i, test.name, marshalled, - test.marshalled) - continue - } - - // Ensure the notification is created without error via the - // generic new notification creation function. - cmd, err := test.newNtfn() - if err != nil { - t.Errorf("Test #%d (%s) unexpected NewCmd error: %v ", - i, test.name, err) - } - - // Marshal the notification as created by the generic new - // notification creation function. The ID is nil for - // notifications. - marshalled, err = btcjson.MarshalCmd(nil, cmd) - if err != nil { - t.Errorf("MarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !bytes.Equal(marshalled, []byte(test.marshalled)) { - t.Errorf("Test #%d (%s) unexpected marshalled data - "+ - "got %s, want %s", i, test.name, marshalled, - test.marshalled) - continue - } - - var request btcjson.Request - if err := json.Unmarshal(marshalled, &request); err != nil { - t.Errorf("Test #%d (%s) unexpected error while "+ - "unmarshalling JSON-RPC request: %v", i, - test.name, err) - continue - } - - cmd, err = btcjson.UnmarshalCmd(&request) - if err != nil { - t.Errorf("UnmarshalCmd #%d (%s) unexpected error: %v", i, - test.name, err) - continue - } - - if !reflect.DeepEqual(cmd, test.unmarshalled) { - t.Errorf("Test #%d (%s) unexpected unmarshalled command "+ - "- got %s, want %s", i, test.name, - fmt.Sprintf("(%T) %+[1]v", cmd), - fmt.Sprintf("(%T) %+[1]v\n", test.unmarshalled)) - continue - } - } -} diff --git a/cmd/btcctl/config.go b/cmd/btcctl/config.go index 01386fc8f..77d4aa563 100644 --- a/cmd/btcctl/config.go +++ b/cmd/btcctl/config.go @@ -15,7 +15,7 @@ import ( "github.com/daglabs/btcd/btcjson" "github.com/daglabs/btcd/util" - flags "github.com/jessevdk/go-flags" + "github.com/jessevdk/go-flags" ) const ( @@ -26,13 +26,11 @@ const ( ) var ( - btcdHomeDir = util.AppDataDir("btcd", false) - btcctlHomeDir = util.AppDataDir("btcctl", false) - btcwalletHomeDir = util.AppDataDir("btcwallet", false) - defaultConfigFile = filepath.Join(btcctlHomeDir, "btcctl.conf") - defaultRPCServer = "localhost" - defaultRPCCertFile = filepath.Join(btcdHomeDir, "rpc.cert") - defaultWalletCertFile = filepath.Join(btcwalletHomeDir, "rpc.cert") + btcdHomeDir = util.AppDataDir("btcd", false) + btcctlHomeDir = util.AppDataDir("btcctl", false) + defaultConfigFile = filepath.Join(btcctlHomeDir, "btcctl.conf") + defaultRPCServer = "localhost" + defaultRPCCertFile = filepath.Join(btcdHomeDir, "rpc.cert") ) // listCommands categorizes and lists all of the usable commands along with @@ -40,7 +38,6 @@ var ( func listCommands() { const ( categoryChain uint8 = iota - categoryWallet numCategories ) @@ -69,16 +66,12 @@ func listCommands() { // Categorize the command based on the usage flags. category := categoryChain - if flags&btcjson.UFWalletOnly != 0 { - category = categoryWallet - } categorized[category] = append(categorized[category], usage) } // Display the command according to their categories. categoryTitles := make([]string, numCategories) categoryTitles[categoryChain] = "Chain Server Commands:" - categoryTitles[categoryWallet] = "Wallet Server Commands (--wallet):" for category := uint8(0); category < numCategories; category++ { fmt.Println(categoryTitles[category]) for _, usage := range categorized[category] { @@ -107,12 +100,11 @@ type config struct { SimNet bool `long:"simnet" description:"Connect to the simulation test network"` DevNet bool `long:"devnet" description:"Connect to the development test network"` TLSSkipVerify bool `long:"skipverify" description:"Do not verify tls certificates (not recommended!)"` - Wallet bool `long:"wallet" description:"Connect to wallet"` } // normalizeAddress returns addr with the passed default port appended if // there is not already a port specified. -func normalizeAddress(addr string, useTestNet3, useSimNet, useDevNet, useWallet bool) string { +func normalizeAddress(addr string, useTestNet3, useSimNet, useDevNet bool) string { _, _, err := net.SplitHostPort(addr) if err != nil { var defaultPort string @@ -120,23 +112,11 @@ func normalizeAddress(addr string, useTestNet3, useSimNet, useDevNet, useWallet case useDevNet: fallthrough case useTestNet3: - if useWallet { - defaultPort = "18332" - } else { - defaultPort = "18334" - } + defaultPort = "18334" case useSimNet: - if useWallet { - defaultPort = "18554" - } else { - defaultPort = "18556" - } + defaultPort = "18556" default: - if useWallet { - defaultPort = "8332" - } else { - defaultPort = "8334" - } + defaultPort = "8334" } return net.JoinHostPort(addr, defaultPort) @@ -215,12 +195,7 @@ func loadConfig() (*config, []string, error) { if _, err := os.Stat(preCfg.ConfigFile); os.IsNotExist(err) { // Use config file for RPC server to create default btcctl config - var serverConfigPath string - if preCfg.Wallet { - serverConfigPath = filepath.Join(btcwalletHomeDir, "btcwallet.conf") - } else { - serverConfigPath = filepath.Join(btcdHomeDir, "btcd.conf") - } + serverConfigPath := filepath.Join(btcdHomeDir, "btcd.conf") err := createDefaultConfigFile(preCfg.ConfigFile, serverConfigPath) if err != nil { @@ -268,26 +243,20 @@ func loadConfig() (*config, []string, error) { return nil, nil, err } - // Override the RPC certificate if the --wallet flag was specified and - // the user did not specify one. - if cfg.Wallet && cfg.RPCCert == defaultRPCCertFile { - cfg.RPCCert = defaultWalletCertFile - } - // Handle environment variable expansion in the RPC certificate path. cfg.RPCCert = cleanAndExpandPath(cfg.RPCCert) - // Add default port to RPC server based on --testnet and --wallet flags + // Add default port to RPC server based on --testnet and --simnet flags // if needed. cfg.RPCServer = normalizeAddress(cfg.RPCServer, cfg.TestNet3, - cfg.SimNet, cfg.DevNet, cfg.Wallet) + cfg.SimNet, cfg.DevNet) return &cfg, remainingArgs, nil } // createDefaultConfig creates a basic config file at the given destination path. -// For this it tries to read the config file for the RPC server (either btcd or -// btcwallet), and extract the RPC user and password from it. +// For this it tries to read the config file for the RPC server and extract the +// RPC user and password from it. func createDefaultConfigFile(destinationPath, serverConfigPath string) error { // Read the RPC server config serverConfigFile, err := os.Open(serverConfigPath) diff --git a/rpcclient/examples/btcwalletwebsockets/README.md b/rpcclient/examples/btcwalletwebsockets/README.md deleted file mode 100644 index eb79d9aa7..000000000 --- a/rpcclient/examples/btcwalletwebsockets/README.md +++ /dev/null @@ -1,37 +0,0 @@ -btcwallet Websockets Example -============================ - -This example shows how to use the rpcclient package to connect to a btcwallet -RPC server using TLS-secured websockets, register for notifications about -changes to account balances, and get a list of unspent transaction outputs -(utxos) the wallet can sign. - -This example also sets a timer to shutdown the client after 10 seconds to -demonstrate clean shutdown. - -## Running the Example - -The first step is to use `go get` to download and install the rpcclient package: - -```bash -$ go get github.com/daglabs/btcd/rpcclient -``` - -Next, modify the `main.go` source to specify the correct RPC username and -password for the RPC server: - -```Go - User: "yourrpcuser", - Pass: "yourrpcpass", -``` - -Finally, navigate to the example's directory and run it with: - -```bash -$ cd $GOPATH/src/github.com/daglabs/btcd/rpcclient/examples/btcwalletwebsockets -$ go run *.go -``` - -## License - -This example is licensed under the [copyfree](http://copyfree.org) ISC License. diff --git a/rpcclient/examples/btcwalletwebsockets/main.go b/rpcclient/examples/btcwalletwebsockets/main.go deleted file mode 100644 index a7dc2be77..000000000 --- a/rpcclient/examples/btcwalletwebsockets/main.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2014-2017 The btcsuite developers -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package main - -import ( - "io/ioutil" - "log" - "path/filepath" - "time" - - "github.com/daglabs/btcd/rpcclient" - "github.com/daglabs/btcd/util" - "github.com/davecgh/go-spew/spew" -) - -func main() { - // Only override the handlers for notifications you care about. - // Also note most of the handlers will only be called if you register - // for notifications. See the documentation of the rpcclient - // NotificationHandlers type for more details about each handler. - ntfnHandlers := rpcclient.NotificationHandlers{ - OnAccountBalance: func(account string, balance util.Amount, confirmed bool) { - log.Printf("New balance for account %s: %s", account, - balance) - }, - } - - // Connect to local btcwallet RPC server using websockets. - certHomeDir := util.AppDataDir("btcwallet", false) - certs, err := ioutil.ReadFile(filepath.Join(certHomeDir, "rpc.cert")) - if err != nil { - log.Fatal(err) - } - connCfg := &rpcclient.ConnConfig{ - Host: "localhost:18332", - Endpoint: "ws", - User: "yourrpcuser", - Pass: "yourrpcpass", - Certificates: certs, - } - client, err := rpcclient.New(connCfg, &ntfnHandlers) - if err != nil { - log.Fatal(err) - } - - // Get the list of unspent transaction outputs (utxos) that the - // connected wallet has at least one private key for. - unspent, err := client.ListUnspent() - if err != nil { - log.Fatal(err) - } - log.Printf("Num unspent outputs (utxos): %d", len(unspent)) - if len(unspent) > 0 { - log.Printf("First utxo:\n%s", spew.Sdump(unspent[0])) - } - - // For this example gracefully shutdown the client after 10 seconds. - // Ordinarily when to shutdown the client is highly application - // specific. - log.Println("Client shutdown in 10 seconds...") - time.AfterFunc(time.Second*10, func() { - log.Println("Client shutting down...") - client.Shutdown() - log.Println("Client shutdown complete.") - }) - - // Wait until the client either shuts down gracefully (or the user - // terminates the process with Ctrl+C). - client.WaitForShutdown() -} diff --git a/rpcclient/extensions.go b/rpcclient/extensions.go index 7df47644f..da2b3ae6e 100644 --- a/rpcclient/extensions.go +++ b/rpcclient/extensions.go @@ -7,13 +7,9 @@ package rpcclient import ( "bytes" - "encoding/base64" "encoding/hex" "encoding/json" - "fmt" - "github.com/daglabs/btcd/btcjson" - "github.com/daglabs/btcd/util" "github.com/daglabs/btcd/util/daghash" "github.com/daglabs/btcd/wire" ) @@ -66,86 +62,6 @@ func (c *Client) DebugLevel(levelSpec string) (string, error) { return c.DebugLevelAsync(levelSpec).Receive() } -// FutureCreateEncryptedWalletResult is a future promise to deliver the error -// result of a CreateEncryptedWalletAsync RPC invocation. -type FutureCreateEncryptedWalletResult chan *response - -// Receive waits for and returns the error response promised by the future. -func (r FutureCreateEncryptedWalletResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// CreateEncryptedWalletAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See CreateEncryptedWallet for the blocking version and more details. -// -// NOTE: This is a btcwallet extension. -func (c *Client) CreateEncryptedWalletAsync(passphrase string) FutureCreateEncryptedWalletResult { - cmd := btcjson.NewCreateEncryptedWalletCmd(passphrase) - return c.sendCmd(cmd) -} - -// CreateEncryptedWallet requests the creation of an encrypted wallet. Wallets -// managed by btcwallet are only written to disk with encrypted private keys, -// and generating wallets on the fly is impossible as it requires user input for -// the encryption passphrase. This RPC specifies the passphrase and instructs -// the wallet creation. This may error if a wallet is already opened, or the -// new wallet cannot be written to disk. -// -// NOTE: This is a btcwallet extension. -func (c *Client) CreateEncryptedWallet(passphrase string) error { - return c.CreateEncryptedWalletAsync(passphrase).Receive() -} - -// FutureListAddressTransactionsResult is a future promise to deliver the result -// of a ListAddressTransactionsAsync RPC invocation (or an applicable error). -type FutureListAddressTransactionsResult chan *response - -// Receive waits for the response promised by the future and returns information -// about all transactions associated with the provided addresses. -func (r FutureListAddressTransactionsResult) Receive() ([]btcjson.ListTransactionsResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal the result as an array of listtransactions objects. - var transactions []btcjson.ListTransactionsResult - err = json.Unmarshal(res, &transactions) - if err != nil { - return nil, err - } - return transactions, nil -} - -// ListAddressTransactionsAsync returns an instance of a type that can be used -// to get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListAddressTransactions for the blocking version and more details. -// -// NOTE: This is a btcd extension. -func (c *Client) ListAddressTransactionsAsync(addresses []util.Address, account string) FutureListAddressTransactionsResult { - // Convert addresses to strings. - addrs := make([]string, 0, len(addresses)) - for _, addr := range addresses { - addrs = append(addrs, addr.EncodeAddress()) - } - cmd := btcjson.NewListAddressTransactionsCmd(addrs, &account) - return c.sendCmd(cmd) -} - -// ListAddressTransactions returns information about all transactions associated -// with the provided addresses. -// -// NOTE: This is a btcwallet extension. -func (c *Client) ListAddressTransactions(addresses []util.Address, account string) ([]btcjson.ListTransactionsResult, error) { - return c.ListAddressTransactionsAsync(addresses, account).Receive() -} - // FutureGetBestBlockResult is a future promise to deliver the result of a // GetBestBlockAsync RPC invocation (or an applicable error). type FutureGetBestBlockResult chan *response @@ -323,75 +239,6 @@ func (c *Client) GetHeaders(blockLocators []*daghash.Hash, stopHash *daghash.Has return c.GetHeadersAsync(blockLocators, stopHash).Receive() } -// FutureExportWatchingWalletResult is a future promise to deliver the result of -// an ExportWatchingWalletAsync RPC invocation (or an applicable error). -type FutureExportWatchingWalletResult chan *response - -// Receive waits for the response promised by the future and returns the -// exported wallet. -func (r FutureExportWatchingWalletResult) Receive() ([]byte, []byte, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, nil, err - } - - // Unmarshal result as a JSON object. - var obj map[string]interface{} - err = json.Unmarshal(res, &obj) - if err != nil { - return nil, nil, err - } - - // Check for the wallet and tx string fields in the object. - base64Wallet, ok := obj["wallet"].(string) - if !ok { - return nil, nil, fmt.Errorf("unexpected response type for "+ - "exportwatchingwallet 'wallet' field: %T\n", - obj["wallet"]) - } - base64TxStore, ok := obj["tx"].(string) - if !ok { - return nil, nil, fmt.Errorf("unexpected response type for "+ - "exportwatchingwallet 'tx' field: %T\n", - obj["tx"]) - } - - walletBytes, err := base64.StdEncoding.DecodeString(base64Wallet) - if err != nil { - return nil, nil, err - } - - txStoreBytes, err := base64.StdEncoding.DecodeString(base64TxStore) - if err != nil { - return nil, nil, err - } - - return walletBytes, txStoreBytes, nil - -} - -// ExportWatchingWalletAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ExportWatchingWallet for the blocking version and more details. -// -// NOTE: This is a btcwallet extension. -func (c *Client) ExportWatchingWalletAsync(account string) FutureExportWatchingWalletResult { - cmd := btcjson.NewExportWatchingWalletCmd(&account, btcjson.Bool(true)) - return c.sendCmd(cmd) -} - -// ExportWatchingWallet returns the raw bytes for a watching-only version of -// wallet.bin and tx.bin, respectively, for the specified account that can be -// used by btcwallet to enable a wallet which does not have the private keys -// necessary to spend funds. -// -// NOTE: This is a btcwallet extension. -func (c *Client) ExportWatchingWallet(account string) ([]byte, []byte, error) { - return c.ExportWatchingWalletAsync(account).Receive() -} - // FutureSessionResult is a future promise to deliver the result of a // SessionAsync RPC invocation (or an applicable error). type FutureSessionResult chan *response diff --git a/rpcclient/notify.go b/rpcclient/notify.go index 4f6c548c7..f41483fb5 100644 --- a/rpcclient/notify.go +++ b/rpcclient/notify.go @@ -108,25 +108,6 @@ type NotificationHandlers struct { // made to register for the notification and the function is non-nil. OnTxAcceptedVerbose func(txDetails *btcjson.TxRawResult) - // OnBtcdConnected is invoked when a wallet connects or disconnects from - // btcd. - // - // This will only be available when client is connected to a wallet - // server such as btcwallet. - OnBtcdConnected func(connected bool) - - // OnAccountBalance is invoked with account balance updates. - // - // This will only be available when speaking to a wallet server - // such as btcwallet. - OnAccountBalance func(account string, balance util.Amount, confirmed bool) - - // OnWalletLockState is invoked when a wallet is locked or unlocked. - // - // This will only be available when client is connected to a wallet - // server such as btcwallet. - OnWalletLockState func(locked bool) - // OnUnknownNotification is invoked when an unrecognized notification // is received. This typically means the notification handling code // for this package needs to be updated for a new notification type or @@ -218,59 +199,6 @@ func (c *Client) handleNotification(ntfn *rawNotification) { c.ntfnHandlers.OnTxAcceptedVerbose(rawTx) - // OnBtcdConnected - case btcjson.BtcdConnectedNtfnMethod: - // Ignore the notification if the client is not interested in - // it. - if c.ntfnHandlers.OnBtcdConnected == nil { - return - } - - connected, err := parseBtcdConnectedNtfnParams(ntfn.Params) - if err != nil { - log.Warnf("Received invalid btcd connected "+ - "notification: %s", err) - return - } - - c.ntfnHandlers.OnBtcdConnected(connected) - - // OnAccountBalance - case btcjson.AccountBalanceNtfnMethod: - // Ignore the notification if the client is not interested in - // it. - if c.ntfnHandlers.OnAccountBalance == nil { - return - } - - account, bal, conf, err := parseAccountBalanceNtfnParams(ntfn.Params) - if err != nil { - log.Warnf("Received invalid account balance "+ - "notification: %s", err) - return - } - - c.ntfnHandlers.OnAccountBalance(account, bal, conf) - - // OnWalletLockState - case btcjson.WalletLockStateNtfnMethod: - // Ignore the notification if the client is not interested in - // it. - if c.ntfnHandlers.OnWalletLockState == nil { - return - } - - // The account name is not notified, so the return value is - // discarded. - _, locked, err := parseWalletLockStateNtfnParams(ntfn.Params) - if err != nil { - log.Warnf("Received invalid wallet lock state "+ - "notification: %s", err) - return - } - - c.ntfnHandlers.OnWalletLockState(locked) - // OnUnknownNotification default: if c.ntfnHandlers.OnUnknownNotification == nil { @@ -513,85 +441,6 @@ func parseTxAcceptedVerboseNtfnParams(params []json.RawMessage) (*btcjson.TxRawR return &rawTx, nil } -// parseBtcdConnectedNtfnParams parses out the connection status of btcd -// and btcwallet from the parameters of a btcdconnected notification. -func parseBtcdConnectedNtfnParams(params []json.RawMessage) (bool, error) { - if len(params) != 1 { - return false, wrongNumParams(len(params)) - } - - // Unmarshal first parameter as a boolean. - var connected bool - err := json.Unmarshal(params[0], &connected) - if err != nil { - return false, err - } - - return connected, nil -} - -// parseAccountBalanceNtfnParams parses out the account name, total balance, -// and whether or not the balance is confirmed or unconfirmed from the -// parameters of an accountbalance notification. -func parseAccountBalanceNtfnParams(params []json.RawMessage) (account string, - balance util.Amount, confirmed bool, err error) { - - if len(params) != 3 { - return "", 0, false, wrongNumParams(len(params)) - } - - // Unmarshal first parameter as a string. - err = json.Unmarshal(params[0], &account) - if err != nil { - return "", 0, false, err - } - - // Unmarshal second parameter as a floating point number. - var fbal float64 - err = json.Unmarshal(params[1], &fbal) - if err != nil { - return "", 0, false, err - } - - // Unmarshal third parameter as a boolean. - err = json.Unmarshal(params[2], &confirmed) - if err != nil { - return "", 0, false, err - } - - // Bounds check amount. - bal, err := util.NewAmount(fbal) - if err != nil { - return "", 0, false, err - } - - return account, bal, confirmed, nil -} - -// parseWalletLockStateNtfnParams parses out the account name and locked -// state of an account from the parameters of a walletlockstate notification. -func parseWalletLockStateNtfnParams(params []json.RawMessage) (account string, - locked bool, err error) { - - if len(params) != 2 { - return "", false, wrongNumParams(len(params)) - } - - // Unmarshal first parameter as a string. - err = json.Unmarshal(params[0], &account) - if err != nil { - return "", false, err - } - - // Unmarshal second parameter as a boolean. - err = json.Unmarshal(params[1], &locked) - if err != nil { - return "", false, err - } - - return account, locked, nil -} - // FutureNotifyBlocksResult is a future promise to deliver the result of a // NotifyBlocksAsync RPC invocation (or an applicable error). type FutureNotifyBlocksResult chan *response diff --git a/rpcclient/rawtransactions.go b/rpcclient/rawtransactions.go index cf0f5bea1..716c1cf8a 100644 --- a/rpcclient/rawtransactions.go +++ b/rpcclient/rawtransactions.go @@ -15,49 +15,6 @@ import ( "github.com/daglabs/btcd/wire" ) -// SigHashType enumerates the available signature hashing types that the -// SignRawTransaction function accepts. -type SigHashType string - -// Constants used to indicate the signature hash type for SignRawTransaction. -const ( - // SigHashAll indicates ALL of the outputs should be signed. - SigHashAll SigHashType = "ALL" - - // SigHashNone indicates NONE of the outputs should be signed. This - // can be thought of as specifying the signer does not care where the - // bitcoins go. - SigHashNone SigHashType = "NONE" - - // SigHashSingle indicates that a SINGLE output should be signed. This - // can be thought of specifying the signer only cares about where ONE of - // the outputs goes, but not any of the others. - SigHashSingle SigHashType = "SINGLE" - - // SigHashAllAnyoneCanPay indicates that signer does not care where the - // other inputs to the transaction come from, so it allows other people - // to add inputs. In addition, it uses the SigHashAll signing method - // for outputs. - SigHashAllAnyoneCanPay SigHashType = "ALL|ANYONECANPAY" - - // SigHashNoneAnyoneCanPay indicates that signer does not care where the - // other inputs to the transaction come from, so it allows other people - // to add inputs. In addition, it uses the SigHashNone signing method - // for outputs. - SigHashNoneAnyoneCanPay SigHashType = "NONE|ANYONECANPAY" - - // SigHashSingleAnyoneCanPay indicates that signer does not care where - // the other inputs to the transaction come from, so it allows other - // people to add inputs. In addition, it uses the SigHashSingle signing - // method for outputs. - SigHashSingleAnyoneCanPay SigHashType = "SINGLE|ANYONECANPAY" -) - -// String returns the SighHashType in human-readable form. -func (s SigHashType) String() string { - return string(s) -} - // FutureGetRawTransactionResult is a future promise to deliver the result of a // GetRawTransactionAsync RPC invocation (or an applicable error). type FutureGetRawTransactionResult chan *response @@ -306,205 +263,6 @@ func (c *Client) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (*daghas return c.SendRawTransactionAsync(tx, allowHighFees).Receive() } -// FutureSignRawTransactionResult is a future promise to deliver the result -// of one of the SignRawTransactionAsync family of RPC invocations (or an -// applicable error). -type FutureSignRawTransactionResult chan *response - -// Receive waits for the response promised by the future and returns the -// signed transaction as well as whether or not all inputs are now signed. -func (r FutureSignRawTransactionResult) Receive() (*wire.MsgTx, bool, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, false, err - } - - // Unmarshal as a signrawtransaction result. - var signRawTxResult btcjson.SignRawTransactionResult - err = json.Unmarshal(res, &signRawTxResult) - if err != nil { - return nil, false, err - } - - // Decode the serialized transaction hex to raw bytes. - serializedTx, err := hex.DecodeString(signRawTxResult.Hex) - if err != nil { - return nil, false, err - } - - // Deserialize the transaction and return it. - var msgTx wire.MsgTx - if err := msgTx.Deserialize(bytes.NewReader(serializedTx)); err != nil { - return nil, false, err - } - - return &msgTx, signRawTxResult.Complete, nil -} - -// SignRawTransactionAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See SignRawTransaction for the blocking version and more details. -func (c *Client) SignRawTransactionAsync(tx *wire.MsgTx) FutureSignRawTransactionResult { - txHex := "" - if tx != nil { - // Serialize the transaction and convert to hex string. - buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) - if err := tx.Serialize(buf); err != nil { - return newFutureError(err) - } - txHex = hex.EncodeToString(buf.Bytes()) - } - - cmd := btcjson.NewSignRawTransactionCmd(txHex, nil, nil, nil) - return c.sendCmd(cmd) -} - -// SignRawTransaction signs inputs for the passed transaction and returns the -// signed transaction as well as whether or not all inputs are now signed. -// -// This function assumes the RPC server already knows the input transactions and -// private keys for the passed transaction which needs to be signed and uses the -// default signature hash type. Use one of the SignRawTransaction# variants to -// specify that information if needed. -func (c *Client) SignRawTransaction(tx *wire.MsgTx) (*wire.MsgTx, bool, error) { - return c.SignRawTransactionAsync(tx).Receive() -} - -// SignRawTransaction2Async returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See SignRawTransaction2 for the blocking version and more details. -func (c *Client) SignRawTransaction2Async(tx *wire.MsgTx, inputs []btcjson.RawTxInput) FutureSignRawTransactionResult { - txHex := "" - if tx != nil { - // Serialize the transaction and convert to hex string. - buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) - if err := tx.Serialize(buf); err != nil { - return newFutureError(err) - } - txHex = hex.EncodeToString(buf.Bytes()) - } - - cmd := btcjson.NewSignRawTransactionCmd(txHex, &inputs, nil, nil) - return c.sendCmd(cmd) -} - -// SignRawTransaction2 signs inputs for the passed transaction given the list -// of information about the input transactions needed to perform the signing -// process. -// -// This only input transactions that need to be specified are ones the -// RPC server does not already know. Already known input transactions will be -// merged with the specified transactions. -// -// See SignRawTransaction if the RPC server already knows the input -// transactions. -func (c *Client) SignRawTransaction2(tx *wire.MsgTx, inputs []btcjson.RawTxInput) (*wire.MsgTx, bool, error) { - return c.SignRawTransaction2Async(tx, inputs).Receive() -} - -// SignRawTransaction3Async returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See SignRawTransaction3 for the blocking version and more details. -func (c *Client) SignRawTransaction3Async(tx *wire.MsgTx, - inputs []btcjson.RawTxInput, - privKeysWIF []string) FutureSignRawTransactionResult { - - txHex := "" - if tx != nil { - // Serialize the transaction and convert to hex string. - buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) - if err := tx.Serialize(buf); err != nil { - return newFutureError(err) - } - txHex = hex.EncodeToString(buf.Bytes()) - } - - cmd := btcjson.NewSignRawTransactionCmd(txHex, &inputs, &privKeysWIF, - nil) - return c.sendCmd(cmd) -} - -// SignRawTransaction3 signs inputs for the passed transaction given the list -// of information about extra input transactions and a list of private keys -// needed to perform the signing process. The private keys must be in wallet -// import format (WIF). -// -// This only input transactions that need to be specified are ones the -// RPC server does not already know. Already known input transactions will be -// merged with the specified transactions. This means the list of transaction -// inputs can be nil if the RPC server already knows them all. -// -// NOTE: Unlike the merging functionality of the input transactions, ONLY the -// specified private keys will be used, so even if the server already knows some -// of the private keys, they will NOT be used. -// -// See SignRawTransaction if the RPC server already knows the input -// transactions and private keys or SignRawTransaction2 if it already knows the -// private keys. -func (c *Client) SignRawTransaction3(tx *wire.MsgTx, - inputs []btcjson.RawTxInput, - privKeysWIF []string) (*wire.MsgTx, bool, error) { - - return c.SignRawTransaction3Async(tx, inputs, privKeysWIF).Receive() -} - -// SignRawTransaction4Async returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See SignRawTransaction4 for the blocking version and more details. -func (c *Client) SignRawTransaction4Async(tx *wire.MsgTx, - inputs []btcjson.RawTxInput, privKeysWIF []string, - hashType SigHashType) FutureSignRawTransactionResult { - - txHex := "" - if tx != nil { - // Serialize the transaction and convert to hex string. - buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize())) - if err := tx.Serialize(buf); err != nil { - return newFutureError(err) - } - txHex = hex.EncodeToString(buf.Bytes()) - } - - cmd := btcjson.NewSignRawTransactionCmd(txHex, &inputs, &privKeysWIF, - btcjson.String(string(hashType))) - return c.sendCmd(cmd) -} - -// SignRawTransaction4 signs inputs for the passed transaction using the -// the specified signature hash type given the list of information about extra -// input transactions and a potential list of private keys needed to perform -// the signing process. The private keys, if specified, must be in wallet -// import format (WIF). -// -// The only input transactions that need to be specified are ones the RPC server -// does not already know. This means the list of transaction inputs can be nil -// if the RPC server already knows them all. -// -// NOTE: Unlike the merging functionality of the input transactions, ONLY the -// specified private keys will be used, so even if the server already knows some -// of the private keys, they will NOT be used. The list of private keys can be -// nil in which case any private keys the RPC server knows will be used. -// -// This function should only used if a non-default signature hash type is -// desired. Otherwise, see SignRawTransaction if the RPC server already knows -// the input transactions and private keys, SignRawTransaction2 if it already -// knows the private keys, or SignRawTransaction3 if it does not know both. -func (c *Client) SignRawTransaction4(tx *wire.MsgTx, - inputs []btcjson.RawTxInput, privKeysWIF []string, - hashType SigHashType) (*wire.MsgTx, bool, error) { - - return c.SignRawTransaction4Async(tx, inputs, privKeysWIF, - hashType).Receive() -} - // FutureSearchRawTransactionsResult is a future promise to deliver the result // of the SearchRawTransactionsAsync RPC invocation (or an applicable error). type FutureSearchRawTransactionsResult chan *response diff --git a/rpcclient/wallet.go b/rpcclient/wallet.go deleted file mode 100644 index 005bd63ee..000000000 --- a/rpcclient/wallet.go +++ /dev/null @@ -1,2240 +0,0 @@ -// Copyright (c) 2014-2017 The btcsuite developers -// Use of this source code is governed by an ISC -// license that can be found in the LICENSE file. - -package rpcclient - -import ( - "encoding/json" - "strconv" - - "github.com/daglabs/btcd/btcjson" - "github.com/daglabs/btcd/util" - "github.com/daglabs/btcd/util/daghash" - "github.com/daglabs/btcd/wire" -) - -// ***************************** -// Transaction Listing Functions -// ***************************** - -// FutureGetTransactionResult is a future promise to deliver the result -// of a GetTransactionAsync RPC invocation (or an applicable error). -type FutureGetTransactionResult chan *response - -// Receive waits for the response promised by the future and returns detailed -// information about a wallet transaction. -func (r FutureGetTransactionResult) Receive() (*btcjson.GetTransactionResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a gettransaction result object - var getTx btcjson.GetTransactionResult - err = json.Unmarshal(res, &getTx) - if err != nil { - return nil, err - } - - return &getTx, nil -} - -// GetTransactionAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See GetTransaction for the blocking version and more details. -func (c *Client) GetTransactionAsync(txHash *daghash.Hash) FutureGetTransactionResult { - hash := "" - if txHash != nil { - hash = txHash.String() - } - - cmd := btcjson.NewGetTransactionCmd(hash, nil) - return c.sendCmd(cmd) -} - -// GetTransaction returns detailed information about a wallet transaction. -// -// See GetRawTransaction to return the raw transaction instead. -func (c *Client) GetTransaction(txHash *daghash.Hash) (*btcjson.GetTransactionResult, error) { - return c.GetTransactionAsync(txHash).Receive() -} - -// FutureListTransactionsResult is a future promise to deliver the result of a -// ListTransactionsAsync, ListTransactionsCountAsync, or -// ListTransactionsCountFromAsync RPC invocation (or an applicable error). -type FutureListTransactionsResult chan *response - -// Receive waits for the response promised by the future and returns a list of -// the most recent transactions. -func (r FutureListTransactionsResult) Receive() ([]btcjson.ListTransactionsResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as an array of listtransaction result objects. - var transactions []btcjson.ListTransactionsResult - err = json.Unmarshal(res, &transactions) - if err != nil { - return nil, err - } - - return transactions, nil -} - -// ListTransactionsAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See ListTransactions for the blocking version and more details. -func (c *Client) ListTransactionsAsync(account string) FutureListTransactionsResult { - cmd := btcjson.NewListTransactionsCmd(&account, nil, nil, nil) - return c.sendCmd(cmd) -} - -// ListTransactions returns a list of the most recent transactions. -// -// See the ListTransactionsCount and ListTransactionsCountFrom to control the -// number of transactions returned and starting point, respectively. -func (c *Client) ListTransactions(account string) ([]btcjson.ListTransactionsResult, error) { - return c.ListTransactionsAsync(account).Receive() -} - -// ListTransactionsCountAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListTransactionsCount for the blocking version and more details. -func (c *Client) ListTransactionsCountAsync(account string, count int) FutureListTransactionsResult { - cmd := btcjson.NewListTransactionsCmd(&account, &count, nil, nil) - return c.sendCmd(cmd) -} - -// ListTransactionsCount returns a list of the most recent transactions up -// to the passed count. -// -// See the ListTransactions and ListTransactionsCountFrom functions for -// different options. -func (c *Client) ListTransactionsCount(account string, count int) ([]btcjson.ListTransactionsResult, error) { - return c.ListTransactionsCountAsync(account, count).Receive() -} - -// ListTransactionsCountFromAsync returns an instance of a type that can be used -// to get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListTransactionsCountFrom for the blocking version and more details. -func (c *Client) ListTransactionsCountFromAsync(account string, count, from int) FutureListTransactionsResult { - cmd := btcjson.NewListTransactionsCmd(&account, &count, &from, nil) - return c.sendCmd(cmd) -} - -// ListTransactionsCountFrom returns a list of the most recent transactions up -// to the passed count while skipping the first 'from' transactions. -// -// See the ListTransactions and ListTransactionsCount functions to use defaults. -func (c *Client) ListTransactionsCountFrom(account string, count, from int) ([]btcjson.ListTransactionsResult, error) { - return c.ListTransactionsCountFromAsync(account, count, from).Receive() -} - -// FutureListUnspentResult is a future promise to deliver the result of a -// ListUnspentAsync, ListUnspentMinAsync, ListUnspentMinMaxAsync, or -// ListUnspentMinMaxAddressesAsync RPC invocation (or an applicable error). -type FutureListUnspentResult chan *response - -// Receive waits for the response promised by the future and returns all -// unspent wallet transaction outputs returned by the RPC call. If the -// future wac returned by a call to ListUnspentMinAsync, ListUnspentMinMaxAsync, -// or ListUnspentMinMaxAddressesAsync, the range may be limited by the -// parameters of the RPC invocation. -func (r FutureListUnspentResult) Receive() ([]btcjson.ListUnspentResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as an array of listunspent results. - var unspent []btcjson.ListUnspentResult - err = json.Unmarshal(res, &unspent) - if err != nil { - return nil, err - } - - return unspent, nil -} - -// ListUnspentAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function -// on the returned instance. -// -// See ListUnspent for the blocking version and more details. -func (c *Client) ListUnspentAsync() FutureListUnspentResult { - cmd := btcjson.NewListUnspentCmd(nil, nil, nil) - return c.sendCmd(cmd) -} - -// ListUnspentMinAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function -// on the returned instance. -// -// See ListUnspentMin for the blocking version and more details. -func (c *Client) ListUnspentMinAsync(minConf int) FutureListUnspentResult { - cmd := btcjson.NewListUnspentCmd(&minConf, nil, nil) - return c.sendCmd(cmd) -} - -// ListUnspentMinMaxAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function -// on the returned instance. -// -// See ListUnspentMinMax for the blocking version and more details. -func (c *Client) ListUnspentMinMaxAsync(minConf, maxConf int) FutureListUnspentResult { - cmd := btcjson.NewListUnspentCmd(&minConf, &maxConf, nil) - return c.sendCmd(cmd) -} - -// ListUnspentMinMaxAddressesAsync returns an instance of a type that can be -// used to get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListUnspentMinMaxAddresses for the blocking version and more details. -func (c *Client) ListUnspentMinMaxAddressesAsync(minConf, maxConf int, addrs []util.Address) FutureListUnspentResult { - addrStrs := make([]string, 0, len(addrs)) - for _, a := range addrs { - addrStrs = append(addrStrs, a.EncodeAddress()) - } - - cmd := btcjson.NewListUnspentCmd(&minConf, &maxConf, &addrStrs) - return c.sendCmd(cmd) -} - -// ListUnspent returns all unspent transaction outputs known to a wallet, using -// the default number of minimum and maximum number of confirmations as a -// filter (1 and 999999, respectively). -func (c *Client) ListUnspent() ([]btcjson.ListUnspentResult, error) { - return c.ListUnspentAsync().Receive() -} - -// ListUnspentMin returns all unspent transaction outputs known to a wallet, -// using the specified number of minimum conformations and default number of -// maximum confiramtions (999999) as a filter. -func (c *Client) ListUnspentMin(minConf int) ([]btcjson.ListUnspentResult, error) { - return c.ListUnspentMinAsync(minConf).Receive() -} - -// ListUnspentMinMax returns all unspent transaction outputs known to a wallet, -// using the specified number of minimum and maximum number of confirmations as -// a filter. -func (c *Client) ListUnspentMinMax(minConf, maxConf int) ([]btcjson.ListUnspentResult, error) { - return c.ListUnspentMinMaxAsync(minConf, maxConf).Receive() -} - -// ListUnspentMinMaxAddresses returns all unspent transaction outputs that pay -// to any of specified addresses in a wallet using the specified number of -// minimum and maximum number of confirmations as a filter. -func (c *Client) ListUnspentMinMaxAddresses(minConf, maxConf int, addrs []util.Address) ([]btcjson.ListUnspentResult, error) { - return c.ListUnspentMinMaxAddressesAsync(minConf, maxConf, addrs).Receive() -} - -// FutureListSinceBlockResult is a future promise to deliver the result of a -// ListSinceBlockAsync or ListSinceBlockMinConfAsync RPC invocation (or an -// applicable error). -type FutureListSinceBlockResult chan *response - -// Receive waits for the response promised by the future and returns all -// transactions added in blocks since the specified block hash, or all -// transactions if it is nil. -func (r FutureListSinceBlockResult) Receive() (*btcjson.ListSinceBlockResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a listsinceblock result object. - var listResult btcjson.ListSinceBlockResult - err = json.Unmarshal(res, &listResult) - if err != nil { - return nil, err - } - - return &listResult, nil -} - -// ListSinceBlockAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See ListSinceBlock for the blocking version and more details. -func (c *Client) ListSinceBlockAsync(blockHash *daghash.Hash) FutureListSinceBlockResult { - var hash *string - if blockHash != nil { - hash = btcjson.String(blockHash.String()) - } - - cmd := btcjson.NewListSinceBlockCmd(hash, nil, nil) - return c.sendCmd(cmd) -} - -// ListSinceBlock returns all transactions added in blocks since the specified -// block hash, or all transactions if it is nil, using the default number of -// minimum confirmations as a filter. -// -// See ListSinceBlockMinConf to override the minimum number of confirmations. -func (c *Client) ListSinceBlock(blockHash *daghash.Hash) (*btcjson.ListSinceBlockResult, error) { - return c.ListSinceBlockAsync(blockHash).Receive() -} - -// ListSinceBlockMinConfAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListSinceBlockMinConf for the blocking version and more details. -func (c *Client) ListSinceBlockMinConfAsync(blockHash *daghash.Hash, minConfirms int) FutureListSinceBlockResult { - var hash *string - if blockHash != nil { - hash = btcjson.String(blockHash.String()) - } - - cmd := btcjson.NewListSinceBlockCmd(hash, &minConfirms, nil) - return c.sendCmd(cmd) -} - -// ListSinceBlockMinConf returns all transactions added in blocks since the -// specified block hash, or all transactions if it is nil, using the specified -// number of minimum confirmations as a filter. -// -// See ListSinceBlock to use the default minimum number of confirmations. -func (c *Client) ListSinceBlockMinConf(blockHash *daghash.Hash, minConfirms int) (*btcjson.ListSinceBlockResult, error) { - return c.ListSinceBlockMinConfAsync(blockHash, minConfirms).Receive() -} - -// ************************** -// Transaction Send Functions -// ************************** - -// FutureLockUnspentResult is a future promise to deliver the error result of a -// LockUnspentAsync RPC invocation. -type FutureLockUnspentResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of locking or unlocking the unspent output(s). -func (r FutureLockUnspentResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// LockUnspentAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See LockUnspent for the blocking version and more details. -func (c *Client) LockUnspentAsync(unlock bool, ops []*wire.Outpoint) FutureLockUnspentResult { - outputs := make([]btcjson.TransactionInput, len(ops)) - for i, op := range ops { - outputs[i] = btcjson.TransactionInput{ - TxID: op.TxID.String(), - Vout: op.Index, - } - } - cmd := btcjson.NewLockUnspentCmd(unlock, outputs) - return c.sendCmd(cmd) -} - -// LockUnspent marks outputs as locked or unlocked, depending on the value of -// the unlock bool. When locked, the unspent output will not be selected as -// input for newly created, non-raw transactions, and will not be returned in -// future ListUnspent results, until the output is marked unlocked again. -// -// If unlock is false, each outpoint in ops will be marked locked. If unlocked -// is true and specific outputs are specified in ops (len != 0), exactly those -// outputs will be marked unlocked. If unlocked is true and no outpoints are -// specified, all previous locked outputs are marked unlocked. -// -// The locked or unlocked state of outputs are not written to disk and after -// restarting a wallet process, this data will be reset (every output unlocked). -// -// NOTE: While this method would be a bit more readable if the unlock bool was -// reversed (that is, LockUnspent(true, ...) locked the outputs), it has been -// left as unlock to keep compatibility with the reference client API and to -// avoid confusion for those who are already familiar with the lockunspent RPC. -func (c *Client) LockUnspent(unlock bool, ops []*wire.Outpoint) error { - return c.LockUnspentAsync(unlock, ops).Receive() -} - -// FutureListLockUnspentResult is a future promise to deliver the result of a -// ListLockUnspentAsync RPC invocation (or an applicable error). -type FutureListLockUnspentResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of all currently locked unspent outputs. -func (r FutureListLockUnspentResult) Receive() ([]*wire.Outpoint, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal as an array of transaction inputs. - var inputs []btcjson.TransactionInput - err = json.Unmarshal(res, &inputs) - if err != nil { - return nil, err - } - - // Create a slice of outpoints from the transaction input structs. - ops := make([]*wire.Outpoint, len(inputs)) - for i, input := range inputs { - txID, err := daghash.NewTxIDFromStr(input.TxID) - if err != nil { - return nil, err - } - ops[i] = wire.NewOutpoint(txID, input.Vout) - } - - return ops, nil -} - -// ListLockUnspentAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See ListLockUnspent for the blocking version and more details. -func (c *Client) ListLockUnspentAsync() FutureListLockUnspentResult { - cmd := btcjson.NewListLockUnspentCmd() - return c.sendCmd(cmd) -} - -// ListLockUnspent returns a slice of outpoints for all unspent outputs marked -// as locked by a wallet. Unspent outputs may be marked locked using -// LockOutput. -func (c *Client) ListLockUnspent() ([]*wire.Outpoint, error) { - return c.ListLockUnspentAsync().Receive() -} - -// FutureSetTxFeeResult is a future promise to deliver the result of a -// SetTxFeeAsync RPC invocation (or an applicable error). -type FutureSetTxFeeResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of setting an optional transaction fee per KB that helps ensure transactions -// are processed quickly. Most transaction are 1KB. -func (r FutureSetTxFeeResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// SetTxFeeAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See SetTxFee for the blocking version and more details. -func (c *Client) SetTxFeeAsync(fee util.Amount) FutureSetTxFeeResult { - cmd := btcjson.NewSetTxFeeCmd(fee.ToBTC()) - return c.sendCmd(cmd) -} - -// SetTxFee sets an optional transaction fee per KB that helps ensure -// transactions are processed quickly. Most transaction are 1KB. -func (c *Client) SetTxFee(fee util.Amount) error { - return c.SetTxFeeAsync(fee).Receive() -} - -// FutureSendToAddressResult is a future promise to deliver the result of a -// SendToAddressAsync RPC invocation (or an applicable error). -type FutureSendToAddressResult chan *response - -// Receive waits for the response promised by the future and returns the hash -// of the transaction sending the passed amount to the given address. -func (r FutureSendToAddressResult) Receive() (*daghash.Hash, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a string. - var txHash string - err = json.Unmarshal(res, &txHash) - if err != nil { - return nil, err - } - - return daghash.NewHashFromStr(txHash) -} - -// SendToAddressAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See SendToAddress for the blocking version and more details. -func (c *Client) SendToAddressAsync(address util.Address, amount util.Amount) FutureSendToAddressResult { - addr := address.EncodeAddress() - cmd := btcjson.NewSendToAddressCmd(addr, amount.ToBTC(), nil, nil) - return c.sendCmd(cmd) -} - -// SendToAddress sends the passed amount to the given address. -// -// See SendToAddressComment to associate comments with the transaction in the -// wallet. The comments are not part of the transaction and are only internal -// to the wallet. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) SendToAddress(address util.Address, amount util.Amount) (*daghash.Hash, error) { - return c.SendToAddressAsync(address, amount).Receive() -} - -// SendToAddressCommentAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See SendToAddressComment for the blocking version and more details. -func (c *Client) SendToAddressCommentAsync(address util.Address, - amount util.Amount, comment, - commentTo string) FutureSendToAddressResult { - - addr := address.EncodeAddress() - cmd := btcjson.NewSendToAddressCmd(addr, amount.ToBTC(), &comment, - &commentTo) - return c.sendCmd(cmd) -} - -// SendToAddressComment sends the passed amount to the given address and stores -// the provided comment and comment to in the wallet. The comment parameter is -// intended to be used for the purpose of the transaction while the commentTo -// parameter is indended to be used for who the transaction is being sent to. -// -// The comments are not part of the transaction and are only internal -// to the wallet. -// -// See SendToAddress to avoid using comments. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) SendToAddressComment(address util.Address, amount util.Amount, comment, commentTo string) (*daghash.Hash, error) { - return c.SendToAddressCommentAsync(address, amount, comment, - commentTo).Receive() -} - -// FutureSendFromResult is a future promise to deliver the result of a -// SendFromAsync, SendFromMinConfAsync, or SendFromCommentAsync RPC invocation -// (or an applicable error). -type FutureSendFromResult chan *response - -// Receive waits for the response promised by the future and returns the hash -// of the transaction sending amount to the given address using the provided -// account as a source of funds. -func (r FutureSendFromResult) Receive() (*daghash.Hash, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a string. - var txHash string - err = json.Unmarshal(res, &txHash) - if err != nil { - return nil, err - } - - return daghash.NewHashFromStr(txHash) -} - -// SendFromAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See SendFrom for the blocking version and more details. -func (c *Client) SendFromAsync(fromAccount string, toAddress util.Address, amount util.Amount) FutureSendFromResult { - addr := toAddress.EncodeAddress() - cmd := btcjson.NewSendFromCmd(fromAccount, addr, amount.ToBTC(), nil, - nil, nil) - return c.sendCmd(cmd) -} - -// SendFrom sends the passed amount to the given address using the provided -// account as a source of funds. Only funds with the default number of minimum -// confirmations will be used. -// -// See SendFromMinConf and SendFromComment for different options. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) SendFrom(fromAccount string, toAddress util.Address, amount util.Amount) (*daghash.Hash, error) { - return c.SendFromAsync(fromAccount, toAddress, amount).Receive() -} - -// SendFromMinConfAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See SendFromMinConf for the blocking version and more details. -func (c *Client) SendFromMinConfAsync(fromAccount string, toAddress util.Address, amount util.Amount, minConfirms int) FutureSendFromResult { - addr := toAddress.EncodeAddress() - cmd := btcjson.NewSendFromCmd(fromAccount, addr, amount.ToBTC(), - &minConfirms, nil, nil) - return c.sendCmd(cmd) -} - -// SendFromMinConf sends the passed amount to the given address using the -// provided account as a source of funds. Only funds with the passed number of -// minimum confirmations will be used. -// -// See SendFrom to use the default number of minimum confirmations and -// SendFromComment for additional options. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) SendFromMinConf(fromAccount string, toAddress util.Address, amount util.Amount, minConfirms int) (*daghash.Hash, error) { - return c.SendFromMinConfAsync(fromAccount, toAddress, amount, - minConfirms).Receive() -} - -// SendFromCommentAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See SendFromComment for the blocking version and more details. -func (c *Client) SendFromCommentAsync(fromAccount string, - toAddress util.Address, amount util.Amount, minConfirms int, - comment, commentTo string) FutureSendFromResult { - - addr := toAddress.EncodeAddress() - cmd := btcjson.NewSendFromCmd(fromAccount, addr, amount.ToBTC(), - &minConfirms, &comment, &commentTo) - return c.sendCmd(cmd) -} - -// SendFromComment sends the passed amount to the given address using the -// provided account as a source of funds and stores the provided comment and -// comment to in the wallet. The comment parameter is intended to be used for -// the purpose of the transaction while the commentTo parameter is indended to -// be used for who the transaction is being sent to. Only funds with the passed -// number of minimum confirmations will be used. -// -// See SendFrom and SendFromMinConf to use defaults. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) SendFromComment(fromAccount string, toAddress util.Address, - amount util.Amount, minConfirms int, - comment, commentTo string) (*daghash.Hash, error) { - - return c.SendFromCommentAsync(fromAccount, toAddress, amount, - minConfirms, comment, commentTo).Receive() -} - -// FutureSendManyResult is a future promise to deliver the result of a -// SendManyAsync, SendManyMinConfAsync, or SendManyCommentAsync RPC invocation -// (or an applicable error). -type FutureSendManyResult chan *response - -// Receive waits for the response promised by the future and returns the hash -// of the transaction sending multiple amounts to multiple addresses using the -// provided account as a source of funds. -func (r FutureSendManyResult) Receive() (*daghash.Hash, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmashal result as a string. - var txHash string - err = json.Unmarshal(res, &txHash) - if err != nil { - return nil, err - } - - return daghash.NewHashFromStr(txHash) -} - -// SendManyAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See SendMany for the blocking version and more details. -func (c *Client) SendManyAsync(fromAccount string, amounts map[util.Address]util.Amount) FutureSendManyResult { - convertedAmounts := make(map[string]float64, len(amounts)) - for addr, amount := range amounts { - convertedAmounts[addr.EncodeAddress()] = amount.ToBTC() - } - cmd := btcjson.NewSendManyCmd(fromAccount, convertedAmounts, nil, nil) - return c.sendCmd(cmd) -} - -// SendMany sends multiple amounts to multiple addresses using the provided -// account as a source of funds in a single transaction. Only funds with the -// default number of minimum confirmations will be used. -// -// See SendManyMinConf and SendManyComment for different options. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) SendMany(fromAccount string, amounts map[util.Address]util.Amount) (*daghash.Hash, error) { - return c.SendManyAsync(fromAccount, amounts).Receive() -} - -// SendManyMinConfAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See SendManyMinConf for the blocking version and more details. -func (c *Client) SendManyMinConfAsync(fromAccount string, - amounts map[util.Address]util.Amount, - minConfirms int) FutureSendManyResult { - - convertedAmounts := make(map[string]float64, len(amounts)) - for addr, amount := range amounts { - convertedAmounts[addr.EncodeAddress()] = amount.ToBTC() - } - cmd := btcjson.NewSendManyCmd(fromAccount, convertedAmounts, - &minConfirms, nil) - return c.sendCmd(cmd) -} - -// SendManyMinConf sends multiple amounts to multiple addresses using the -// provided account as a source of funds in a single transaction. Only funds -// with the passed number of minimum confirmations will be used. -// -// See SendMany to use the default number of minimum confirmations and -// SendManyComment for additional options. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) SendManyMinConf(fromAccount string, - amounts map[util.Address]util.Amount, - minConfirms int) (*daghash.Hash, error) { - - return c.SendManyMinConfAsync(fromAccount, amounts, minConfirms).Receive() -} - -// SendManyCommentAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See SendManyComment for the blocking version and more details. -func (c *Client) SendManyCommentAsync(fromAccount string, - amounts map[util.Address]util.Amount, minConfirms int, - comment string) FutureSendManyResult { - - convertedAmounts := make(map[string]float64, len(amounts)) - for addr, amount := range amounts { - convertedAmounts[addr.EncodeAddress()] = amount.ToBTC() - } - cmd := btcjson.NewSendManyCmd(fromAccount, convertedAmounts, - &minConfirms, &comment) - return c.sendCmd(cmd) -} - -// SendManyComment sends multiple amounts to multiple addresses using the -// provided account as a source of funds in a single transaction and stores the -// provided comment in the wallet. The comment parameter is intended to be used -// for the purpose of the transaction Only funds with the passed number of -// minimum confirmations will be used. -// -// See SendMany and SendManyMinConf to use defaults. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) SendManyComment(fromAccount string, - amounts map[util.Address]util.Amount, minConfirms int, - comment string) (*daghash.Hash, error) { - - return c.SendManyCommentAsync(fromAccount, amounts, minConfirms, - comment).Receive() -} - -// ************************* -// Address/Account Functions -// ************************* - -// FutureAddMultisigAddressResult is a future promise to deliver the result of a -// AddMultisigAddressAsync RPC invocation (or an applicable error). -type FutureAddMultisigAddressResult chan *response - -// Receive waits for the response promised by the future and returns the -// multisignature address that requires the specified number of signatures for -// the provided addresses. -func (r FutureAddMultisigAddressResult) Receive() (util.Address, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a string. - var addr string - err = json.Unmarshal(res, &addr) - if err != nil { - return nil, err - } - - return util.DecodeAddress(addr, util.Bech32PrefixDAGCoin) -} - -// AddMultisigAddressAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See AddMultisigAddress for the blocking version and more details. -func (c *Client) AddMultisigAddressAsync(requiredSigs int, addresses []util.Address, account string) FutureAddMultisigAddressResult { - addrs := make([]string, 0, len(addresses)) - for _, addr := range addresses { - addrs = append(addrs, addr.String()) - } - - cmd := btcjson.NewAddMultisigAddressCmd(requiredSigs, addrs, &account) - return c.sendCmd(cmd) -} - -// AddMultisigAddress adds a multisignature address that requires the specified -// number of signatures for the provided addresses to the wallet. -func (c *Client) AddMultisigAddress(requiredSigs int, addresses []util.Address, account string) (util.Address, error) { - return c.AddMultisigAddressAsync(requiredSigs, addresses, - account).Receive() -} - -// FutureCreateMultisigResult is a future promise to deliver the result of a -// CreateMultisigAsync RPC invocation (or an applicable error). -type FutureCreateMultisigResult chan *response - -// Receive waits for the response promised by the future and returns the -// multisignature address and script needed to redeem it. -func (r FutureCreateMultisigResult) Receive() (*btcjson.CreateMultiSigResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a createmultisig result object. - var multisigRes btcjson.CreateMultiSigResult - err = json.Unmarshal(res, &multisigRes) - if err != nil { - return nil, err - } - - return &multisigRes, nil -} - -// CreateMultisigAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See CreateMultisig for the blocking version and more details. -func (c *Client) CreateMultisigAsync(requiredSigs int, addresses []util.Address) FutureCreateMultisigResult { - addrs := make([]string, 0, len(addresses)) - for _, addr := range addresses { - addrs = append(addrs, addr.String()) - } - - cmd := btcjson.NewCreateMultisigCmd(requiredSigs, addrs) - return c.sendCmd(cmd) -} - -// CreateMultisig creates a multisignature address that requires the specified -// number of signatures for the provided addresses and returns the -// multisignature address and script needed to redeem it. -func (c *Client) CreateMultisig(requiredSigs int, addresses []util.Address) (*btcjson.CreateMultiSigResult, error) { - return c.CreateMultisigAsync(requiredSigs, addresses).Receive() -} - -// FutureCreateNewAccountResult is a future promise to deliver the result of a -// CreateNewAccountAsync RPC invocation (or an applicable error). -type FutureCreateNewAccountResult chan *response - -// Receive waits for the response promised by the future and returns the -// result of creating new account. -func (r FutureCreateNewAccountResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// CreateNewAccountAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See CreateNewAccount for the blocking version and more details. -func (c *Client) CreateNewAccountAsync(account string) FutureCreateNewAccountResult { - cmd := btcjson.NewCreateNewAccountCmd(account) - return c.sendCmd(cmd) -} - -// CreateNewAccount creates a new wallet account. -func (c *Client) CreateNewAccount(account string) error { - return c.CreateNewAccountAsync(account).Receive() -} - -// FutureGetNewAddressResult is a future promise to deliver the result of a -// GetNewAddressAsync RPC invocation (or an applicable error). -type FutureGetNewAddressResult chan *response - -// Receive waits for the response promised by the future and returns a new -// address. -func (r FutureGetNewAddressResult) Receive() (util.Address, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a string. - var addr string - err = json.Unmarshal(res, &addr) - if err != nil { - return nil, err - } - - return util.DecodeAddress(addr, util.Bech32PrefixDAGCoin) -} - -// GetNewAddressAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See GetNewAddress for the blocking version and more details. -func (c *Client) GetNewAddressAsync(account string) FutureGetNewAddressResult { - cmd := btcjson.NewGetNewAddressCmd(&account) - return c.sendCmd(cmd) -} - -// GetNewAddress returns a new address. -func (c *Client) GetNewAddress(account string) (util.Address, error) { - return c.GetNewAddressAsync(account).Receive() -} - -// FutureGetRawChangeAddressResult is a future promise to deliver the result of -// a GetRawChangeAddressAsync RPC invocation (or an applicable error). -type FutureGetRawChangeAddressResult chan *response - -// Receive waits for the response promised by the future and returns a new -// address for receiving change that will be associated with the provided -// account. Note that this is only for raw transactions and NOT for normal use. -func (r FutureGetRawChangeAddressResult) Receive() (util.Address, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a string. - var addr string - err = json.Unmarshal(res, &addr) - if err != nil { - return nil, err - } - - return util.DecodeAddress(addr, util.Bech32PrefixDAGCoin) -} - -// GetRawChangeAddressAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See GetRawChangeAddress for the blocking version and more details. -func (c *Client) GetRawChangeAddressAsync(account string) FutureGetRawChangeAddressResult { - cmd := btcjson.NewGetRawChangeAddressCmd(&account) - return c.sendCmd(cmd) -} - -// GetRawChangeAddress returns a new address for receiving change that will be -// associated with the provided account. Note that this is only for raw -// transactions and NOT for normal use. -func (c *Client) GetRawChangeAddress(account string) (util.Address, error) { - return c.GetRawChangeAddressAsync(account).Receive() -} - -// FutureGetAccountAddressResult is a future promise to deliver the result of a -// GetAccountAddressAsync RPC invocation (or an applicable error). -type FutureGetAccountAddressResult chan *response - -// Receive waits for the response promised by the future and returns the current -// Bitcoin address for receiving payments to the specified account. -func (r FutureGetAccountAddressResult) Receive() (util.Address, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a string. - var addr string - err = json.Unmarshal(res, &addr) - if err != nil { - return nil, err - } - - return util.DecodeAddress(addr, util.Bech32PrefixDAGCoin) -} - -// GetAccountAddressAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See GetAccountAddress for the blocking version and more details. -func (c *Client) GetAccountAddressAsync(account string) FutureGetAccountAddressResult { - cmd := btcjson.NewGetAccountAddressCmd(account) - return c.sendCmd(cmd) -} - -// GetAccountAddress returns the current Bitcoin address for receiving payments -// to the specified account. -func (c *Client) GetAccountAddress(account string) (util.Address, error) { - return c.GetAccountAddressAsync(account).Receive() -} - -// FutureGetAccountResult is a future promise to deliver the result of a -// GetAccountAsync RPC invocation (or an applicable error). -type FutureGetAccountResult chan *response - -// Receive waits for the response promised by the future and returns the account -// associated with the passed address. -func (r FutureGetAccountResult) Receive() (string, error) { - res, err := receiveFuture(r) - if err != nil { - return "", err - } - - // Unmarshal result as a string. - var account string - err = json.Unmarshal(res, &account) - if err != nil { - return "", err - } - - return account, nil -} - -// GetAccountAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See GetAccount for the blocking version and more details. -func (c *Client) GetAccountAsync(address util.Address) FutureGetAccountResult { - addr := address.EncodeAddress() - cmd := btcjson.NewGetAccountCmd(addr) - return c.sendCmd(cmd) -} - -// GetAccount returns the account associated with the passed address. -func (c *Client) GetAccount(address util.Address) (string, error) { - return c.GetAccountAsync(address).Receive() -} - -// FutureSetAccountResult is a future promise to deliver the result of a -// SetAccountAsync RPC invocation (or an applicable error). -type FutureSetAccountResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of setting the account to be associated with the passed address. -func (r FutureSetAccountResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// SetAccountAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See SetAccount for the blocking version and more details. -func (c *Client) SetAccountAsync(address util.Address, account string) FutureSetAccountResult { - addr := address.EncodeAddress() - cmd := btcjson.NewSetAccountCmd(addr, account) - return c.sendCmd(cmd) -} - -// SetAccount sets the account associated with the passed address. -func (c *Client) SetAccount(address util.Address, account string) error { - return c.SetAccountAsync(address, account).Receive() -} - -// FutureGetAddressesByAccountResult is a future promise to deliver the result -// of a GetAddressesByAccountAsync RPC invocation (or an applicable error). -type FutureGetAddressesByAccountResult chan *response - -// Receive waits for the response promised by the future and returns the list of -// addresses associated with the passed account. -func (r FutureGetAddressesByAccountResult) Receive() ([]util.Address, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmashal result as an array of string. - var addrStrings []string - err = json.Unmarshal(res, &addrStrings) - if err != nil { - return nil, err - } - - addrs := make([]util.Address, 0, len(addrStrings)) - for _, addrStr := range addrStrings { - addr, err := util.DecodeAddress(addrStr, - util.Bech32PrefixDAGCoin) - if err != nil { - return nil, err - } - addrs = append(addrs, addr) - } - - return addrs, nil -} - -// GetAddressesByAccountAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See GetAddressesByAccount for the blocking version and more details. -func (c *Client) GetAddressesByAccountAsync(account string) FutureGetAddressesByAccountResult { - cmd := btcjson.NewGetAddressesByAccountCmd(account) - return c.sendCmd(cmd) -} - -// GetAddressesByAccount returns the list of addresses associated with the -// passed account. -func (c *Client) GetAddressesByAccount(account string) ([]util.Address, error) { - return c.GetAddressesByAccountAsync(account).Receive() -} - -// FutureMoveResult is a future promise to deliver the result of a MoveAsync, -// MoveMinConfAsync, or MoveCommentAsync RPC invocation (or an applicable -// error). -type FutureMoveResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of the move operation. -func (r FutureMoveResult) Receive() (bool, error) { - res, err := receiveFuture(r) - if err != nil { - return false, err - } - - // Unmarshal result as a boolean. - var moveResult bool - err = json.Unmarshal(res, &moveResult) - if err != nil { - return false, err - } - - return moveResult, nil -} - -// MoveAsync returns an instance of a type that can be used to get the result of -// the RPC at some future time by invoking the Receive function on the returned -// instance. -// -// See Move for the blocking version and more details. -func (c *Client) MoveAsync(fromAccount, toAccount string, amount util.Amount) FutureMoveResult { - cmd := btcjson.NewMoveCmd(fromAccount, toAccount, amount.ToBTC(), nil, - nil) - return c.sendCmd(cmd) -} - -// Move moves specified amount from one account in your wallet to another. Only -// funds with the default number of minimum confirmations will be used. -// -// See MoveMinConf and MoveComment for different options. -func (c *Client) Move(fromAccount, toAccount string, amount util.Amount) (bool, error) { - return c.MoveAsync(fromAccount, toAccount, amount).Receive() -} - -// MoveMinConfAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See MoveMinConf for the blocking version and more details. -func (c *Client) MoveMinConfAsync(fromAccount, toAccount string, - amount util.Amount, minConfirms int) FutureMoveResult { - - cmd := btcjson.NewMoveCmd(fromAccount, toAccount, amount.ToBTC(), - &minConfirms, nil) - return c.sendCmd(cmd) -} - -// MoveMinConf moves specified amount from one account in your wallet to -// another. Only funds with the passed number of minimum confirmations will be -// used. -// -// See Move to use the default number of minimum confirmations and MoveComment -// for additional options. -func (c *Client) MoveMinConf(fromAccount, toAccount string, amount util.Amount, minConf int) (bool, error) { - return c.MoveMinConfAsync(fromAccount, toAccount, amount, minConf).Receive() -} - -// MoveCommentAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See MoveComment for the blocking version and more details. -func (c *Client) MoveCommentAsync(fromAccount, toAccount string, - amount util.Amount, minConfirms int, comment string) FutureMoveResult { - - cmd := btcjson.NewMoveCmd(fromAccount, toAccount, amount.ToBTC(), - &minConfirms, &comment) - return c.sendCmd(cmd) -} - -// MoveComment moves specified amount from one account in your wallet to -// another and stores the provided comment in the wallet. The comment -// parameter is only available in the wallet. Only funds with the passed number -// of minimum confirmations will be used. -// -// See Move and MoveMinConf to use defaults. -func (c *Client) MoveComment(fromAccount, toAccount string, amount util.Amount, - minConf int, comment string) (bool, error) { - - return c.MoveCommentAsync(fromAccount, toAccount, amount, minConf, - comment).Receive() -} - -// FutureRenameAccountResult is a future promise to deliver the result of a -// RenameAccountAsync RPC invocation (or an applicable error). -type FutureRenameAccountResult chan *response - -// Receive waits for the response promised by the future and returns the -// result of creating new account. -func (r FutureRenameAccountResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// RenameAccountAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See RenameAccount for the blocking version and more details. -func (c *Client) RenameAccountAsync(oldAccount, newAccount string) FutureRenameAccountResult { - cmd := btcjson.NewRenameAccountCmd(oldAccount, newAccount) - return c.sendCmd(cmd) -} - -// RenameAccount creates a new wallet account. -func (c *Client) RenameAccount(oldAccount, newAccount string) error { - return c.RenameAccountAsync(oldAccount, newAccount).Receive() -} - -// FutureValidateAddressResult is a future promise to deliver the result of a -// ValidateAddressAsync RPC invocation (or an applicable error). -type FutureValidateAddressResult chan *response - -// Receive waits for the response promised by the future and returns information -// about the given bitcoin address. -func (r FutureValidateAddressResult) Receive() (*btcjson.ValidateAddressWalletResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a validateaddress result object. - var addrResult btcjson.ValidateAddressWalletResult - err = json.Unmarshal(res, &addrResult) - if err != nil { - return nil, err - } - - return &addrResult, nil -} - -// ValidateAddressAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See ValidateAddress for the blocking version and more details. -func (c *Client) ValidateAddressAsync(address util.Address) FutureValidateAddressResult { - addr := address.EncodeAddress() - cmd := btcjson.NewValidateAddressCmd(addr) - return c.sendCmd(cmd) -} - -// ValidateAddress returns information about the given bitcoin address. -func (c *Client) ValidateAddress(address util.Address) (*btcjson.ValidateAddressWalletResult, error) { - return c.ValidateAddressAsync(address).Receive() -} - -// FutureKeyPoolRefillResult is a future promise to deliver the result of a -// KeyPoolRefillAsync RPC invocation (or an applicable error). -type FutureKeyPoolRefillResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of refilling the key pool. -func (r FutureKeyPoolRefillResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// KeyPoolRefillAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See KeyPoolRefill for the blocking version and more details. -func (c *Client) KeyPoolRefillAsync() FutureKeyPoolRefillResult { - cmd := btcjson.NewKeyPoolRefillCmd(nil) - return c.sendCmd(cmd) -} - -// KeyPoolRefill fills the key pool as necessary to reach the default size. -// -// See KeyPoolRefillSize to override the size of the key pool. -func (c *Client) KeyPoolRefill() error { - return c.KeyPoolRefillAsync().Receive() -} - -// KeyPoolRefillSizeAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See KeyPoolRefillSize for the blocking version and more details. -func (c *Client) KeyPoolRefillSizeAsync(newSize uint) FutureKeyPoolRefillResult { - cmd := btcjson.NewKeyPoolRefillCmd(&newSize) - return c.sendCmd(cmd) -} - -// KeyPoolRefillSize fills the key pool as necessary to reach the specified -// size. -func (c *Client) KeyPoolRefillSize(newSize uint) error { - return c.KeyPoolRefillSizeAsync(newSize).Receive() -} - -// ************************ -// Amount/Balance Functions -// ************************ - -// FutureListAccountsResult is a future promise to deliver the result of a -// ListAccountsAsync or ListAccountsMinConfAsync RPC invocation (or an -// applicable error). -type FutureListAccountsResult chan *response - -// Receive waits for the response promised by the future and returns returns a -// map of account names and their associated balances. -func (r FutureListAccountsResult) Receive() (map[string]util.Amount, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a json object. - var accounts map[string]float64 - err = json.Unmarshal(res, &accounts) - if err != nil { - return nil, err - } - - accountsMap := make(map[string]util.Amount) - for k, v := range accounts { - amount, err := util.NewAmount(v) - if err != nil { - return nil, err - } - - accountsMap[k] = amount - } - - return accountsMap, nil -} - -// ListAccountsAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See ListAccounts for the blocking version and more details. -func (c *Client) ListAccountsAsync() FutureListAccountsResult { - cmd := btcjson.NewListAccountsCmd(nil) - return c.sendCmd(cmd) -} - -// ListAccounts returns a map of account names and their associated balances -// using the default number of minimum confirmations. -// -// See ListAccountsMinConf to override the minimum number of confirmations. -func (c *Client) ListAccounts() (map[string]util.Amount, error) { - return c.ListAccountsAsync().Receive() -} - -// ListAccountsMinConfAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListAccountsMinConf for the blocking version and more details. -func (c *Client) ListAccountsMinConfAsync(minConfirms int) FutureListAccountsResult { - cmd := btcjson.NewListAccountsCmd(&minConfirms) - return c.sendCmd(cmd) -} - -// ListAccountsMinConf returns a map of account names and their associated -// balances using the specified number of minimum confirmations. -// -// See ListAccounts to use the default minimum number of confirmations. -func (c *Client) ListAccountsMinConf(minConfirms int) (map[string]util.Amount, error) { - return c.ListAccountsMinConfAsync(minConfirms).Receive() -} - -// FutureGetBalanceResult is a future promise to deliver the result of a -// GetBalanceAsync or GetBalanceMinConfAsync RPC invocation (or an applicable -// error). -type FutureGetBalanceResult chan *response - -// Receive waits for the response promised by the future and returns the -// available balance from the server for the specified account. -func (r FutureGetBalanceResult) Receive() (util.Amount, error) { - res, err := receiveFuture(r) - if err != nil { - return 0, err - } - - // Unmarshal result as a floating point number. - var balance float64 - err = json.Unmarshal(res, &balance) - if err != nil { - return 0, err - } - - amount, err := util.NewAmount(balance) - if err != nil { - return 0, err - } - - return amount, nil -} - -// FutureGetBalanceParseResult is same as FutureGetBalanceResult except -// that the result is expected to be a string which is then parsed into -// a float64 value -// This is required for compatibility with servers like blockchain.info -type FutureGetBalanceParseResult chan *response - -// Receive waits for the response promised by the future and returns the -// available balance from the server for the specified account. -func (r FutureGetBalanceParseResult) Receive() (util.Amount, error) { - res, err := receiveFuture(r) - if err != nil { - return 0, err - } - - // Unmarshal result as a string - var balanceString string - err = json.Unmarshal(res, &balanceString) - if err != nil { - return 0, err - } - - balance, err := strconv.ParseFloat(balanceString, 64) - if err != nil { - return 0, err - } - amount, err := util.NewAmount(balance) - if err != nil { - return 0, err - } - - return amount, nil -} - -// GetBalanceAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See GetBalance for the blocking version and more details. -func (c *Client) GetBalanceAsync(account string) FutureGetBalanceResult { - cmd := btcjson.NewGetBalanceCmd(&account, nil) - return c.sendCmd(cmd) -} - -// GetBalance returns the available balance from the server for the specified -// account using the default number of minimum confirmations. The account may -// be "*" for all accounts. -// -// See GetBalanceMinConf to override the minimum number of confirmations. -func (c *Client) GetBalance(account string) (util.Amount, error) { - return c.GetBalanceAsync(account).Receive() -} - -// GetBalanceMinConfAsync returns an instance of a type that can be used to get -// the result of the RPC at some future time by invoking the Receive function on -// the returned instance. -// -// See GetBalanceMinConf for the blocking version and more details. -func (c *Client) GetBalanceMinConfAsync(account string, minConfirms int) FutureGetBalanceResult { - cmd := btcjson.NewGetBalanceCmd(&account, &minConfirms) - return c.sendCmd(cmd) -} - -// GetBalanceMinConf returns the available balance from the server for the -// specified account using the specified number of minimum confirmations. The -// account may be "*" for all accounts. -// -// See GetBalance to use the default minimum number of confirmations. -func (c *Client) GetBalanceMinConf(account string, minConfirms int) (util.Amount, error) { - if c.config.EnableBCInfoHacks { - response := c.GetBalanceMinConfAsync(account, minConfirms) - return FutureGetBalanceParseResult(response).Receive() - } - return c.GetBalanceMinConfAsync(account, minConfirms).Receive() -} - -// FutureGetReceivedByAccountResult is a future promise to deliver the result of -// a GetReceivedByAccountAsync or GetReceivedByAccountMinConfAsync RPC -// invocation (or an applicable error). -type FutureGetReceivedByAccountResult chan *response - -// Receive waits for the response promised by the future and returns the total -// amount received with the specified account. -func (r FutureGetReceivedByAccountResult) Receive() (util.Amount, error) { - res, err := receiveFuture(r) - if err != nil { - return 0, err - } - - // Unmarshal result as a floating point number. - var balance float64 - err = json.Unmarshal(res, &balance) - if err != nil { - return 0, err - } - - amount, err := util.NewAmount(balance) - if err != nil { - return 0, err - } - - return amount, nil -} - -// GetReceivedByAccountAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See GetReceivedByAccount for the blocking version and more details. -func (c *Client) GetReceivedByAccountAsync(account string) FutureGetReceivedByAccountResult { - cmd := btcjson.NewGetReceivedByAccountCmd(account, nil) - return c.sendCmd(cmd) -} - -// GetReceivedByAccount returns the total amount received with the specified -// account with at least the default number of minimum confirmations. -// -// See GetReceivedByAccountMinConf to override the minimum number of -// confirmations. -func (c *Client) GetReceivedByAccount(account string) (util.Amount, error) { - return c.GetReceivedByAccountAsync(account).Receive() -} - -// GetReceivedByAccountMinConfAsync returns an instance of a type that can be -// used to get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See GetReceivedByAccountMinConf for the blocking version and more details. -func (c *Client) GetReceivedByAccountMinConfAsync(account string, minConfirms int) FutureGetReceivedByAccountResult { - cmd := btcjson.NewGetReceivedByAccountCmd(account, &minConfirms) - return c.sendCmd(cmd) -} - -// GetReceivedByAccountMinConf returns the total amount received with the -// specified account with at least the specified number of minimum -// confirmations. -// -// See GetReceivedByAccount to use the default minimum number of confirmations. -func (c *Client) GetReceivedByAccountMinConf(account string, minConfirms int) (util.Amount, error) { - return c.GetReceivedByAccountMinConfAsync(account, minConfirms).Receive() -} - -// FutureGetUnconfirmedBalanceResult is a future promise to deliver the result -// of a GetUnconfirmedBalanceAsync RPC invocation (or an applicable error). -type FutureGetUnconfirmedBalanceResult chan *response - -// Receive waits for the response promised by the future and returns returns the -// unconfirmed balance from the server for the specified account. -func (r FutureGetUnconfirmedBalanceResult) Receive() (util.Amount, error) { - res, err := receiveFuture(r) - if err != nil { - return 0, err - } - - // Unmarshal result as a floating point number. - var balance float64 - err = json.Unmarshal(res, &balance) - if err != nil { - return 0, err - } - - amount, err := util.NewAmount(balance) - if err != nil { - return 0, err - } - - return amount, nil -} - -// GetUnconfirmedBalanceAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See GetUnconfirmedBalance for the blocking version and more details. -func (c *Client) GetUnconfirmedBalanceAsync(account string) FutureGetUnconfirmedBalanceResult { - cmd := btcjson.NewGetUnconfirmedBalanceCmd(&account) - return c.sendCmd(cmd) -} - -// GetUnconfirmedBalance returns the unconfirmed balance from the server for -// the specified account. -func (c *Client) GetUnconfirmedBalance(account string) (util.Amount, error) { - return c.GetUnconfirmedBalanceAsync(account).Receive() -} - -// FutureGetReceivedByAddressResult is a future promise to deliver the result of -// a GetReceivedByAddressAsync or GetReceivedByAddressMinConfAsync RPC -// invocation (or an applicable error). -type FutureGetReceivedByAddressResult chan *response - -// Receive waits for the response promised by the future and returns the total -// amount received by the specified address. -func (r FutureGetReceivedByAddressResult) Receive() (util.Amount, error) { - res, err := receiveFuture(r) - if err != nil { - return 0, err - } - - // Unmarshal result as a floating point number. - var balance float64 - err = json.Unmarshal(res, &balance) - if err != nil { - return 0, err - } - - amount, err := util.NewAmount(balance) - if err != nil { - return 0, err - } - - return amount, nil -} - -// GetReceivedByAddressAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See GetReceivedByAddress for the blocking version and more details. -func (c *Client) GetReceivedByAddressAsync(address util.Address) FutureGetReceivedByAddressResult { - addr := address.EncodeAddress() - cmd := btcjson.NewGetReceivedByAddressCmd(addr, nil) - return c.sendCmd(cmd) - -} - -// GetReceivedByAddress returns the total amount received by the specified -// address with at least the default number of minimum confirmations. -// -// See GetReceivedByAddressMinConf to override the minimum number of -// confirmations. -func (c *Client) GetReceivedByAddress(address util.Address) (util.Amount, error) { - return c.GetReceivedByAddressAsync(address).Receive() -} - -// GetReceivedByAddressMinConfAsync returns an instance of a type that can be -// used to get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See GetReceivedByAddressMinConf for the blocking version and more details. -func (c *Client) GetReceivedByAddressMinConfAsync(address util.Address, minConfirms int) FutureGetReceivedByAddressResult { - addr := address.EncodeAddress() - cmd := btcjson.NewGetReceivedByAddressCmd(addr, &minConfirms) - return c.sendCmd(cmd) -} - -// GetReceivedByAddressMinConf returns the total amount received by the specified -// address with at least the specified number of minimum confirmations. -// -// See GetReceivedByAddress to use the default minimum number of confirmations. -func (c *Client) GetReceivedByAddressMinConf(address util.Address, minConfirms int) (util.Amount, error) { - return c.GetReceivedByAddressMinConfAsync(address, minConfirms).Receive() -} - -// FutureListReceivedByAccountResult is a future promise to deliver the result -// of a ListReceivedByAccountAsync, ListReceivedByAccountMinConfAsync, or -// ListReceivedByAccountIncludeEmptyAsync RPC invocation (or an applicable -// error). -type FutureListReceivedByAccountResult chan *response - -// Receive waits for the response promised by the future and returns a list of -// balances by account. -func (r FutureListReceivedByAccountResult) Receive() ([]btcjson.ListReceivedByAccountResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal as an array of listreceivedbyaccount result objects. - var received []btcjson.ListReceivedByAccountResult - err = json.Unmarshal(res, &received) - if err != nil { - return nil, err - } - - return received, nil -} - -// ListReceivedByAccountAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListReceivedByAccount for the blocking version and more details. -func (c *Client) ListReceivedByAccountAsync() FutureListReceivedByAccountResult { - cmd := btcjson.NewListReceivedByAccountCmd(nil, nil, nil) - return c.sendCmd(cmd) -} - -// ListReceivedByAccount lists balances by account using the default number -// of minimum confirmations and including accounts that haven't received any -// payments. -// -// See ListReceivedByAccountMinConf to override the minimum number of -// confirmations and ListReceivedByAccountIncludeEmpty to filter accounts that -// haven't received any payments from the results. -func (c *Client) ListReceivedByAccount() ([]btcjson.ListReceivedByAccountResult, error) { - return c.ListReceivedByAccountAsync().Receive() -} - -// ListReceivedByAccountMinConfAsync returns an instance of a type that can be -// used to get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListReceivedByAccountMinConf for the blocking version and more details. -func (c *Client) ListReceivedByAccountMinConfAsync(minConfirms int) FutureListReceivedByAccountResult { - cmd := btcjson.NewListReceivedByAccountCmd(&minConfirms, nil, nil) - return c.sendCmd(cmd) -} - -// ListReceivedByAccountMinConf lists balances by account using the specified -// number of minimum confirmations not including accounts that haven't received -// any payments. -// -// See ListReceivedByAccount to use the default minimum number of confirmations -// and ListReceivedByAccountIncludeEmpty to also include accounts that haven't -// received any payments in the results. -func (c *Client) ListReceivedByAccountMinConf(minConfirms int) ([]btcjson.ListReceivedByAccountResult, error) { - return c.ListReceivedByAccountMinConfAsync(minConfirms).Receive() -} - -// ListReceivedByAccountIncludeEmptyAsync returns an instance of a type that can -// be used to get the result of the RPC at some future time by invoking the -// Receive function on the returned instance. -// -// See ListReceivedByAccountIncludeEmpty for the blocking version and more details. -func (c *Client) ListReceivedByAccountIncludeEmptyAsync(minConfirms int, includeEmpty bool) FutureListReceivedByAccountResult { - cmd := btcjson.NewListReceivedByAccountCmd(&minConfirms, &includeEmpty, - nil) - return c.sendCmd(cmd) -} - -// ListReceivedByAccountIncludeEmpty lists balances by account using the -// specified number of minimum confirmations and including accounts that -// haven't received any payments depending on specified flag. -// -// See ListReceivedByAccount and ListReceivedByAccountMinConf to use defaults. -func (c *Client) ListReceivedByAccountIncludeEmpty(minConfirms int, includeEmpty bool) ([]btcjson.ListReceivedByAccountResult, error) { - return c.ListReceivedByAccountIncludeEmptyAsync(minConfirms, - includeEmpty).Receive() -} - -// FutureListReceivedByAddressResult is a future promise to deliver the result -// of a ListReceivedByAddressAsync, ListReceivedByAddressMinConfAsync, or -// ListReceivedByAddressIncludeEmptyAsync RPC invocation (or an applicable -// error). -type FutureListReceivedByAddressResult chan *response - -// Receive waits for the response promised by the future and returns a list of -// balances by address. -func (r FutureListReceivedByAddressResult) Receive() ([]btcjson.ListReceivedByAddressResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal as an array of listreceivedbyaddress result objects. - var received []btcjson.ListReceivedByAddressResult - err = json.Unmarshal(res, &received) - if err != nil { - return nil, err - } - - return received, nil -} - -// ListReceivedByAddressAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListReceivedByAddress for the blocking version and more details. -func (c *Client) ListReceivedByAddressAsync() FutureListReceivedByAddressResult { - cmd := btcjson.NewListReceivedByAddressCmd(nil, nil, nil) - return c.sendCmd(cmd) -} - -// ListReceivedByAddress lists balances by address using the default number -// of minimum confirmations not including addresses that haven't received any -// payments or watching only addresses. -// -// See ListReceivedByAddressMinConf to override the minimum number of -// confirmations and ListReceivedByAddressIncludeEmpty to also include addresses -// that haven't received any payments in the results. -func (c *Client) ListReceivedByAddress() ([]btcjson.ListReceivedByAddressResult, error) { - return c.ListReceivedByAddressAsync().Receive() -} - -// ListReceivedByAddressMinConfAsync returns an instance of a type that can be -// used to get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See ListReceivedByAddressMinConf for the blocking version and more details. -func (c *Client) ListReceivedByAddressMinConfAsync(minConfirms int) FutureListReceivedByAddressResult { - cmd := btcjson.NewListReceivedByAddressCmd(&minConfirms, nil, nil) - return c.sendCmd(cmd) -} - -// ListReceivedByAddressMinConf lists balances by address using the specified -// number of minimum confirmations not including addresses that haven't received -// any payments. -// -// See ListReceivedByAddress to use the default minimum number of confirmations -// and ListReceivedByAddressIncludeEmpty to also include addresses that haven't -// received any payments in the results. -func (c *Client) ListReceivedByAddressMinConf(minConfirms int) ([]btcjson.ListReceivedByAddressResult, error) { - return c.ListReceivedByAddressMinConfAsync(minConfirms).Receive() -} - -// ListReceivedByAddressIncludeEmptyAsync returns an instance of a type that can -// be used to get the result of the RPC at some future time by invoking the -// Receive function on the returned instance. -// -// See ListReceivedByAccountIncludeEmpty for the blocking version and more details. -func (c *Client) ListReceivedByAddressIncludeEmptyAsync(minConfirms int, includeEmpty bool) FutureListReceivedByAddressResult { - cmd := btcjson.NewListReceivedByAddressCmd(&minConfirms, &includeEmpty, - nil) - return c.sendCmd(cmd) -} - -// ListReceivedByAddressIncludeEmpty lists balances by address using the -// specified number of minimum confirmations and including addresses that -// haven't received any payments depending on specified flag. -// -// See ListReceivedByAddress and ListReceivedByAddressMinConf to use defaults. -func (c *Client) ListReceivedByAddressIncludeEmpty(minConfirms int, includeEmpty bool) ([]btcjson.ListReceivedByAddressResult, error) { - return c.ListReceivedByAddressIncludeEmptyAsync(minConfirms, - includeEmpty).Receive() -} - -// ************************ -// Wallet Locking Functions -// ************************ - -// FutureWalletLockResult is a future promise to deliver the result of a -// WalletLockAsync RPC invocation (or an applicable error). -type FutureWalletLockResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of locking the wallet. -func (r FutureWalletLockResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// WalletLockAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See WalletLock for the blocking version and more details. -func (c *Client) WalletLockAsync() FutureWalletLockResult { - cmd := btcjson.NewWalletLockCmd() - return c.sendCmd(cmd) -} - -// WalletLock locks the wallet by removing the encryption key from memory. -// -// After calling this function, the WalletPassphrase function must be used to -// unlock the wallet prior to calling any other function which requires the -// wallet to be unlocked. -func (c *Client) WalletLock() error { - return c.WalletLockAsync().Receive() -} - -// WalletPassphrase unlocks the wallet by using the passphrase to derive the -// decryption key which is then stored in memory for the specified timeout -// (in seconds). -func (c *Client) WalletPassphrase(passphrase string, timeoutSecs int64) error { - cmd := btcjson.NewWalletPassphraseCmd(passphrase, timeoutSecs) - _, err := c.sendCmdAndWait(cmd) - return err -} - -// FutureWalletPassphraseChangeResult is a future promise to deliver the result -// of a WalletPassphraseChangeAsync RPC invocation (or an applicable error). -type FutureWalletPassphraseChangeResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of changing the wallet passphrase. -func (r FutureWalletPassphraseChangeResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// WalletPassphraseChangeAsync returns an instance of a type that can be used to -// get the result of the RPC at some future time by invoking the Receive -// function on the returned instance. -// -// See WalletPassphraseChange for the blocking version and more details. -func (c *Client) WalletPassphraseChangeAsync(old, new string) FutureWalletPassphraseChangeResult { - cmd := btcjson.NewWalletPassphraseChangeCmd(old, new) - return c.sendCmd(cmd) -} - -// WalletPassphraseChange changes the wallet passphrase from the specified old -// to new passphrase. -func (c *Client) WalletPassphraseChange(old, new string) error { - return c.WalletPassphraseChangeAsync(old, new).Receive() -} - -// ************************* -// Message Signing Functions -// ************************* - -// FutureSignMessageResult is a future promise to deliver the result of a -// SignMessageAsync RPC invocation (or an applicable error). -type FutureSignMessageResult chan *response - -// Receive waits for the response promised by the future and returns the message -// signed with the private key of the specified address. -func (r FutureSignMessageResult) Receive() (string, error) { - res, err := receiveFuture(r) - if err != nil { - return "", err - } - - // Unmarshal result as a string. - var b64 string - err = json.Unmarshal(res, &b64) - if err != nil { - return "", err - } - - return b64, nil -} - -// SignMessageAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See SignMessage for the blocking version and more details. -func (c *Client) SignMessageAsync(address util.Address, message string) FutureSignMessageResult { - addr := address.EncodeAddress() - cmd := btcjson.NewSignMessageCmd(addr, message) - return c.sendCmd(cmd) -} - -// SignMessage signs a message with the private key of the specified address. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) SignMessage(address util.Address, message string) (string, error) { - return c.SignMessageAsync(address, message).Receive() -} - -// FutureVerifyMessageResult is a future promise to deliver the result of a -// VerifyMessageAsync RPC invocation (or an applicable error). -type FutureVerifyMessageResult chan *response - -// Receive waits for the response promised by the future and returns whether or -// not the message was successfully verified. -func (r FutureVerifyMessageResult) Receive() (bool, error) { - res, err := receiveFuture(r) - if err != nil { - return false, err - } - - // Unmarshal result as a boolean. - var verified bool - err = json.Unmarshal(res, &verified) - if err != nil { - return false, err - } - - return verified, nil -} - -// VerifyMessageAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See VerifyMessage for the blocking version and more details. -func (c *Client) VerifyMessageAsync(address util.Address, signature, message string) FutureVerifyMessageResult { - addr := address.EncodeAddress() - cmd := btcjson.NewVerifyMessageCmd(addr, signature, message) - return c.sendCmd(cmd) -} - -// VerifyMessage verifies a signed message. -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) VerifyMessage(address util.Address, signature, message string) (bool, error) { - return c.VerifyMessageAsync(address, signature, message).Receive() -} - -// ********************* -// Dump/Import Functions -// ********************* - -// FutureDumpPrivKeyResult is a future promise to deliver the result of a -// DumpPrivKeyAsync RPC invocation (or an applicable error). -type FutureDumpPrivKeyResult chan *response - -// Receive waits for the response promised by the future and returns the private -// key corresponding to the passed address encoded in the wallet import format -// (WIF) -func (r FutureDumpPrivKeyResult) Receive() (*util.WIF, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a string. - var privKeyWIF string - err = json.Unmarshal(res, &privKeyWIF) - if err != nil { - return nil, err - } - - return util.DecodeWIF(privKeyWIF) -} - -// DumpPrivKeyAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See DumpPrivKey for the blocking version and more details. -func (c *Client) DumpPrivKeyAsync(address util.Address) FutureDumpPrivKeyResult { - addr := address.EncodeAddress() - cmd := btcjson.NewDumpPrivKeyCmd(addr) - return c.sendCmd(cmd) -} - -// DumpPrivKey gets the private key corresponding to the passed address encoded -// in the wallet import format (WIF). -// -// NOTE: This function requires to the wallet to be unlocked. See the -// WalletPassphrase function for more details. -func (c *Client) DumpPrivKey(address util.Address) (*util.WIF, error) { - return c.DumpPrivKeyAsync(address).Receive() -} - -// FutureImportAddressResult is a future promise to deliver the result of an -// ImportAddressAsync RPC invocation (or an applicable error). -type FutureImportAddressResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of importing the passed public address. -func (r FutureImportAddressResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// ImportAddressAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See ImportAddress for the blocking version and more details. -func (c *Client) ImportAddressAsync(address string) FutureImportAddressResult { - cmd := btcjson.NewImportAddressCmd(address, nil) - return c.sendCmd(cmd) -} - -// ImportAddress imports the passed public address. -func (c *Client) ImportAddress(address string) error { - return c.ImportAddressAsync(address).Receive() -} - -// ImportAddressRescanAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See ImportAddress for the blocking version and more details. -func (c *Client) ImportAddressRescanAsync(address string, rescan bool) FutureImportAddressResult { - cmd := btcjson.NewImportAddressCmd(address, &rescan) - return c.sendCmd(cmd) -} - -// ImportAddressRescan imports the passed public address. When rescan is true, -// the block history is scanned for transactions addressed to provided address. -func (c *Client) ImportAddressRescan(address string, rescan bool) error { - return c.ImportAddressRescanAsync(address, rescan).Receive() -} - -// FutureImportPrivKeyResult is a future promise to deliver the result of an -// ImportPrivKeyAsync RPC invocation (or an applicable error). -type FutureImportPrivKeyResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of importing the passed private key which must be the wallet import format -// (WIF). -func (r FutureImportPrivKeyResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// ImportPrivKeyAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See ImportPrivKey for the blocking version and more details. -func (c *Client) ImportPrivKeyAsync(privKeyWIF *util.WIF) FutureImportPrivKeyResult { - wif := "" - if privKeyWIF != nil { - wif = privKeyWIF.String() - } - - cmd := btcjson.NewImportPrivKeyCmd(wif, nil, nil) - return c.sendCmd(cmd) -} - -// ImportPrivKey imports the passed private key which must be the wallet import -// format (WIF). -func (c *Client) ImportPrivKey(privKeyWIF *util.WIF) error { - return c.ImportPrivKeyAsync(privKeyWIF).Receive() -} - -// ImportPrivKeyLabelAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See ImportPrivKey for the blocking version and more details. -func (c *Client) ImportPrivKeyLabelAsync(privKeyWIF *util.WIF, label string) FutureImportPrivKeyResult { - wif := "" - if privKeyWIF != nil { - wif = privKeyWIF.String() - } - - cmd := btcjson.NewImportPrivKeyCmd(wif, &label, nil) - return c.sendCmd(cmd) -} - -// ImportPrivKeyLabel imports the passed private key which must be the wallet import -// format (WIF). It sets the account label to the one provided. -func (c *Client) ImportPrivKeyLabel(privKeyWIF *util.WIF, label string) error { - return c.ImportPrivKeyLabelAsync(privKeyWIF, label).Receive() -} - -// ImportPrivKeyRescanAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See ImportPrivKey for the blocking version and more details. -func (c *Client) ImportPrivKeyRescanAsync(privKeyWIF *util.WIF, label string, rescan bool) FutureImportPrivKeyResult { - wif := "" - if privKeyWIF != nil { - wif = privKeyWIF.String() - } - - cmd := btcjson.NewImportPrivKeyCmd(wif, &label, &rescan) - return c.sendCmd(cmd) -} - -// ImportPrivKeyRescan imports the passed private key which must be the wallet import -// format (WIF). It sets the account label to the one provided. When rescan is true, -// the block history is scanned for transactions addressed to provided privKey. -func (c *Client) ImportPrivKeyRescan(privKeyWIF *util.WIF, label string, rescan bool) error { - return c.ImportPrivKeyRescanAsync(privKeyWIF, label, rescan).Receive() -} - -// FutureImportPubKeyResult is a future promise to deliver the result of an -// ImportPubKeyAsync RPC invocation (or an applicable error). -type FutureImportPubKeyResult chan *response - -// Receive waits for the response promised by the future and returns the result -// of importing the passed public key. -func (r FutureImportPubKeyResult) Receive() error { - _, err := receiveFuture(r) - return err -} - -// ImportPubKeyAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See ImportPubKey for the blocking version and more details. -func (c *Client) ImportPubKeyAsync(pubKey string) FutureImportPubKeyResult { - cmd := btcjson.NewImportPubKeyCmd(pubKey, nil) - return c.sendCmd(cmd) -} - -// ImportPubKey imports the passed public key. -func (c *Client) ImportPubKey(pubKey string) error { - return c.ImportPubKeyAsync(pubKey).Receive() -} - -// ImportPubKeyRescanAsync returns an instance of a type that can be used to get the -// result of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See ImportPubKey for the blocking version and more details. -func (c *Client) ImportPubKeyRescanAsync(pubKey string, rescan bool) FutureImportPubKeyResult { - cmd := btcjson.NewImportPubKeyCmd(pubKey, &rescan) - return c.sendCmd(cmd) -} - -// ImportPubKeyRescan imports the passed public key. When rescan is true, the -// block history is scanned for transactions addressed to provided pubkey. -func (c *Client) ImportPubKeyRescan(pubKey string, rescan bool) error { - return c.ImportPubKeyRescanAsync(pubKey, rescan).Receive() -} - -// *********************** -// Miscellaneous Functions -// *********************** - -// NOTE: While getinfo is implemented here (in wallet.go), a btcd chain server -// will respond to getinfo requests as well, excluding any wallet information. - -// FutureGetInfoResult is a future promise to deliver the result of a -// GetInfoAsync RPC invocation (or an applicable error). -type FutureGetInfoResult chan *response - -// Receive waits for the response promised by the future and returns the info -// provided by the server. -func (r FutureGetInfoResult) Receive() (*btcjson.InfoWalletResult, error) { - res, err := receiveFuture(r) - if err != nil { - return nil, err - } - - // Unmarshal result as a getinfo result object. - var infoRes btcjson.InfoWalletResult - err = json.Unmarshal(res, &infoRes) - if err != nil { - return nil, err - } - - return &infoRes, nil -} - -// GetInfoAsync returns an instance of a type that can be used to get the result -// of the RPC at some future time by invoking the Receive function on the -// returned instance. -// -// See GetInfo for the blocking version and more details. -func (c *Client) GetInfoAsync() FutureGetInfoResult { - cmd := btcjson.NewGetInfoCmd() - return c.sendCmd(cmd) -} - -// GetInfo returns miscellaneous info regarding the RPC server. The returned -// info object may be void of wallet information if the remote server does -// not include wallet functionality. -func (c *Client) GetInfo() (*btcjson.InfoWalletResult, error) { - return c.GetInfoAsync().Receive() -} - -// TODO(davec): Implement -// backupwallet (NYI in btcwallet) -// encryptwallet (Won't be supported by btcwallet since it's always encrypted) -// getwalletinfo (NYI in btcwallet or btcjson) -// listaddressgroupings (NYI in btcwallet) -// listreceivedbyaccount (NYI in btcwallet) - -// DUMP -// importwallet (NYI in btcwallet) -// dumpwallet (NYI in btcwallet) diff --git a/server/rpc/rpcserver.go b/server/rpc/rpcserver.go index f0c36e676..717c98437 100644 --- a/server/rpc/rpcserver.go +++ b/server/rpc/rpcserver.go @@ -121,13 +121,6 @@ var ( Code: btcjson.ErrRPCUnimplemented, Message: "Command unimplemented", } - - // ErrRPCNoWallet is an error returned to RPC clients when the provided - // command is recognized as a wallet command. - ErrRPCNoWallet = &btcjson.RPCError{ - Code: btcjson.ErrRPCNoWallet, - Message: "This implementation does not implement wallet commands", - } ) type commandHandler func(*Server, interface{}, <-chan struct{}) (interface{}, error) @@ -188,54 +181,6 @@ var rpcHandlersBeforeInit = map[string]commandHandler{ "flushDbCache": handleFlushDBCache, } -// list of commands that we recognize, but for which btcd has no support because -// it lacks support for wallet functionality. For these commands the user -// should ask a connected instance of btcwallet. -var rpcAskWallet = map[string]struct{}{ - "addMultisigAddress": {}, - "backupWallet": {}, - "createEncryptedWallet": {}, - "createMultisig": {}, - "dumpPrivKey": {}, - "dumpWallet": {}, - "encryptWallet": {}, - "getAccount": {}, - "getAccountAddress": {}, - "getAddressesByAccount": {}, - "getBalance": {}, - "getNewAddress": {}, - "getRawChangeAddress": {}, - "getReceivedByAccount": {}, - "getReceivedByAddress": {}, - "getTransaction": {}, - "getTxOutSetInfo": {}, - "getUnconfirmedBalance": {}, - "getWalletInfo": {}, - "importPrivKey": {}, - "importWallet": {}, - "keyPoolRefill": {}, - "listAccounts": {}, - "listAddressGroupings": {}, - "listLockUnspent": {}, - "listReceivedByAccount": {}, - "listReceivedByAddress": {}, - "listSinceBlock": {}, - "listTransactions": {}, - "listUnspent": {}, - "lockUnspent": {}, - "move": {}, - "sendFrom": {}, - "sendMany": {}, - "sendToAddress": {}, - "setAccount": {}, - "setTxFee": {}, - "signMessage": {}, - "signRawTransaction": {}, - "walletLock": {}, - "walletPassphrase": {}, - "walletPassphraseChange": {}, -} - // Commands that are currently unimplemented, but should ultimately be. var rpcUnimplemented = map[string]struct{}{ "estimatePriority": {}, @@ -363,13 +308,6 @@ func handleUnimplemented(s *Server, cmd interface{}, closeChan <-chan struct{}) return nil, ErrRPCUnimplemented } -// handleAskWallet is the handler for commands that are recognized as valid, but -// are unable to answer correctly since it involves wallet state. -// These commands will be implemented in btcwallet. -func handleAskWallet(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { - return nil, ErrRPCNoWallet -} - // handleAddManualNode handles addManualNode commands. func handleAddManualNode(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.AddManualNodeCmd) @@ -3802,11 +3740,6 @@ func (s *Server) standardCmdResult(cmd *parsedRPCCmd, closeChan <-chan struct{}) if ok { goto handled } - _, ok = rpcAskWallet[cmd.method] - if ok { - handler = handleAskWallet - goto handled - } _, ok = rpcUnimplemented[cmd.method] if ok { handler = handleUnimplemented diff --git a/server/rpc/rpcserverhelp.go b/server/rpc/rpcserverhelp.go index 7c208bae7..227f46e14 100644 --- a/server/rpc/rpcserverhelp.go +++ b/server/rpc/rpcserverhelp.go @@ -46,8 +46,7 @@ var helpDescsEnUS = map[string]string{ // CreateRawTransactionCmd help. "createRawTransaction--synopsis": "Returns a new transaction spending the provided inputs and sending to the provided addresses.\n" + - "The transaction inputs are not signed in the created transaction.\n" + - "The signrawtransaction RPC command provided by wallet must be used to sign the resulting transaction.", + "The transaction inputs are not signed in the created transaction, and as such must be signed separately.", "createRawTransaction-inputs": "The inputs to the transaction", "createRawTransaction-amounts": "JSON object with the destination addresses as keys and amounts as values", "createRawTransaction-amounts--key": "address", @@ -382,25 +381,6 @@ var helpDescsEnUS = map[string]string{ "infoDagResult-relayFee": "The minimum relay fee for non-free transactions in BTC/KB", "infoDagResult-errors": "Any current errors", - // InfoWalletResult help. - "infoWalletResult-version": "The version of the server", - "infoWalletResult-protocolVersion": "The latest supported protocol version", - "infoWalletResult-walletVersion": "The version of the wallet server", - "infoWalletResult-balance": "The total bitcoin balance of the wallet", - "infoWalletResult-blocks": "The number of blocks processed", - "infoWalletResult-timeOffset": "The time offset", - "infoWalletResult-connections": "The number of connected peers", - "infoWalletResult-proxy": "The proxy used by the server", - "infoWalletResult-difficulty": "The current target difficulty", - "infoWalletResult-testNet": "Whether or not server is using testnet", - "infoWalletResult-devNet": "Whether or not server is using devnet", - "infoWalletResult-keypoolOldest": "Seconds since 1 Jan 1970 GMT of the oldest pre-generated key in the key pool", - "infoWalletResult-keypoolSize": "The number of new keys that are pre-generated", - "infoWalletResult-unlockedUntil": "The timestamp in seconds since 1 Jan 1970 GMT that the wallet is unlocked for transfers, or 0 if the wallet is locked", - "infoWalletResult-payTxFee": "The transaction fee set in BTC/KB", - "infoWalletResult-relayFee": "The minimum relay fee for non-free transactions in BTC/KB", - "infoWalletResult-errors": "Any current errors", - // GetTopHeadersCmd help. "getTopHeaders--synopsis": "Returns the top block headers starting with the provided start hash (not inclusive)", "getTopHeaders-startHash": "Block hash to stop including block headers for; if not found, all headers to the latest known block are returned.",