319 Commits
Author SHA1 Message Date
Roy Lee 04763e36f0 doc: update README.md
CI / Format, compilation and lint check (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
2022-10-31 21:21:45 -07:00
Roy Lee ca56a420ee rpc: implement rescanblockchain 2022-10-31 19:53:16 -07:00
Roy Lee 67c9c48940 wallet: break recovery() to recovery() and rescanblockchain()
Now the recovery, which runs at startup, only scans for known
addresses that were generated and recorded by this wallet.

The coming rescanblockchain RPC implementation, which requires the
wallet to be unlocked, does account discovery.
2022-10-31 19:53:16 -07:00
Roy Lee c6842ef6fb go mod: update lbcd to v0.22.118 2022-10-31 19:53:16 -07:00
Roy Lee 1fa143fa0e wallet: update passphrase user experience.
For users don't want to set/manage a passphrase a default passphrase
"passphrase" will be used during wallet creation.

At startup, the wallet tries to unlock itself using the default
passphrase, or a user provided one (using -p).

Users that prefer a passphrase can override the default one at wallet
creation time using -p, or use the walletpassphrase rpc when
the wallet is running. This will prevent the wallet from auto-unlock,
and preserve the lock-by-default behavior.
2022-10-31 19:53:16 -07:00
Roy Lee 3aca0be46a consolidate: refactor prompt related code
CI / Format, compilation and lint check (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
2022-09-29 00:06:51 -07:00
Roy Lee dc7f1e88eb config: remove SigNet and SimNet related code 2022-09-28 23:42:21 -07:00
Roy Lee be7892a2ae config: unify lbcd and lbcwallet RPC credentails
1. remove lbcdusername and lbcdpassword
2. rename (username, password) to (rpcuser, rpcpass)

Most users are confused with the lbcduser and username at first,
and choose to use the same credentials between lbcd and lbcwallet.
2022-09-28 23:29:20 -07:00
Roy Lee 7a4cd602bb config: remove noinitload related configs 2022-09-28 23:04:56 -07:00
Roy Lee 10d58126b5 config: remove spv related configs 2022-09-28 23:04:32 -07:00
Roy Lee 08e57e9ee3 config: remove gRPC related configs 2022-09-28 23:04:22 -07:00
Roy Lee 1917978ae8 consolidate: remove obsoleted files 2022-09-28 22:27:03 -07:00
Roy Lee 79da868c74 wallet: remove public passphrase prompt
1. Remove passphrase support for public keys.
2. Rename privPassphrase to passphrase to avoid confusion.

Note:

There has been a bug in the prompt, which prevents users from
specifying a custom public passphrase. So, most wallet databases
have been using the default password for the public keys, anyway.
2022-09-28 22:12:38 -07:00
Roy Lee 9c20f19d23 go mod: update lbcd version to include rpc commend updates 2022-09-28 11:48:23 -07:00
Roy Lee e78e49d0f6 multi-account: update rpc help messages 2022-09-28 11:48:23 -07:00
Roy Lee 50950fb0d5 multi-account: update listaddresstransactions 2022-09-28 11:48:23 -07:00
Roy Lee 51e700e7d9 multi-account: update listsinceblock 2022-09-28 11:48:23 -07:00
Roy Lee 1edb90e0aa multi-account: update listalltransactions 2022-09-28 11:48:23 -07:00
Roy Lee 2e8dcc4312 multi-account: update listtransactions 2022-09-28 11:48:23 -07:00
Roy Lee 4acd03be8b multi-account: update listreceivedbyaddress 2022-09-28 11:48:23 -07:00
Roy Lee b34aa61e4d multi-account: update listreceivedbyaccount 2022-09-28 11:48:23 -07:00
Roy Lee 93b33edbcd multi-account: update sendtoaddress 2022-09-28 11:48:23 -07:00
Roy Lee e6a4b3d1fd multi-account: update gettransaction 2022-09-28 11:48:23 -07:00
Roy Lee c42e8a0705 multi-account: update validateaddress 2022-09-28 11:48:23 -07:00
Roy Lee 03256c049b multi-account: update getreceivedbyaccount 2022-09-28 11:48:23 -07:00
Roy Lee 678379ce45 multi-account: update listaccounts 2022-09-28 11:48:23 -07:00
Roy Lee 64554cfbc0 multi-account: update sendfrom 2022-09-28 11:48:23 -07:00
Roy Lee af2d35a604 multi-account: update sendmany 2022-09-28 11:48:23 -07:00
Roy Lee 43bbf0a089 multi-account: update getrawchangeaddress 2022-09-28 11:48:23 -07:00
Roy Lee c0b263ece7 multi-account: update renameaccount 2022-09-28 11:48:23 -07:00
Roy Lee 531c461383 multi-account: update createNewAccount 2022-09-28 11:48:23 -07:00
Roy Lee 03dd33f8c9 multi-account: update getunconfirmedbalance 2022-09-28 11:48:23 -07:00
Roy Lee 09ec547ed6 multi-account: update getaccount 2022-09-28 11:48:23 -07:00
Roy Lee 608e4dddb5 multi-account: update getbalance 2022-09-28 11:48:23 -07:00
Roy Lee 71f8ba68a0 multi-account: update getaccountaddress 2022-09-28 11:48:23 -07:00
Roy Lee 6a610a8cdf multi-account: update getaddressbyaccount 2022-09-28 11:48:23 -07:00
Roy Lee a02435bbf7 multi-account: update getnewaddress 2022-09-28 11:48:23 -07:00
Roy Lee 47e8dbda55 multi-account: set DefaultScope to KeyScopeBIP0044
By design, all scopes shared the same account name/number space.
2022-09-28 11:48:23 -07:00
Roy Lee 5a0c010688 multi-account: update sendPairs to take keyscope pointer 2022-09-28 11:48:23 -07:00
Roy Lee 00c29c3936 multi-account: add forEachKeyScope uitility iterator 2022-09-28 11:48:23 -07:00
Roy Lee 169abd446c multi-account: support BIP44 account discovery 2022-09-28 11:48:23 -07:00
Roy Lee 0410b7ce01 consolidate: merge internal/external branches 2022-09-28 11:48:23 -07:00
Roy Lee de408d4133 consolidate: remove watch-only address/account support 2022-09-20 00:29:47 -07:00
Roy Lee 2b0d245b1f consolidate: remove gRPC APIs 2022-09-19 16:04:51 -07:00
Roy Lee efb8e0b699 consolidate: remove legacystore related code 2022-09-19 15:56:14 -07:00
Roy Lee e0cb7b7a91 multi-scope: use BIP0049 instead of BIP0049Plus 2022-09-17 14:39:05 -07:00
Roy Lee f27ea6094e rpc: remove all address type alias in lookupKeyScope
Use the same address type name as bitcoind getnewaddress()
2022-09-17 14:15:12 -07:00
Roy Lee 78b8743ced waddrmgr: use Derive() instead of DeriveNonStandard() 2022-09-17 13:58:07 -07:00
Roy Lee 1f05a9858b wallet: unblock Lock() when the wallet is shutdown 2022-09-17 13:39:19 -07:00
Roy Lee 79bcb8365c wallet: handle corner cases for reorg
CI / Format, compilation and lint check (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
2022-09-13 11:40:06 -07:00
Roy Lee b7013bf5e1 wallet: revert blockhash properly during reorg 2022-09-13 11:40:06 -07:00
Roy Lee aecb972d75 test: update birthday related tests 2022-09-13 10:59:26 -07:00
Roy Lee f4ba8a01d1 Revert "wallet: rescan 2 days past the birthday block"
This reverts commit af82460075.

The 48-hour margin has been set in the waddrmgr.Create() right before
written to the databasw.
2022-09-13 10:59:26 -07:00
Roy Lee af82460075 wallet: rescan 2 days past the birthday block
CI / Format, compilation and lint check (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
2022-08-19 17:04:32 -07:00
Roy Lee 40f7d7cefe prompt: ask birthday for user provided seed 2022-08-19 17:04:32 -07:00
Roy Lee d9d257a9f6 prompt: minror refactoring 2022-08-19 17:04:32 -07:00
Roy Lee 92acdcbfca rpc: reverse the order of listtransactions to align with lbrycrd (2nd attempt)
CI / Format, compilation and lint check (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
The previous change doesn't handle the truncated list.
2022-08-08 17:54:42 -07:00
Roy Lee 893a820c65 hack: trating all imported privatekey as non-watchonly
CI / Format, compilation and lint check (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
This is to unblock partner integration.

More comprehensive solution will be available soon.
2022-08-08 01:53:47 -07:00
Roy Lee 46f4df5a64 rpc: reverse the order of listtransactions to align with lbrycrd
CI / Format, compilation and lint check (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
2022-08-08 01:26:28 -07:00
Roy Lee 610ec20ea8 ci: run "make fmt" 2022-08-08 01:26:02 -07:00
Roy Lee 0c2b21840d ci: update github Worflow, and Go 1.19 2022-08-08 01:26:02 -07:00
Roy Lee 3e45c66f34 Merge pull request #11 from lbryio/roylee17/fix-signrawtransaction
rpc: handle "input not found" case in signrawtransaction
2022-08-04 22:04:03 -07:00
Roy Lee fd92031e27 rpc: handle "input not found" case in signrawtransaction 2022-08-04 21:55:39 -07:00
Roy Lee eff01c9e63 Merge pull request #12 from lbryio/roylee17/update-ci-go-version
ci: update workflow and Go 1.19
2022-08-04 21:50:24 -07:00
Roy Lee 2428b381da ci: run "make fmt" 2022-08-04 21:41:06 -07:00
Roy Lee 2e95c1427f ci: update github Worflow, and Go 1.19 2022-08-04 21:40:57 -07:00
Roy Lee 13a42b37ce ci: add tools package to lock Go tooling versions 2022-08-04 21:40:37 -07:00
Roy Lee 18b605c6e1 mod: update go dependencies 2022-08-04 21:40:19 -07:00
Roy Lee c21be77e05 configs: updated docs/comments about disabling tls for remote connections 2022-08-04 17:24:24 -07:00
Roy Lee d1700f2658 rpc: allow listtransaction take "default" as account
golangci-lint / lint (push) Waiting to run
CI / lint (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
This is also another quirks that lbcwallet mixes account with label.
2022-07-27 10:32:52 -07:00
Roy Lee be9df55a7c rpc: remove deprecated rpc "move" and "setaccount" 2022-07-27 10:29:35 -07:00
Roy Lee 9d812ab865 [lbry] config: allow non-localhost connections with TLS disabled
golangci-lint / lint (push) Waiting to run
CI / lint (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
2022-07-11 16:22:35 -07:00
Roy Lee b4a9f5f524 [lbry] version: bump lbcd depencency to include version handling fix
golangci-lint / lint (push) Waiting to run
CI / lint (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
2022-07-06 20:47:07 -07:00
Roy Lee 56a178f545 test: fix race conditions in tests
golangci-lint / lint (push) Waiting to run
CI / lint (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
2022-07-05 22:09:03 -07:00
Roy Lee a7cbb7c481 [lbry] ci: disable few tests for now to unblock CI 2022-07-05 21:06:53 -07:00
Roy Lee c4421900c1 test: fix fmt string directive. 2022-07-05 21:06:53 -07:00
Roy Lee e5f7fefaac [lbry] rpc: update getaddressinfo help messages 2022-07-05 21:06:53 -07:00
Roy Lee 5d95b1cd9a Merge pull request #7 from lbryio/roylee/hardcode-paytxfee-to-zero
[lbry] fee: update getinfo.paytxfee to 0
2022-06-14 17:06:52 -07:00
Roy Lee 444fc83aad [lbry] fee: update getinfo.paytxfee to 0
golangci-lint / lint (push) Waiting to run
CI / lint (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
This is a hack fix to unblock lbrypool.net.

The paytxfee in lbcwallet is actually not being used anywhere, and is
hardcoded to DefaultRelayFee, which is 1000. Lbrycrd sets default to 0.

Also, since the paytxfee is not actually used/implemented, the
'settxfee' RPC is also
2022-06-14 17:03:16 -07:00
Roy Lee ce9b4eb809 [lbry] version: use version package
golangci-lint / lint (push) Waiting to run
CI / lint (push) Waiting to run
CI / run unit tests (unit-cover) (push) Waiting to run
CI / run unit tests (unit-race) (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
2022-05-24 11:00:43 -07:00
Roy Lee 10b9f52e03 [lbry] ci: update Makefile and remove goclean.sh 2022-05-24 11:00:43 -07:00
Roy Lee 471b2d1987 [lbry] ci: update Dockerfile 2022-05-24 11:00:43 -07:00
Roy Lee df1d2ee1a1 [lbry] ci: support GoReleaser 2022-05-24 11:00:43 -07:00
Roy Lee 3671cd0c05 [lbry] ci: add github workflows 2022-05-24 10:48:28 -07:00
Roy Lee 57e8d9cdd2 [lbry] ci: update golangci settings 2022-05-24 10:48:28 -07:00
Roy Lee 5c8800691c [lbry] go module: update dependencies 2022-05-24 10:48:28 -07:00
Roy Lee 49e78d88cb [lbry] rpc: support --skipverify on TLS connection to lbcd 2022-05-24 10:48:28 -07:00
Roy Lee 09ae692b44 [lbry] rpc: update help docs 2022-05-24 10:48:28 -07:00
Brannon King 1d0ef1da6d [lbry] added staked value to balance call 2022-05-24 10:48:28 -07:00
Brannon King 23f883be7e [lbry] eliminated btcd dependency 2022-05-24 10:48:28 -07:00
Brannon King d5328e1834 [lbry] coin selection and balance no longer include stakes 2022-05-24 10:48:28 -07:00
Brannon King 4c6e495f86 [lbry] use address type parameter in getnewaddress 2022-05-24 10:48:20 -07:00
Roy Lee 10d0a26792 [lbry] update backend list 2022-05-24 10:31:06 -07:00
Roy Lee d6434b148a [lbry] enable regtest for --createtemp (temporary wallet) 2022-05-24 10:31:06 -07:00
Roy LeeandBrannon King f52bea1e37 [lbry] rpc: getaddressinfo
Co-authored-by: Brannon King <countprimes@gmail.com>
2022-05-24 10:31:06 -07:00
Roy Lee 879bf10dde [lbry] chain: bring back removed chainParams for a testcase 2022-05-24 10:31:06 -07:00
Roy Lee cedfab95fa [lbry] update coin_type to LBC (140) 2022-05-24 10:31:06 -07:00
Roy Lee 5c96fa9cda [lbry] docs: Update README.md 2022-05-24 10:31:06 -07:00
Roy Lee 36554814e8 [lbry] align port settings between lbcd, lbcctl, and lbcwallet 2022-05-24 10:31:06 -07:00
Roy Lee 202374ebd8 [lbry] fork from btcsuite to lbryio
1. btcd -> lbcd
2. btcwallet -> lbcallet
3. btcutil -> lbcutil
2022-05-24 10:31:06 -07:00
Roy Lee 7b5b2ff774 [lbry] remove nested go mudules 2022-05-24 03:09:34 -07:00
Roy Lee 8701ecb329 [lbry] build: remove neutrino and bitcoind support 2022-05-24 03:09:34 -07:00
Roy Lee 0e82225623 [lbry] git: ignore dist/ and .vscode 2022-05-24 03:09:34 -07:00
ennmichael e74c3939aa Fixed a bug where unconfirmed txn notifications were missing a label 2022-05-24 03:09:34 -07:00
Yaacov Akiba Slama 759741dccc waddrmgr: add support for pay to witness script address
With this commit we refactor the existing script address into a
baseScriptAddress struct and then add a new witnessScriptAddress type
that manages a pay-to-witness-script address.
2022-05-24 03:09:34 -07:00
Oliver Gugger 9eb48cb6ab waddrmgr: add adtWitnessScript serialization 2022-05-24 03:09:34 -07:00
Oliver Gugger 6d7b545acb waddrmgr: rename ambiguous scriptCT to scriptClearText
Since CT can mean both Cipher Text as well as Clear Text, the variable
name scriptCT lead to confusion about its meaning. We rename it to make
it more clear how it's used.
2022-05-24 03:09:34 -07:00
Oliver Gugger cb3343ae15 mod: update btcutil dep to pull in TaprootAddress type 2022-05-24 03:09:34 -07:00
Oliver Gugger f2ec9f1ec8 wallet: export ScriptForOutput
We need to be able to call ScriptForOutput in external code, so we
export it.
2022-05-24 03:09:34 -07:00
Olaoluwa Osuntokun 6eede89a43 chain: fix peer selection for the pruned block dispatcher
In this commit, we fix the peer selection for the pruned block
dispatcher. Turns out that the bits are actually mutually exclusive: a
node can set the network bit _and_ the limited (pruned bit).

The prior logic would only seek out "pure" nodes, meaning older nodes
that wouldn't set the limited bit when they're a full-full node. We fix
this by ignoring the limited bit, and we'll only look at the network and
segwit bits.

A unit test has also been added to show the issue in the prior filter
function.
2022-05-24 03:09:34 -07:00
Oliver Gugger b4e83b1f8c waddrmgr: fix concurrent map access
Fixes lightningnetwork/lnd#5864.
The loadAccountInfo does load an account as its name suggests. But after
loading it, the account is also added to a map to cache it. That map
write should be seen as a writing operation and therefore the _write_
lock must be held, not just the read lock.
2022-05-24 03:09:33 -07:00
Oliver Gugger 45a94de617 wallet: return unsigned TX in watch-only SendOutputs
If SendOutputs is called on a watch-only wallet then a transaction is
created but without any signatures. Publishing that transaction will
always fail. But the attempt to publish will already update the internal
state of the wallet so we shouldn't try to publish this unsigned TX.
Instead we return a new error along with the unsigned transaction to
give the caller the chance to sign and publish it through other means.
2022-05-24 03:09:33 -07:00
Bjarne Magnussen 9f1eb98666 wallet: add minimum confirmation parameter to FundPsbt
Setting the minimum confirmation is used for the coin selection when no inputs are provided.
2022-05-24 03:09:33 -07:00
Olaoluwa Osuntokun b218504ca9 build: update to latest versions of txauthor, txrules, and txsize 2022-05-24 03:09:33 -07:00
eugene 0fe2b53b69 wallet/txauthor+txrules: update go mod to include btcd changes 2022-05-24 03:09:33 -07:00
Oliver Gugger 8e853a7fb5 wallet: add ImportAccountWithScope
When creating a fully watch-only wallet, we know exactly what accounts
we are importing and what scope should be used for them.
2022-05-24 03:09:33 -07:00
Oliver Gugger 47a13774bb wallet: don't hold unlock in watch-only mode
If we're running in watch-only mode, there is no unlock possible.
Therefore, we also don't need to prevent any unlocks from happening when
doing coin selection in that mode.
2022-05-24 03:09:33 -07:00
Olaoluwa Osuntokun cdf737027b build: pin mid Go version to 1.16, run new go mod tidy
By running `go mod tidy -go=1.16`, we also automatically convert the
"legacy" build tag syntax to use the new Go 1.17 compatible variant.
2022-05-24 03:09:33 -07:00
Oliver Gugger 70f11dbca2 Travis+GitHub: switch CI from Travis to GitHub actions 2022-05-24 03:09:33 -07:00
Oliver Gugger 4e131c23d0 waddrmgr: fix test compilation 2022-05-24 03:09:33 -07:00
Olaoluwa Osuntokun e0c5ce72cf waddrmgr: add new DeriveFromKeyPathCache method for faster key retrieval
In this commit, we add a new method `DeriveFromKeyPathCache` that gives
callers a way to more quickly obtain a private key they know they'll be
using frequently. This method lets a caller avoid the write database
transaction as well as the EC operations to derive the key itself (BIP
32).
2022-05-24 03:09:33 -07:00
Oliver Gugger 4a75796117 wallet+waddrmgr: refactor to use extended key instead of seed
To allow a wallet to be created directly from an extended master root
key (xprv), we move the derivation from seed to extended key to the
loader instead of the address manager itself.
2022-05-24 03:09:33 -07:00
Olaoluwa Osuntokun 6f4c9ce731 Merge pull request #758 from Crypt-iQ/btcd_isdust_08032021
mod+wallet: use btcd/mempool IsDust for calculating mempool dust
2021-08-10 16:44:39 -07:00
eugene 3cb2c46b02 mod+wallet: use btcd/mempool IsDust for calculating mempool dust
We can now get rid of our incorrect dust calculation which did not
give exact values for segwit outputs as it was based on spending a
P2PKH output instead.
2021-08-03 16:42:20 -04:00
Olaoluwa Osuntokun eebed51155 Merge pull request #757 from guggero/wallet-db-tx
wallet+walletdb: remove manual DB transactions, use custom `View/Update` implementation when provided
2021-08-02 17:40:36 -07:00
Oliver Gugger a27bab6eb9 walletdb: add View and Update to DB interface
We want to make sure that every database backend has their own
implementation of the View() and Update() methods to make sure any
custom retry/commit/rollback strategies are used even when invoked
through the package-provided View() and Update() functions.
2021-07-29 16:53:09 +02:00
Oliver Gugger f07fdfb6b9 wallet: refactor txToOutputs to use walletdb.Update
To make sure we don't create any manual DB transactions, we refactor the
txToOutputs method to use walletdb.Update and the new
walletdb.ErrDryRunRollBack error for making sure a rollback is issued.
2021-07-23 12:49:38 +02:00
Oliver Gugger 178152bcd0 wallet: refactor ImportAccountDryRun to use walletdb.Update
To make sure we don't create any manual DB transactions, we refactor the
ImportAccountDryRun method to use walletdb.Update and the new
walletdb.ErrDryRunRollBack error for making sure a rollback is issued.
2021-07-23 12:49:37 +02:00
Oliver Gugger 9c839caddf walletdb: add new ErrDryRunRollBack error
We need a way to signal that a DB transaction should be rolled back
because its changes were a dry-run only. We add a new specific error for
that case so the automatic rollback on error in the walletdb.View and
walletdb.Update comes to play. But we can still return the result of a
dry-run where we need to by inspecting for this specific error.
2021-07-23 12:49:37 +02:00
Oliver Gugger 33a0a065f9 wallet: use walletdb.Update in FundPsbt
To make sure we don't create any manual DB transactions, we refactor
FundPsbt to use walletdb.Update instead.
2021-07-23 12:49:37 +02:00
Oliver Gugger 60a04006d6 wtxmgr: remove unused functions 2021-07-23 12:49:36 +02:00
Olaoluwa Osuntokun 5e96a26171 Merge pull request #752 from guggero/go-mod-fix
mod: fix submodule versions
2021-07-13 16:08:50 -07:00
Olaoluwa Osuntokun 5649a66307 Merge pull request #751 from LN-Zap/fix-2398
Prevent duplicate notifications for (un)confirmed transactions
2021-07-13 16:05:48 -07:00
Bjarne Magnussen 419381b749 wallet: call InsertTxCheckIfExists to add a relevant tx
Let the method `addRelevantTx` use `InsertTxCheckIfExists` to insert a relevant 
transaction. If the transaction has already been recorded, the method call 
`addRelevantTx` will return early and not proceed with duplicating work of 
checking every output and duplicating the tx notification to the notification 
server.
2021-07-13 09:24:53 +02:00
Olaoluwa Osuntokun 8e18674563 Merge pull request #753 from joostjager/zero-output-psbt
wallet: allow zero output psbt funding
2021-07-12 17:00:24 -07:00
Olaoluwa Osuntokun aaf03fee73 Merge pull request #754 from joostjager/filter-leases
wtxmgr: filter out expired leases
2021-07-06 16:48:07 -07:00
Joost Jager 5b1e64abde wtxmgr: filter out expired leases
Expired leases are kept in the database until the next cleaning round.
This commit makes sure that expired leases look like they do not exist
to outside callers.
2021-07-05 08:57:33 +02:00
Joost Jager 9f1d73d6d3 wallet: allow zero output psbt funding
To support the cpfp fee bump use case where no external outputs are
required.
2021-06-28 12:06:36 +02:00
Oliver Gugger 6a822c2bf2 mod: fix submodule versions
The submodules wallet/txauthor and wallet/txsizes were updated without a
new tag being created. This works fine when compiling btcwallet from
source but fails when using "go get" as that ignores the replace
directives.
2021-05-31 09:18:27 +02:00
Bjarne Magnussen 0066eee3ea wtxmgr: add InsertTxCheckIfExsists to check if a tx already recorded
Adds new error `ErrDuplicateTx` and method `InserTxCheckIfExists` to check if a transaction to be inserted was already recorded.
2021-05-28 14:29:48 +02:00
Olaoluwa Osuntokun 6ab9b61557 Merge pull request #740 from bottlepay/random-coins
wallet: add random coin selection
2021-05-19 15:53:59 -07:00
Joost Jager 0efc499b8c build: extend unit-race timeout 2021-05-19 09:11:31 +02:00
Joost Jager 4d2665ee3a wallet: add random coin selection 2021-05-19 08:34:55 +02:00
Olaoluwa Osuntokun c31e149775 Merge pull request #749 from guggero/wasm
internal/prompt: allow compilation in js/wasm environment
2021-05-18 16:50:50 -07:00
Oliver Gugger 825ff779a1 make: increase test timeout to 20 minutes 2021-05-18 13:26:45 +02:00
Oliver Gugger b5fd915162 internal/prompt: allow compilation in js/wasm environment
The wallet loader has a dependency to the internal/prompt package for
prompting the user for certain inputs (e.g. wallet password or new
seed).
This makes it impossible for projects that use the wallet as a
dependency and always provide those inputs as parameters to compile for
JavaScript/WebAssembly targets because the prompt code uses some
terminal functionality that is not available in JS syscalls.
By providing a JS specific implementation that just returns an error we
can compile the dependent projects.
Adding acutal support for prompting the user in the browser is currently
not planned as that can easily be circumvented by providing all inputs
as parameters.
2021-05-14 12:41:35 +02:00
Olaoluwa Osuntokun 36f4c930d7 Merge pull request #748 from lightninglabs-deploy/go-mod-update-2021-5
build: update pinned modules to latest versions
2021-05-13 17:12:18 -07:00
Olaoluwa Osuntokun 47e0edadcd build: update pinned modules to latest versions 2021-05-13 16:36:34 -07:00
Olaoluwa Osuntokun 3a2f12e3a9 Merge pull request #745 from bhandras/walletdb_foreach
walletdb: add ForEachBucket to the ReadTx with bbolt implementation
2021-05-12 21:38:50 -07:00
Olaoluwa Osuntokun 82fa030bda Merge pull request #746 from wpaulino/import-dry-run
wallet: add dry run implementation of ImportAccount
2021-05-06 18:27:17 -07:00
Wilmer Paulino 5053325946 wallet: add dry run implementation of ImportAccount
This method returns the first N external and internal addresses, which
can be presented to users to confirm whether the account has been
imported correctly.
2021-05-06 16:32:58 -07:00
Olaoluwa Osuntokun a7a9234968 Merge pull request #734 from bhandras/external_db
wallet: allow using external wallet db
2021-04-29 15:48:04 -07:00
Andras Banki-Horvath 13966db554 waddrmgr: test flake fix 2021-04-29 11:31:04 +02:00
Andras Banki-Horvath 98ba16748e loader: add txn callback when wallet is created 2021-04-28 17:44:11 +02:00
Andras Banki-Horvath a795db6b12 wallet: support for external wallet DB 2021-04-28 17:44:10 +02:00
Olaoluwa Osuntokun 0b7de5efbb Merge pull request #735 from guggero/signet
Update btcd dependency, add Signet params
2021-04-27 17:04:10 -07:00
Olaoluwa Osuntokun cf6b7830cb Merge pull request #744 from wpaulino/pruned-node-getnodeaddresses
chain: implement GetNodeAddresses fallback for PrunedBlockDispatcher
2021-04-27 16:43:14 -07:00
Andras Banki-Horvath c6f007b74a walletdb: add ForEachBucket to the ReadTx with bbolt implementation
This commit extends the ReadTx (and ReadWriteTx) interface with
ForEachBucket which can be used to iterate through all top level
buckets. This is a missing piece from the walletdb abstraction which
will allow us to iterate all keys in a walletdb opening the possibility
to build generic tools to browse and edit walletdb files regardless of
the underlying driver.
2021-04-27 11:14:43 +02:00
Oliver Gugger 1f1ffb56b5 multi: add signet params
With this commit we add the signet test network parameters to all switch
cases where we distinguish between the different networks.
2021-04-27 09:59:14 +02:00
Oliver Gugger c7c36be14b build: update btcd dependency 2021-04-27 09:15:55 +02:00
Wilmer Paulino 526d132f09 chain: implement GetNodeAddresses fallback for PrunedBlockDispatcher
It's possible for bitcoind instances to only have connections to pruned
nodes after its initial block download, which are incompatible with the
PrunedBlockDispatcher. This would result in GetBlock requests for pruned
blocks to never resolve. Since bitcoind also exposes a GetNodeAddresses
RPC, which returns random reachable addresses from its address manager,
we can leverage it to obtain a new candidate set of peers that we
otherwise wouldn't obtain through GetPeers.
2021-04-23 13:28:56 -07:00
Wilmer Paulino f7241cd95f chain: prevent logging of ping/pong msgs in PrunedBlockDispatcher
These messages are also part of normal operation, so we should log
stating they are unexpected.
2021-04-23 13:28:55 -07:00
Wilmer Paulino 61d3b2da6d chain: use correct pruned node service bit 2021-04-23 13:28:55 -07:00
Olaoluwa Osuntokun 50978fcf79 Merge pull request #743 from wpaulino/simnet-account-import
waddrmgr+wallet: allow account import for simnet wallets
2021-04-20 19:19:04 -07:00
Wilmer Paulino 0388171622 build: bump goacc commit
Addresses an issue with the previous version where one of its
dependencies was removed:

go: github.com/ory/x@v0.0.216 requires
        github.com/ory/cli@v0.0.49 requires
        github.com/ory/kratos@v0.5.5-alpha.1.0.20210319103511-3726ed4d145a requires
        github.com/ory/kratos/corp@v0.0.0-00010101000000-000000000000: invalid version: unknown revision 000000000000
2021-04-20 14:54:57 -07:00
Wilmer Paulino e1dfc4d1b7 waddrmgr+wallet: allow account import for simnet wallets
Simnet was previously left out as it didn't have defined HD versions for
some of our key scopes. To allow testing importing accounts into simnet
wallets, we fall back to use the mainnet HD versions.

This commit also addresses an issue with simnet wallets that would arise
whenever ScopedKeyManager.AccountProperties was invoked:

`failed to retrieve account public key: unsupported net SimNet`
2021-04-14 17:21:07 -07:00
Olaoluwa Osuntokun fe61cc5d78 Merge pull request #742 from wpaulino/bitcoind-conn-atomic-alignment
chain: fix alignment of atomic integers in bitcoind conn struct
2021-04-13 15:30:01 -07:00
Olaoluwa Osuntokun 2ff451f6bc chain: fix alignment of atomic integers in bitcoind conn struct
As reported by https://github.com/lightningnetwork/lnd/issues/5196, the
new atomic integer isn't properly aligned which can caus panics on
32-bit operating systems.. Tof fix this issue, we move the 64-bit
integer to lay after the two 32-bit integers at the top of the struct.
2021-04-11 16:32:45 -07:00
Olaoluwa Osuntokun 683061f797 Merge pull request #737 from wpaulino/block-from-network
chain: request pruned blocks from backend peers
2021-04-05 13:14:49 -07:00
Wilmer Paulino 20c02df1e3 chain: request pruned blocks from backend peers
At the moment, this is only done for the BitcoindClient, as the other
backends don't support block pruning.
2021-04-02 17:28:07 -07:00
Wilmer Paulino 3fed46822c chain: refactor BitcoindConn init params into config struct 2021-04-02 17:28:06 -07:00
Wilmer Paulino 178d124b76 chain: add PrunedBlockDispatcher implementation
To minimally support wallets connected to pruned nodes, we add a new
subsystem that can be integrated with chain clients to request blocks
that the server has already pruned. This is done by connecting to the
server's full node peers and querying them directly. Ideally, this is a
capability supported by the server, though this is not yet possible with
bitcoind.
2021-04-02 17:28:05 -07:00
Wilmer Paulino e3523abe7b build: update btcd dependency
This exposes the new AllowSelfConns config option allowing external
testing of peer.Peer.
2021-04-02 17:28:03 -07:00
Olaoluwa Osuntokun e0607006dc Merge pull request #733 from wpaulino/watch-only-account-utils
waddrmgr+wallet: support transaction creation and signing for watch-only accounts
2021-03-29 16:32:42 -07:00
Wilmer Paulino 02fedd6780 build: remove goveralls 2021-03-29 16:01:27 -07:00
Wilmer PaulinoandOliver Gugger b9b4d4efe1 wallet: include redeem script for NP2WKH inputs in PSBT generation
This allows external signers to properly sign NP2WKH inputs.

Co-authored-by: Oliver Gugger <gugger@gmail.com>
2021-03-29 16:00:53 -07:00
Wilmer Paulino b318e99f4f wallet: extend ChangeSource to support all key scopes 2021-03-29 16:00:53 -07:00
Wilmer Paulino ddbe5ecee4 wallet: expose AccountPropertiesByName 2021-03-29 16:00:52 -07:00
Wilmer Paulino bbd7f8f887 waddrmgr+wallet: expose LookupAccount
This exposes a mapping of account name to its corresponding key scope
and internal account number to facilitate the use of external APIs by
users.
2021-03-29 16:00:51 -07:00
Wilmer Paulino a180b0fcaa wallet: allow filtering of transactions by account 2021-03-29 16:00:50 -07:00
Wilmer Paulino f5845dfb42 wallet: prevent input signing for transactions on watch-only accounts
Watch-only accounts don't have any type of private key information
stored, so we avoid populating input signatures in those cases.
2021-03-29 16:00:49 -07:00
Wilmer Paulino 2301069644 wallet: require key scope of account for transaction creation methods
Now that we're able to fund transactions from multiple accounts within
different key scopes, we extend our transaction creation methods to
accept a key scope parameter as well, to determine the correct account
to select inputs from.
2021-03-29 16:00:48 -07:00
Wilmer Paulino 7fa80abc44 waddrmgr: include master key fingerprint in derivation path
Following the previous commit, some external hardware signers require a
master key fingerprint to be present within the PSBT input derivation
paths so that the signer can recognize which inputs are relevant and
must be signed.
2021-03-29 16:00:47 -07:00
Wilmer Paulino 35b4b237c9 wallet: include BIP 32 derivation paths for inputs in PSBTs
Watch-only accounts are usually backed by an external hardware signer,
some of which require derivation paths to be populated for each relevant
input to sign.
2021-03-29 16:00:46 -07:00
Olaoluwa Osuntokun 07d4cc155e Merge pull request #738 from guggero/build-improvement
Add Makefile, use golangci-lint
2021-03-29 15:55:46 -07:00
Oliver Gugger 371f7a583d appveyor: remove appveyor configuration
This configuration to run the checks on appveyor looks very old and
unused since it still refers to glide for dependency management. We
remove the file as it no longer serves a purpose.
2021-03-24 14:44:33 +01:00
Oliver Gugger 8d9d0b9001 Travis: use make commands instead of goclean.sh
Now that we have a Makefile with all tasks previously executed in
goclean.sh, we no longer need to use that file.
2021-03-24 14:44:33 +01:00
Oliver Gugger 3a5d9f84b0 multi: fix linter issues 2021-03-24 14:44:32 +01:00
Oliver Gugger ac3ec4fa03 lint: add new linter configuration
We use the golangci-lint in lnd and it has quite a few more detections
enabled than what's in the current gotest.sh script.
We don't start with a given base commit on purpose but instead fix
everything the linter finds in the following commits.
2021-03-24 14:44:32 +01:00
Oliver Gugger 40414fde37 rpc: run make fmt to format all code 2021-03-24 13:45:11 +01:00
Oliver Gugger 41e12c16c5 make: add Makefile
As a preparation to get rid of the clunky to handle goclean.sh, we add a
Makefile that behaves in mostly the same way as does lnd's Makefile.
2021-03-24 13:44:16 +01:00
Olaoluwa Osuntokun 5c08d49e19 Merge pull request #732 from wpaulino/import-account-or-pubkey
wallet: support derived public key import
2021-03-23 18:39:13 -07:00
Wilmer Paulino f1b329f680 waddrmgr: add TODO to determine proper address type of imported key
For key scopes which have an address schema where the external and
internal branches differ, we always assume that imported keys use the
external address type defined in the scope's address schema. This may
not always be the case however, and should be handled correctly.
Ideally, we generate two addresses per imported key (only if the
external and internal address types differ) and scan for both in the
chain.
2021-03-15 19:27:13 -07:00
Wilmer PaulinoandOliver Gugger b0a4956231 wallet: add derived public key import
Co-authored-by: Oliver Gugger <gugger@gmail.com>
2021-03-15 19:27:12 -07:00
Wilmer Paulino 9d909110f9 waddrmgr: use proper version for account key of non-watch-only accounts 2021-03-15 19:27:11 -07:00
Wilmer Paulino adb3d77c86 waddrmgr: extend AccountProperties with watch-only account properties 2021-03-15 19:27:10 -07:00
Wilmer Paulino 283f914b95 waddrmgr: return err when priv key is requested for watch-only addr 2021-03-15 19:27:09 -07:00
Wilmer Paulino 0b5eca1835 wallet: move ImportPrivateKey to import.go 2021-03-15 19:27:08 -07:00
Wilmer Paulino e2d54f001b waddrmgr: derive account addresses with schema override
This change was motivated by the need to support importing BIP-0049 keys
that use the standard address derivation scheme, where nested witness
pubkeys are used for both the external and internal branches. Our
BIP-0049 key scope is slightly different, in that addresses derived from
the internal branch use the witness pubkey address type. By having the
option of overriding the address schema for a particular account, we can
support importing standard BIP-0049 keys.
2021-03-15 19:27:07 -07:00
Wilmer Paulino 89e1671f0c waddrmgr: extend watch-only account init with new parameters
The master fingerprint corresponds to the fingerprint of the root master
public key (otherwise known as m/). This is required by some hardware
wallets for proper identification and signing.

The address schema is an optional field that allows an account to
override its corresponding address schema with a custom one.
2021-03-15 19:27:06 -07:00
Wilmer Paulino 198b0b8dae waddrmgr: store watch-only accounts under new account type
Watch-only accounts are usually backed by an external signer as they do
not contain any private key information. Some external signers require a
root key fingerprint for identification and signing purposes. In order
to guarantee compatibility with external signers, we need to persist the
root key fingerprint within the database.

Before this change, watch-only accounts used the default account
database structure. In this commit, we introduce a new account type to
store different information for watch-only accounts only. This isn't a
breaking change as watch-only accounts have yet to be supported by the
primary user of the wallet (lnd). With this new account type, we can
avoid the empty private key fields, which are irrelevant to watch-only
accounts, and we can store the root key fingerprint.
2021-03-15 19:27:05 -07:00
Wilmer Paulino 0492cb4507 waddrmgr: use correct DerivationPath for watch-only accounts
Previously, addresses that belong to a watch-only account would have a
derivation path using the internal account number used to identify
accounts within the databse, rather than the actual account number based
on the account's master public key child index. This wasn't an issue
before as only one account would exist within the wallet, the 0 account,
which is also the default. To ensure users of the DerivationPath struct
can arrive at addresses correctly, we introduce a new field
InternalAccount to denote the internal account number and repurpose the
existing Account field to its actual meaning.
2021-03-15 19:27:04 -07:00
Wilmer Paulino dead1a89d9 waddrmgr: add ImportPublicKey 2021-03-15 19:27:03 -07:00
Wilmer Paulino ee9a1fb0ce waddrmgr: refactor code from ImportPrivateKey into methods 2021-03-15 19:27:03 -07:00
Wilmer Paulino 02c4a1a54f build: update btcutil dependency 2021-03-15 19:27:02 -07:00
Wilmer Paulino 967f663f84 travis: bump go version to 1.15.x 2021-03-15 19:27:01 -07:00
Wilmer Paulino 742d879352 multi: fix linter 2021-03-15 19:27:00 -07:00
Wilmer Paulino 6ff982ccdc wtxmgr: prevent race condition by using local vars 2021-03-15 19:08:06 -07:00
Olaoluwa Osuntokun 4ec908df93 Merge pull request #736 from bottlepay/wtxmgr-leases
wallet: list leases and parameterize duration
2021-03-12 15:29:44 -08:00
Joost Jager 8932811695 wallet: parameterize lock duration
Allow arbitrary lock durations instead of a hard-coded ten minute
period.
2021-03-12 12:51:15 +01:00
Joost Jager ff2577a0e7 wtxmgr: add ListLeases 2021-03-12 12:51:15 +01:00
Olaoluwa Osuntokun 39cbb7bdd9 Merge pull request #731 from wpaulino/wtxmgr-migration-delete-bucket-fix
wtxmgr: ignore ErrBucketNotFound error upon locked outputs bucket deletion
2021-02-17 15:06:27 -08:00
Wilmer Paulino 690a12fa8b wtxmgr: ignore ErrBucketNotFound error upon locked outputs bucket deletion
This error would be seen when an old wallet that has yet to update is
performing the latest wtxmgr migration. It's possible for the locked
outputs bucket to not exist if outputs haven't been locked before, so we
should its deletion correctly.
2021-02-15 14:40:34 -08:00
Olaoluwa Osuntokun 415f37ff11 Merge pull request #726 from wpaulino/wallet-db-go-mod-updates
wtxmgr+btcwallet: update to latest walletdb version
2020-12-07 15:33:35 -08:00
Olaoluwa Osuntokun 12a2c88b26 btcwallet: update to walletdb v1.3.4 2020-12-01 19:13:04 -08:00
Olaoluwa Osuntokun 526c9a6103 wtxmgr: update to walletdb v1.3.4 2020-12-01 19:12:58 -08:00
Olaoluwa Osuntokun 664f77ded1 Merge pull request #714 from yyforyongyu/add-bdb-timeout
bdb: Add timeout options for bbolt
2020-11-18 18:28:10 -08:00
Olaoluwa Osuntokun 5ee84d89ca Merge pull request #724 from guggero/namespace-fix
wallet: fix incorrect namespace name
2020-11-18 11:51:56 -08:00
Oliver Gugger be57c71c9c wallet: fix incorrect namespace name
This commit fixes a panic introduced with #718 that was caused by
looking up addresses in the wrong namespace.
2020-11-18 19:42:12 +01:00
yyforyongyu e34b43b938 multi: unify WalletDBName and DefaultDBTimeout in loader 2020-11-07 22:01:51 +08:00
yyforyongyu 1cacaac9ea btcwallet: use db timeout param 2020-11-07 22:01:51 +08:00
yyforyongyu 86bc349c6e wallet: use db timeout in loader 2020-11-07 22:01:35 +08:00
yyforyongyu 368301866e wtxmgr: update tests to use db timeout param 2020-11-06 23:58:09 +08:00
yyforyongyu f6ea9d4d7b waddrmgr: update tests to use db timeout param 2020-11-06 23:58:09 +08:00
yyforyongyu 08308c81ed walletdb: update tests to use db timeout param 2020-11-06 23:57:05 +08:00
yyforyongyu 28c804ccc8 bdb: add timeout option in bbolt 2020-11-06 23:48:34 +08:00
Olaoluwa Osuntokun 9bd6d26f83 Merge pull request #718 from wpaulino/relevant-addr-spend
wallet: only request spend notification for our outputs
2020-11-05 16:52:34 -08:00
Olaoluwa Osuntokun a6f3888450 Merge pull request #723 from guggero/drop-history
Export dropwtxmgr functionality as utility function
2020-11-03 18:21:05 -08:00
Oliver Gugger fa26b1f022 cmd/dropwtxmgr: use DropTransactionHistory from wallet package
Now that the function to remove the wallet's transaction history is
exported as a utility function, we can use that in the dropwtxmgr
command.
2020-10-24 16:39:41 +02:00
Oliver Gugger 38fbfe36c5 wallet: add DropTransactionHistory function
We create a more generic copy of the dropwtxmgr command's functionality
and export it as the DropTransactionHistory function.
It removes all transaction history from the given wallet to force a
full chain rescan. Optionally the user-defined transaction labels can be
preserved.
2020-10-24 16:39:41 +02:00
Olaoluwa Osuntokun a7f551a630 Merge pull request #722 from guggero/psbt-script-sig-fix
psbt: don't add scriptSig to txIn
2020-10-05 11:48:31 -07:00
Oliver Gugger 3252f9fc11 psbt: don't add scriptSig to txIn
Because of an incorrect test, it wasn't discovered that the scriptSig
field was being set on the unsigned TX inputs for a nested SegWit input.
This commit fixes the bug and also refactors the test so it would have
caught this specific bug.
2020-10-05 11:33:51 +02:00
Olaoluwa Osuntokun e6d01202cb Merge pull request #721 from guggero/psbt-change-fix
wallet: use constant input source for change calculation
2020-10-01 17:39:44 -07:00
Oliver Gugger 98e779a102 wallet: use constant input source for change calculation
To fix a bug where specifying multiple UTXOs that are by themselves
large enough to satisfy the output amount would lead to the rest of them
being added to fees, we need to provide the transaction author with a
constant list of UTXOs. If we didn't, the author would only consider one
input and calculate the change based on that alone. But since we'd add
all inputs to the PSBT, the rest of the amounts would go to fees.
2020-10-01 15:19:13 +02:00
Oliver Gugger 34bfc5efb9 wallet: return change index from FundPsbt
To make it easy to show the user what change output was created (if any)
during the funding process, we return its index (or -1 if no change
output was created).
2020-10-01 14:57:05 +02:00
Olaoluwa Osuntokun 9d8d984207 Merge pull request #713 from yyforyongyu/fix-walletdb-param
btcwallet: add missing noFreelistSync in spv mode and temp wallet
2020-09-15 17:13:06 -07:00
Olaoluwa Osuntokun 2c5947a452 Merge pull request #711 from guggero/psbt-signing
wallet: add new PSBT funding and finalizing methods
2020-09-03 19:27:54 -07:00
Oliver Gugger c4c2a9052e wallet: add PSBT funding+finalizing methods 2020-08-27 21:15:00 +02:00
Oliver Gugger 78d8c81e0a wallet: add ComputeInputScript 2020-08-27 21:14:59 +02:00
Oliver Gugger 1f2ed87055 wallet: add FetchInputInfo 2020-08-27 21:14:57 +02:00
Oliver Gugger 4aa36af74c wallet: extract addrMgrWithChangeSource 2020-08-27 21:14:56 +02:00
Oliver Gugger 314cd98152 wallet: extract addUtxo in create TX test 2020-08-27 21:14:55 +02:00
Oliver Gugger 66edcae704 mod: update psbt library version 2020-08-27 21:14:53 +02:00
Wilmer Paulino 682bd8d33e wallet: only request spend notification for our outputs
We would previously request spend notifications for all transaction
outputs, leading to irrelevant transactions being found in the wallet's
transaction store.
2020-08-25 11:35:49 -07:00
Olaoluwa Osuntokun 1d31f4ea6f Merge pull request #717 from cfromknecht/fix-dust-calc
wallet/txauthor: fix bug in dust calculation
2020-08-13 17:14:39 -07:00
Olaoluwa Osuntokun cde4b5dca4 wallet/txauthor: rename relayFeePerKb to feeRatePerKb
The new name more accurately reflects the usage of the value. This is
the target fee rate that the constructed transaction should aim to meet.
2020-08-13 16:57:32 -07:00
Olaoluwa Osuntokun fbb3bc184d wallet/txauthor: fix bug in dust calculation
In this commit, we fix a 3 year old bug in dust calculation. Before this
commit, the target fee of the transaction to be crafted would be used to
determine dust. If the target fee is very high, then this would cause
over all higher fees, as we'd base that dust computation off of that fee
rate, rather than the min relay fee.

To fix this, we always use the min relay fee at all times when computing
dust.
2020-08-13 16:43:00 -07:00
Olaoluwa Osuntokun eb8bb02086 Merge pull request #715 from guggero/locked-outpoints-mutex
wallet: add mutex for locked outpoints
2020-08-13 12:08:07 -07:00
Oliver Gugger f8cc233758 wallet: add mutex for locked outpoints 2020-08-13 20:33:31 +02:00
yyforyongyu 8e2b9db6f2 btcwallet: add missing noFreelistSync option in wallet.Create 2020-08-12 03:13:18 +08:00
Olaoluwa Osuntokun ca24ed58cf Merge pull request #710 from cfromknecht/update-root-module-walletdb
build: update to latest walletdb and wtxmgr versions
2020-06-15 17:46:19 -07:00
Olaoluwa Osuntokun 1edb2b51c3 build: update to latest walletdb and wtxmgr versions 2020-06-15 16:20:30 -07:00
Olaoluwa Osuntokun d68942b7f3 Merge pull request #709 from cfromknecht/bbolt-import-path
walletdb: eliminate old bbolt ref by using uniform import path
2020-06-15 16:16:57 -07:00
Olaoluwa Osuntokun 79727f4e6f walletdb: eliminate old bbolt ref by using uniform import path 2020-06-15 14:24:49 -07:00
Olaoluwa Osuntokun bf76ca145a Merge pull request #708 from cfromknecht/fin-wallet-db-update
wtxmgr: update to walletdb v1.3.2
2020-06-15 14:16:54 -07:00
Olaoluwa Osuntokun 186417b824 wtxmgr: update to walletdb v1.3.2 2020-06-15 12:08:53 -07:00
Olaoluwa Osuntokun 3502b46b2d Merge pull request #707 from cfromknecht/wallet-db-update
build: update to walletdb v1.3.2
2020-06-15 11:45:02 -07:00
Olaoluwa Osuntokun 6dd0b0d376 build: update to walletdb v1.3.2
In this commit, we update `walletdb` to the latest version which makes
it compatible with Go 1.14.
2020-06-15 11:29:28 -07:00
Olaoluwa Osuntokun ea0fb843a0 Merge pull request #706 from cfromknecht/bbolt-bug-fix
walletdb: update to latest bbolt version w/ Go 1.14 bug fix
2020-06-15 11:27:18 -07:00
Olaoluwa Osuntokun 727ca139b8 walletdb: update to latest bbolt version w/ Go 1.14 bug fix 2020-06-15 11:17:46 -07:00
Olaoluwa Osuntokun 48addcd559 Merge pull request #705 from wpaulino/bitcoind-20-compat
wallet: handle new error string for missing/spent input in bitcoind 0.20
2020-06-11 18:25:34 -07:00
Wilmer Paulino 2bd41b9dd1 wallet: handle new error string for missing/spent input in bitcoind 0.20
The error string was updated in:

https://github.com/bitcoin/bitcoin/pull/15921/commits/3004d5a12d09d94bfc4dee2a8e8f2291996a4aaf
2020-06-09 12:46:36 -07:00
Olaoluwa Osuntokun 6390f167e5 Merge pull request #703 from wpaulino/genesis-block-timestamp-sync-info
waddrmgr: set timestamp for genesis block sync info
2020-06-03 17:53:47 -07:00
Wilmer Paulino 6aa23a2389 waddrmgr: set timestamp for genesis block sync info
Not setting this would result in a non-sensible unix timestamp
(2288912640) being exposed when the wallet hasn't synced any blocks,
like in the case when it's waiting for the backend to sync.
2020-06-01 12:51:58 -07:00
Olaoluwa Osuntokun c52dcaf17c Merge pull request #700 from wpaulino/persistent-output-locking
wallet: introduce persistent output leases
2020-05-29 15:48:44 -07:00
Wilmer Paulino 0f2b15bb4d wallet: expose persistent output leases 2020-05-28 17:53:50 -07:00
Wilmer Paulino c42130075c wtxmgr: introduce persistent output leases
This commit allows for the ability to lease an output to a particular ID
for a limited amount of time, ensuring that no other processes can use
said output for their coin selection needs. An output can either be
unlocked manually, or lazily whenever required.
2020-05-28 17:53:49 -07:00
Olaoluwa Osuntokun 43c9c2e2f7 Merge pull request #702 from carlaKC/dropwtxmgr-keeplabels
dropwtxmgr: add drop labels option
2020-05-28 16:07:41 -07:00
carla 338cf08088 dropwtxmgr: keep tx labels, with an optional DropLabels flag 2020-05-28 09:09:15 +02:00
carla ab19740c94 wtxmgr: extract label deserialization into separate function
Requrired so that we can use the same logic in dropwtxmgr.
2020-05-28 09:07:31 +02:00
carla 4ec3fb4928 wtxmgr: separate PutTxLabel into store-independent function
Separate out the logic we use to write labels so that it can be used
in dropwtxmgr to re-add labels if we want to keep them when we drop the
rest of the db.
2020-05-27 14:54:25 +02:00
Olaoluwa Osuntokun e0e62245ec Merge pull request #699 from wpaulino/btcd-dep-update
build: update to latest btcd version
2020-05-15 15:49:13 -07:00
Wilmer Paulino 17c23a9266 build: update to latest btcd version 2020-05-14 15:43:23 -07:00
Wilmer Paulino ce888ed941 wallet: use GetBlockHeaderVerbose to retrieve block heights in GetTransactions
There's no need to retrieve the full block as we're only interesting in
retrieve its corresponding height, which can be done with
GetBlockHeaderVerbose.
2020-05-14 15:43:03 -07:00
Olaoluwa Osuntokun b07494fc2d Merge pull request #696 from carlaKC/txn-labels
wtxmgr: add labels to transactions
2020-05-11 17:12:28 -07:00
carla 212575f7d1 wallet: add label transaction function
Add function which allows you to retrospectively label a transaction,
optionally overwriting the existing label.
2020-05-11 15:19:42 +02:00
carla 3465d2ecc6 wallet/test: extract testWallet generation into separate function 2020-05-11 15:18:38 +02:00
carla 3809a6d553 wallet: add transaction label to transaction summary 2020-05-11 15:18:34 +02:00
carla f852d2f991 wtxmgr: add transaction label to TxDetails 2020-05-11 15:18:15 +02:00
carla 9aed49070d wtxmgr: update rangeBlockTransactions to use minedTxDetails
Code is duplicated across these two functions, so update
rangeBlockTransactions to use minedTxDetails. When iterating through
a block, we do have the block metadata already (which is looked up by
minedTxDetails). This change can be further optimized to split
minedTxDetails into minedTxDetails and minedTxDetailsWithoutBlock to
reduce this redundancy.
2020-05-11 15:18:06 +02:00
carla 9e2f2ce157 wallet: add label parameter to SendOutputs 2020-05-11 15:17:55 +02:00
carla d2f9185f6a wallet: add label to PublishTransaction
All label parameter to PublishTransaction. Pass in an empty string
in rpc call as a placeholder for follow up PR which will add a label
parameter to the PublishTransaction request.
2020-05-11 15:16:22 +02:00
carla 50869085eb wtxmgr: add put and fetch functions for optional transaction label
Add and test functions which can be used to write optional transaction
labels to disk in their own bucket. These labels are keyed by txid and
write the labels to disk using-length value encoding scheme. Although
the length field is not required at present, it is added to allow future
extensibility without a migration.

This approach is chosen over adding this information to txRecords,
Because a migration would be required to add a field after the variable
Length serialized tx.

The put label function will overwrite existing labels if called more
than once for the same txid. User side validation of whether we want
to override this label should be performed by calling code. Labels must
be > 0 characters and <= 500 characters (an arbitrarily chosen limit).
2020-05-11 15:16:11 +02:00
Dev RandomandKen Sedgwick 4c5bc1b15d waddrmgr: create watch-only address managers and accounts
This PR allows the creation of managers and accounts that are watch-only. The state of the database after creation would be identical to the state after calling 

Manager.ConvertToWatchingOnly, assuming accounts with the right xpubs were created in the former case.

Co-authored-by: Ken Sedgwick <ken@bonsai.com>
2020-04-24 17:44:21 -07:00
Olaoluwa Osuntokun ada7ca077e Merge pull request #691 from wpaulino/pin-walletdb-v1.3.1
build: pin to walletdb v1.3.1
2020-04-03 15:22:02 -07:00
Wilmer Paulino d2ce512b4b build: pin to walletdb v1.3.1 2020-04-03 15:08:07 -07:00
Olaoluwa Osuntokun 2fed914b79 Merge pull request #690 from wpaulino/walletdb-revert-bolt-v1.3.4
walletdb: revert bolt v1.3.4
2020-04-03 15:01:46 -07:00
Wilmer Paulino 57be08fbbf Revert "walletdb: update to bolt v1.3.4"
The v1.3.4 version of the bolt module contained a bug fix to allow the
use of go1.14, but it uncovered a GC issue.
2020-04-03 14:18:22 -07:00
Wilmer Paulino e51b4821ce walletdb: use temp dir for db filepaths in tests 2020-04-03 14:13:53 -07:00
Olaoluwa Osuntokun 237a3ee772 Merge pull request #688 from wpaulino/neutrino-recovery-batch-filters
chain: batch filter fetches for neutrino chain client
2020-03-31 18:28:17 -07:00
Wilmer Paulino 90a0744ae4 chain: batch filter fetches for neutrino chain client
This greatly speeds up wallet recovery with a neutrino backend, as we'll
avoid unnecessary round trips for each block filter fetch.
2020-03-31 13:37:56 -07:00
Olaoluwa Osuntokun 60299130c6 Merge pull request #682 from wpaulino/scan-key-scopes
wallet: rescan and recover addresses in all relevant key scopes
2020-03-31 11:10:45 -07:00
Wilmer Paulino 31c027e19f wallet: perform recovery on all registered key scopes
In similar fashion to the previous commit, due to a no longer existing
bug within the wallet, it was possible for change addresses to be
created outside of their intended key scope (the default), so wallets
affected by this now need to ensure upon recovery that they scan the
chain for _all_ existing key scopes, rather than just the default ones,
to reflect their proper balance. Through manual testing, it was shown
that the impact of recovering the additional key scopes is negligible in
most cases for both full nodes and light clients.
2020-03-30 15:35:50 -07:00
Wilmer Paulino 1285049923 wallet: include addresses from relevant key scopes in rescan
Due to a no longer existing bug within the wallet, it was possible for
change addresses to be created outside of their intended key scope (the
default), so wallets affected by this now need to ensure they scan the
chain for all addresses within the default key scopes (as expected), and
all _internal_ addresses (branch used for change addresses) within any
other registered key scopes to reflect their proper balance.
2020-03-30 15:35:49 -07:00
Wilmer Paulino 43e19da868 Revert "waddrmgr+wallet: only watch addresses within default key scopes"
The commit being reverted resulted in the discovery of a bug in which
change addresses could at times be created outside of the default key
scopes, causing us to not properly determine their spends.
2020-03-30 15:31:44 -07:00
Wilmer Paulino 60fce250f4 wallet: derive change addresses from the provided key scope
Previously, the wallet would determine the key scope to use for change
addresses by locating the one compatible with P2WPKH addresses, but this
wasn't always safe like in the case when multiple key scopes that
supported these addresses existed within the address manager, leading
the change address to be created outside of the intended key scope.
2020-03-30 15:30:53 -07:00
Olaoluwa Osuntokun 7b2cbe89f8 Merge pull request #686 from wpaulino/walletdb-upgrade
build: update to walletdb v1.3.0
2020-03-25 19:46:02 -07:00
Olaoluwa Osuntokun ba45925bcb build: update to walletdb v1.3.0 2020-03-25 18:53:31 -07:00
Olaoluwa Osuntokun 60327da210 Merge pull request #684 from wpaulino/bbolt-134
walletdb: update to bolt v1.3.4
2020-03-25 18:50:50 -07:00
Olaoluwa Osuntokun 43b5326afa walletdb: update to bolt v1.3.4 2020-03-25 15:28:30 -07:00
Olaoluwa Osuntokun 015c045a3b Merge pull request #681 from guggero/neutrino-recovery
wallet: wait for chain sync on Neutrino recovery
2020-03-23 16:53:26 -07:00
Oliver Gugger fc64a1c704 wallet: wait for chain sync on Neutrino recovery
Normally the wallet doesn't wait for the chain backend to be synced
on regtest/simnet because there we cannot be certain if we are at
the chain tip, as there are no other nodes to compare to. For
Neutrino, this is a bit different because we rely on the cfheader
server to tell us what it thinks the chain tip is. For a wallet
recovery on Neutrino we therefore need to make sure we are at least
synced up to what the server thinks is the tip.
2020-03-16 10:24:27 +01:00
Olaoluwa Osuntokun ae9416ad76 Merge pull request #676 from wpaulino/watch-default-account-addrs-only
waddrmgr+wallet: only watch addresses within default key scopes
2020-02-18 16:46:49 -08:00
Olaoluwa Osuntokun a8ff50bc4b Merge pull request #678 from bhandras/walletdb-testing
walletdb: generic param passing for walletdb test
2020-02-18 16:42:02 -08:00
Andras Banki-Horvath f2ed9c1c77 walletdb: generic param passing for walletdb test
This commit removes bbolt specific parameters from the interface
test to enable testing of other DB drivers trough the same entry
point.
2020-02-18 17:10:33 +01:00
Wilmer Paulino 51b362d7c5 waddrmgr+wallet: only watch addresses within default key scopes
It was discovered that the wallet can scan the chain for unnecessary
additional addresses that are derived by higher-level applications using
custom key scopes. This isn't much of an issue for full nodes, but it
can cause light clients to scan more than what's required, triggering
more false positive matches which lead to block retrieval.

Now, we'll only scan the chain for addresses that exist within the
default key scopes, as those are the only ones the wallet should be
concerned about.
2020-01-24 17:12:23 -08:00
Olaoluwa Osuntokun 704cd189ac Merge pull request #675 from guggero/testing-scrypt
waddrmgr: export fast scrypt options
2020-01-23 18:38:27 -08:00
Oliver Gugger 655c23db1d waddrmgr: export fast scrypt options 2020-01-23 13:47:02 +01:00
Olaoluwa Osuntokun f93a69f8f3 Merge pull request #673 from cfromknecht/wtxmgr-update-gomod
wtxmgr: update go.mod to walletdb 1.2.0
2020-01-15 16:33:20 -08:00
Conner Fromknecht 282ee8f09f wtxmgr: update go.mod to walletdb 1.2.0 2020-01-15 12:40:34 -08:00
Olaoluwa Osuntokun 824604d88b Merge pull request #672 from cfromknecht/walletdb-sequence
walletdb: add sequence methods from bbolt to the main bucket interface
2020-01-15 12:35:53 -08:00
Olaoluwa Osuntokun 2c6a714c14 walletdb: add new Batch package-level function
In this commit, we add a new package-level function to emulate the
existing Batch interface for bbolt. We do this via a new super-set
interface which is then checked against in the main implementation of
the Batch method.
2020-01-15 04:52:44 -08:00
Olaoluwa Osuntokun da2fe0e3b0 walletdb: ensure transactions are rolled back on panic 2020-01-15 04:52:34 -08:00
Olaoluwa Osuntokun e7e46cd6f9 build: update goclean.sh to properly test all packages
In this commit, we update our `go list` command to account for the
changes to the output of the command when modules are active. If modules
are active, then any packages which are themselves a sub-module won't
properly be listed.
2020-01-15 04:51:38 -08:00
Olaoluwa Osuntokun 95064ae858 wtxmgr+build: update all packges to point towards walletdb v1.2.0 2020-01-15 04:51:25 -08:00
Olaoluwa Osuntokun 0bcbb4cc4a walletdb: add sequence methods to main interface, update bdb to implement
In this commit, we add the trio of sequence based methods that bbolt
ships with to the main bucket interface. We do this in order to easily
allow walletdb as is to be slotted into place where bbolt is currently
used, without sacrificing any functionality.
2020-01-15 04:51:15 -08:00
Olaoluwa Osuntokun eb2582bbde walletdb: update examples to acccount for new 2nd param for bdb Open/Create 2020-01-15 04:50:22 -08:00
Olaoluwa Osuntokun 4aacb4a413 Merge pull request #665 from jcvernaleo/jcv_buildDocs
README: Update build instructions for switch from glide to modules
2020-01-13 14:20:16 -08:00
John C. Vernaleo c765989b51 README: Update build instructions for switch from glide to modules 2019-11-19 15:11:22 -05:00
157 changed files with 10556 additions and 19280 deletions

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
name: CI
on:
workflow_dispatch:
inputs:
note:
description: 'Note'
required: false
default: ''
push:
tags:
- '*'
branches:
- "master"
pull_request:
branches:
- "*"
defaults:
run:
shell: bash
env:
# go needs absolute directories, using the $HOME variable doesn't work here.
GOCACHE: /home/runner/work/go/pkg/build
GOPATH: /home/runner/work/go
GO_VERSION: '^1.19'
jobs:
########################
# Format, compileation and lint check
########################
lint-check:
name: Format, compilation and lint check
runs-on: ubuntu-latest
steps:
- name: git checkout
uses: actions/checkout@v2
- name: setup go ${{ env.GO_VERSION }}
uses: actions/setup-go@v2
with:
go-version: '${{ env.GO_VERSION }}'
- name: run format
run: make fmt
- name: compile code
run: go install -v ./...
- name: run lint
run: make lint
########################
# run unit tests
########################
unit-test:
name: run unit tests
runs-on: ubuntu-latest
strategy:
# Allow other tests in the matrix to continue if one fails.
fail-fast: false
matrix:
unit_type:
- unit-race
- unit-cover
steps:
- name: git checkout
uses: actions/checkout@v2
- name: go cache
uses: actions/cache@v1
with:
path: /home/runner/work/go
key: lbcwallet-${{ runner.os }}-go-${{ env.GO_VERSION }}-${{ github.job }}-${{ hashFiles('**/go.sum') }}
restore-keys: |
lbcwallet-${{ runner.os }}-go-${{ env.GO_VERSION }}-${{ github.job }}-${{ hashFiles('**/go.sum') }}
lbcwallet-${{ runner.os }}-go-${{ env.GO_VERSION }}-${{ github.job }}-
lbcwallet-${{ runner.os }}-go-${{ env.GO_VERSION }}-
lbcwallet-${{ runner.os }}-go-
- name: setup go ${{ env.GO_VERSION }}
uses: actions/setup-go@v2
with:
go-version: '${{ env.GO_VERSION }}'
- name: run ${{ matrix.unit_type }}
run: make ${{ matrix.unit_type }}
- name: Send coverage
uses: shogo82148/actions-goveralls@v1
if: matrix.unit_type == 'unit-cover'
with:
path-to-profile: coverage.txt
parallel: true
+57
View File
@@ -0,0 +1,57 @@
name: goreleaser
on:
workflow_dispatch:
inputs:
note:
description: 'Note'
required: false
default: ''
pull_request:
push:
tags:
- '*'
permissions:
contents: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
-
name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.19
# Login against a Docker registry except on PR
# https://github.com/docker/login-action
- name: Log into registry docker.io
if: github.event_name != 'pull_request'
uses: docker/login-action@28218f9b04b4f3f62068d7b6ce6ca5b26e35336c
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
with:
distribution: goreleaser
version: latest
args: release --rm-dist
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-
name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: lbcwallet-${{ github.sha }}
path: |
dist/checksums.txt
dist/*.tar.gz
+5 -1
View File
@@ -1,3 +1,7 @@
btcwallet
lbcwallet
vendor
.idea
.vscode
coverage.txt
dist/
+152
View File
@@ -0,0 +1,152 @@
linters-settings:
depguard:
list-type: blacklist
packages:
# logging is allowed only by logutils.Log, logrus
# is allowed to use only in logutils package
- github.com/sirupsen/logrus
packages-with-error-message:
- github.com/sirupsen/logrus: "logging is allowed only by logutils.Log"
dupl:
threshold: 100
funlen:
lines: 100
statements: 50
gci:
local-prefixes: github.com/golangci/golangci-lint
goconst:
min-len: 2
min-occurrences: 2
gocritic:
enabled-tags:
- diagnostic
- experimental
- opinionated
- performance
- style
disabled-checks:
- dupImport # https://github.com/go-critic/go-critic/issues/845
- ifElseChain
- octalLiteral
- whyNoLint
- wrapperFunc
gocyclo:
min-complexity: 15
goimports:
local-prefixes: github.com/golangci/golangci-lint
gomnd:
settings:
mnd:
# don't include the "operation" and "assign"
checks:
- argument
- case
- condition
- return
govet:
check-shadowing: true
settings:
printf:
funcs:
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
lll:
line-length: 140
maligned:
suggest-new: true
misspell:
locale: US
nolintlint:
allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space)
allow-unused: false # report any unused nolint directives
require-explanation: false # don't require an explanation for nolint directives
require-specific: false # don't require nolint directives to be specific about which linter is being skipped
linters:
disable-all: true
enable:
- asciicheck
- bodyclose
# - deadcode
- depguard
# - dogsled
# - dupl
# - errcheck
# - exhaustive
- exportloopref
# - funlen
# - gochecknoglobals
# - gochecknoinits
# - gocognit
# - goconst
# - gocritic
# - gocyclo
# - godot
# - godox
# - goerr113
- gofmt
- goimports
# - gomnd
- goprintffuncname
# - gosec
# - gosimple
# - govet
# - ineffassign
# - interfacer
# - lll
# - maligned
# - misspell
- nakedret
# - nestif
# - noctx
# - nolintlint
# - prealloc
# - rowserrcheck # Disabled due to generic, see https://github.com/golangci/golangci-lint/issues/2649
# - revive
# - scopelint
# - staticcheck
# - structcheck
# - stylecheck
# - testpackage
# - typecheck
- unconvert
# - unparam
# - unused
# - varcheck
# - whitespace
# - wsl
issues:
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
- path: _test\.go
linters:
- gomnd
- path: pkg/golinters/errcheck.go
text: "SA1019: errCfg.Exclude is deprecated: use ExcludeFunctions instead"
- path: pkg/commands/run.go
text: "SA1019: lsc.Errcheck.Exclude is deprecated: use ExcludeFunctions instead"
# TODO must be removed after the release of the next version (v1.41.0)
- path: pkg/commands/run.go
linters:
- gomnd
# TODO must be removed after the release of the next version (v1.41.0)
- path: pkg/golinters/nolintlint/nolintlint.go
linters:
- gomnd
# TODO must be removed after the release of the next version (v1.41.0)
- path: pkg/printers/tab.go
linters:
- gomnd
run:
skip-dirs:
- test/testdata_etc
- internal/cache
- internal/renameio
- internal/robustio
+48
View File
@@ -0,0 +1,48 @@
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
before:
hooks:
# You may remove this if you don't use go modules.
- go mod tidy
# you may remove this if you don't need go generate
- go generate ./...
builds:
- main: .
id: "lbcwallet"
binary: "lbcwallet"
env:
- CGO_ENABLED=0
flags:
- -trimpath
ldflags:
- -s -w
- -X github.com/lbryio/lbcd/version.appTag={{ .Tag }}
targets:
- linux_amd64
- linux_arm64
- darwin_amd64
- darwin_arm64
- windows_amd64
mod_timestamp: '{{ .CommitTimestamp }}'
checksum:
name_template: 'checksums.txt'
snapshot:
name_template: "{{ .Version }}+{{ .Commit }}"
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
dockers:
- use: buildx
dockerfile: Dockerfile.goreleaser
image_templates:
- "docker.io/lbry/lbcwallet:{{ .Tag }}"
- "docker.io/lbry/lbcwallet:latest"
release:
draft: true
prerelease: auto
-13
View File
@@ -1,13 +0,0 @@
language: go
go:
- "1.13.x"
sudo: false
install:
- GO111MODULE=on go install -v ./...
- GO111MODULE=off go get -v golang.org/x/tools/cmd/cover
- GO111MODULE=off go get -v golang.org/x/lint/golint
- GO111MODULE=off go get -v github.com/davecgh/go-spew/spew
script:
- export PATH=$PATH:$HOME/gopath/bin
- export GO111MODULE=on
- ./goclean.sh
-527
View File
@@ -1,527 +0,0 @@
============================================================================
User visible changes for btcwallet
A wallet daemon for btcd, written in Go
============================================================================
Changes in 0.7.0 (Mon Nov 23 2015)
- New features:
- Wallet will now detect network inactivity and reconnect to the btcd
RPC server if the connection was lost (#320)
- Bug fixes:
- Removed data races in the RPC server (#292) and waddrmgr package
(#293)
- Corrected handling of btcutil.AddressPubKey addresses when querying
for a ManagedAddress from the address manager (#313)
- Fixed signmessage and verifymessage algorithm to match the equivalent
algorithms used by Core (#324)
- Notable developer-related changes:
- Added support for AppVeyor continuous integration (#299)
- Take advantage of optimized zeroing from the Go 1.5 release (#286)
- Added IsError function to waddrmgr to check that an error is a
ManagerError and contains a matching error code (#289). Simplified
error handling in the wallet package and RPC server with this function
(#290).
- Switched to using a more space efficient data structure for the
wtxmgr CreditRecord type (#295)
- Incorporated latest updates to the votingpool package (#315)
- Miscellaneous:
- Updated websocket notification handlers to latest API required by
btcd (#294)
- Enabled the logging subsystem of the rpcclient package (#328)
- Contributors (alphabetical order):
- Alex Yocom-Piatt
- cjepson
- Dave Collins
- John C. Vernaleo
- Josh Rickmar
- Rune T. Aune
Changes in 0.6.0 (Wed May 27 2015)
- New features:
- Add initial account support (#155):
- Add account names for each account number
- Create initial account with the "default" name
- Create new accounts using the createnewaccount RPC
- All accounts (with the exception of the imported account) may be
renamed using the renameaccount RPC
- RPC requests with an unspecified account that default to the unnamed
account in Bitcoin Core Wallet default to "default", the name of the
initial account
- Several RPCs with account parameters do not work with btcwallet
accounts due to concerns over expectations of API compatibility with
Bitcoin Core Wallet. A new RPC API is being planned to rectify this
(#220).
- Store transactions, transaction history, and spend tracking in the
database (#217, #234)
- A full rescan is required when updating from previous wallet
versions to rebuild the transaction history
- Add utility (cmd/dropwtxmgr) to drop transaction history and force a
rescan (#234)
- Implement the help RPC to return single line usages of all wallet and
btcd server requests as well as detailed usage for a single request
- Bug fixes:
- Handle chain reorgs by unconfirming transactions from removed blocks
(#248)
- Rollback all transaction history when none of the saved recently seen
block hashes are known to btcd (#234, #281)
- Prevent the situation where the default account was renamed but cannot
be renamed back to "" or "default" by removing the special case naming
policy for the default account (#253)
- Create the initial account address if needed when calling the
getaccountaddress RPC (#238)
- Prevent listsinceblock RPC from including all listtransactions result
objects for all transactions since the genesis block (fix included in
#227)
- Add missing fields to listtransactions and gettransaction RPC results
(#265)
- Remove target confirmations limit on listsinceblock results (#266)
- Add JSON array to report errors creating input signature for
signrawtransaction RPC (#267)
- Use negative fees with listtransactions result types (#272)
- Prevent duplicate wallet lock attempt after timeout if explicitly
locked (#275)
- Use correct RPC server JSON-RPC error code for incorrect passphrases
with a walletpassphrase request (#284)
- Regressions:
- Inserting transactions and marking outputs as controlled by wallet in
the new transaction database is extremely slow compared to the previous
in-memory implementation. Later versions may improve this performance
regression by using write-ahead logging (WAL) and performing more
updates at a time under a single database transaction.
- Notable developer-related changes:
- Relicense all code to the btcsuite developers (#258)
- Replace txstore package with wtxmgr, the walletdb-based transaction
store (#217, #234)
- Add Cursor API to walletdb for forwards and backwards iteration over
a bucket (included in #234)
- Factor out much of main's wallet.go into a wallet package (#213,
#276, #255)
- Convert RPC server and client to btcjson v2 API (#233, #227)
- Help text and single line usages for the help RPC are pregenerated
from descriptions in the internal/rpchelp package and saved as
globals in main. Help text must be regenerated (using `go generate`)
each time the btcjson struct tags change or the help definitions are
modified.
- Add additional features to the votingpool package:
- Implement StartWithdrawal API to begin an Open Transactions
withdrawal (#178)
- Add internal APIs to store withdrawal transactions in the wallet's
transaction database (#221)
- Addresses marked as used after appearing publicly on the blockchain or
in mempool; required for future single-use address support (#207)
- Modified waddrmgr APIs to use ForEach functions to iterate over
address strings and managed addresses to improve scability (#216)
- Move legacy directory under internal directory to prevent importing
of unmaintained packages (enforced since Go 1.5) (#285)
- Improve test coverage in the waddrmgr and wtxmgr packages (#239, #217)
- Contributors (alphabetical order):
- Dave Collins
- Guilherme Salgado
- Javed Khan
- Josh Rickmar
- Manan Patel
Changes in 0.5.1 (Fri Mar 06 2015)
- New features:
- Add flag (--createtemp) to create a temporary simnet wallet
- Bug fixes:
- Mark newly received transactions confirmed when the wallet is initially
created or opened with no addresses
- Notable developer-related changes:
- Refactor the address manager database upgrade paths for easier future
upgrades
- Private key zeroing functions consolidated into the internal zero package
and optimized
Changes in 0.5.0 (Tue Mar 03 2015)
- New features:
- Add a new address manager package (waddrmgr) to replace the previous
wallet/keystore package:
- BIP0032 hierarchical deterministic keys
- BIP0043/BIP0044 multi-account hierarchy
- Strong focus on security:
- Wallet master encryption keys protected by scrypt PBKDF
- NaCl-based secretbox cryptography (XSalsa20 and Poly1305)
- Mandatory encryption of private keys and P2SH redeeming scripts
- Optional encryption of public data, including extended public keys
and addresses
- Different crypto keys for redeeming scripts to mitigate cryptanalysis
- Hardened against memory scraping through the use of actively clearing
private material from memory when locked
- Different crypto keys used for public, private, and script data
- Ability for different passphrases for public and private data
- Multi-tier scalable key design to allow instant password changes
regardless of the number of addresses stored
- Import WIF keys
- Import pay-to-script-hash scripts for things such as multi-signature
transactions
- Ability to export a watching-only version which does not contain any
private key material
- Programmatically detectable errors, including encapsulation of errors
from packages it relies on
- Address synchronization capabilities
- Add a new namespaced database package (walletdb):
- Key/value store
- Namespace support
- Allows multiple packages to have their own area in the database without
worrying about conflicts
- Read-only and read-write transactions with both manual and managed modes
- Nested buckets
- Supports registration of backend databases
- Comprehensive test coverage
- Replace the createencryptedwallet RPC with a wizard-style prompt
(--create) to create a new walletdb-backed wallet file and import keys
from the old Armory wallet file (if any)
- Transaction creation changes:
- Drop default transaction fee to 0.00001 BTC per kB
- Use standard script flags provided by the txscript package for
transaction creation and sanity checking
- Randomize change output index
- Includes amounts (total spendable, total needed, and fee) in all
insufficient funds errors
- Add support for simnet, the private simulation test network
- Implement the following Bitcoin Core RPCs:
- listreceivedbyaddress (#53)
- lockunspent, listlockunspent (#50, #55)
- getreceivedbyaddress
- listreceivedbyaccount
- Reimplement btcd RPCs which return the best block to use the block most
recently processed by wallet to avoid confirmation races:
- getbestblockhash
- getblockcount
- Perform clean shutdown on interrupt or when a stop RPC is received (#69)
- Throttle the number of connected HTTP POST and websocket client
connections (tunable using the rpcmaxclients and rpcmaxwebsockets config
options)
- Provide the ability to disable TLS when connecting to a localhost btcd or
serving localhost clients
- Rescan improvements:
- Add a rescan notification for when the rescan has completed and no more
rescan notifications are expected (#99)
- Use the most recent partial sync height from a rescan progress
notification when a rescan is restarted after the btcd connection is lost
- Force a rescan if the transaction store cannot be opened (due to a
missing file or if the deserialization failed)
- RPC compatibility improvements:
- Allow the use of the `*` account name to refer to all accounts
- Make the account parameter optional for the getbalance and
listalltransactions requests
- Add iswatchonly field to the validateaddress response result
- Check address equivalence in verifymessage by comparing pubkeys and pubkey
hashes rather than requiring the address being verified to be one
controlled by the wallet and using its private key for verification
- Bug fixes:
- Prevent an out-of-bounds panic when handling a gettransaction RPC.
- Prevent a panic on client disconnect (#110).
- Prevent double spending coins when creating multiple transactions at once
by serializing access to the transaction creation logic (#120)
- Mark unconfirmed transaction credits as spent when another unconfirmed
transaction spends one (#91)
- Exclude immature coinbase outputs from listunspent results (#103)
- Fix several data and logic races during sync with btcd (#101)
- Avoid a memory issue from incorrect slice usage which caused both
duplicate and missing blocks in the transaction store when middle
inserting transactions from a new block
- Only spend P2PKH outputs when creating sendfrom/sendmany/sendtoaddress
transactions (#89)
- Return the correct UTXO set when fetching all wallet UTXOs by fixing an
incorrect slice append
- Remove a deadlock caused by filling the btcd notification channel (#100)
- Avoid a confirmation race by using the most recently processed block in
RPC handlers, rather than using the most recently notified block by btcd
- Marshal empty JSON arrays as `[]` instead of the JSON `null` by using
empty, non-nil Go slices
- Flush logs and run all deferred functions before main returns and the
process exits
- Sync temporary transaction store flat file before closing and renaming
- Accept hex strings with an odd number of characters
- Notable developer-related changes:
- Switch from the go.net websocket package to gorilla websockets
- Refactor the RPC server:
- Move several global variables to the rpcServer struct
- Dynamically look up appropriate handlers for the current btcd connection
status and wallet sync state
- Begin creating websocket notifications by sending to one of many
notification channels in the rpcServer struct, which are in turn
marshalled and broadcast to each websocket client
- Separate the RPC client code into the chain package:
- Uses rpcclient for a btcd websocket RPC client
- Converts all notification callbacks to typed messages sent over channels
- Uses an unbounded queue for waiting notifications
- Import a new voting pool package (votingpool):
- Create and fetch voting pools and series from a walletdb namespace
- Generate deposit addresses utilizing m-of-n multisig P2SH scripts
- Improve transaction creation readability by splitting a monolithic
function into several smaller ones
- Check and handle all errors in some way, or explicitly comment why a
particular error was left unchecked
- Simplify RPC error handling by wrapping specific errors in unique types to
create an appropriate btcjson error before the response is marshalled
- Add a map of unspent outputs (keyed by outpoint) to the transaction store
for quick lookup of any UTXO and access to the full wallet UTXO set
without iterating over many transactions looking for unspent credits
- Modify several data structures and function signatures have been modified
to reduce the number of needed allocations and be more cache friendly
- Miscellaneous:
- Rewrite paths relative to the data directory when an alternate data
directory is provided on the command line
- Switch the websocket endpoint to `ws` to match btcd
- Remove the getaddressbalance extension RPC to discourage address reuse and
encourage watching for expected payments by using listunspent
- Increase transaction creation performance by moving the sorting of
transaction outputs by their amount out of an inner loop
- Add additional logging to the transaction store:
- Log each transaction added to the store
- Log each previously unconfirmed transaction that is mined
- [debug] Log which previous outputs are marked spent by a newly inserted
debiting transaction
- [debug] Log each transaction that is removed in a rollback
- Only log rollbacks if transactions are reorged out of the old chain
- Save logs to network-specific directories
(e.g. ~/.btcwallet/logs/testnet3) to match btcd behavior (#114)
Changes in 0.4.0 (Sun May 25 2014)
- Implement the following standard bitcoin server RPC requests:
- signmessage (https://github.com/conformal/btcwallet/issues/58)
- verifymessage (https://github.com/conformal/btcwallet/issues/61)
- listunspent (https://github.com/conformal/btcwallet/issues/54)
- validateaddress (https://github.com/conformal/btcwallet/issues/60)
- addressmultisig (https://github.com/conformal/btcwallet/issues/37)
- createmultisig (https://github.com/conformal/btcwallet/issues/37)
- signrawtransaction (https://github.com/conformal/btcwallet/issues/59)
- Add authenticate extension RPC request to authenticate a websocket
session without requiring the use of the HTTP Authorization header
- Add btcdusername and btcdpassword options to allow separate
authentication credentials from wallet clients when authenticating to a
btcd websocket RPC server
- Fix RPC response passthrough: JSON unmarshaling and marshaling is now
delayed until necessary and JSON result objects from btcd are sent to
clients directly without an extra decode+encode that may change the
representation of large integer values
- Fix several websocket client connection issues:
- Disconnect clients are cleanly removed without hanging on any final
sends
- Set deadline for websocket client sends to prevent hanging on
misbehaving clients or clients with a bad connection
- Fix return result for dumprivkey by always padding the private key bytes
to a length of 32
- Fix rescan for transaction history for imported addresses
(https://github.com/conformal/btcwallet/issues/74)
- Fix listsinceblock request handler to consider the minimum confirmation
parameter (https://github.com/conformal/btcwallet/issues/80)
- Fix several RPC handlers which require an unlocked wallet to check
for an unlocked wallet before continuing
(https://github.com/conformal/btcwallet/issues/65)
- Fix handling for block rewards (coinbase transactions):
- Update listtransactions results to use "generate" category for
coinbase outputs
- Prevent inclusion of immature coinbase outputs for newly created
transactions
- Rewrite the transaction store to handle several issues regarding
transation malleability and performance issues
- The new transaction store is written to disk in a different format
then before, and upgrades will require a rescan to rebuild the
transaction history
- Improve rescan:
- Begin rescan with known UTXO set at start height
- Serialize executation of all rescan requests
- Merge waiting rescan jobs so all jobs can be handled with a single
rescan
- Support parially synced addresses in the keystore and incrementally
mark rescan progress. If a rescan is unable to continue (wallet
closes, btcd disconnects, etc.) a new rescan can start at the last
synced chain height
- Notify (with an unsolicited notification) websocket clients of btcd
connection state
- Improve logging:
- Log reason for disconnecting a websocket client
- Updates for btcd websocket API changes
- Stability fixes, internal API changes, general code cleanup, and comment
corrections
Changes in 0.3.0 (Mon Feb 10 2014)
- Use correct hash algorithm for chained addresses (fixes a bug where
address chaining was still deterministic, but forked from Armory and
previous btcwallet implementations)
- Change websocket endpoint to connect to btcd 0.6.0-alpha
- Redo server implementation to serialize handling of client requests
- Redo account locking to greatly reduce btcwallet lockups caused by
incorrect mutex usage
- Open all accounts, rather than just the default account, at startup
- Generate new addresses using pubkey chaining if keypool is depleted and
wallet is locked
- Make maximum keypool size a configuration option (keypoolsize)
- Add disallowfree configuration option (default false) to force adding
the minimum fee to all outbound transactions
- Implement the following standard bitcoin server RPC requests:
- getinfo (https://github.com/conformal/btcwallet/issues/63)
- getrawchangeaddress (https://github.com/conformal/btcwallet/issues/41)
- getreceivedbyaccount (https://github.com/conformal/btcwallet/issues/42)
- gettransaction (https://github.com/conformal/btcwallet/issues/44)
- keypoolrefill (https://github.com/conformal/btcwallet/issues/48)
- listsinceblock (https://github.com/conformal/btcwallet/issues/52)
- sendtoaddress (https://github.com/conformal/btcwallet/issues/56)
- Add empty (unimplemented) handlers for the following RPC requests so
requests are not passed down to btcd:
- getblocktemplate
- getwork
- stop
- Add RPC extension request, exportwatchingwallet, to export an account
with a watching-only wallet from an account with a hot wallet that
may be used by a separate btcwallet instance
- Require all account wallets to share the same passphrase
- Change walletlock and walletpassphrase RPC requests to lock or unlock
all account wallets
- Allow opening accounts with watching-only wallets
- Return txid for sendfrom RPC requests
(https://github.com/conformal/btcwallet/issues/64)
- Rescan imported private keys in background
(https://github.com/conformal/btcwallet/issues/34)
- Do not import duplicate private keys
(https://github.com/conformal/btcwallet/issues/35)
- Write all three account files for a new account, rather than just
the wallet (https://github.com/conformal/btcwallet/issues/30)
- Create any missing directories before writing autogenerated certificate
pair
- Fix rescanning of a new account's root address
- Fix error in the wallet file serialization causing duplicate address
encryption attempts
- Fix issue calculating eligible transaction inputs caused by a bad
confirmation check
- Fix file locking issue on Windows caused by not closing files before
renaming
- Fix typos in README file
Changes in 0.2.1 (Thu Jan 10 2014)
- Fix a mutex issue which caused btcwallet to lockup on all
RPC requests needing to read or write an account
Changes in 0.2.0 (Thu Jan 09 2014)
- Enable mainnet support (disabled by default, use --mainnet to enable)
- Don't hardcode localhost btcd connections. Instead, add a --connect
option to specify the hostname or address and port of a local or
remote btcd instance
(https://github.com/conformal/btcwallet/issues/1)
- Remove --serverport port and replace with --listen. This option works
just like btcd's --rpclisten and allows to specify the interfaces to
listen for RPC connections
- Require TLS and Basic HTTP authentication before wallet can be
controlled over RPC
- Refill keypool if wallet is unlocked and keypool is emptied
- Detect and rollback saved tx/utxo info after btcd performs blockchain
reorganizations while btcwallet was disconnected
- Add support for the following standard bitcoin JSON-RPC calls:
- dumpprivkey (https://github.com/conformal/btcwallet/issues/9)
- getaccount
- getaccountaddress
- importprivkey (https://github.com/conformal/btcwallet/issues/2)
- listtransactions (https://github.com/conformal/btcwallet/issues/12)
- Add several extension RPC calls for websocket connections:
- getaddressbalance: get the balance associated with a single address
- getunconfirmedbalance: get total balance for unconfirmed transactions
- listaddresstransactions: list transactions for a single address
(https://github.com/conformal/btcwallet/issues/27)
- listalltransactions: lists all transactions without specifying a range
- Make RPC extensions available only to websocket connections, with the
exception of createencryptedwallet
- Add dummy handlers for unimplemented wallet RPC calls
(https://github.com/conformal/btcwallet/issues/29)
- Add socks5/tor proxy support
- Calculate and add minimum transaction fee to created transactions
- Use OS-specific rename calls to provide atomic file renames which
can replace a currently-existing file
(https://github.com/conformal/btcwallet/issues/20)
- Move account files to a single directory per bitcoin network to
prevent a future scaling issue
(https://github.com/conformal/btcwallet/issues/16)
- Fix several data races and mutex mishandling
- Fix a bug where the RPC server hung on requests requiring btcd
when a btcd connection was never established
- Fix a bug where creating account files did not create all necessary
directories (https://github.com/conformal/btcwallet/issues/15)
- Fix a bug where '~' did not expand to a home or user directory
(https://github.com/conformal/btcwallet/issues/17)
- Fix a bug where returning account names as strings did not remove
trailing ending 0s
- Fix a bug where help usage was displayed twice using the -h or --help
flag
- Fix sample listening address in sample configuration file
- Update sample configuration file with all available options with
descriptions and defaults for each
Initial Release 0.1.0 (Wed Nov 13 2013)
- Initial release
+39
View File
@@ -0,0 +1,39 @@
# This Dockerfile builds lbcwallet from source and creates a small (55 MB) docker container based on alpine linux.
#
# Clone this repository and run the following command to build and tag a fresh lbcwallet amd64 container:
#
# docker build . -t yourregistry/lbcwallet
#
# You can use the following command to buid an arm64v8 container:
#
# docker build . -t yourregistry/lbcwallet --build-arg ARCH=arm64v8
#
# For more information how to use this docker image visit:
# https://github.com/lbryio/lbcwallet/tree/master/docs
#
# 9244 Mainet Wallet RPC port
ARG ARCH=amd64
FROM golang:1.19 AS build-container
ARG ARCH
ADD . /app
WORKDIR /app
RUN set -ex \
&& if [ "${ARCH}" = "amd64" ]; then export GOARCH=amd64; fi \
&& if [ "${ARCH}" = "arm32v7" ]; then export GOARCH=arm; fi \
&& if [ "${ARCH}" = "arm64v8" ]; then export GOARCH=arm64; fi \
&& echo "Compiling for $GOARCH" \
&& go install -v . ./cmd/...
FROM $ARCH/debian:bullseye-20220418-slim
COPY --from=build-container /go/bin /bin
VOLUME ["/root/.lbcwallet"]
EXPOSE 9244
ENTRYPOINT ["lbcwallet"]
+9
View File
@@ -0,0 +1,9 @@
FROM debian:bullseye-20220418-slim
COPY lbcwallet /bin/
VOLUME ["/root/.lbcwallet"]
EXPOSE 9244
ENTRYPOINT ["lbcwallet"]
+122
View File
@@ -0,0 +1,122 @@
PKG := github.com/lbryio/lbcwallet
LINT_PKG := github.com/golangci/golangci-lint/cmd/golangci-lint
GOACC_PKG := github.com/ory/go-acc
GOIMPORTS_PKG := golang.org/x/tools/cmd/goimports
GOPATH ?= ${HOME}/go
GO_BIN := ${GOPATH}/bin
LINT_BIN := ${GO_BIN}/golangci-lint
GOACC_BIN := $(GO_BIN)/go-acc
LINT_COMMIT := v1.48
GOACC_COMMIT := v0.2.8
DEPGET := go install
GOBUILD := go build -v
GOINSTALL := go install -v
GOTEST := go test
GOLIST := go list -deps $(PKG)/... | grep '$(PKG)'
GOLIST_COVER := $$(go list -deps $(PKG)/... | grep '$(PKG)')
GOFILES_NOVENDOR = $(shell find . -type f -name '*.go' -not -path "./vendor/*")
RM := rm -f
CP := cp
MAKE := make
XARGS := xargs -L 1
# Linting uses a lot of memory, so keep it under control by limiting the number
# of workers if requested.
ifneq ($(workers),)
LINT_WORKERS = --concurrency=$(workers)
endif
LINT = $(LINT_BIN) run -v $(LINT_WORKERS)
GREEN := "\\033[0;32m"
NC := "\\033[0m"
define print
echo $(GREEN)$1$(NC)
endef
default: build
all: build check
# ============
# DEPENDENCIES
# ============
$(LINT_BIN):
@$(call print, "Fetching linter")
$(DEPGET) $(LINT_PKG)@$(LINT_COMMIT)
$(GOACC_BIN):
@$(call print, "Fetching go-acc")
$(DEPGET) $(GOACC_PKG)@$(GOACC_COMMIT)
goimports:
@$(call print, "Installing goimports.")
$(DEPGET) $(GOIMPORTS_PKG)
# ============
# INSTALLATION
# ============
build:
@$(call print, "Compiling lbcwallet.")
$(GOBUILD) $(PKG)/...
install:
@$(call print, "Installing lbcwallet.")
$(GOINSTALL) $(PKG)
$(GOINSTALL) $(PKG)/cmd/dropwtxmgr
$(GOINSTALL) $(PKG)/cmd/sweepaccount
# =======
# TESTING
# =======
check: unit
unit:
@$(call print, "Running unit tests.")
$(GOLIST) | $(XARGS) env $(GOTEST) -test.timeout=20m
unit-cover: $(GOACC_BIN)
@$(call print, "Running unit coverage tests.")
$(GOACC_BIN) $(GOLIST_COVER)
unit-race:
@$(call print, "Running unit race tests.")
env CGO_ENABLED=1 GORACE="history_size=7 halt_on_errors=1" $(GOLIST) | $(XARGS) env $(GOTEST) -race -test.timeout=20m
# =========
# UTILITIES
# =========
fmt: goimports
@$(call print, "Fixing imports.")
goimports -w $(GOFILES_NOVENDOR)
@$(call print, "Formatting source.")
gofmt -l -w -s $(GOFILES_NOVENDOR)
lint: $(LINT_BIN)
@$(call print, "Linting source.")
$(LINT)
clean:
@$(call print, "Cleaning source.$(NC)")
$(RM) coverage.txt
.PHONY: all \
default \
build \
check \
unit \
unit-cover \
unit-race \
fmt \
lint \
clean
+61 -183
View File
@@ -1,218 +1,96 @@
btcwallet
=========
# lbcwallet
[![Build Status](https://travis-ci.org/btcsuite/btcwallet.png?branch=master)](https://travis-ci.org/btcsuite/btcwallet)
[![Build status](https://ci.appveyor.com/api/projects/status/88nxvckdj8upqr36/branch/master?svg=true)](https://ci.appveyor.com/project/jrick/btcwallet/branch/master)
lbcwallet implements HD Wallet functionality which conforms to
[BIP0032](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki),
[BIP0043](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki),
and [BIP0044](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki).
btcwallet is a daemon handling bitcoin wallet functionality for a
single user. It acts as both an RPC client to btcd and an RPC server
for wallet clients and legacy RPC applications.
## Security
Public and private keys are derived using the hierarchical
deterministic format described by
[BIP0032](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki).
Unencrypted private keys are not supported and are never written to
disk. btcwallet uses the
`m/44'/<coin type>'/<account>'/<branch>/<address index>`
HD path for all derived addresses, as described by
[BIP0044](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki).
We take security seriously. Please contact [security](mailto:security@lbry.com) regarding any security issues.
Our PGP key is [here](https://lbry.com/faq/pgp-key) if you need it.
Due to the sensitive nature of public data in a BIP0032 wallet,
btcwallet provides the option of encrypting not just private keys, but
public data as well. This is intended to thwart privacy risks where a
wallet file is compromised without exposing all current and future
addresses (public keys) managed by the wallet. While access to this
information would not allow an attacker to spend or steal coins, it
does mean they could track all transactions involving your addresses
and therefore know your exact balance. In a future release, public data
encryption will extend to transactions as well.
## Build from Source Code
btcwallet is not an SPV client and requires connecting to a local or
remote btcd instance for asynchronous blockchain queries and
notifications over websockets. Full btcd installation instructions
can be found [here](https://github.com/btcsuite/btcd). An alternative
SPV mode that is compatible with btcd and Bitcoin Core is planned for
a future release.
Requires [Go](http://golang.org) 1.19 or newer. Install Go according to its [installation instructions](http://golang.org/doc/install).
Wallet clients can use one of two RPC servers:
1. A legacy JSON-RPC server mostly compatible with Bitcoin Core
The JSON-RPC server exists to ease the migration of wallet applications
from Core, but complete compatibility is not guaranteed. Some portions of
the API (and especially accounts) have to work differently due to other
design decisions (mostly due to BIP0044). However, if you find a
compatibility issue and feel that it could be reasonably supported, please
report an issue. This server is enabled by default.
2. An experimental gRPC server
The gRPC server uses a new API built for btcwallet, but the API is not
stabilized and the server is feature gated behind a config option
(`--experimentalrpclisten`). If you don't mind applications breaking due
to API changes, don't want to deal with issues of the legacy API, or need
notifications for changes to the wallet, this is the RPC server to use.
The gRPC server is documented [here](./rpc/documentation/README.md).
## Installation and updating
### Windows - MSIs Available
Install the latest MSIs available here:
https://github.com/btcsuite/btcd/releases
https://github.com/btcsuite/btcwallet/releases
### Windows/Linux/BSD/POSIX - Build from source
Building or updating from source requires the following build dependencies:
- **Go 1.5 or 1.6**
Installation instructions can be found here: http://golang.org/doc/install.
It is recommended to add `$GOPATH/bin` to your `PATH` at this point.
**Note:** If you are using Go 1.5, you must manually enable the vendor
experiment by setting the `GO15VENDOREXPERIMENT` environment variable to
`1`. This step is not required for Go 1.6.
- **Glide**
Glide is used to manage project dependencies and provide reproducible builds.
To install:
`go get -u github.com/Masterminds/glide`
Unfortunately, the use of `glide` prevents a handy tool such as `go get` from
automatically downloading, building, and installing the source in a single
command. Instead, the latest project and dependency sources must be first
obtained manually with `git` and `glide`, and then `go` is used to build and
install the project.
**Getting the source**:
For a first time installation, the project and dependency sources can be
obtained manually with `git` and `glide` (create directories as needed):
```
git clone https://github.com/btcsuite/btcwallet $GOPATH/src/github.com/btcsuite/btcwallet
cd $GOPATH/src/github.com/btcsuite/btcwallet
glide install
``` sh
git clone https://github.com/lbryio/lbcwallet
cd lbcwallet
go build .
```
To update an existing source tree, pull the latest changes and install the
matching dependencies:
## **lbcd** & **lbcwallet**
```
cd $GOPATH/src/github.com/btcsuite/btcwallet
git pull
glide install
```
`lbcwallet` is not an SPV client and requires connecting to a `lbcd` node for asynchronous blockchain queries and notifications over websockets.
**Building/Installing**:
lbcwallet can serve wallet related RPCs and proxy lbcd RPCs to the assocated lbcd. It's sufficient for a user to connect just the **lbcwallet** instead of both.
The `go` tool is used to build or install (to `GOPATH`) the project. Some
example build instructions are provided below (all must run from the `btcwallet`
project directory).
``` mermaid
sequenceDiagram
actor C as lbcctl
participant W as lbcwallet (port: 9244)
participant D as lbcd (port: 9245)
To build and install `btcwallet` and all helper commands (in the `cmd`
directory) to `$GOPATH/bin/`, as well as installing all compiled packages to
`$GOPATH/pkg/` (**use this if you are unsure which command to run**):
rect rgb(200,200,200)
Note over C,W: lbcctl --wallet balance
C ->>+ W: getbalance
W -->>- C: response
end
```
go install . ./cmd/...
```
To build a `btcwallet` executable and install it to `$GOPATH/bin/`:
```
go install
```
To build a `btcwallet` executable and place it in the current directory:
```
go build
rect rgb(200,200,200)
Note over C,D: lbcctl --wallet getblockcount (lbcd RPC service proxied by lbcwallet)
C ->>+ W: getblockcount
W ->>+ D: getblockcount
D -->>- W: response
W -->>- C: response
end
```
## Getting Started
The following instructions detail how to get started with btcwallet connecting
to a localhost btcd. Commands should be run in `cmd.exe` or PowerShell on
Windows, or any terminal emulator on *nix.
Create a new wallet with a randomly generated seed or an existing one.
- Run the following command to start btcd:
``` sh
lbcwallet --create
```
btcd -u rpcuser -P rpcpass
Do you have an existing wallet seed you want to use? (n/no/y/yes) [no]: no
Your wallet generation seed is: 3d005498ad5e9b7439b857249e328ec34e21845b7d1a7d2a5641d4050c02d0da
```
- Run the following command to create a wallet:
The created wallet protects the seed with a default passphrase (`"passphrase"`), which can be override with `-p` option:
```
btcwallet -u rpcuser -P rpcpass --create
``` sh
lbcwallet --create -p my-passphrase
```
- Run the following command to start btcwallet:
Start wallet server, and connect it to a lbcd instance.
```
btcwallet -u rpcuser -P rpcpass
``` sh
lbcwallet --rpcuser=rpcuser --rpcpass=rpcpass # --rpcconnect=localhost:9245
```
If everything appears to be working, it is recommended at this point to
copy the sample btcd and btcwallet configurations and update with your
RPC username and password.
At startup, the wallet will try to unlock itself with the default passphrase (`passphrase`) or an user provided one (using `-p` option).
PowerShell (Installed from MSI):
```
PS> cp "$env:ProgramFiles\Btcd Suite\Btcd\sample-btcd.conf" $env:LOCALAPPDATA\Btcd\btcd.conf
PS> cp "$env:ProgramFiles\Btcd Suite\Btcwallet\sample-btcwallet.conf" $env:LOCALAPPDATA\Btcwallet\btcwallet.conf
PS> $editor $env:LOCALAPPDATA\Btcd\btcd.conf
PS> $editor $env:LOCALAPPDATA\Btcwallet\btcwallet.conf
If the passphrase does not match, the wallet remains locked. User can lock/unlock the wallet using `walletlock` and `walletpassphrase` RPCs.
``` sh
lbcwallet --rpcuser=rpcuser --rpcpass=rpcpass -p my_passphrase
```
PowerShell (Installed from source):
```
PS> cp $env:GOPATH\src\github.com\btcsuite\btcd\sample-btcd.conf $env:LOCALAPPDATA\Btcd\btcd.conf
PS> cp $env:GOPATH\src\github.com\btcsuite\btcwallet\sample-btcwallet.conf $env:LOCALAPPDATA\Btcwallet\btcwallet.conf
PS> $editor $env:LOCALAPPDATA\Btcd\btcd.conf
PS> $editor $env:LOCALAPPDATA\Btcwallet\btcwallet.conf
```
## Contributing
Linux/BSD/POSIX (Installed from source):
```bash
$ cp $GOPATH/src/github.com/btcsuite/btcd/sample-btcd.conf ~/.btcd/btcd.conf
$ cp $GOPATH/src/github.com/btcsuite/btcwallet/sample-btcwallet.conf ~/.btcwallet/btcwallet.conf
$ $EDITOR ~/.btcd/btcd.conf
$ $EDITOR ~/.btcwallet/btcwallet.conf
```
Contributions to this project are welcome, encouraged, and compensated.
The [integrated github issue tracker](https://github.com/lbryio/lbcwallet/issues)
is used for this project. All pull requests will be considered.
## Issue Tracker
The [integrated github issue tracker](https://github.com/btcsuite/btcwallet/issues)
is used for this project.
## GPG Verification Key
All official release tags are signed by Conformal so users can ensure the code
has not been tampered with and is coming from the btcsuite developers. To
verify the signature perform the following:
- Download the public key from the Conformal website at
https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt
- Import the public key into your GPG keyring:
```bash
gpg --import GIT-GPG-KEY-conformal.txt
```
- Verify the release tag with the following command where `TAG_NAME` is a
placeholder for the specific tag:
```bash
git tag -v TAG_NAME
```
<!-- ## Release Verification
Please see our [documentation on the current build/verification
process](https://github.com/lbryio/lbcwallet/tree/master/release) for all our
releases for information on how to verify the integrity of published releases
using our reproducible build system.
-->
## License
btcwallet is licensed under the liberal ISC License.
lbcwallet is licensed under the liberal ISC License.
-22
View File
@@ -1,22 +0,0 @@
version: "{build}"
clone_folder: c:\projects\src\github.com\btcsuite\btcwallet
environment:
PATH: c:\projects\bin;%PATH%
GOPATH: c:\projects
GORACE: halt_on_error=1
init:
- go version
- go get -u github.com/Masterminds/glide
- go get -u github.com/davecgh/go-spew/spew
install:
- glide install
build_script:
- ps: go get $(glide novendor)
test_script:
- ps: go test -race $(glide novendor)
File diff suppressed because it is too large. Load diff
-460
View File
@@ -1,460 +0,0 @@
package chain
import (
"bytes"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/wire"
"github.com/lightninglabs/gozmq"
)
const (
// rawBlockZMQCommand is the command used to receive raw block
// notifications from bitcoind through ZMQ.
rawBlockZMQCommand = "rawblock"
// rawTxZMQCommand is the command used to receive raw transaction
// notifications from bitcoind through ZMQ.
rawTxZMQCommand = "rawtx"
// maxRawBlockSize is the maximum size in bytes for a raw block received
// from bitcoind through ZMQ.
maxRawBlockSize = 4e6
// maxRawTxSize is the maximum size in bytes for a raw transaction
// received from bitcoind through ZMQ.
maxRawTxSize = maxRawBlockSize
// seqNumLen is the length of the sequence number of a message sent from
// bitcoind through ZMQ.
seqNumLen = 4
)
// BitcoindConn represents a persistent client connection to a bitcoind node
// that listens for events read from a ZMQ connection.
type BitcoindConn struct {
started int32 // To be used atomically.
stopped int32 // To be used atomically.
// rescanClientCounter is an atomic counter that assigns a unique ID to
// each new bitcoind rescan client using the current bitcoind
// connection.
rescanClientCounter uint64
// chainParams identifies the current network the bitcoind node is
// running on.
chainParams *chaincfg.Params
// client is the RPC client to the bitcoind node.
client *rpcclient.Client
// zmqBlockConn is the ZMQ connection we'll use to read raw block
// events.
zmqBlockConn *gozmq.Conn
// zmqTxConn is the ZMQ connection we'll use to read raw transaction
// events.
zmqTxConn *gozmq.Conn
// rescanClients is the set of active bitcoind rescan clients to which
// ZMQ event notfications will be sent to.
rescanClientsMtx sync.Mutex
rescanClients map[uint64]*BitcoindClient
quit chan struct{}
wg sync.WaitGroup
}
// NewBitcoindConn creates a client connection to the node described by the host
// string. The ZMQ connections are established immediately to ensure liveness.
// If the remote node does not operate on the same bitcoin network as described
// by the passed chain parameters, the connection will be disconnected.
func NewBitcoindConn(chainParams *chaincfg.Params,
host, user, pass, zmqBlockHost, zmqTxHost string,
zmqPollInterval time.Duration) (*BitcoindConn, error) {
clientCfg := &rpcclient.ConnConfig{
Host: host,
User: user,
Pass: pass,
DisableAutoReconnect: false,
DisableConnectOnNew: true,
DisableTLS: true,
HTTPPostMode: true,
}
client, err := rpcclient.New(clientCfg, nil)
if err != nil {
return nil, err
}
// Establish two different ZMQ connections to bitcoind to retrieve block
// and transaction event notifications. We'll use two as a separation of
// concern to ensure one type of event isn't dropped from the connection
// queue due to another type of event filling it up.
zmqBlockConn, err := gozmq.Subscribe(
zmqBlockHost, []string{rawBlockZMQCommand}, zmqPollInterval,
)
if err != nil {
return nil, fmt.Errorf("unable to subscribe for zmq block "+
"events: %v", err)
}
zmqTxConn, err := gozmq.Subscribe(
zmqTxHost, []string{rawTxZMQCommand}, zmqPollInterval,
)
if err != nil {
zmqBlockConn.Close()
return nil, fmt.Errorf("unable to subscribe for zmq tx "+
"events: %v", err)
}
conn := &BitcoindConn{
chainParams: chainParams,
client: client,
zmqBlockConn: zmqBlockConn,
zmqTxConn: zmqTxConn,
rescanClients: make(map[uint64]*BitcoindClient),
quit: make(chan struct{}),
}
return conn, nil
}
// Start attempts to establish a RPC and ZMQ connection to a bitcoind node. If
// successful, a goroutine is spawned to read events from the ZMQ connection.
// It's possible for this function to fail due to a limited number of connection
// attempts. This is done to prevent waiting forever on the connection to be
// established in the case that the node is down.
func (c *BitcoindConn) Start() error {
if !atomic.CompareAndSwapInt32(&c.started, 0, 1) {
return nil
}
// Verify that the node is running on the expected network.
net, err := c.getCurrentNet()
if err != nil {
return err
}
if net != c.chainParams.Net {
return fmt.Errorf("expected network %v, got %v",
c.chainParams.Net, net)
}
c.wg.Add(2)
go c.blockEventHandler()
go c.txEventHandler()
return nil
}
// Stop terminates the RPC and ZMQ connection to a bitcoind node and removes any
// active rescan clients.
func (c *BitcoindConn) Stop() {
if !atomic.CompareAndSwapInt32(&c.stopped, 0, 1) {
return
}
for _, client := range c.rescanClients {
client.Stop()
}
close(c.quit)
c.client.Shutdown()
c.zmqBlockConn.Close()
c.zmqTxConn.Close()
c.client.WaitForShutdown()
c.wg.Wait()
}
// blockEventHandler reads raw blocks events from the ZMQ block socket and
// forwards them along to the current rescan clients.
//
// NOTE: This must be run as a goroutine.
func (c *BitcoindConn) blockEventHandler() {
defer c.wg.Done()
log.Info("Started listening for bitcoind block notifications via ZMQ "+
"on", c.zmqBlockConn.RemoteAddr())
// Set up the buffers we expect our messages to consume. ZMQ
// messages from bitcoind include three parts: the command, the
// data, and the sequence number.
//
// We'll allocate a fixed data slice that we'll reuse when reading
// blocks from bitcoind through ZMQ. There's no need to recycle this
// slice (zero out) after using it, as further reads will overwrite the
// slice and we'll only be deserializing the bytes needed.
var (
command [len(rawBlockZMQCommand)]byte
seqNum [seqNumLen]byte
data = make([]byte, maxRawBlockSize)
)
for {
// Before attempting to read from the ZMQ socket, we'll make
// sure to check if we've been requested to shut down.
select {
case <-c.quit:
return
default:
}
// Poll an event from the ZMQ socket.
var (
bufs = [][]byte{command[:], data, seqNum[:]}
err error
)
bufs, err = c.zmqBlockConn.Receive(bufs)
if err != nil {
// EOF should only be returned if the connection was
// explicitly closed, so we can exit at this point.
if err == io.EOF {
return
}
// It's possible that the connection to the socket
// continuously times out, so we'll prevent logging this
// error to prevent spamming the logs.
netErr, ok := err.(net.Error)
if ok && netErr.Timeout() {
log.Trace("Re-establishing timed out ZMQ " +
"block connection")
continue
}
log.Errorf("Unable to receive ZMQ %v message: %v",
rawBlockZMQCommand, err)
continue
}
// We have an event! We'll now ensure it is a block event,
// deserialize it, and report it to the different rescan
// clients.
eventType := string(bufs[0])
switch eventType {
case rawBlockZMQCommand:
block := &wire.MsgBlock{}
r := bytes.NewReader(bufs[1])
if err := block.Deserialize(r); err != nil {
log.Errorf("Unable to deserialize block: %v",
err)
continue
}
c.rescanClientsMtx.Lock()
for _, client := range c.rescanClients {
select {
case client.zmqBlockNtfns <- block:
case <-client.quit:
case <-c.quit:
c.rescanClientsMtx.Unlock()
return
}
}
c.rescanClientsMtx.Unlock()
default:
// It's possible that the message wasn't fully read if
// bitcoind shuts down, which will produce an unreadable
// event type. To prevent from logging it, we'll make
// sure it conforms to the ASCII standard.
if eventType == "" || !isASCII(eventType) {
continue
}
log.Warnf("Received unexpected event type from %v "+
"subscription: %v", rawBlockZMQCommand,
eventType)
}
}
}
// txEventHandler reads raw blocks events from the ZMQ block socket and forwards
// them along to the current rescan clients.
//
// NOTE: This must be run as a goroutine.
func (c *BitcoindConn) txEventHandler() {
defer c.wg.Done()
log.Info("Started listening for bitcoind transaction notifications "+
"via ZMQ on", c.zmqTxConn.RemoteAddr())
// Set up the buffers we expect our messages to consume. ZMQ
// messages from bitcoind include three parts: the command, the
// data, and the sequence number.
//
// We'll allocate a fixed data slice that we'll reuse when reading
// transactions from bitcoind through ZMQ. There's no need to recycle
// this slice (zero out) after using it, as further reads will overwrite
// the slice and we'll only be deserializing the bytes needed.
var (
command [len(rawTxZMQCommand)]byte
seqNum [seqNumLen]byte
data = make([]byte, maxRawTxSize)
)
for {
// Before attempting to read from the ZMQ socket, we'll make
// sure to check if we've been requested to shut down.
select {
case <-c.quit:
return
default:
}
// Poll an event from the ZMQ socket.
var (
bufs = [][]byte{command[:], data, seqNum[:]}
err error
)
bufs, err = c.zmqTxConn.Receive(bufs)
if err != nil {
// EOF should only be returned if the connection was
// explicitly closed, so we can exit at this point.
if err == io.EOF {
return
}
// It's possible that the connection to the socket
// continuously times out, so we'll prevent logging this
// error to prevent spamming the logs.
netErr, ok := err.(net.Error)
if ok && netErr.Timeout() {
log.Trace("Re-establishing timed out ZMQ " +
"transaction connection")
continue
}
log.Errorf("Unable to receive ZMQ %v message: %v",
rawTxZMQCommand, err)
continue
}
// We have an event! We'll now ensure it is a transaction event,
// deserialize it, and report it to the different rescan
// clients.
eventType := string(bufs[0])
switch eventType {
case rawTxZMQCommand:
tx := &wire.MsgTx{}
r := bytes.NewReader(bufs[1])
if err := tx.Deserialize(r); err != nil {
log.Errorf("Unable to deserialize "+
"transaction: %v", err)
continue
}
c.rescanClientsMtx.Lock()
for _, client := range c.rescanClients {
select {
case client.zmqTxNtfns <- tx:
case <-client.quit:
case <-c.quit:
c.rescanClientsMtx.Unlock()
return
}
}
c.rescanClientsMtx.Unlock()
default:
// It's possible that the message wasn't fully read if
// bitcoind shuts down, which will produce an unreadable
// event type. To prevent from logging it, we'll make
// sure it conforms to the ASCII standard.
if eventType == "" || !isASCII(eventType) {
continue
}
log.Warnf("Received unexpected event type from %v "+
"subscription: %v", rawTxZMQCommand, eventType)
}
}
}
// getCurrentNet returns the network on which the bitcoind node is running.
func (c *BitcoindConn) getCurrentNet() (wire.BitcoinNet, error) {
hash, err := c.client.GetBlockHash(0)
if err != nil {
return 0, err
}
switch *hash {
case *chaincfg.TestNet3Params.GenesisHash:
return chaincfg.TestNet3Params.Net, nil
case *chaincfg.RegressionNetParams.GenesisHash:
return chaincfg.RegressionNetParams.Net, nil
case *chaincfg.MainNetParams.GenesisHash:
return chaincfg.MainNetParams.Net, nil
default:
return 0, fmt.Errorf("unknown network with genesis hash %v", hash)
}
}
// NewBitcoindClient returns a bitcoind client using the current bitcoind
// connection. This allows us to share the same connection using multiple
// clients.
func (c *BitcoindConn) NewBitcoindClient() *BitcoindClient {
return &BitcoindClient{
quit: make(chan struct{}),
id: atomic.AddUint64(&c.rescanClientCounter, 1),
chainParams: c.chainParams,
chainConn: c,
rescanUpdate: make(chan interface{}),
watchedAddresses: make(map[string]struct{}),
watchedOutPoints: make(map[wire.OutPoint]struct{}),
watchedTxs: make(map[chainhash.Hash]struct{}),
notificationQueue: NewConcurrentQueue(20),
zmqTxNtfns: make(chan *wire.MsgTx),
zmqBlockNtfns: make(chan *wire.MsgBlock),
mempool: make(map[chainhash.Hash]struct{}),
expiredMempool: make(map[int32]map[chainhash.Hash]struct{}),
}
}
// AddClient adds a client to the set of active rescan clients of the current
// chain connection. This allows the connection to include the specified client
// in its notification delivery.
//
// NOTE: This function is safe for concurrent access.
func (c *BitcoindConn) AddClient(client *BitcoindClient) {
c.rescanClientsMtx.Lock()
defer c.rescanClientsMtx.Unlock()
c.rescanClients[client.id] = client
}
// RemoveClient removes the client with the given ID from the set of active
// rescan clients. Once removed, the client will no longer receive block and
// transaction notifications from the chain connection.
//
// NOTE: This function is safe for concurrent access.
func (c *BitcoindConn) RemoveClient(id uint64) {
c.rescanClientsMtx.Lock()
defer c.rescanClientsMtx.Unlock()
delete(c.rescanClients, id)
}
// isASCII is a helper method that checks whether all bytes in `data` would be
// printable ASCII characters if interpreted as a string.
func isASCII(s string) bool {
for _, c := range s {
if c < 32 || c > 126 {
return false
}
}
return true
}
+21 -57
View File
@@ -1,11 +1,11 @@
package chain
import (
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/txscript"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/waddrmgr"
)
// BlockFilterer is used to iteratively scan blocks for a set of addresses of
@@ -31,26 +31,18 @@ type BlockFilterer struct {
// Params specifies the chain params of the current network.
Params *chaincfg.Params
// ExReverseFilter holds a reverse index mapping an external address to
// ReverseFilter holds a reverse index mapping an external address to
// the scoped index from which it was derived.
ExReverseFilter map[string]waddrmgr.ScopedIndex
// InReverseFilter holds a reverse index mapping an internal address to
// the scoped index from which it was derived.
InReverseFilter map[string]waddrmgr.ScopedIndex
ReverseFilter map[string]waddrmgr.ScopedIndex
// WathcedOutPoints is a global set of outpoints being tracked by the
// wallet. This allows the block filterer to check for spends from an
// outpoint we own.
WatchedOutPoints map[wire.OutPoint]btcutil.Address
// FoundExternal is a two-layer map recording the scope and index of
// FoundAddresses is a two-layer map recording the scope and index of
// external addresses found in a single block.
FoundExternal map[waddrmgr.KeyScope]map[uint32]struct{}
// FoundInternal is a two-layer map recording the scope and index of
// internal addresses found in a single block.
FoundInternal map[waddrmgr.KeyScope]map[uint32]struct{}
FoundAddresses map[waddrmgr.ScopedIndex]struct{}
// FoundOutPoints is a set of outpoints found in a single block whose
// address belongs to the wallet.
@@ -71,31 +63,20 @@ func NewBlockFilterer(params *chaincfg.Params,
// Construct a reverse index by address string for the requested
// external addresses.
nExAddrs := len(req.ExternalAddrs)
exReverseFilter := make(map[string]waddrmgr.ScopedIndex, nExAddrs)
for scopedIndex, addr := range req.ExternalAddrs {
exReverseFilter[addr.EncodeAddress()] = scopedIndex
nAddrs := len(req.Addresses)
reverseFilter := make(map[string]waddrmgr.ScopedIndex, nAddrs)
for scopedIndex, addr := range req.Addresses {
reverseFilter[addr.EncodeAddress()] = scopedIndex
}
// Construct a reverse index by address string for the requested
// internal addresses.
nInAddrs := len(req.InternalAddrs)
inReverseFilter := make(map[string]waddrmgr.ScopedIndex, nInAddrs)
for scopedIndex, addr := range req.InternalAddrs {
inReverseFilter[addr.EncodeAddress()] = scopedIndex
}
foundExternal := make(map[waddrmgr.KeyScope]map[uint32]struct{})
foundInternal := make(map[waddrmgr.KeyScope]map[uint32]struct{})
foundAddresses := make(map[waddrmgr.ScopedIndex]struct{})
foundOutPoints := make(map[wire.OutPoint]btcutil.Address)
return &BlockFilterer{
Params: params,
ExReverseFilter: exReverseFilter,
InReverseFilter: inReverseFilter,
ReverseFilter: reverseFilter,
WatchedOutPoints: req.WatchedOutPoints,
FoundExternal: foundExternal,
FoundInternal: foundInternal,
FoundAddresses: foundAddresses,
FoundOutPoints: foundOutPoints,
}
}
@@ -183,12 +164,8 @@ func (bf *BlockFilterer) FilterOutputAddrs(addrs []btcutil.Address) bool {
var isRelevant bool
for _, addr := range addrs {
addrStr := addr.EncodeAddress()
if scopedIndex, ok := bf.ExReverseFilter[addrStr]; ok {
bf.foundExternal(scopedIndex)
isRelevant = true
}
if scopedIndex, ok := bf.InReverseFilter[addrStr]; ok {
bf.foundInternal(scopedIndex)
if scopedIndex, ok := bf.ReverseFilter[addrStr]; ok {
bf.found(scopedIndex)
isRelevant = true
}
}
@@ -196,22 +173,9 @@ func (bf *BlockFilterer) FilterOutputAddrs(addrs []btcutil.Address) bool {
return isRelevant
}
// foundExternal marks the scoped index as found within the block filterer's
// found marks the scoped index as found within the block filterer's
// FoundExternal map. If this the first index found for a particular scope, the
// scope's second layer map will be initialized before marking the index.
func (bf *BlockFilterer) foundExternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundExternal[scopedIndex.Scope]; !ok {
bf.FoundExternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundExternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
}
// foundInternal marks the scoped index as found within the block filterer's
// FoundInternal map. If this the first index found for a particular scope, the
// scope's second layer map will be initialized before marking the index.
func (bf *BlockFilterer) foundInternal(scopedIndex waddrmgr.ScopedIndex) {
if _, ok := bf.FoundInternal[scopedIndex.Scope]; !ok {
bf.FoundInternal[scopedIndex.Scope] = make(map[uint32]struct{})
}
bf.FoundInternal[scopedIndex.Scope][scopedIndex.Index] = struct{}{}
func (bf *BlockFilterer) found(scopedIndex waddrmgr.ScopedIndex) {
bf.FoundAddresses[scopedIndex] = struct{}{}
}
+6 -6
View File
@@ -5,11 +5,11 @@ import (
"testing"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/chain"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/chain"
)
var Block100000 = wire.MsgBlock{
@@ -282,7 +282,7 @@ func TestBlockFiltererOneInOneOut(t *testing.T) {
req := &chain.FilterBlocksRequest{
WatchedOutPoints: watchedOutPoints,
}
blockFilterer := chain.NewBlockFilterer(&chaincfg.SimNetParams, req)
blockFilterer := chain.NewBlockFilterer(&chaincfg.RegressionNetParams, req)
// Filter block 100000, which should find matches for the watched
// outpoints.
+16 -17
View File
@@ -3,11 +3,11 @@ package chain
import (
"time"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/wtxmgr"
)
// isCurrentDelta is the delta duration we'll use from the present time to
@@ -19,14 +19,15 @@ const isCurrentDelta = 2 * time.Hour
// TODO: Refactor each into a driver and use dynamic registration.
func BackEnds() []string {
return []string{
"bitcoind",
"btcd",
"neutrino",
"lbrycrd",
"lbcd",
}
}
// Interface allows more than one backing blockchain source, such as a
// btcd RPC chain server, or an SPV library, as long as we write a driver for
//
// RPC chain server, or an SPV library, as long as we write a driver for
//
// it.
type Interface interface {
Start() error
@@ -74,8 +75,7 @@ type (
// is also included to monitor for spends.
FilterBlocksRequest struct {
Blocks []wtxmgr.BlockMeta
ExternalAddrs map[waddrmgr.ScopedIndex]btcutil.Address
InternalAddrs map[waddrmgr.ScopedIndex]btcutil.Address
Addresses map[waddrmgr.ScopedIndex]btcutil.Address
WatchedOutPoints map[wire.OutPoint]btcutil.Address
}
@@ -87,12 +87,11 @@ type (
// caller can reinitiate a request for the subsequent block after
// updating the addresses of interest.
FilterBlocksResponse struct {
BatchIndex uint32
BlockMeta wtxmgr.BlockMeta
FoundExternalAddrs map[waddrmgr.KeyScope]map[uint32]struct{}
FoundInternalAddrs map[waddrmgr.KeyScope]map[uint32]struct{}
FoundOutPoints map[wire.OutPoint]btcutil.Address
RelevantTxns []*wire.MsgTx
BatchIndex uint32
BlockMeta wtxmgr.BlockMeta
FoundAddresses map[waddrmgr.ScopedIndex]struct{}
FoundOutPoints map[wire.OutPoint]btcutil.Address
RelevantTxns []*wire.MsgTx
}
// BlockDisconnected is a notifcation that the block described by the
+3 -27
View File
@@ -4,7 +4,9 @@
package chain
import "github.com/btcsuite/btclog"
import (
"github.com/btcsuite/btclog"
)
// log is a logger that is initialized with no output filters. This
// means the package will not perform any logging by default until the caller
@@ -28,29 +30,3 @@ func DisableLog() {
func UseLogger(logger btclog.Logger) {
log = logger
}
// LogClosure is a closure that can be printed with %v to be used to
// generate expensive-to-create data for a detailed log level and avoid doing
// the work if the data isn't printed.
type logClosure func() string
// String invokes the log closure and returns the results string.
func (c logClosure) String() string {
return c()
}
// newLogClosure returns a new closure over the passed function which allows
// it to be used as a parameter in a logging function that is only invoked when
// the logging level is such that the message will actually be logged.
func newLogClosure(c func() string) logClosure {
return logClosure(c)
}
// pickNoun returns the singular or plural form of a noun depending
// on the count n.
func pickNoun(n int, singular, plural string) string {
if n == 1 {
return singular
}
return plural
}
+3 -711
View File
@@ -1,257 +1,9 @@
package chain
import (
"errors"
"fmt"
"sync"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/gcs"
"github.com/btcsuite/btcutil/gcs/builder"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/lightninglabs/neutrino"
"github.com/lightninglabs/neutrino/headerfs"
"github.com/lbryio/lbcd/txscript"
)
// NeutrinoClient is an implementation of the btcwalet chain.Interface interface.
type NeutrinoClient struct {
CS *neutrino.ChainService
chainParams *chaincfg.Params
// We currently support one rescan/notifiction goroutine per client
rescan *neutrino.Rescan
enqueueNotification chan interface{}
dequeueNotification chan interface{}
startTime time.Time
lastProgressSent bool
lastFilteredBlockHeader *wire.BlockHeader
currentBlock chan *waddrmgr.BlockStamp
quit chan struct{}
rescanQuit chan struct{}
rescanErr <-chan error
wg sync.WaitGroup
started bool
scanning bool
finished bool
isRescan bool
clientMtx sync.Mutex
}
// NewNeutrinoClient creates a new NeutrinoClient struct with a backing
// ChainService.
func NewNeutrinoClient(chainParams *chaincfg.Params,
chainService *neutrino.ChainService) *NeutrinoClient {
return &NeutrinoClient{
CS: chainService,
chainParams: chainParams,
}
}
// BackEnd returns the name of the driver.
func (s *NeutrinoClient) BackEnd() string {
return "neutrino"
}
// Start replicates the RPC client's Start method.
func (s *NeutrinoClient) Start() error {
s.CS.Start()
s.clientMtx.Lock()
defer s.clientMtx.Unlock()
if !s.started {
s.enqueueNotification = make(chan interface{})
s.dequeueNotification = make(chan interface{})
s.currentBlock = make(chan *waddrmgr.BlockStamp)
s.quit = make(chan struct{})
s.started = true
s.wg.Add(1)
go func() {
select {
case s.enqueueNotification <- ClientConnected{}:
case <-s.quit:
}
}()
go s.notificationHandler()
}
return nil
}
// Stop replicates the RPC client's Stop method.
func (s *NeutrinoClient) Stop() {
s.clientMtx.Lock()
defer s.clientMtx.Unlock()
if !s.started {
return
}
close(s.quit)
s.started = false
}
// WaitForShutdown replicates the RPC client's WaitForShutdown method.
func (s *NeutrinoClient) WaitForShutdown() {
s.wg.Wait()
}
// GetBlock replicates the RPC client's GetBlock command.
func (s *NeutrinoClient) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock, error) {
// TODO(roasbeef): add a block cache?
// * which evication strategy? depends on use case
// Should the block cache be INSIDE neutrino instead of in btcwallet?
block, err := s.CS.GetBlock(*hash)
if err != nil {
return nil, err
}
return block.MsgBlock(), nil
}
// GetBlockHeight gets the height of a block by its hash. It serves as a
// replacement for the use of GetBlockVerboseTxAsync for the wallet package
// since we can't actually return a FutureGetBlockVerboseResult because the
// underlying type is private to rpcclient.
func (s *NeutrinoClient) GetBlockHeight(hash *chainhash.Hash) (int32, error) {
return s.CS.GetBlockHeight(hash)
}
// GetBestBlock replicates the RPC client's GetBestBlock command.
func (s *NeutrinoClient) GetBestBlock() (*chainhash.Hash, int32, error) {
chainTip, err := s.CS.BestBlock()
if err != nil {
return nil, 0, err
}
return &chainTip.Hash, chainTip.Height, nil
}
// BlockStamp returns the latest block notified by the client, or an error
// if the client has been shut down.
func (s *NeutrinoClient) BlockStamp() (*waddrmgr.BlockStamp, error) {
select {
case bs := <-s.currentBlock:
return bs, nil
case <-s.quit:
return nil, errors.New("disconnected")
}
}
// GetBlockHash returns the block hash for the given height, or an error if the
// client has been shut down or the hash at the block height doesn't exist or
// is unknown.
func (s *NeutrinoClient) GetBlockHash(height int64) (*chainhash.Hash, error) {
return s.CS.GetBlockHash(height)
}
// GetBlockHeader returns the block header for the given block hash, or an error
// if the client has been shut down or the hash doesn't exist or is unknown.
func (s *NeutrinoClient) GetBlockHeader(
blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
return s.CS.GetBlockHeader(blockHash)
}
// IsCurrent returns whether the chain backend considers its view of the network
// as "current".
func (s *NeutrinoClient) IsCurrent() bool {
return s.CS.IsCurrent()
}
// SendRawTransaction replicates the RPC client's SendRawTransaction command.
func (s *NeutrinoClient) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (
*chainhash.Hash, error) {
err := s.CS.SendTransaction(tx)
if err != nil {
return nil, err
}
hash := tx.TxHash()
return &hash, nil
}
// FilterBlocks scans the blocks contained in the FilterBlocksRequest for any
// addresses of interest. For each requested block, the corresponding compact
// filter will first be checked for matches, skipping those that do not report
// anything. If the filter returns a postive match, the full block will be
// fetched and filtered. This method returns a FilterBlocksReponse for the first
// block containing a matching address. If no matches are found in the range of
// blocks requested, the returned response will be nil.
func (s *NeutrinoClient) FilterBlocks(
req *FilterBlocksRequest) (*FilterBlocksResponse, error) {
blockFilterer := NewBlockFilterer(s.chainParams, req)
// Construct the watchlist using the addresses and outpoints contained
// in the filter blocks request.
watchList, err := buildFilterBlocksWatchList(req)
if err != nil {
return nil, err
}
// Iterate over the requested blocks, fetching the compact filter for
// each one, and matching it against the watchlist generated above. If
// the filter returns a positive match, the full block is then requested
// and scanned for addresses using the block filterer.
for i, blk := range req.Blocks {
filter, err := s.pollCFilter(&blk.Hash)
if err != nil {
return nil, err
}
// Skip any empty filters.
if filter == nil || filter.N() == 0 {
continue
}
key := builder.DeriveKey(&blk.Hash)
matched, err := filter.MatchAny(key, watchList)
if err != nil {
return nil, err
} else if !matched {
continue
}
log.Infof("Fetching block height=%d hash=%v",
blk.Height, blk.Hash)
// TODO(conner): can optimize bandwidth by only fetching
// stripped blocks
rawBlock, err := s.GetBlock(&blk.Hash)
if err != nil {
return nil, err
}
if !blockFilterer.FilterBlock(rawBlock) {
continue
}
// If any external or internal addresses were detected in this
// block, we return them to the caller so that the rescan
// windows can widened with subsequent addresses. The
// `BatchIndex` is returned so that the caller can compute the
// *next* block from which to begin again.
resp := &FilterBlocksResponse{
BatchIndex: uint32(i),
BlockMeta: blk,
FoundExternalAddrs: blockFilterer.FoundExternal,
FoundInternalAddrs: blockFilterer.FoundInternal,
FoundOutPoints: blockFilterer.FoundOutPoints,
RelevantTxns: blockFilterer.RelevantTxns,
}
return resp, nil
}
// No addresses were found for this range.
return nil, nil
}
// buildFilterBlocksWatchList constructs a watchlist used for matching against a
// cfilter from a FilterBlocksRequest. The watchlist will be populated with all
// external addresses, internal addresses, and outpoints contained in the
@@ -260,22 +12,12 @@ func buildFilterBlocksWatchList(req *FilterBlocksRequest) ([][]byte, error) {
// Construct a watch list containing the script addresses of all
// internal and external addresses that were requested, in addition to
// the set of outpoints currently being watched.
watchListSize := len(req.ExternalAddrs) +
len(req.InternalAddrs) +
watchListSize := len(req.Addresses) +
len(req.WatchedOutPoints)
watchList := make([][]byte, 0, watchListSize)
for _, addr := range req.ExternalAddrs {
p2shAddr, err := txscript.PayToAddrScript(addr)
if err != nil {
return nil, err
}
watchList = append(watchList, p2shAddr)
}
for _, addr := range req.InternalAddrs {
for _, addr := range req.Addresses {
p2shAddr, err := txscript.PayToAddrScript(addr)
if err != nil {
return nil, err
@@ -295,453 +37,3 @@ func buildFilterBlocksWatchList(req *FilterBlocksRequest) ([][]byte, error) {
return watchList, nil
}
// pollCFilter attempts to fetch a CFilter from the neutrino client. This is
// used to get around the fact that the filter headers may lag behind the
// highest known block header.
func (s *NeutrinoClient) pollCFilter(hash *chainhash.Hash) (*gcs.Filter, error) {
var (
filter *gcs.Filter
err error
count int
)
const maxFilterRetries = 50
for count < maxFilterRetries {
if count > 0 {
time.Sleep(100 * time.Millisecond)
}
filter, err = s.CS.GetCFilter(*hash, wire.GCSFilterRegular)
if err != nil {
count++
continue
}
return filter, nil
}
return nil, err
}
// Rescan replicates the RPC client's Rescan command.
func (s *NeutrinoClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address,
outPoints map[wire.OutPoint]btcutil.Address) error {
s.clientMtx.Lock()
if !s.started {
s.clientMtx.Unlock()
return fmt.Errorf("can't do a rescan when the chain client " +
"is not started")
}
if s.scanning {
// Restart the rescan by killing the existing rescan.
close(s.rescanQuit)
rescan := s.rescan
s.clientMtx.Unlock()
rescan.WaitForShutdown()
s.clientMtx.Lock()
s.rescan = nil
s.rescanErr = nil
}
s.rescanQuit = make(chan struct{})
s.scanning = true
s.finished = false
s.lastProgressSent = false
s.lastFilteredBlockHeader = nil
s.isRescan = true
s.clientMtx.Unlock()
bestBlock, err := s.CS.BestBlock()
if err != nil {
return fmt.Errorf("Can't get chain service's best block: %s", err)
}
header, err := s.CS.GetBlockHeader(&bestBlock.Hash)
if err != nil {
return fmt.Errorf("Can't get block header for hash %v: %s",
bestBlock.Hash, err)
}
// If the wallet is already fully caught up, or the rescan has started
// with state that indicates a "fresh" wallet, we'll send a
// notification indicating the rescan has "finished".
if header.BlockHash() == *startHash {
s.clientMtx.Lock()
s.finished = true
rescanQuit := s.rescanQuit
s.clientMtx.Unlock()
// Release the lock while dispatching the notification since
// it's possible for the notificationHandler to be waiting to
// acquire it before receiving the notification.
select {
case s.enqueueNotification <- &RescanFinished{
Hash: startHash,
Height: int32(bestBlock.Height),
Time: header.Timestamp,
}:
case <-s.quit:
return nil
case <-rescanQuit:
return nil
}
}
var inputsToWatch []neutrino.InputWithScript
for op, addr := range outPoints {
addrScript, err := txscript.PayToAddrScript(addr)
if err != nil {
return err
}
inputsToWatch = append(inputsToWatch, neutrino.InputWithScript{
OutPoint: op,
PkScript: addrScript,
})
}
s.clientMtx.Lock()
newRescan := neutrino.NewRescan(
&neutrino.RescanChainSource{
ChainService: s.CS,
},
neutrino.NotificationHandlers(rpcclient.NotificationHandlers{
OnBlockConnected: s.onBlockConnected,
OnFilteredBlockConnected: s.onFilteredBlockConnected,
OnBlockDisconnected: s.onBlockDisconnected,
}),
neutrino.StartBlock(&headerfs.BlockStamp{Hash: *startHash}),
neutrino.StartTime(s.startTime),
neutrino.QuitChan(s.rescanQuit),
neutrino.WatchAddrs(addrs...),
neutrino.WatchInputs(inputsToWatch...),
)
s.rescan = newRescan
s.rescanErr = s.rescan.Start()
s.clientMtx.Unlock()
return nil
}
// NotifyBlocks replicates the RPC client's NotifyBlocks command.
func (s *NeutrinoClient) NotifyBlocks() error {
s.clientMtx.Lock()
// If we're scanning, we're already notifying on blocks. Otherwise,
// start a rescan without watching any addresses.
if !s.scanning {
s.clientMtx.Unlock()
return s.NotifyReceived([]btcutil.Address{})
}
s.clientMtx.Unlock()
return nil
}
// NotifyReceived replicates the RPC client's NotifyReceived command.
func (s *NeutrinoClient) NotifyReceived(addrs []btcutil.Address) error {
s.clientMtx.Lock()
// If we have a rescan running, we just need to add the appropriate
// addresses to the watch list.
if s.scanning {
s.clientMtx.Unlock()
return s.rescan.Update(neutrino.AddAddrs(addrs...))
}
s.rescanQuit = make(chan struct{})
s.scanning = true
// Don't need RescanFinished or RescanProgress notifications.
s.finished = true
s.lastProgressSent = true
s.lastFilteredBlockHeader = nil
// Rescan with just the specified addresses.
newRescan := neutrino.NewRescan(
&neutrino.RescanChainSource{
ChainService: s.CS,
},
neutrino.NotificationHandlers(rpcclient.NotificationHandlers{
OnBlockConnected: s.onBlockConnected,
OnFilteredBlockConnected: s.onFilteredBlockConnected,
OnBlockDisconnected: s.onBlockDisconnected,
}),
neutrino.StartTime(s.startTime),
neutrino.QuitChan(s.rescanQuit),
neutrino.WatchAddrs(addrs...),
)
s.rescan = newRescan
s.rescanErr = s.rescan.Start()
s.clientMtx.Unlock()
return nil
}
// Notifications replicates the RPC client's Notifications method.
func (s *NeutrinoClient) Notifications() <-chan interface{} {
return s.dequeueNotification
}
// SetStartTime is a non-interface method to set the birthday of the wallet
// using this object. Since only a single rescan at a time is currently
// supported, only one birthday needs to be set. This does not fully restart a
// running rescan, so should not be used to update a rescan while it is running.
// TODO: When factoring out to multiple rescans per Neutrino client, add a
// birthday per client.
func (s *NeutrinoClient) SetStartTime(startTime time.Time) {
s.clientMtx.Lock()
defer s.clientMtx.Unlock()
s.startTime = startTime
}
// onFilteredBlockConnected sends appropriate notifications to the notification
// channel.
func (s *NeutrinoClient) onFilteredBlockConnected(height int32,
header *wire.BlockHeader, relevantTxs []*btcutil.Tx) {
ntfn := FilteredBlockConnected{
Block: &wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Hash: header.BlockHash(),
Height: height,
},
Time: header.Timestamp,
},
}
for _, tx := range relevantTxs {
rec, err := wtxmgr.NewTxRecordFromMsgTx(tx.MsgTx(),
header.Timestamp)
if err != nil {
log.Errorf("Cannot create transaction record for "+
"relevant tx: %s", err)
// TODO(aakselrod): Return?
continue
}
ntfn.RelevantTxs = append(ntfn.RelevantTxs, rec)
}
select {
case s.enqueueNotification <- ntfn:
case <-s.quit:
return
case <-s.rescanQuit:
return
}
s.clientMtx.Lock()
s.lastFilteredBlockHeader = header
s.clientMtx.Unlock()
// Handle RescanFinished notification if required.
s.dispatchRescanFinished()
}
// onBlockDisconnected sends appropriate notifications to the notification
// channel.
func (s *NeutrinoClient) onBlockDisconnected(hash *chainhash.Hash, height int32,
t time.Time) {
select {
case s.enqueueNotification <- BlockDisconnected{
Block: wtxmgr.Block{
Hash: *hash,
Height: height,
},
Time: t,
}:
case <-s.quit:
case <-s.rescanQuit:
}
}
func (s *NeutrinoClient) onBlockConnected(hash *chainhash.Hash, height int32,
time time.Time) {
// TODO: Move this closure out and parameterize it? Is it useful
// outside here?
sendRescanProgress := func() {
select {
case s.enqueueNotification <- &RescanProgress{
Hash: hash,
Height: height,
Time: time,
}:
case <-s.quit:
case <-s.rescanQuit:
}
}
// Only send BlockConnected notification if we're processing blocks
// before the birthday. Otherwise, we can just update using
// RescanProgress notifications.
if time.Before(s.startTime) {
// Send a RescanProgress notification every 10K blocks.
if height%10000 == 0 {
s.clientMtx.Lock()
shouldSend := s.isRescan && !s.finished
s.clientMtx.Unlock()
if shouldSend {
sendRescanProgress()
}
}
} else {
// Send a RescanProgress notification if we're just going over
// the boundary between pre-birthday and post-birthday blocks,
// and note that we've sent it.
s.clientMtx.Lock()
if !s.lastProgressSent {
shouldSend := s.isRescan && !s.finished
if shouldSend {
s.clientMtx.Unlock()
sendRescanProgress()
s.clientMtx.Lock()
s.lastProgressSent = true
}
}
s.clientMtx.Unlock()
select {
case s.enqueueNotification <- BlockConnected{
Block: wtxmgr.Block{
Hash: *hash,
Height: height,
},
Time: time,
}:
case <-s.quit:
case <-s.rescanQuit:
}
}
// Check if we're able to dispatch our final RescanFinished notification
// after processing this block.
s.dispatchRescanFinished()
}
// dispatchRescanFinished determines whether we're able to dispatch our final
// RescanFinished notification in order to mark the wallet as synced with the
// chain. If the notification has already been dispatched, then it won't be done
// again.
func (s *NeutrinoClient) dispatchRescanFinished() {
bs, err := s.CS.BestBlock()
if err != nil {
log.Errorf("Can't get chain service's best block: %s", err)
return
}
s.clientMtx.Lock()
// Only send the RescanFinished notification once.
if s.lastFilteredBlockHeader == nil || s.finished {
s.clientMtx.Unlock()
return
}
// Only send the RescanFinished notification once the underlying chain
// service sees itself as current.
if bs.Hash != s.lastFilteredBlockHeader.BlockHash() {
s.clientMtx.Unlock()
return
}
s.finished = s.CS.IsCurrent() && s.lastProgressSent
if !s.finished {
s.clientMtx.Unlock()
return
}
header := s.lastFilteredBlockHeader
s.clientMtx.Unlock()
select {
case s.enqueueNotification <- &RescanFinished{
Hash: &bs.Hash,
Height: bs.Height,
Time: header.Timestamp,
}:
case <-s.quit:
return
case <-s.rescanQuit:
return
}
}
// notificationHandler queues and dequeues notifications. There are currently
// no bounds on the queue, so the dequeue channel should be read continually to
// avoid running out of memory.
func (s *NeutrinoClient) notificationHandler() {
hash, height, err := s.GetBestBlock()
if err != nil {
log.Errorf("Failed to get best block from chain service: %s",
err)
s.Stop()
s.wg.Done()
return
}
bs := &waddrmgr.BlockStamp{Hash: *hash, Height: height}
// TODO: Rather than leaving this as an unbounded queue for all types of
// notifications, try dropping ones where a later enqueued notification
// can fully invalidate one waiting to be processed. For example,
// blockconnected notifications for greater block heights can remove the
// need to process earlier blockconnected notifications still waiting
// here.
var notifications []interface{}
enqueue := s.enqueueNotification
var dequeue chan interface{}
var next interface{}
out:
for {
s.clientMtx.Lock()
rescanErr := s.rescanErr
s.clientMtx.Unlock()
select {
case n, ok := <-enqueue:
if !ok {
// If no notifications are queued for handling,
// the queue is finished.
if len(notifications) == 0 {
break out
}
// nil channel so no more reads can occur.
enqueue = nil
continue
}
if len(notifications) == 0 {
next = n
dequeue = s.dequeueNotification
}
notifications = append(notifications, n)
case dequeue <- next:
if n, ok := next.(BlockConnected); ok {
bs = &waddrmgr.BlockStamp{
Height: n.Height,
Hash: n.Hash,
}
}
notifications[0] = nil
notifications = notifications[1:]
if len(notifications) != 0 {
next = notifications[0]
} else {
// If no more notifications can be enqueued, the
// queue is finished.
if enqueue == nil {
break out
}
dequeue = nil
}
case err := <-rescanErr:
if err != nil {
log.Errorf("Neutrino rescan ended with error: %s", err)
}
case s.currentBlock <- bs:
case <-s.quit:
break out
}
}
s.Stop()
close(s.dequeueNotification)
s.wg.Done()
}
+25 -23
View File
@@ -9,16 +9,16 @@ import (
"sync"
"time"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/gcs"
"github.com/btcsuite/btcutil/gcs/builder"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/lbryio/lbcd/btcjson"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/rpcclient"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcutil/gcs"
"github.com/lbryio/lbcutil/gcs/builder"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/wtxmgr"
)
// RPCClient represents a persistent client connection to a bitcoin RPC server
@@ -46,7 +46,7 @@ type RPCClient struct {
// operate on the same bitcoin network as described by the passed chain
// parameters, the connection will be disconnected.
func NewRPCClient(chainParams *chaincfg.Params, connect, user, pass string, certs []byte,
disableTLS bool, reconnectAttempts int) (*RPCClient, error) {
disableTLS bool, skipverify bool, reconnectAttempts int) (*RPCClient, error) {
if reconnectAttempts < 0 {
return nil, errors.New("reconnectAttempts must be positive")
@@ -62,6 +62,7 @@ func NewRPCClient(chainParams *chaincfg.Params, connect, user, pass string, cert
DisableAutoReconnect: false,
DisableConnectOnNew: true,
DisableTLS: disableTLS,
SkipVerify: skipverify,
},
chainParams: chainParams,
reconnectAttempts: reconnectAttempts,
@@ -89,7 +90,7 @@ func NewRPCClient(chainParams *chaincfg.Params, connect, user, pass string, cert
// BackEnd returns the name of the driver.
func (c *RPCClient) BackEnd() string {
return "btcd"
return "lbcd"
}
// Start attempts to establish a client connection with the remote server.
@@ -154,8 +155,8 @@ func (c *RPCClient) IsCurrent() bool {
return bestHeader.Timestamp.After(time.Now().Add(-isCurrentDelta))
}
// Rescan wraps the normal Rescan command with an additional paramter that
// allows us to map an oupoint to the address in the chain that it pays to.
// Rescan wraps the normal Rescan command with an additional parameter that
// allows us to map an outpoint to the address in the chain that it pays to.
// This is useful when using BIP 158 filters as they include the prev pkScript
// rather than the full outpoint.
func (c *RPCClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address,
@@ -163,10 +164,12 @@ func (c *RPCClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address,
flatOutpoints := make([]*wire.OutPoint, 0, len(outPoints))
for ops := range outPoints {
ops := ops
flatOutpoints = append(flatOutpoints, &ops)
}
return c.Client.Rescan(startHash, addrs, flatOutpoints)
return c.Client.Rescan(startHash, addrs, flatOutpoints) // nolint:staticcheck
}
// WaitForShutdown blocks until both the client has finished disconnecting
@@ -198,8 +201,8 @@ func (c *RPCClient) BlockStamp() (*waddrmgr.BlockStamp, error) {
// FilterBlocks scans the blocks contained in the FilterBlocksRequest for any
// addresses of interest. For each requested block, the corresponding compact
// filter will first be checked for matches, skipping those that do not report
// anything. If the filter returns a postive match, the full block will be
// fetched and filtered. This method returns a FilterBlocksReponse for the first
// anything. If the filter returns a positive match, the full block will be
// fetched and filtered. This method returns a FilterBlocksResponse for the first
// block containing a matching address. If no matches are found in the range of
// blocks requested, the returned response will be nil.
func (c *RPCClient) FilterBlocks(
@@ -267,12 +270,11 @@ func (c *RPCClient) FilterBlocks(
// `BatchIndex` is returned so that the caller can compute the
// *next* block from which to begin again.
resp := &FilterBlocksResponse{
BatchIndex: uint32(i),
BlockMeta: blk,
FoundExternalAddrs: blockFilterer.FoundExternal,
FoundInternalAddrs: blockFilterer.FoundInternal,
FoundOutPoints: blockFilterer.FoundOutPoints,
RelevantTxns: blockFilterer.RelevantTxns,
BatchIndex: uint32(i),
BlockMeta: blk,
FoundAddresses: blockFilterer.FoundAddresses,
FoundOutPoints: blockFilterer.FoundOutPoints,
RelevantTxns: blockFilterer.RelevantTxns,
}
return resp, nil
+234
View File
@@ -0,0 +1,234 @@
package chain
import (
"fmt"
"io"
"math"
"net"
"runtime"
"sync"
"time"
"github.com/lbryio/lbcd/blockchain"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
)
var chainParams = chaincfg.RegressionNetParams
// conn mocks a network connection by implementing the net.Conn interface. It is
// used to test peer connection without actually opening a network connection.
type conn struct {
io.Reader
io.Writer
io.Closer
localAddr string
remoteAddr string
}
func (c conn) LocalAddr() net.Addr {
return &addr{"tcp", c.localAddr}
}
func (c conn) RemoteAddr() net.Addr {
return &addr{"tcp", c.remoteAddr}
}
func (c conn) SetDeadline(t time.Time) error { return nil }
func (c conn) SetReadDeadline(t time.Time) error { return nil }
func (c conn) SetWriteDeadline(t time.Time) error { return nil }
// addr mocks a network address.
type addr struct {
net, address string
}
func (m addr) Network() string { return m.net }
func (m addr) String() string { return m.address }
// pipe turns two mock connections into a full-duplex connection similar to
// net.Pipe to allow pipe's with (fake) addresses.
func pipe(c1, c2 *conn) (*conn, *conn) {
r1, w1 := io.Pipe()
r2, w2 := io.Pipe()
c1.Writer = w1
c1.Closer = w1
c2.Reader = r1
c1.Reader = r2
c2.Writer = w2
c2.Closer = w2
return c1, c2
}
// calcMerkleRoot creates a merkle tree from the slice of transactions and
// returns the root of the tree.
//
// This function was copied from:
//
// https://github.com/lbryio/lbcd/blob/36a96f6a0025b6aeaebe4106821c2d46ee4be8d4/blockchain/fullblocktests/generate.go#L303
func calcMerkleRoot(txns []*wire.MsgTx) chainhash.Hash {
if len(txns) == 0 {
return chainhash.Hash{}
}
utilTxns := make([]*btcutil.Tx, 0, len(txns))
for _, tx := range txns {
utilTxns = append(utilTxns, btcutil.NewTx(tx))
}
merkles := blockchain.BuildMerkleTreeStore(utilTxns, false)
return *merkles[len(merkles)-1]
}
// solveBlock attempts to find a nonce which makes the passed block header hash
// to a value less than the target difficulty. When a successful solution is
// found true is returned and the nonce field of the passed header is updated
// with the solution. False is returned if no solution exists.
//
// This function was copied from:
//
// https://github.com/lbryio/lbcd/blob/36a96f6a0025b6aeaebe4106821c2d46ee4be8d4/blockchain/fullblocktests/generate.go#L324
func solveBlock(header *wire.BlockHeader) bool {
// sbResult is used by the solver goroutines to send results.
type sbResult struct {
found bool
nonce uint32
}
// Make sure all spawned goroutines finish executing before returning.
var wg sync.WaitGroup
defer func() {
wg.Wait()
}()
// solver accepts a block header and a nonce range to test. It is
// intended to be run as a goroutine.
targetDifficulty := blockchain.CompactToBig(header.Bits)
quit := make(chan bool)
results := make(chan sbResult)
solver := func(hdr wire.BlockHeader, startNonce, stopNonce uint32) {
defer wg.Done()
// We need to modify the nonce field of the header, so make sure
// we work with a copy of the original header.
for i := startNonce; i >= startNonce && i <= stopNonce; i++ {
select {
case <-quit:
return
default:
hdr.Nonce = i
hash := hdr.BlockHash()
if blockchain.HashToBig(&hash).Cmp(
targetDifficulty) <= 0 {
select {
case results <- sbResult{true, i}:
case <-quit:
}
return
}
}
}
select {
case results <- sbResult{false, 0}:
case <-quit:
}
}
startNonce := uint32(1)
stopNonce := uint32(math.MaxUint32)
numCores := uint32(runtime.NumCPU())
noncesPerCore := (stopNonce - startNonce) / numCores
wg.Add(int(numCores))
for i := uint32(0); i < numCores; i++ {
rangeStart := startNonce + (noncesPerCore * i)
rangeStop := startNonce + (noncesPerCore * (i + 1)) - 1
if i == numCores-1 {
rangeStop = stopNonce
}
go solver(*header, rangeStart, rangeStop)
}
for i := uint32(0); i < numCores; i++ {
result := <-results
if result.found {
close(quit)
header.Nonce = result.nonce
return true
}
}
return false
}
// genBlockChain generates a test chain with the given number of blocks.
func genBlockChain(numBlocks uint32) ([]*chainhash.Hash, map[chainhash.Hash]*wire.MsgBlock) {
prevHash := chainParams.GenesisHash
prevHeader := &chainParams.GenesisBlock.Header
hashes := make([]*chainhash.Hash, numBlocks)
blocks := make(map[chainhash.Hash]*wire.MsgBlock, numBlocks)
// Each block contains three transactions, including the coinbase
// transaction. Each non-coinbase transaction spends outputs from
// the previous block. We also need to produce blocks that succeed
// validation through blockchain.CheckBlockSanity.
script := []byte{0x01, 0x01}
createTx := func(prevOut wire.OutPoint) *wire.MsgTx {
return &wire.MsgTx{
TxIn: []*wire.TxIn{{
PreviousOutPoint: prevOut,
SignatureScript: script,
}},
TxOut: []*wire.TxOut{{PkScript: script}},
}
}
for i := uint32(0); i < numBlocks; i++ {
txs := []*wire.MsgTx{
createTx(wire.OutPoint{Index: wire.MaxPrevOutIndex}),
createTx(wire.OutPoint{Hash: *prevHash, Index: 0}),
createTx(wire.OutPoint{Hash: *prevHash, Index: 1}),
}
header := &wire.BlockHeader{
Version: 1,
PrevBlock: *prevHash,
MerkleRoot: calcMerkleRoot(txs),
Timestamp: prevHeader.Timestamp.Add(10 * time.Minute),
Bits: chainParams.PowLimitBits,
Nonce: 0,
}
if !solveBlock(header) {
panic(fmt.Sprintf("could not solve block at idx %v", i))
}
block := &wire.MsgBlock{
Header: *header,
Transactions: txs,
}
blockHash := block.BlockHash()
hashes[i] = &blockHash
blocks[blockHash] = block
prevHash = &blockHash
prevHeader = header
}
return hashes, blocks
}
// producesInvalidBlock produces a copy of the block that duplicates the last
// transaction. When the block has an odd number of transactions, this results
// in the invalid block maintaining the same hash as the valid block.
func produceInvalidBlock(block *wire.MsgBlock) *wire.MsgBlock {
numTxs := len(block.Transactions)
lastTx := block.Transactions[numTxs-1]
blockCopy := &wire.MsgBlock{
Header: block.Header,
Transactions: make([]*wire.MsgTx, numTxs),
}
copy(blockCopy.Transactions, block.Transactions)
blockCopy.AddTransaction(lastTx)
return blockCopy
}
-156
View File
@@ -1,156 +0,0 @@
// Copyright (c) 2015-2016 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 (
"bufio"
"fmt"
"os"
"path/filepath"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/walletdb"
_ "github.com/btcsuite/btcwallet/walletdb/bdb"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/jessevdk/go-flags"
)
const defaultNet = "mainnet"
var datadir = btcutil.AppDataDir("btcwallet", false)
// Flags.
var opts = struct {
Force bool `short:"f" description:"Force removal without prompt"`
DbPath string `long:"db" description:"Path to wallet database"`
}{
Force: false,
DbPath: filepath.Join(datadir, defaultNet, "wallet.db"),
}
func init() {
_, err := flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
}
var (
// Namespace keys.
waddrmgrNamespace = []byte("waddrmgr")
wtxmgrNamespace = []byte("wtxmgr")
)
func yes(s string) bool {
switch s {
case "y", "Y", "yes", "Yes":
return true
default:
return false
}
}
func no(s string) bool {
switch s {
case "n", "N", "no", "No":
return true
default:
return false
}
}
func main() {
os.Exit(mainInt())
}
func mainInt() int {
fmt.Println("Database path:", opts.DbPath)
_, err := os.Stat(opts.DbPath)
if os.IsNotExist(err) {
fmt.Println("Database file does not exist")
return 1
}
for !opts.Force {
fmt.Print("Drop all btcwallet transaction history? [y/N] ")
scanner := bufio.NewScanner(bufio.NewReader(os.Stdin))
if !scanner.Scan() {
// Exit on EOF.
return 0
}
err := scanner.Err()
if err != nil {
fmt.Println()
fmt.Println(err)
return 1
}
resp := scanner.Text()
if yes(resp) {
break
}
if no(resp) || resp == "" {
return 0
}
fmt.Println("Enter yes or no.")
}
db, err := walletdb.Open("bdb", opts.DbPath, true)
if err != nil {
fmt.Println("Failed to open database:", err)
return 1
}
defer db.Close()
fmt.Println("Dropping btcwallet transaction history")
err = walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
err := tx.DeleteTopLevelBucket(wtxmgrNamespace)
if err != nil && err != walletdb.ErrBucketNotFound {
return err
}
ns, err := tx.CreateTopLevelBucket(wtxmgrNamespace)
if err != nil {
return err
}
err = wtxmgr.Create(ns)
if err != nil {
return err
}
ns = tx.ReadWriteBucket(waddrmgrNamespace)
birthdayBlock, err := waddrmgr.FetchBirthdayBlock(ns)
if err != nil {
fmt.Println("Wallet does not have a birthday block " +
"set, falling back to rescan from genesis")
startBlock, err := waddrmgr.FetchStartBlock(ns)
if err != nil {
return err
}
return waddrmgr.PutSyncedTo(ns, startBlock)
}
// We'll need to remove our birthday block first because it
// serves as a barrier when updating our state to detect reorgs
// due to the wallet not storing all block hashes of the chain.
if err := waddrmgr.DeleteBirthdayBlock(ns); err != nil {
return err
}
if err := waddrmgr.PutSyncedTo(ns, &birthdayBlock); err != nil {
return err
}
return waddrmgr.PutBirthdayBlock(ns, birthdayBlock)
})
if err != nil {
fmt.Println("Failed to drop and re-create namespace:", err)
return 1
}
return 0
}
-352
View File
@@ -1,352 +0,0 @@
// Copyright (c) 2015-2016 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 (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"golang.org/x/crypto/ssh/terminal"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/internal/cfgutil"
"github.com/btcsuite/btcwallet/netparams"
"github.com/btcsuite/btcwallet/wallet/txauthor"
"github.com/btcsuite/btcwallet/wallet/txrules"
"github.com/jessevdk/go-flags"
)
var (
walletDataDirectory = btcutil.AppDataDir("btcwallet", false)
newlineBytes = []byte{'\n'}
)
func fatalf(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
os.Stderr.Write(newlineBytes)
os.Exit(1)
}
func errContext(err error, context string) error {
return fmt.Errorf("%s: %v", context, err)
}
// Flags.
var opts = struct {
TestNet3 bool `long:"testnet" description:"Use the test bitcoin network (version 3)"`
SimNet bool `long:"simnet" description:"Use the simulation bitcoin network"`
RPCConnect string `short:"c" long:"connect" description:"Hostname[:port] of wallet RPC server"`
RPCUsername string `short:"u" long:"rpcuser" description:"Wallet RPC username"`
RPCCertificateFile string `long:"cafile" description:"Wallet RPC TLS certificate"`
FeeRate *cfgutil.AmountFlag `long:"feerate" description:"Transaction fee per kilobyte"`
SourceAccount string `long:"sourceacct" description:"Account to sweep outputs from"`
DestinationAccount string `long:"destacct" description:"Account to send sweeped outputs to"`
RequiredConfirmations int64 `long:"minconf" description:"Required confirmations to include an output"`
}{
TestNet3: false,
SimNet: false,
RPCConnect: "localhost",
RPCUsername: "",
RPCCertificateFile: filepath.Join(walletDataDirectory, "rpc.cert"),
FeeRate: cfgutil.NewAmountFlag(txrules.DefaultRelayFeePerKb),
SourceAccount: "imported",
DestinationAccount: "default",
RequiredConfirmations: 1,
}
// Parse and validate flags.
func init() {
// Unset localhost defaults if certificate file can not be found.
certFileExists, err := cfgutil.FileExists(opts.RPCCertificateFile)
if err != nil {
fatalf("%v", err)
}
if !certFileExists {
opts.RPCConnect = ""
opts.RPCCertificateFile = ""
}
_, err = flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
if opts.TestNet3 && opts.SimNet {
fatalf("Multiple bitcoin networks may not be used simultaneously")
}
var activeNet = &netparams.MainNetParams
if opts.TestNet3 {
activeNet = &netparams.TestNet3Params
} else if opts.SimNet {
activeNet = &netparams.SimNetParams
}
if opts.RPCConnect == "" {
fatalf("RPC hostname[:port] is required")
}
rpcConnect, err := cfgutil.NormalizeAddress(opts.RPCConnect, activeNet.RPCServerPort)
if err != nil {
fatalf("Invalid RPC network address `%v`: %v", opts.RPCConnect, err)
}
opts.RPCConnect = rpcConnect
if opts.RPCUsername == "" {
fatalf("RPC username is required")
}
certFileExists, err = cfgutil.FileExists(opts.RPCCertificateFile)
if err != nil {
fatalf("%v", err)
}
if !certFileExists {
fatalf("RPC certificate file `%s` not found", opts.RPCCertificateFile)
}
if opts.FeeRate.Amount > 1e6 {
fatalf("Fee rate `%v/kB` is exceptionally high", opts.FeeRate.Amount)
}
if opts.FeeRate.Amount < 1e2 {
fatalf("Fee rate `%v/kB` is exceptionally low", opts.FeeRate.Amount)
}
if opts.SourceAccount == opts.DestinationAccount {
fatalf("Source and destination accounts should not be equal")
}
if opts.RequiredConfirmations < 0 {
fatalf("Required confirmations must be non-negative")
}
}
// noInputValue describes an error returned by the input source when no inputs
// were selected because each previous output value was zero. Callers of
// txauthor.NewUnsignedTransaction need not report these errors to the user.
type noInputValue struct {
}
func (noInputValue) Error() string { return "no input value" }
// makeInputSource creates an InputSource that creates inputs for every unspent
// output with non-zero output values. The target amount is ignored since every
// output is consumed. The InputSource does not return any previous output
// scripts as they are not needed for creating the unsinged transaction and are
// looked up again by the wallet during the call to signrawtransaction.
func makeInputSource(outputs []btcjson.ListUnspentResult) txauthor.InputSource {
var (
totalInputValue btcutil.Amount
inputs = make([]*wire.TxIn, 0, len(outputs))
inputValues = make([]btcutil.Amount, 0, len(outputs))
sourceErr error
)
for _, output := range outputs {
outputAmount, err := btcutil.NewAmount(output.Amount)
if err != nil {
sourceErr = fmt.Errorf(
"invalid amount `%v` in listunspent result",
output.Amount)
break
}
if outputAmount == 0 {
continue
}
if !saneOutputValue(outputAmount) {
sourceErr = fmt.Errorf(
"impossible output amount `%v` in listunspent result",
outputAmount)
break
}
totalInputValue += outputAmount
previousOutPoint, err := parseOutPoint(&output)
if err != nil {
sourceErr = fmt.Errorf(
"invalid data in listunspent result: %v",
err)
break
}
inputs = append(inputs, wire.NewTxIn(&previousOutPoint, nil, nil))
inputValues = append(inputValues, outputAmount)
}
if sourceErr == nil && totalInputValue == 0 {
sourceErr = noInputValue{}
}
return func(btcutil.Amount) (btcutil.Amount, []*wire.TxIn, []btcutil.Amount, [][]byte, error) {
return totalInputValue, inputs, inputValues, nil, sourceErr
}
}
// makeDestinationScriptSource creates a ChangeSource which is used to receive
// all correlated previous input value. A non-change address is created by this
// function.
func makeDestinationScriptSource(rpcClient *rpcclient.Client, accountName string) txauthor.ChangeSource {
return func() ([]byte, error) {
destinationAddress, err := rpcClient.GetNewAddress(accountName)
if err != nil {
return nil, err
}
return txscript.PayToAddrScript(destinationAddress)
}
}
func main() {
err := sweep()
if err != nil {
fatalf("%v", err)
}
}
func sweep() error {
rpcPassword, err := promptSecret("Wallet RPC password")
if err != nil {
return errContext(err, "failed to read RPC password")
}
// Open RPC client.
rpcCertificate, err := ioutil.ReadFile(opts.RPCCertificateFile)
if err != nil {
return errContext(err, "failed to read RPC certificate")
}
rpcClient, err := rpcclient.New(&rpcclient.ConnConfig{
Host: opts.RPCConnect,
User: opts.RPCUsername,
Pass: rpcPassword,
Certificates: rpcCertificate,
HTTPPostMode: true,
}, nil)
if err != nil {
return errContext(err, "failed to create RPC client")
}
defer rpcClient.Shutdown()
// Fetch all unspent outputs, ignore those not from the source
// account, and group by their destination address. Each grouping of
// outputs will be used as inputs for a single transaction sending to a
// new destination account address.
unspentOutputs, err := rpcClient.ListUnspent()
if err != nil {
return errContext(err, "failed to fetch unspent outputs")
}
sourceOutputs := make(map[string][]btcjson.ListUnspentResult)
for _, unspentOutput := range unspentOutputs {
if !unspentOutput.Spendable {
continue
}
if unspentOutput.Confirmations < opts.RequiredConfirmations {
continue
}
if unspentOutput.Account != opts.SourceAccount {
continue
}
sourceAddressOutputs := sourceOutputs[unspentOutput.Address]
sourceOutputs[unspentOutput.Address] = append(sourceAddressOutputs, unspentOutput)
}
var privatePassphrase string
if len(sourceOutputs) != 0 {
privatePassphrase, err = promptSecret("Wallet private passphrase")
if err != nil {
return errContext(err, "failed to read private passphrase")
}
}
var totalSwept btcutil.Amount
var numErrors int
var reportError = func(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
os.Stderr.Write(newlineBytes)
numErrors++
}
for _, previousOutputs := range sourceOutputs {
inputSource := makeInputSource(previousOutputs)
destinationSource := makeDestinationScriptSource(rpcClient, opts.DestinationAccount)
tx, err := txauthor.NewUnsignedTransaction(nil, opts.FeeRate.Amount,
inputSource, destinationSource)
if err != nil {
if err != (noInputValue{}) {
reportError("Failed to create unsigned transaction: %v", err)
}
continue
}
// Unlock the wallet, sign the transaction, and immediately lock.
err = rpcClient.WalletPassphrase(privatePassphrase, 60)
if err != nil {
reportError("Failed to unlock wallet: %v", err)
continue
}
signedTransaction, complete, err := rpcClient.SignRawTransaction(tx.Tx)
_ = rpcClient.WalletLock()
if err != nil {
reportError("Failed to sign transaction: %v", err)
continue
}
if !complete {
reportError("Failed to sign every input")
continue
}
// Publish the signed sweep transaction.
txHash, err := rpcClient.SendRawTransaction(signedTransaction, false)
if err != nil {
reportError("Failed to publish transaction: %v", err)
continue
}
outputAmount := btcutil.Amount(tx.Tx.TxOut[0].Value)
fmt.Printf("Swept %v to destination account with transaction %v\n",
outputAmount, txHash)
totalSwept += outputAmount
}
numPublished := len(sourceOutputs) - numErrors
transactionNoun := pickNoun(numErrors, "transaction", "transactions")
if numPublished != 0 {
fmt.Printf("Swept %v to destination account across %d %s\n",
totalSwept, numPublished, transactionNoun)
}
if numErrors > 0 {
return fmt.Errorf("Failed to publish %d %s", numErrors, transactionNoun)
}
return nil
}
func promptSecret(what string) (string, error) {
fmt.Printf("%s: ", what)
fd := int(os.Stdin.Fd())
input, err := terminal.ReadPassword(fd)
fmt.Println()
if err != nil {
return "", err
}
return string(input), nil
}
func saneOutputValue(amount btcutil.Amount) bool {
return amount >= 0 && amount <= btcutil.MaxSatoshi
}
func parseOutPoint(input *btcjson.ListUnspentResult) (wire.OutPoint, error) {
txHash, err := chainhash.NewHashFromStr(input.TxID)
if err != nil {
return wire.OutPoint{}, err
}
return wire.OutPoint{Hash: *txHash, Index: input.Vout}, nil
}
func pickNoun(n int, singularForm, pluralForm string) string {
if n == 1 {
return singularForm
}
return pluralForm
}
+107 -220
View File
@@ -15,30 +15,28 @@ import (
"strings"
"time"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/internal/cfgutil"
"github.com/btcsuite/btcwallet/internal/legacy/keystore"
"github.com/btcsuite/btcwallet/netparams"
"github.com/btcsuite/btcwallet/wallet"
flags "github.com/jessevdk/go-flags"
"github.com/lightninglabs/neutrino"
"github.com/lbryio/lbcd/version"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/internal/cfgutil"
"github.com/lbryio/lbcwallet/netparams"
"github.com/lbryio/lbcwallet/wallet"
)
const (
defaultCAFilename = "btcd.cert"
defaultConfigFilename = "btcwallet.conf"
defaultCAFilename = "lbcd.cert"
defaultConfigFilename = "lbcwallet.conf"
defaultLogLevel = "info"
defaultLogDirname = "logs"
defaultLogFilename = "btcwallet.log"
defaultLogFilename = "lbcwallet.log"
defaultRPCMaxClients = 10
defaultRPCMaxWebsockets = 25
walletDbName = "wallet.db"
defaultPassphrase = "password"
)
var (
btcdDefaultCAFile = filepath.Join(btcutil.AppDataDir("btcd", false), "rpc.cert")
defaultAppDataDir = btcutil.AppDataDir("btcwallet", false)
lbcdDefaultCAFile = filepath.Join(btcutil.AppDataDir("lbcd", false), "rpc.cert")
defaultAppDataDir = btcutil.AppDataDir("lbcwallet", false)
defaultConfigFile = filepath.Join(defaultAppDataDir, defaultConfigFilename)
defaultRPCKeyFile = filepath.Join(defaultAppDataDir, "rpc.key")
defaultRPCCertFile = filepath.Join(defaultAppDataDir, "rpc.cert")
@@ -47,62 +45,40 @@ var (
type config struct {
// General application behavior
ConfigFile *cfgutil.ExplicitString `short:"C" long:"configfile" description:"Path to configuration file"`
ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
Create bool `long:"create" description:"Create the wallet if it does not exist"`
CreateTemp bool `long:"createtemp" description:"Create a temporary simulation wallet (pass=password) in the data directory indicated; must call with --datadir"`
AppDataDir *cfgutil.ExplicitString `short:"A" long:"appdata" description:"Application data directory for wallet config, databases and logs"`
TestNet3 bool `long:"testnet" description:"Use the test Bitcoin network (version 3) (default mainnet)"`
SimNet bool `long:"simnet" description:"Use the simulation test network (default mainnet)"`
NoInitialLoad bool `long:"noinitialload" description:"Defer wallet creation/opening on startup and enable loading wallets over RPC"`
DebugLevel string `short:"d" long:"debuglevel" description:"Logging level {trace, debug, info, warn, error, critical}"`
LogDir string `long:"logdir" description:"Directory to log output."`
Profile string `long:"profile" description:"Enable HTTP profiling on given port -- NOTE port must be between 1024 and 65536"`
ConfigFile *cfgutil.ExplicitString `short:"C" long:"configfile" description:"Path to configuration file"`
ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
Create bool `long:"create" description:"Create the wallet if it does not exist"`
CreateTemp bool `long:"createtemp" description:"Create a temporary simulation wallet (pass=password) in the data directory indicated; must call with --datadir"`
AppDataDir *cfgutil.ExplicitString `short:"A" long:"appdata" description:"Application data directory for wallet config, databases and logs"`
TestNet3 bool `long:"testnet" description:"Use the test Bitcoin network (version 3) (default client port: 19244, server port: 19245)"`
Regtest bool `long:"regtest" description:"Use the regression test network (default client port: 29244, server port: 29245)"`
DebugLevel string `short:"d" long:"debuglevel" description:"Logging level {trace, debug, info, warn, error, critical}"`
LogDir string `long:"logdir" description:"Directory to log output."`
Profile string `long:"profile" description:"Enable HTTP profiling on given port -- NOTE port must be between 1024 and 65536"`
DBTimeout time.Duration `long:"dbtimeout" description:"The timeout value to use when opening the wallet database."`
// Wallet options
WalletPass string `long:"walletpass" default-mask:"-" description:"The public wallet password -- Only required if the wallet was created with one"`
// Passphrase options
Passphrase string `short:"p" long:"passphrase" default-mask:"-" description:"The wallet passphrase (default: \"passphrase\")"`
// RPC client options
RPCConnect string `short:"c" long:"rpcconnect" description:"Hostname/IP and port of btcd RPC server to connect to (default localhost:8334, testnet: localhost:18334, simnet: localhost:18556)"`
CAFile *cfgutil.ExplicitString `long:"cafile" description:"File containing root certificates to authenticate a TLS connections with btcd"`
DisableClientTLS bool `long:"noclienttls" description:"Disable TLS for the RPC client -- NOTE: This is only allowed if the RPC client is connecting to localhost"`
BtcdUsername string `long:"btcdusername" description:"Username for btcd authentication"`
BtcdPassword string `long:"btcdpassword" default-mask:"-" description:"Password for btcd authentication"`
RPCConnect string `short:"c" long:"rpcconnect" description:"Hostname/IP and port of lbcd RPC server to connect to (default localhost:9245, testnet: localhost:19245, regtest: localhost:29245)"`
CAFile *cfgutil.ExplicitString `long:"cafile" description:"File containing root certificates to authenticate a TLS connections with lbcd"`
DisableClientTLS bool `long:"noclienttls" description:"Disable TLS for the RPC client"`
SkipVerify bool `long:"skipverify" description:"Skip verifying TLS for the RPC client"`
Proxy string `long:"proxy" description:"Connect via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
ProxyUser string `long:"proxyuser" description:"Username for proxy server"`
ProxyPass string `long:"proxypass" default-mask:"-" description:"Password for proxy server"`
// SPV client options
UseSPV bool `long:"usespv" description:"Enables the experimental use of SPV rather than RPC for chain synchronization"`
AddPeers []string `short:"a" long:"addpeer" description:"Add a peer to connect with at startup"`
ConnectPeers []string `long:"connect" description:"Connect only to the specified peers at startup"`
MaxPeers int `long:"maxpeers" description:"Max number of inbound and outbound peers"`
BanDuration time.Duration `long:"banduration" description:"How long to ban misbehaving peers. Valid time units are {s, m, h}. Minimum 1 second"`
BanThreshold uint32 `long:"banthreshold" description:"Maximum allowed ban score before disconnecting and banning misbehaving peers."`
// RPC server options
//
// The legacy server is still enabled by default (and eventually will be
// replaced with the experimental server) so prepare for that change by
// renaming the struct fields (but not the configuration options).
//
// Usernames can also be used for the consensus RPC client, so they
// aren't considered legacy.
RPCCert *cfgutil.ExplicitString `long:"rpccert" description:"File containing the certificate file"`
RPCKey *cfgutil.ExplicitString `long:"rpckey" description:"File containing the certificate key"`
OneTimeTLSKey bool `long:"onetimetlskey" description:"Generate a new TLS certpair at startup, but only write the certificate to disk"`
DisableServerTLS bool `long:"noservertls" description:"Disable TLS for the RPC server -- NOTE: This is only allowed if the RPC server is bound to localhost"`
LegacyRPCListeners []string `long:"rpclisten" description:"Listen for legacy RPC connections on this interface/port (default port: 8332, testnet: 18332, simnet: 18554)"`
DisableServerTLS bool `long:"noservertls" description:"Disable TLS for the RPC server"`
LegacyRPCListeners []string `long:"rpclisten" description:"Listen for legacy RPC connections on this interface/port (default port: 9244, testnet: 19244, regtest: 29244)"`
LegacyRPCMaxClients int64 `long:"rpcmaxclients" description:"Max number of legacy RPC clients for standard connections"`
LegacyRPCMaxWebsockets int64 `long:"rpcmaxwebsockets" description:"Max number of legacy RPC websocket connections"`
Username string `short:"u" long:"username" description:"Username for legacy RPC and btcd authentication (if btcdusername is unset)"`
Password string `short:"P" long:"password" default-mask:"-" description:"Password for legacy RPC and btcd authentication (if btcdpassword is unset)"`
// EXPERIMENTAL RPC server options
//
// These options will change (and require changes to config files, etc.)
// when the new gRPC server is enabled.
ExperimentalRPCListeners []string `long:"experimentalrpclisten" description:"Listen for RPC connections on this interface/port"`
LegacyRPCMaxWebsockets int64 `long:"rpcmaxwebsockets" description:"Max number of RPC websocket connections"`
RPCUser string `short:"u" long:"rpcuser" description:"Username for RPC and lbcd authentication"`
RPCPass string `short:"P" long:"rpcpass" default-mask:"-" description:"Password for RPC and lbcd authentication"`
// Deprecated options
DataDir *cfgutil.ExplicitString `short:"b" long:"datadir" default-mask:"-" description:"DEPRECATED -- use appdata instead"`
@@ -199,7 +175,7 @@ func parseAndSetDebugLevels(debugLevel string) error {
if !strings.Contains(debugLevel, ",") && !strings.Contains(debugLevel, "=") {
// Validate debug log level.
if !validLogLevel(debugLevel) {
str := "The specified debug level [%v] is invalid"
str := "the specified debug level [%v] is invalid"
return fmt.Errorf(str, debugLevel)
}
@@ -213,7 +189,7 @@ func parseAndSetDebugLevels(debugLevel string) error {
// issues and update the log levels accordingly.
for _, logLevelPair := range strings.Split(debugLevel, ",") {
if !strings.Contains(logLevelPair, "=") {
str := "The specified debug level contains an invalid " +
str := "the specified debug level contains an invalid " +
"subsystem/level pair [%v]"
return fmt.Errorf(str, logLevelPair)
}
@@ -224,14 +200,14 @@ func parseAndSetDebugLevels(debugLevel string) error {
// Validate subsystem.
if _, exists := subsystemLoggers[subsysID]; !exists {
str := "The specified subsystem [%v] is invalid -- " +
str := "the specified subsystem [%v] is invalid -- " +
"supported subsytems %v"
return fmt.Errorf(str, subsysID, supportedSubsystems())
}
// Validate log level.
if !validLogLevel(logLevel) {
str := "The specified debug level [%v] is invalid"
str := "the specified debug level [%v] is invalid"
return fmt.Errorf(str, logLevel)
}
@@ -245,12 +221,12 @@ func parseAndSetDebugLevels(debugLevel string) error {
// line options.
//
// The configuration proceeds as follows:
// 1) Start with a default config with sane settings
// 2) Pre-parse the command line to check for an alternative config file
// 3) Load configuration file overwriting defaults with any specified options
// 4) Parse CLI options and overwrite/add any specified options
// 1. Start with a default config with sane settings
// 2. Pre-parse the command line to check for an alternative config file
// 3. Load configuration file overwriting defaults with any specified options
// 4. Parse CLI options and overwrite/add any specified options
//
// The above results in btcwallet functioning properly without any config
// The above results in lbcwallet functioning properly without any config
// settings while still allowing the user to override settings with config files
// and command line options. Command line options always take precedence.
func loadConfig() (*config, []string, error) {
@@ -260,19 +236,14 @@ func loadConfig() (*config, []string, error) {
ConfigFile: cfgutil.NewExplicitString(defaultConfigFile),
AppDataDir: cfgutil.NewExplicitString(defaultAppDataDir),
LogDir: defaultLogDir,
WalletPass: wallet.InsecurePubPassphrase,
CAFile: cfgutil.NewExplicitString(""),
RPCKey: cfgutil.NewExplicitString(defaultRPCKeyFile),
RPCCert: cfgutil.NewExplicitString(defaultRPCCertFile),
LegacyRPCMaxClients: defaultRPCMaxClients,
LegacyRPCMaxWebsockets: defaultRPCMaxWebsockets,
DataDir: cfgutil.NewExplicitString(defaultAppDataDir),
UseSPV: false,
AddPeers: []string{},
ConnectPeers: []string{},
MaxPeers: neutrino.MaxPeers,
BanDuration: neutrino.BanDuration,
BanThreshold: neutrino.BanThreshold,
DBTimeout: wallet.DefaultDBTimeout,
Passphrase: defaultPassphrase,
}
// Pre-parse the command line options to see if an alternative config
@@ -293,7 +264,7 @@ func loadConfig() (*config, []string, error) {
appName = strings.TrimSuffix(appName, filepath.Ext(appName))
usageMessage := fmt.Sprintf("Use %s -h to show usage", appName)
if preCfg.ShowVersion {
fmt.Println(appName, "version", version())
fmt.Println(appName, "version", version.Full())
os.Exit(0)
}
@@ -361,13 +332,12 @@ func loadConfig() (*config, []string, error) {
activeNet = &netparams.TestNet3Params
numNets++
}
if cfg.SimNet {
activeNet = &netparams.SimNetParams
if cfg.Regtest {
activeNet = &netparams.RegTestParams
numNets++
}
if numNets > 1 {
str := "%s: The testnet and simnet params can't be used " +
"together -- choose one"
str := "%s: more than one networks has been specified"
err := fmt.Errorf(str, "loadConfig")
fmt.Fprintln(os.Stderr, err)
parser.WriteHelp(os.Stderr)
@@ -397,29 +367,32 @@ func loadConfig() (*config, []string, error) {
return nil, nil, err
}
// Exit if you try to use a simulation wallet with a standard
// data directory.
if !(cfg.AppDataDir.ExplicitlySet() || cfg.DataDir.ExplicitlySet()) && cfg.CreateTemp {
fmt.Fprintln(os.Stderr, "Tried to create a temporary simulation "+
"wallet, but failed to specify data directory!")
os.Exit(0)
}
if cfg.CreateTemp {
errMsg := "Tried to create a temporary simulation wallet"
// Exit if you try to use a simulation wallet with a standard
// data directory.
if !(cfg.AppDataDir.ExplicitlySet() || cfg.DataDir.ExplicitlySet()) {
errMsg += ", but failed to specify data directory!"
fmt.Fprintln(os.Stderr, errMsg)
os.Exit(0)
}
// Exit if you try to use a simulation wallet on anything other than
// simnet or testnet3.
if !cfg.SimNet && cfg.CreateTemp {
fmt.Fprintln(os.Stderr, "Tried to create a temporary simulation "+
"wallet for network other than simnet!")
os.Exit(0)
// Exit if you try to use a simulation wallet on anything other than
// regtest or testnet3.
if !(cfg.Regtest || cfg.TestNet3) {
errMsg += "for network other than regtest, or testnet3"
fmt.Fprintln(os.Stderr, errMsg)
os.Exit(0)
}
}
// Ensure the wallet exists or create it when the create flag is set.
netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
dbPath := filepath.Join(netDir, walletDbName)
dbPath := filepath.Join(netDir, wallet.WalletDBName)
if cfg.CreateTemp && cfg.Create {
err := fmt.Errorf("The flags --create and --createtemp can not " +
"be specified together. Use --help for more information.")
err := fmt.Errorf("the flags --create and --createtemp can not " +
"be specified together. Use --help for more information")
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
@@ -430,7 +403,7 @@ func loadConfig() (*config, []string, error) {
return nil, nil, err
}
if cfg.CreateTemp {
if cfg.CreateTemp { // nolint:gocritic
tempWalletExists := false
if dbFileExists {
@@ -457,8 +430,8 @@ func loadConfig() (*config, []string, error) {
// Error if the create flag is set and the wallet already
// exists.
if dbFileExists {
err := fmt.Errorf("The wallet database file `%v` "+
"already exists.", dbPath)
err := fmt.Errorf("the wallet database file `%v` "+
"already exists", dbPath)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
@@ -477,22 +450,6 @@ func loadConfig() (*config, []string, error) {
// Created successfully, so exit now with success.
os.Exit(0)
} else if !dbFileExists && !cfg.NoInitialLoad {
keystorePath := filepath.Join(netDir, keystore.Filename)
keystoreExists, err := cfgutil.FileExists(keystorePath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
if !keystoreExists {
err = fmt.Errorf("The wallet does not exist. Run with the " +
"--create option to initialize and create it.")
} else {
err = fmt.Errorf("The wallet is in legacy format. Run with the " +
"--create option to import it.")
}
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
localhostListeners := map[string]struct{}{
@@ -501,73 +458,52 @@ func loadConfig() (*config, []string, error) {
"::1": {},
}
if cfg.UseSPV {
neutrino.MaxPeers = cfg.MaxPeers
neutrino.BanDuration = cfg.BanDuration
neutrino.BanThreshold = cfg.BanThreshold
} else {
if cfg.RPCConnect == "" {
cfg.RPCConnect = net.JoinHostPort("localhost", activeNet.RPCClientPort)
}
if cfg.RPCConnect == "" {
cfg.RPCConnect = net.JoinHostPort("localhost", activeNet.RPCClientPort)
}
// Add default port to connect flag if missing.
cfg.RPCConnect, err = cfgutil.NormalizeAddress(cfg.RPCConnect,
activeNet.RPCClientPort)
if err != nil {
fmt.Fprintf(os.Stderr,
"Invalid rpcconnect network address: %v\n", err)
return nil, nil, err
}
// Add default port to connect flag if missing.
cfg.RPCConnect, err = cfgutil.NormalizeAddress(cfg.RPCConnect,
activeNet.RPCClientPort)
if err != nil {
fmt.Fprintf(os.Stderr,
"Invalid rpcconnect network address: %v\n", err)
return nil, nil, err
}
RPCHost, _, err := net.SplitHostPort(cfg.RPCConnect)
if err != nil {
return nil, nil, err
}
if cfg.DisableClientTLS {
if _, ok := localhostListeners[RPCHost]; !ok {
str := "%s: the --noclienttls option may not be used " +
"when connecting RPC to non localhost " +
"addresses: %s"
err := fmt.Errorf(str, funcName, cfg.RPCConnect)
RPCHost, _, err := net.SplitHostPort(cfg.RPCConnect)
if err != nil {
return nil, nil, err
}
if !cfg.DisableClientTLS {
// If CAFile is unset, choose either the copy or local lbcd cert.
if !cfg.CAFile.ExplicitlySet() {
cfg.CAFile.Value = filepath.Join(cfg.AppDataDir.Value, defaultCAFilename)
// If the CA copy does not exist, check if we're connecting to
// a local lbcd and switch to its RPC cert if it exists.
certExists, err := cfgutil.FileExists(cfg.CAFile.Value)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
} else {
// If CAFile is unset, choose either the copy or local btcd cert.
if !cfg.CAFile.ExplicitlySet() {
cfg.CAFile.Value = filepath.Join(cfg.AppDataDir.Value, defaultCAFilename)
// If the CA copy does not exist, check if we're connecting to
// a local btcd and switch to its RPC cert if it exists.
certExists, err := cfgutil.FileExists(cfg.CAFile.Value)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
if !certExists {
if _, ok := localhostListeners[RPCHost]; ok {
btcdCertExists, err := cfgutil.FileExists(
btcdDefaultCAFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
if btcdCertExists {
cfg.CAFile.Value = btcdDefaultCAFile
}
if !certExists {
if _, ok := localhostListeners[RPCHost]; ok {
lbcdCertExists, err := cfgutil.FileExists(
lbcdDefaultCAFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
if lbcdCertExists {
cfg.CAFile.Value = lbcdDefaultCAFile
}
}
}
}
}
// Only set default RPC listeners when there are no listeners set for
// the experimental RPC server. This is required to prevent the old RPC
// server from sharing listen addresses, since it is impossible to
// remove defaults from go-flags slice options without assigning
// specific behavior to a particular string.
if len(cfg.ExperimentalRPCListeners) == 0 && len(cfg.LegacyRPCListeners) == 0 {
if len(cfg.LegacyRPCListeners) == 0 {
addrs, err := net.LookupHost("localhost")
if err != nil {
return nil, nil, err
@@ -588,39 +524,10 @@ func loadConfig() (*config, []string, error) {
"Invalid network address in legacy RPC listeners: %v\n", err)
return nil, nil, err
}
cfg.ExperimentalRPCListeners, err = cfgutil.NormalizeAddresses(
cfg.ExperimentalRPCListeners, activeNet.RPCServerPort)
if err != nil {
fmt.Fprintf(os.Stderr,
"Invalid network address in RPC listeners: %v\n", err)
return nil, nil, err
}
// Both RPC servers may not listen on the same interface/port.
if len(cfg.LegacyRPCListeners) > 0 && len(cfg.ExperimentalRPCListeners) > 0 {
seenAddresses := make(map[string]struct{}, len(cfg.LegacyRPCListeners))
for _, addr := range cfg.LegacyRPCListeners {
seenAddresses[addr] = struct{}{}
}
for _, addr := range cfg.ExperimentalRPCListeners {
_, seen := seenAddresses[addr]
if seen {
err := fmt.Errorf("Address `%s` may not be "+
"used as a listener address for both "+
"RPC servers", addr)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
}
}
// Only allow server TLS to be disabled if the RPC server is bound to
// localhost addresses.
if cfg.DisableServerTLS {
allListeners := append(cfg.LegacyRPCListeners,
cfg.ExperimentalRPCListeners...)
for _, addr := range allListeners {
host, _, err := net.SplitHostPort(addr)
for _, addr := range cfg.LegacyRPCListeners {
_, _, err := net.SplitHostPort(addr)
if err != nil {
str := "%s: RPC listen interface '%s' is " +
"invalid: %v"
@@ -629,15 +536,6 @@ func loadConfig() (*config, []string, error) {
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
if _, ok := localhostListeners[host]; !ok {
str := "%s: the --noservertls option may not be used " +
"when binding RPC to non localhost " +
"addresses: %s"
err := fmt.Errorf(str, funcName, addr)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
}
}
@@ -646,17 +544,6 @@ func loadConfig() (*config, []string, error) {
cfg.RPCCert.Value = cleanAndExpandPath(cfg.RPCCert.Value)
cfg.RPCKey.Value = cleanAndExpandPath(cfg.RPCKey.Value)
// If the btcd username or password are unset, use the same auth as for
// the client. The two settings were previously shared for btcd and
// client auth, so this avoids breaking backwards compatibility while
// allowing users to use different auth settings for btcd and wallet.
if cfg.BtcdUsername == "" {
cfg.BtcdUsername = cfg.Username
}
if cfg.BtcdPassword == "" {
cfg.BtcdPassword = cfg.Password
}
// Warn about missing config file after the final command line parse
// succeeds. This prevents the warning on help messages and invalid
// options.
-28
View File
@@ -1,28 +0,0 @@
Dependency Commits
==================
btcwallet 0.7.0 Alpha
----------------
bolt 1139dd23c5f9d1a28096b511959044b29364a3fe
btcd cea5d3c1cc16eb07a1686c557db23004655ae11b
btclog 5005b7240f310ae8f01c7664a3954d280241eb2b
btcrpcclient b81555beeac8eda71e8150cc9d63631aaa756965
btcutil ff82dacded1c76d101bce55c394c03c0bbff69e8
fastsha256 302ad4db268b46f9ebda3078f6f7397f96047735
go-flags 6c288d648c1cc1befcb90cb5511dcacf64ae8e61
go-socks cfe8b59e565c1a5bd4e2005d77cd9aa8b2e14524
golangcrypto 53f62d9b43e87a6c56975cf862af7edf33a8d0df
seelog 313961b101eb55f65ae0f03ddd4e322731763b6c
websocket 31079b6807923eb23992c421b114992b95131b55
btcwallet 0.1.0 Alpha
----------------
btcd 3108b944017b14a3c5863ed1401f1a2471907d84
btcec a97fd5fe2c670030f8d77dc13b9fa8401ef9f349
btcjson d20f958c92e1444d83215c3cf98d6eef41898dcb
btcscript f4a6449ad3b90d0c830bf2895b83ced8d5fb91e9
btcutil aa811871654079f5036d3692dcf6c66928d19447
btcwire dd41f7e91a682b7c1ceed633e12ece6ba7b6bc72
btcws 497f1770445677372557d70621782d921a5318e3
go-flags fa177a84d3b73bf7e4b79125b2a963bc134eff77
seelog 6b91ad56123bb473755caa213db2bde5422177bf
-3
View File
@@ -1,3 +0,0 @@
### Guides
[Rebuilding all transaction history with forced rescans](https://github.com/btcsuite/btcwallet/tree/master/docs/force_rescans.md)
-80
View File
@@ -1,80 +0,0 @@
# Rebuilding transaction history
It is unlikely, but possible and unfortunate, that transaction history in the
wallet database may not represent reality. This may be due to a programming
mistake or the transaction database becoming corrupted. Thankfully, all
transactions are publicly recorded on the blockchain, and transactions
necessary for a fully functional wallet can be recovered. This process is
called rescanning, and the following guide will demonstrate how to force such a
rescan.
Rescans are automatically performed each time the wallet syncs to the network.
These are used to "catch up" the wallet to the newest best block in the block
chain. For example, the following log messages at startup indicate that an
out-of-sync wallet started a rescan for all addresses and unspent outputs since
some block.
```
13:45:03 2015-04-13 [INF] WLLT: Started rescan from block 00000000001703b1a9dfd4865d587cd3f3cbb2f8e6ce9b44668e78ad8d4a7377 (height 205921) for 1 address
...
13:45:49 2015-04-13 [INF] WLLT: Finished rescan for 1 address (synced to block 0000000005cecab1013ecb1275a3e0c9623c4a497a57b6b6bf0fc1525aca1fbf, height 335146)
```
During the rescan, relevant transactions from previously unseen blocks are added
to the wallet database and spend tracking is updated accordingly. After the
rescan at startup finishes, a wallet is marked in sync with the chain.
When wallet is started without any transaction history, a rescan is performed
for all blocks since the creation date of the wallet's first address. There are
two situations when this holds true:
1. The wallet is newly created or was recreated from the seed
2. The transaction history is explicitly deleted
The second case is how a forced rescan is performed.
btcwallet will not drop transaction history by itself, as this is something that
should not be necessary under normal wallet operation. However, a tool,
`dropwtxmgr`, is provided in the `cmd/dropwtxmgr` directory which may be used to
drop the wallet transaction manager (wtxmgr) history from a wallet database.
The tool may already be installed in your PATH, but if not, installing it is easy:
```
$ cd $GOPATH/src/github.com/btcsuite/btcwallet/cmd/dropwtxmgr
$ go get
```
Dropping transaction history given the default database location can be
performed by stopping wallet (to release the database) and running the tool,
answering yes to the prompt:
```
$ dropwtxmgr
Database path: /home/username/.btcwallet/mainnet/wallet.db
Drop all btcwallet transaction history? [y/N] y
Dropping wtxmgr namespace
```
If the wallet database is in another location or transaction history for a
different network (e.g. testnet or simnet) must be dropped, the full database
path may be specified:
```
$ dropwtxmgr --db ~/.btcwallet/testnet/wallet.db
Database path: /home/username/.btcwallet/testnet/wallet.db
Drop all btcwallet transaction history? [y/N] y
Dropping wtxmgr namespace
```
After dropping transaction history, btcwallet may be restarted and a full rescan
will be triggered to sync the wallet:
```
$ btcwallet
14:05:31 2015-04-13 [INF] BTCW: No recorded transaction history -- needs full rescan
...
14:05:31 2015-04-13 [INF] WLLT: Started rescan from block 000000000000e37b0f99af2e434834123b5459e31e17937169ce81ed0cc4d61c (height 193191) for 1 address
...
14:07:06 2015-04-13 [INF] WLLT: Finished rescan for 1 address (synced to block 00000000049041b5bd7f8ac86c8f1d32065053aefbe8c31e25ed03ef015a725a, height 335482)
```
+43 -25
View File
@@ -1,35 +1,53 @@
module github.com/btcsuite/btcwallet
module github.com/lbryio/lbcwallet
require (
github.com/btcsuite/btcd v0.20.1-beta
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d
github.com/btcsuite/btcwallet/wallet/txauthor v1.0.0
github.com/btcsuite/btcwallet/wallet/txrules v1.0.0
github.com/btcsuite/btcwallet/walletdb v1.0.0
github.com/btcsuite/btcwallet/wtxmgr v1.0.0
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792
github.com/davecgh/go-spew v1.1.1
github.com/golang/protobuf v1.2.0
github.com/jessevdk/go-flags v1.4.0
github.com/jessevdk/go-flags v1.5.0
github.com/jrick/logrotate v1.0.0
github.com/kkdai/bstream v0.0.0-20181106074824-b3251f7901ec // indirect
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf
github.com/lightninglabs/neutrino v0.11.0
golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67
golang.org/x/net v0.0.0-20190206173232-65e2d4e15006
google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922 // indirect
google.golang.org/grpc v1.18.0
github.com/lbryio/lbcd v0.22.118
github.com/lbryio/lbcutil v1.0.202
github.com/lightningnetwork/lnd/clock v1.1.0
github.com/stretchr/testify v1.7.1
go.etcd.io/bbolt v1.3.6
golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898
golang.org/x/tools v0.1.10
)
replace github.com/btcsuite/btcwallet/walletdb => ./walletdb
require (
github.com/DataDog/zstd v1.5.2 // indirect
github.com/aead/siphash v1.0.1 // indirect
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/cockroachdb/errors v1.9.0 // indirect
github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect
github.com/cockroachdb/pebble v0.0.0-20220523221036-bb2c1501ac23 // indirect
github.com/cockroachdb/redact v1.1.3 // indirect
github.com/codahale/hdrhistogram v0.9.0 // indirect
github.com/getsentry/sentry-go v0.13.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/go-cmp v0.5.8 // indirect
github.com/kkdai/bstream v1.0.0 // indirect
github.com/klauspost/compress v1.15.4 // indirect
github.com/kr/pretty v0.3.0 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rogpeppe/go-internal v1.8.1 // indirect
golang.org/x/exp v0.0.0-20220518171630-0b5c67f07fdf // indirect
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect
golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)
replace github.com/btcsuite/btcwallet/wtxmgr => ./wtxmgr
// The old version of ginko that's used in btcd imports an ancient version of
// gopkg.in/fsnotify.v1 that isn't go mod compatible. We fix that import error
// by replacing ginko (which is only a test library anyway) with a more recent
// version.
replace github.com/onsi/ginkgo => github.com/onsi/ginkgo v1.14.2
replace github.com/btcsuite/btcwallet/wallet/txauthor => ./wallet/txauthor
replace github.com/btcsuite/btcwallet/wallet/txrules => ./wallet/txrules
replace github.com/btcsuite/btcwallet/wallet/txsizes => ./wallet/txsizes
go 1.13
go 1.19
+411 -82
View File
@@ -1,122 +1,451 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/CloudyKit/fastprinter v0.0.0-20170127035650-74b38d55f37a/go.mod h1:EFZQ978U7x8IRnstaskI3IysnWY5Ao3QgZUKOXlsAdw=
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno=
github.com/CloudyKit/jet v2.1.3-0.20180809161101-62edd43e4f88+incompatible/go.mod h1:HPYO+50pSWkPoj9Q/eq0aRGByCL6ScRlUmiEX5Zgm+w=
github.com/CloudyKit/jet/v3 v3.0.0/go.mod h1:HKQPgSJmdK8hdoAbKUUWajkHyHo4RaU5rMdUywE7VMo=
github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo=
github.com/DataDog/zstd v1.5.2 h1:vUG4lAyuPCXO0TLbXvPv7EB7cNK1QV/luu55UHLrrn8=
github.com/DataDog/zstd v1.5.2/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw=
github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY=
github.com/Joker/jade v1.0.1-0.20190614124447-d475f43051e7/go.mod h1:6E6s8o2AE4KhCrqr6GRJjdC/gNfTdxkIXvuGZZda2VM=
github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0=
github.com/aead/siphash v1.0.1 h1:FwHfE/T45KPKYuuSAKyyvE+oPWcaQ+CUmFW0bPlM+kg=
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
github.com/btcsuite/btcd v0.0.0-20190824003749-130ea5bddde3 h1:A/EVblehb75cUgXA5njHPn0kLAsykn6mJGz7rnmW5W0=
github.com/btcsuite/btcd v0.0.0-20190824003749-130ea5bddde3/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI=
github.com/btcsuite/btcd v0.20.1-beta h1:Ik4hyJqN8Jfyv3S4AGBOmyouMsYE3EdYODkMbQjwPGw=
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f h1:bAs4lUbRJpnnkd9VhRV3jjAVU7DJVjMaK+IsvSeZvFo=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d h1:yJzD/yFppdVCf6ApMkVy8cUxV0XrxdP9rVf6D87/Mng=
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd h1:R/opQEbFEy9JGkIguV40SvRY1uliPX8ifOvi6ICsFCw=
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
github.com/btcsuite/goleveldb v1.0.0 h1:Tvd0BfvqX9o823q1j2UZ/epQo09eJh6dTcRp79ilIN4=
github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I=
github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
github.com/btcsuite/snappy-go v1.0.0 h1:ZxaA6lo2EpxGddsA8JwWOcxlzRybb444sgmeJQMJGQE=
github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 h1:R8vQdOQdZ9Y3SkEwmHoWBmX1DNXhXZqlTpq6s4tyJGc=
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/coreos/bbolt v1.3.3 h1:n6AiVyVRKQFNb6mJlwESEvvLoDyiTzXX7ORAUlkeBdY=
github.com/coreos/bbolt v1.3.3/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495 h1:6IyqGr3fnd0tM3YxipK27TUskaOVUjU2nG45yzwcQKY=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/cockroachdb/datadriven v1.0.0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4=
github.com/cockroachdb/datadriven v1.0.1-0.20211007161720-b558070c3be0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4=
github.com/cockroachdb/datadriven v1.0.1-0.20220214170620-9913f5bc19b7/go.mod h1:hi0MtSY3AYDQNDi83kDkMH5/yqM/CsIrsOITkSoH7KI=
github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM=
github.com/cockroachdb/errors v1.8.1/go.mod h1:qGwQn6JmZ+oMjuLwjWzUNqblqk0xl4CVV3SQbGwK7Ac=
github.com/cockroachdb/errors v1.8.8/go.mod h1:z6VnEL3hZ/2ONZEvG7S5Ym0bU2AqPcEKnIiA1wbsSu0=
github.com/cockroachdb/errors v1.9.0 h1:B48dYem5SlAY7iU8AKsgedb4gH6mo+bDkbtLIvM/a88=
github.com/cockroachdb/errors v1.9.0/go.mod h1:vaNcEYYqbIqB5JhKBhFV9CneUqeuEbB2OYJBK4GBNYQ=
github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI=
github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f h1:6jduT9Hfc0njg5jJ1DdKCFPdMBrp/mdZfCpa5h+WM74=
github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs=
github.com/cockroachdb/pebble v0.0.0-20220523221036-bb2c1501ac23 h1:/Pvbuwd61qRxNCIpSIWbx7Oqy1tinfErdetF91DU9gQ=
github.com/cockroachdb/pebble v0.0.0-20220523221036-bb2c1501ac23/go.mod h1:buxOO9GBtOcq1DiXDpIPYrmxY020K2A8lOrwno5FetU=
github.com/cockroachdb/redact v1.0.8/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg=
github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ=
github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg=
github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2/go.mod h1:8BT+cPK6xvFOcRlk0R8eg+OTkcqI6baNH4xAkpiYVvQ=
github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI=
github.com/codahale/hdrhistogram v0.9.0 h1:9GjrtRI+mLEFPtTfR/AZhcxp+Ii8NZYWq5104FbZQY0=
github.com/codahale/hdrhistogram v0.9.0/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI=
github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM=
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw=
github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc=
github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c=
github.com/getsentry/sentry-go v0.13.0 h1:20dgTiUSfxRB/EhMPtxcL9ZEbM1ZdR+W/7f7NWD+xWo=
github.com/getsentry/sentry-go v0.13.0/go.mod h1:EOsfu5ZdvKPfeHYV6pTVQnsjfp30+XA7//UooKNumH0=
github.com/ghemawat/stream v0.0.0-20171120220530-696b145b53b9/go.mod h1:106OIgooyS7OzLDOpUGgm9fA3bQENb/cFSyyBmMoJDs=
github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s=
github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM=
github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98=
github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w=
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8=
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo=
github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM=
github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s=
github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4=
github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89 h1:12K8AlpT0/6QUXSfV0yi4Q0jkbq8NDtIKFtF61AoqV0=
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/hydrogen18/memlistener v0.0.0-20141126152155-54553eb933fb/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE=
github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE=
github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI=
github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0=
github.com/iris-contrib/i18n v0.0.0-20171121225848-987a633949d0/go.mod h1:pMCz62A0xJL6I+umB2YTlFRwWXaDFA0jy+5HzGiJjqI=
github.com/iris-contrib/jade v1.1.3/go.mod h1:H/geBymxJhShH5kecoiOCSssPX7QWYH7UaeZTSWddIk=
github.com/iris-contrib/pongo2 v0.0.1/go.mod h1:Ssh+00+3GAZqSQb30AvBRNxBx7rf0GqwkjqxNd0u65g=
github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrOcOqfqxa4hXw=
github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc=
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/jrick/logrotate v1.0.0 h1:lQ1bL/n9mBNeIXoTUoYRlK4dHuNJVofX9oWqBtPnSzI=
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/juju/errors v0.0.0-20181118221551-089d3ea4e4d5/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q=
github.com/juju/loggo v0.0.0-20180524022052-584905176618/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U=
github.com/juju/testing v0.0.0-20180920084828-472a3e8b2073/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA=
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k=
github.com/kataras/golog v0.0.9/go.mod h1:12HJgwBIZFNGL0EJnMRhmvGA0PQGx8VFwrZtM4CqbAk=
github.com/kataras/golog v0.0.10/go.mod h1:yJ8YKCmyL+nWjERB90Qwn+bdyBZsaQwU3bTVFgkFIp8=
github.com/kataras/iris/v12 v12.0.1/go.mod h1:udK4vLQKkdDqMGJJVd/msuMtN6hpYJhg/lSzuxjhO+U=
github.com/kataras/iris/v12 v12.1.8/go.mod h1:LMYy4VlP67TQ3Zgriz8RE2h2kMZV2SgMYbq3UhfoFmE=
github.com/kataras/neffos v0.0.10/go.mod h1:ZYmJC07hQPW67eKuzlfY7SO3bC0mw83A3j6im82hfqw=
github.com/kataras/neffos v0.0.14/go.mod h1:8lqADm8PnbeFfL7CLXh1WHw53dG27MC3pgi2R1rmoTE=
github.com/kataras/pio v0.0.0-20190103105442-ea782b38602d/go.mod h1:NV88laa9UiiDuX9AhMbDPkGYSPugBOV6yTZB1l2K9Z0=
github.com/kataras/pio v0.0.2/go.mod h1:hAoW0t9UmXi4R5Oyq5Z4irTbaTsOemSrDGUtaTl7Dro=
github.com/kataras/sitemap v0.0.5/go.mod h1:KY2eugMKiPwsJgx7+U103YZehfvNGOXURubcGyk0Bz8=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23 h1:FOOIBWrEkLgmlgGfMuZT83xIwfPDxEI2OHu6xUmJMFE=
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
github.com/kkdai/bstream v0.0.0-20181106074824-b3251f7901ec h1:n1NeQ3SgUHyISrjFFoO5dR748Is8dBL9qpaTNfphQrs=
github.com/kkdai/bstream v0.0.0-20181106074824-b3251f7901ec/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kkdai/bstream v1.0.0 h1:Se5gHwgp2VT2uHfDrkbbgbgEvV9cimLELwrPJctSjg8=
github.com/kkdai/bstream v1.0.0/go.mod h1:FDnDOHt5Yx4p3FaHcioFT0QjDOtgUpvjeZqAs+NVZZA=
github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/compress v1.9.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/klauspost/compress v1.15.4 h1:1kn4/7MepF/CHmYub99/nNX8az0IJjfSOU/jbnTVfqQ=
github.com/klauspost/compress v1.15.4/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf h1:HZKvJUHlcXI/f/O0Avg7t8sqkPo78HFzjmeYFl6DPnc=
github.com/lightninglabs/gozmq v0.0.0-20191113021534-d20a764486bf/go.mod h1:vxmQPeIQxPf6Jf9rM8R+B4rKBqLA2AjttNxkFBL2Plk=
github.com/lightninglabs/neutrino v0.11.0 h1:lPpYFCtsfJX2W5zI4pWycPmbbBdr7zU+BafYdLoD6k0=
github.com/lightninglabs/neutrino v0.11.0/go.mod h1:CuhF0iuzg9Sp2HO6ZgXgayviFTn1QHdSTJlMncK80wg=
github.com/lightningnetwork/lnd/queue v1.0.1 h1:jzJKcTy3Nj5lQrooJ3aaw9Lau3I0IwvQR5sqtjdv2R0=
github.com/lightningnetwork/lnd/queue v1.0.1/go.mod h1:vaQwexir73flPW43Mrm7JOgJHmcEFBWWSl9HlyASoms=
github.com/lightningnetwork/lnd/ticker v1.0.0 h1:S1b60TEGoTtCe2A0yeB+ecoj/kkS4qpwh6l+AkQEZwU=
github.com/lightningnetwork/lnd/ticker v1.0.0/go.mod h1:iaLXJiVgI1sPANIF2qYYUJXjoksPNvGNYowB8aRbpX0=
github.com/onsi/ginkgo v1.6.0 h1:Ix8l273rp3QzYgXSR+c8d1fTG7UPgYkOSELPhiY/YGw=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.4.1 h1:PZSj/UFNaVp3KxrzHOcS7oyuWA7LoOY/77yCTEFu21U=
github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk=
go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44 h1:9lP3x0pW80sDI6t1UMSLA4to18W7R7imwAI/sWS9S8Q=
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67 h1:ng3VDlRp5/DHpSWl02R4rM9I+8M2rhmsuLwAMmkLQWE=
golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g=
github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awStJ6ArI7Y=
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
github.com/lbryio/lbcd v0.22.118 h1:q3HAwCKdINJE2Tj5FrjmSfltSuiqSB5gnuSDAAQVt8A=
github.com/lbryio/lbcd v0.22.118/go.mod h1:YZ2Vi4khEheO7hllkWhDdScXmHhXCBzK4xIQcVDcozs=
github.com/lbryio/lbcutil v1.0.202 h1:L0aRMs2bdCUAicD8Xe4NmUEvevDDea3qkIpCSACnftI=
github.com/lbryio/lbcutil v1.0.202/go.mod h1:LGPtVBBzh4cFXfLFb8ginlFcbA2QwumLNFd0yk/as2o=
github.com/lightningnetwork/lnd/clock v1.1.0 h1:/yfVAwtPmdx45aQBoXQImeY7sOIEr7IXlImRMBOZ7GQ=
github.com/lightningnetwork/lnd/clock v1.1.0/go.mod h1:KnQudQ6w0IAMZi1SgvecLZQZ43ra2vpDNj7H/aasemg=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw=
github.com/mediocregopher/mediocre-go-lib v0.0.0-20181029021733-cb65787f37ed/go.mod h1:dSsfyI2zABAdhcbvkXqgxOxrCsbYeHCPgrZkku60dSg=
github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQGvsUt6O3Pj+LDCQ=
github.com/mediocregopher/radix/v3 v3.4.2/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8=
github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/leAFZyRl6bYmGDlGc=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ=
github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg=
github.com/nats-io/nats.go v1.8.1/go.mod h1:BrFz9vVn0fU3AcH9Vn4Kd7W0NpJ651tD5omQ3M8LwxM=
github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w=
github.com/nats-io/nkeys v0.0.2/go.mod h1:dab7URMsZm6Z/jp9Z5UGa87Uutgc2mVpXLC4B7TDb/4=
github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/onsi/ginkgo v1.14.2/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg=
github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o=
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY=
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w=
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI=
github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg=
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM=
github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZkTdatxwunjIkc=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU=
go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4=
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898 h1:SLP7Q4Di66FONjDJbCYrCRrh97focO6sLogHO7/g8F0=
golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20200513190911-00229845015e/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw=
golang.org/x/exp v0.0.0-20220518171630-0b5c67f07fdf h1:oXVg4h2qJDd9htKxb5SCpFBHLipW6hXmL3qpUixS2jw=
golang.org/x/exp v0.0.0-20220518171630-0b5c67f07fdf/go.mod h1:yh0Ynu2b5ZUe3MQfp2nM0ecK7wsgouWTDN0FNeJuIys=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181106065722-10aee1819953 h1:LuZIitY8waaxUfNIdtajyE/YzA/zyf0YxXG27VpLrkg=
golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190206173232-65e2d4e15006 h1:bfLnR+k0tq5Lqt6dflRLcZiz6UaXCMt3vhYJ1l4FQ80=
golang.org/x/net v0.0.0-20190206173232-65e2d4e15006/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd h1:DBH9mDw0zluJT/R+nGuV3jWFWLFaHyYZWD4tOT+cjn0=
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210909193231-528a39cd75f3/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 h1:EH1Deb8WZJ0xc0WK//leUHXcX9aLE5SymusoTmMZye8=
golang.org/x/term v0.0.0-20220411215600-e5f449aeb171/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20=
golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922 h1:mBVYJnbrXLA/ZCBTCe7PtEgAUP+1bg92qTaFoPHdz+8=
google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922/go.mod h1:L3J43x8/uS+qIUoksaLKe6OS3nUKxOKuIFz1sl2/jx4=
google.golang.org/grpc v1.16.0 h1:dz5IJGuC2BB7qXR5AyHNwAUBhZscK2xVez7mznh72sY=
google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio=
google.golang.org/grpc v1.18.0 h1:IZl7mfBGfbhYx2p2rKRtYgDFw6SBz+kclmxYrCksPPA=
google.golang.org/grpc v1.18.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24=
google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE=
gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y=
gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
-42
View File
@@ -1,42 +0,0 @@
#!/bin/bash
# The script does automatic checking on a Go package and its sub-packages, including:
# 1. go fmt (http://golang.org/cmd/gofmt/)
# 2. golint (https://github.com/golang/lint)
# 3. go vet (http://golang.org/cmd/vet)
# 4. race detector (http://blog.golang.org/race-detector)
set -ex
test_targets=$(go list ./...)
# Automatic checks
test -z "$(go fmt $test_targets | tee /dev/stderr)"
# test -z "$(goimports -l -w . | tee /dev/stderr)"
test -z "$(for package in $test_targets; do golint $package; done | grep -v 'ALL_CAPS\|OP_\|NewFieldVal\|RpcCommand\|RpcRawCommand\|RpcSend\|Dns\|api.pb.go\|StartConsensusRpc\|factory_test.go\|legacy\|UnstableAPI' | tee /dev/stderr)"
test -z "$(go vet $test_targets 2>&1 | grep -v '^exit status \|Example\|newestSha\| not a string in call to Errorf$' | tee /dev/stderr)"
env GORACE="history_size=7 halt_on_errors=1" go test -v -race $test_targets
# Run test coverage on each subdirectories and merge the coverage profile.
#set +x
#echo "mode: count" > profile.cov
# Standard go tooling behavior is to ignore dirs with leading underscores.
#for dir in $(find . -maxdepth 10 -not -path '.' -not -path './.git*' \
# -not -path '*/_*' -not -path './cmd*' -not -path './release*' -type d)
#do
#if ls $dir/*.go &> /dev/null; then
# go test -covermode=count -coverprofile=$dir/profile.tmp $dir
# if [ -f $dir/profile.tmp ]; then
# cat $dir/profile.tmp | tail -n +2 >> profile.cov
# rm $dir/profile.tmp
# fi
#fi
#done
# To submit the test coverage result to coveralls.io,
# use goveralls (https://github.com/mattn/goveralls)
# goveralls -coverprofile=profile.cov -service=travis-ci
+4 -4
View File
@@ -8,7 +8,7 @@ import (
"strconv"
"strings"
"github.com/btcsuite/btcutil"
btcutil "github.com/lbryio/lbcutil"
)
// AmountFlag embeds a btcutil.Amount and implements the flags.Marshaler and
@@ -22,14 +22,14 @@ func NewAmountFlag(defaultValue btcutil.Amount) *AmountFlag {
return &AmountFlag{defaultValue}
}
// MarshalFlag satisifes the flags.Marshaler interface.
// MarshalFlag satisfies the flags.Marshaler interface.
func (a *AmountFlag) MarshalFlag() (string, error) {
return a.Amount.String(), nil
}
// UnmarshalFlag satisifes the flags.Unmarshaler interface.
// UnmarshalFlag satisfies the flags.Unmarshaler interface.
func (a *AmountFlag) UnmarshalFlag(value string) error {
value = strings.TrimSuffix(value, " BTC")
value = strings.TrimSuffix(value, " LBC")
valueF64, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-17
View File
@@ -1,17 +0,0 @@
// Copyright (c) 2013-2014 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
// +build !windows,!plan9
package rename
import (
"os"
)
// Atomic provides an atomic file rename. newpath is replaced if it
// already exists.
func Atomic(oldpath, newpath string) error {
return os.Rename(oldpath, newpath)
}
-71
View File
@@ -1,71 +0,0 @@
// The following is adapted from goleveldb
// (https://github.com/syndtr/goleveldb) under the following license:
//
// Copyright 2012 Suryandaru Triandana <syndtr@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package rename
import (
"syscall"
"unsafe"
)
var (
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
procMoveFileExW = modkernel32.NewProc("MoveFileExW")
)
const (
_MOVEFILE_REPLACE_EXISTING = 1
)
func moveFileEx(from *uint16, to *uint16, flags uint32) error {
r1, _, e1 := syscall.Syscall(procMoveFileExW.Addr(), 3,
uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)),
uintptr(flags))
if r1 == 0 {
if e1 != 0 {
return error(e1)
} else {
return syscall.EINVAL
}
}
return nil
}
// Atomic provides an atomic file rename. newpath is replaced if it
// already exists.
func Atomic(oldpath, newpath string) error {
from, err := syscall.UTF16PtrFromString(oldpath)
if err != nil {
return err
}
to, err := syscall.UTF16PtrFromString(newpath)
if err != nil {
return err
}
return moveFileEx(from, to, _MOVEFILE_REPLACE_EXISTING)
}
+75 -167
View File
@@ -2,6 +2,9 @@
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
//go:build !js
// +build !js
package prompt
import (
@@ -10,17 +13,15 @@ import (
"encoding/hex"
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/btcsuite/btcwallet/internal/legacy/keystore"
"github.com/lbryio/lbcutil/hdkeychain"
"golang.org/x/crypto/ssh/terminal"
)
// ProvideSeed is used to prompt for the wallet seed which maybe required during
// upgrades.
func ProvideSeed() ([]byte, error) {
reader := bufio.NewReader(os.Stdin)
func promptSeed(reader *bufio.Reader) ([]byte, error) {
for {
fmt.Print("Enter existing wallet seed: ")
seedStr, err := reader.ReadString('\n')
@@ -44,26 +45,6 @@ func ProvideSeed() ([]byte, error) {
}
}
// ProvidePrivPassphrase is used to prompt for the private passphrase which
// maybe required during upgrades.
func ProvidePrivPassphrase() ([]byte, error) {
prompt := "Enter the private passphrase of your wallet: "
for {
fmt.Print(prompt)
pass, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return nil, err
}
fmt.Print("\n")
pass = bytes.TrimSpace(pass)
if len(pass) == 0 {
continue
}
return pass, nil
}
}
// promptList prompts the user with the given prefix, list of valid responses,
// and default list entry to use. The function will repeat the prompt to the
// user until they enter a valid response.
@@ -100,8 +81,10 @@ func promptList(reader *bufio.Reader, prefix string, validResponses []string, de
// promptListBool prompts the user for a boolean (yes/no) with the given prefix.
// The function will repeat the prompt to the user until they enter a valid
// reponse.
func promptListBool(reader *bufio.Reader, prefix string, defaultEntry string) (bool, error) {
// response.
func promptListBool(reader *bufio.Reader, prefix string,
defaultEntry string) (bool, error) { // nolint:unparam
// Setup the valid responses.
valid := []string{"n", "no", "y", "yes"}
response, err := promptList(reader, prefix, valid, defaultEntry)
@@ -111,10 +94,41 @@ func promptListBool(reader *bufio.Reader, prefix string, defaultEntry string) (b
return response == "yes" || response == "y", nil
}
// promptPass prompts the user for a passphrase with the given prefix. The
// function will ask the user to confirm the passphrase and will repeat the
// prompts until they enter a matching response.
func promptPass(reader *bufio.Reader, prefix string, confirm bool) ([]byte, error) {
// promptBirhdayUnixTimeStamp prompts the user a Unix timestamp in second.
func promptUnixTimestamp(reader *bufio.Reader, prefix string,
defaultEntry string) (time.Time, error) { // nolint:unparam
prompt := fmt.Sprintf("%s [%s]: ", prefix, defaultEntry)
for {
fmt.Print(prompt)
reply, err := reader.ReadString('\n')
if err != nil {
return time.Time{}, err
}
reply = strings.TrimSpace(strings.ToLower(reply))
if reply == "" {
reply = defaultEntry
}
ts, err := strconv.ParseInt(reply, 10, 64)
if err != nil {
fmt.Print(prompt)
continue
}
return time.Unix(ts, 0), nil
}
}
// promptPassphrase prompts the user for a passphrase with the given prefix.
// The function will ask the user to confirm the passphrase and will repeat
// the prompts until they enter a matching response.
func promptPassphrase(prefix string, confirm bool) ([]byte, error) {
pass := os.Getenv("LBCWALLET_PASSPHRASE")
if len(pass) > 0 {
return []byte(pass), nil
}
// Prompt the user until they enter a passphrase.
prompt := fmt.Sprintf("%s: ", prefix)
for {
@@ -149,110 +163,17 @@ func promptPass(reader *bufio.Reader, prefix string, confirm bool) ([]byte, erro
}
}
// PrivatePass prompts the user for a private passphrase with varying behavior
// depending on whether the passed legacy keystore exists. When it does, the
// user is prompted for the existing passphrase which is then used to unlock it.
// On the other hand, when the legacy keystore is nil, the user is prompted for
// a new private passphrase. All prompts are repeated until the user enters a
// valid response.
func PrivatePass(reader *bufio.Reader, legacyKeyStore *keystore.Store) ([]byte, error) {
// When there is not an existing legacy wallet, simply prompt the user
// for a new private passphase and return it.
if legacyKeyStore == nil {
return promptPass(reader, "Enter the private "+
"passphrase for your new wallet", true)
}
// At this point, there is an existing legacy wallet, so prompt the user
// for the existing private passphrase and ensure it properly unlocks
// the legacy wallet so all of the addresses can later be imported.
fmt.Println("You have an existing legacy wallet. All addresses from " +
"your existing legacy wallet will be imported into the new " +
"wallet format.")
for {
privPass, err := promptPass(reader, "Enter the private "+
"passphrase for your existing wallet", false)
if err != nil {
return nil, err
}
// Keep prompting the user until the passphrase is correct.
if err := legacyKeyStore.Unlock([]byte(privPass)); err != nil {
if err == keystore.ErrWrongPassphrase {
fmt.Println(err)
continue
}
return nil, err
}
return privPass, nil
}
func birthday(reader *bufio.Reader) (time.Time, error) {
prompt := "Enter the birthday of the seed in Unix timestamp " +
"(the walllet will scan the chain from this time)"
return promptUnixTimestamp(reader, prompt, "0")
}
// PublicPass prompts the user whether they want to add an additional layer of
// encryption to the wallet. When the user answers yes and there is already a
// public passphrase provided via the passed config, it prompts them whether or
// not to use that configured passphrase. It will also detect when the same
// passphrase is used for the private and public passphrase and prompt the user
// if they are sure they want to use the same passphrase for both. Finally, all
// prompts are repeated until the user enters a valid response.
func PublicPass(reader *bufio.Reader, privPass []byte,
defaultPubPassphrase, configPubPassphrase []byte) ([]byte, error) {
pubPass := defaultPubPassphrase
usePubPass, err := promptListBool(reader, "Do you want "+
"to add an additional layer of encryption for public "+
"data?", "no")
if err != nil {
return nil, err
}
if !usePubPass {
return pubPass, nil
}
if !bytes.Equal(configPubPassphrase, pubPass) {
useExisting, err := promptListBool(reader, "Use the "+
"existing configured public passphrase for encryption "+
"of public data?", "no")
if err != nil {
return nil, err
}
if useExisting {
return configPubPassphrase, nil
}
}
for {
pubPass, err = promptPass(reader, "Enter the public "+
"passphrase for your new wallet", true)
if err != nil {
return nil, err
}
if bytes.Equal(pubPass, privPass) {
useSamePass, err := promptListBool(reader,
"Are you sure want to use the same passphrase "+
"for public and private data?", "no")
if err != nil {
return nil, err
}
if useSamePass {
break
}
continue
}
break
}
fmt.Println("NOTE: Use the --walletpass option to configure your " +
"public passphrase.")
return pubPass, nil
// Passphrase prompts the user for a passphrase.
// All prompts are repeated until the user enters a valid response.
func Passphrase(confirm bool) ([]byte, error) {
return promptPassphrase("Enter the passphrase "+
"for your new wallet", confirm)
}
// Seed prompts the user whether they want to use an existing wallet generation
@@ -260,34 +181,31 @@ func PublicPass(reader *bufio.Reader, privPass []byte,
// the user along with prompting them for confirmation. When the user answers
// yes, a the user is prompted for it. All prompts are repeated until the user
// enters a valid response.
func Seed(reader *bufio.Reader) ([]byte, error) {
func Seed(reader *bufio.Reader) ([]byte, time.Time, error) {
bday := time.Now()
// Ascertain the wallet generation seed.
useUserSeed, err := promptListBool(reader, "Do you have an "+
"existing wallet seed you want to use?", "no")
if err != nil {
return nil, err
return nil, bday, err
}
if !useUserSeed {
seed, err := hdkeychain.GenerateSeed(hdkeychain.RecommendedSeedLen)
if err != nil {
return nil, err
return nil, bday, err
}
fmt.Println("Your wallet generation seed is:")
fmt.Printf("%x\n", seed)
fmt.Println("IMPORTANT: Keep the seed in a safe place as you\n" +
"will NOT be able to restore your wallet without it.")
fmt.Println("Please keep in mind that anyone who has access\n" +
"to the seed can also restore your wallet thereby\n" +
"giving them access to all your funds, so it is\n" +
"imperative that you keep it in a secure location.")
fmt.Printf("Your wallet generation seed is: %x\n", seed)
fmt.Printf("\nIMPORTANT: Keep the seed in a safe place as you " +
"will NOT be able to restore your wallet without it.\n\n")
for {
fmt.Print(`Once you have stored the seed in a safe ` +
`and secure location, enter "OK" to continue: `)
confirmSeed, err := reader.ReadString('\n')
if err != nil {
return nil, err
return nil, bday, err
}
confirmSeed = strings.TrimSpace(confirmSeed)
confirmSeed = strings.Trim(confirmSeed, `"`)
@@ -296,28 +214,18 @@ func Seed(reader *bufio.Reader) ([]byte, error) {
}
}
return seed, nil
return seed, bday, nil
}
for {
fmt.Print("Enter existing wallet seed: ")
seedStr, err := reader.ReadString('\n')
if err != nil {
return nil, err
}
seedStr = strings.TrimSpace(strings.ToLower(seedStr))
seed, err := hex.DecodeString(seedStr)
if err != nil || len(seed) < hdkeychain.MinSeedBytes ||
len(seed) > hdkeychain.MaxSeedBytes {
fmt.Printf("Invalid seed specified. Must be a "+
"hexadecimal value that is at least %d bits and "+
"at most %d bits\n", hdkeychain.MinSeedBytes*8,
hdkeychain.MaxSeedBytes*8)
continue
}
return seed, nil
seed, err := promptSeed(reader)
if err != nil {
return nil, bday, err
}
bday, err = birthday(reader)
if err != nil {
return nil, bday, err
}
return seed, bday, nil
}
+4 -3
View File
@@ -2,7 +2,8 @@
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
//+build generate
//go:build generate
// +build generate
package main
@@ -12,8 +13,8 @@ import (
"os"
"strings"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcwallet/internal/rpchelp"
"github.com/lbryio/lbcd/btcjson"
"github.com/lbryio/lbcwallet/internal/rpchelp"
)
var outputFile = func() *os.File {
+330 -266
View File
@@ -2,326 +2,427 @@
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
//+build !generate
//go:build !generate
// +build !generate
package rpchelp
var helpDescsEnUS = map[string]string{
// AddMultisigAddressCmd help.
"addmultisigaddress--synopsis": "Generates and imports a multisig address and redeeming script to the 'imported' account.",
"addmultisigaddress-account": "DEPRECATED -- Unused (all imported addresses belong to the imported account)",
"addmultisigaddress-keys": "Pubkeys and/or pay-to-pubkey-hash addresses to partially control the multisig address",
"addmultisigaddress-nrequired": "The number of signatures required to redeem outputs paid to this address",
"addmultisigaddress--result0": "The imported pay-to-script-hash address",
"addmultisigaddress-account": "DEPRECATED -- Unused (all imported addresses belong to the imported account).",
"addmultisigaddress-keys": "Pubkeys and/or pay-to-pubkey-hash addresses to partially control the multisig address.",
"addmultisigaddress-nrequired": "The number of signatures required to redeem outputs paid to this address.",
"addmultisigaddress--result0": "The imported pay-to-script-hash address.",
// CreateMultisigCmd help.
"createmultisig--synopsis": "Generate a multisig address and redeem script.",
"createmultisig-keys": "Pubkeys and/or pay-to-pubkey-hash addresses to partially control the multisig address",
"createmultisig-nrequired": "The number of signatures required to redeem outputs paid to this address",
"createmultisig-keys": "Pubkeys and/or pay-to-pubkey-hash addresses to partially control the multisig address.",
"createmultisig-nrequired": "The number of signatures required to redeem outputs paid to this address.",
// CreateMultisigResult help.
"createmultisigresult-address": "The generated pay-to-script-hash address",
"createmultisigresult-redeemScript": "The script required to redeem outputs paid to the multisig address",
"createmultisigresult-address": "The generated pay-to-script-hash address.",
"createmultisigresult-redeemScript": "The script required to redeem outputs paid to the multisig address.",
// CreateNewAccountCmd help.
"createnewaccount--synopsis": "Creates a new account.",
"createnewaccount-account": "Account name.",
// DumpPrivKeyCmd help.
"dumpprivkey--synopsis": "Returns the private key in WIF encoding that controls some wallet address.",
"dumpprivkey-address": "The address to return a private key for",
"dumpprivkey--result0": "The WIF-encoded private key",
"dumpprivkey-address": "The address to return a private key for.",
"dumpprivkey--result0": "The WIF-encoded private key.",
// ExportWatchingWalletCmd help.
"exportwatchingwallet--synopsis": "Creates and returns a duplicate of the wallet database without any private keys to be used as a watching-only wallet.",
"exportwatchingwallet-account": "Unused (must be unset or \"*\").",
"exportwatchingwallet-download": "Unused.",
"exportwatchingwallet--result0": "The watching-only database encoded as a base64 string.",
// GetAccountCmd help.
"getaccount--synopsis": "DEPRECATED -- Lookup the account name that some wallet address belongs to.",
"getaccount-address": "The address to query the account for",
"getaccount--result0": "The name of the account that 'address' belongs to",
"getaccount--synopsis": "Lookup the account name that some wallet address belongs to.",
"getaccount-address": "The address to query the account for.",
"getaccount--result0": "The name of the account that 'address' belongs to.",
// GetAccountAddressCmd help.
"getaccountaddress--synopsis": "DEPRECATED -- Returns the most recent external payment address for an account that has not been seen publicly.\n" +
"getaccountaddress--synopsis": "Returns the most recent external payment address for an account that has not been seen publicly.\n" +
"A new address is generated for the account if the most recently generated address has been seen on the blockchain or in mempool.",
"getaccountaddress-account": "The account of the returned address",
"getaccountaddress--result0": "The unused address for 'account'",
"getaccountaddress-account": "The account of the returned address. Defaults to 'default'",
"getaccountaddress-addresstype": "Address type. Must be one of 'legacy', 'p2sh-segwit', or 'bech32'. Default to 'legacy'.",
"getaccountaddress--result0": "The unused address for 'account'.",
// GetAddressesByAccountCmd help.
"getaddressesbyaccount--synopsis": "DEPRECATED -- Returns all addresses strings controlled by a single account.",
"getaddressesbyaccount-account": "Account name to fetch addresses for",
"getaddressesbyaccount--result0": "All addresses controlled by 'account'",
"getaddressesbyaccount--synopsis": "Returns all addresses controlled by a single account.",
"getaddressesbyaccount-account": "Account name to fetch addresses for. Defaults to 'default'",
"getaddressesbyaccount-addresstype": "Address type filter. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.",
"getaddressesbyaccount--result0": "All addresses controlled by 'account' filtered by 'addresstype'.",
// GetBalanceCmd help.
"getbalance--synopsis": "Calculates and returns the balance of one or all accounts.",
"getbalance-minconf": "Minimum number of block confirmations required before an unspent output's value is included in the balance",
"getbalance-account": "DEPRECATED -- The account name to query the balance for, or \"*\" to consider all accounts (default=\"*\")",
"getbalance--condition0": "account != \"*\"",
"getbalance--condition1": "account = \"*\"",
"getbalance--result0": "The balance of 'account' valued in bitcoin",
"getbalance--result1": "The balance of all accounts valued in bitcoin",
"getbalance-minconf": "Minimum number of block confirmations required before an unspent output's value is included in the balance.",
"getbalance-account": "Account name or '*' for all accounts to query the balance for. Default to 'default'.",
"getbalance-addresstype": "Address type filter. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Default to '*'.",
"getbalance--result0": "The balance valued in LBC.",
// GetBestBlockCmd help.
"getbestblock--synopsis": "Returns the hash and height of the newest block in the best chain that wallet has finished syncing with.",
// GetBestBlockResult help.
"getbestblockresult-hash": "The hash of the block.",
"getbestblockresult-height": "The blockchain height of the block.",
// GetBestBlockHashCmd help.
"getbestblockhash--synopsis": "Returns the hash of the newest block in the best chain that wallet has finished syncing with.",
"getbestblockhash--result0": "The hash of the most recent synced-to block",
"getbestblockhash--result0": "The hash of the most recent synced-to block.",
// GetBlockCountCmd help.
"getblockcount--synopsis": "Returns the blockchain height of the newest block in the best chain that wallet has finished syncing with.",
"getblockcount--result0": "The blockchain height of the most recent synced-to block",
"getblockcount--result0": "The blockchain height of the most recent synced-to block.",
// GetInfoCmd help.
"getinfo--synopsis": "Returns a JSON object containing various state info.",
// InfoWalletResult help.
"infowalletresult-version": "The version of the server",
"infowalletresult-protocolversion": "The latest supported protocol version",
"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-relayfee": "The minimum relay fee for non-free transactions in BTC/KB",
"infowalletresult-errors": "Any current errors",
"infowalletresult-paytxfee": "The increment used each time more fee is required for an authored transaction",
"infowalletresult-balance": "The balance of all accounts calculated with one block confirmation",
"infowalletresult-walletversion": "The version of the address manager database",
"infowalletresult-unlocked_until": "Unset",
"infowalletresult-keypoolsize": "Unset",
"infowalletresult-keypoololdest": "Unset",
// GetUnconfirmedBalanceCmd help.
"getunconfirmedbalance--synopsis": "Calculates the unspent output value of all unmined transaction outputs.",
"getunconfirmedbalance-account": "The account name to query the unconfirmed balance for. Default to 'default'.",
"getunconfirmedbalance--result0": "Total amount of all unmined unspent outputs of the account valued in LBC.",
// GetAddressInfoCmd help.
"getaddressinfo--synopsis": "Generates and returns a new payment address.",
"getaddressinfo-address": "The address to get the information of.",
// GetAddressInfoResult help.
"getaddressinforesult-embedded": "Information about the address embedded in P2SH or P2WSH, if relevant and known.",
"getaddressinforesult-ismine": "If the address is yours.",
"getaddressinforesult-iswatchonly": "If the address is watchonly.",
"getaddressinforesult-timestamp": "The creation time of the key, if available, expressed in UNIX epoch time.",
"getaddressinforesult-hdkeypath": "The HD keypath, if the key is HD and available.",
"getaddressinforesult-hdseedid": "The Hash160 of the HD seed.",
"getaddressinforesult-address": "The address validatedi.",
"getaddressinforesult-scriptPubKey": "The hex-encoded scriptPubKey generated by the address.",
"getaddressinforesult-desc": "A descriptor for spending coins sent to this address (only when solvable).",
"getaddressinforesult-isscript": "If the key is a script.",
"getaddressinforesult-ischange": "If the address was used for change output.",
"getaddressinforesult-iswitness": "If the address is a witness address.",
"getaddressinforesult-witness_version": "The version number of the witness program.",
"getaddressinforesult-witness_program": "The hex value of the witness program.",
"getaddressinforesult-script": "The output script type. Only if isscript is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown.",
"getaddressinforesult-hex": "The redeemscript for the p2sh address.",
"getaddressinforesult-pubkeys": "The hex value of the raw public key for single-key addresses (possibly embedded in P2SH or P2WSH).",
"getaddressinforesult-sigsrequired": "The number of signatures required to spend multisig output (only if script is multisig).",
"getaddressinforesult-pubkey": "Array of pubkeys associated with the known redeemscript (only if script is multisig).",
"getaddressinforesult-iscompressed": "If the pubkey is compressed.",
"getaddressinforesult-hdmasterfingerprint": "The fingerprint of the master key.",
"getaddressinforesult-labels": "Array of labels associated with the address. Currently limited to one label but returned.",
"embeddedaddressinfo-address": "The address validated.",
"embeddedaddressinfo-scriptPubKey": "The hex-encoded scriptPubKey generated by the address.",
"embeddedaddressinfo-desc": "A descriptor for spending coins sent to this address (only when solvable).",
"embeddedaddressinfo-isscript": "If the key is a script.",
"embeddedaddressinfo-ischange": "If the address was used for change output.",
"embeddedaddressinfo-iswitness": "If the address is a witness address.",
"embeddedaddressinfo-witness_version": "The version number of the witness program.",
"embeddedaddressinfo-witness_program": "The hex value of the witness program.",
"embeddedaddressinfo-script": "The output script type. Only if isscript is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown.",
"embeddedaddressinfo-hex": "The redeemscript for the p2sh address.",
"embeddedaddressinfo-pubkeys": "The hex value of the raw public key for single-key addresses (possibly embedded in P2SH or P2WSH).",
"embeddedaddressinfo-sigsrequired": "The number of signatures required to spend multisig output (only if script is multisig).",
"embeddedaddressinfo-pubkey": "Array of pubkeys associated with the known redeemscript (only if script is multisig).",
"embeddedaddressinfo-iscompressed": "If the pubkey is compressed.",
"embeddedaddressinfo-hdmasterfingerprint": "The fingerprint of the master key.",
"embeddedaddressinfo-labels": "Array of labels associated with the address. Currently limited to one label but returned.",
// GetNewAddressCmd help.
"getnewaddress--synopsis": "Generates and returns a new payment address.",
"getnewaddress-account": "DEPRECATED -- Account name the new address will belong to (default=\"default\")",
"getnewaddress--result0": "The payment address",
"getnewaddress--synopsis": "Generates and returns a new payment address.",
"getnewaddress-account": "Account name the new address will belong to. Defaults to 'default'.",
"getnewaddress-addresstype": "Address type. Must be one of 'legacy', 'p2sh-segwit', or 'bech32'. Default to 'legacy'.",
"getnewaddress--result0": "The payment address.",
// GetRawChangeAddressCmd help.
"getrawchangeaddress--synopsis": "Generates and returns a new internal payment address for use as a change address in raw transactions.",
"getrawchangeaddress-account": "Account name the new internal address will belong to (default=\"default\")",
"getrawchangeaddress--result0": "The internal payment address",
"getrawchangeaddress--synopsis": "Generates and returns a new internal payment address for use as a change address in raw transactions.",
"getrawchangeaddress-account": "Account name the new internal address will belong to. Defaults to 'default'.",
"getrawchangeaddress-addresstype": "Address type. Must be one of 'legacy', 'p2sh-segwit', or 'bech32'. Default to 'legacy'.",
"getrawchangeaddress--result0": "The internal payment address.",
// GetReceivedByAccountCmd help.
"getreceivedbyaccount--synopsis": "DEPRECATED -- Returns the total amount received by addresses of some account, including spent outputs.",
"getreceivedbyaccount-account": "Account name to query total received amount for",
"getreceivedbyaccount-minconf": "Minimum number of block confirmations required before an output's value is included in the total",
"getreceivedbyaccount--result0": "The total received amount valued in bitcoin",
"getreceivedbyaccount--synopsis": "Returns the total amount received by addresses of some account, including spent outputs.",
"getreceivedbyaccount-account": "Account name to query total received amount for. Defaults to 'default'",
"getreceivedbyaccount-minconf": "Minimum number of block confirmations required before an output's value is included in the total. Defaults to 0",
"getreceivedbyaccount--result0": "The total received amount valued in LBC.",
// GetReceivedByAddressCmd help.
"getreceivedbyaddress--synopsis": "Returns the total amount received by a single address, including spent outputs.",
"getreceivedbyaddress-address": "Payment address which received outputs to include in total",
"getreceivedbyaddress-minconf": "Minimum number of block confirmations required before an output's value is included in the total",
"getreceivedbyaddress--result0": "The total received amount valued in bitcoin",
"getreceivedbyaddress-address": "Payment address which received outputs to include in total.",
"getreceivedbyaddress-minconf": "Minimum number of block confirmations required before an output's value is included in the total. Defaults to 1",
"getreceivedbyaddress--result0": "The total received amount valued in LBC.",
// GetTransactionCmd help.
"gettransaction--synopsis": "Returns a JSON object with details regarding a transaction relevant to this wallet.",
"gettransaction-txid": "Hash of the transaction to query",
"gettransaction-includewatchonly": "Also consider transactions involving watched addresses",
"gettransaction-txid": "Hash of the transaction to query.",
"gettransaction-includewatchonly": "Also consider transactions involving watched addresses.",
// GetTransactionResult help.
"gettransactionresult-amount": "The total amount this transaction credits to the wallet, valued in LBC.",
"gettransactionresult-fee": "The total input value minus the total output value, or 0 if 'txid' is not a sent transaction.",
"gettransactionresult-confirmations": "The number of block confirmations of the transaction.",
"gettransactionresult-generated": "Only present if transaction only input is a coinbase one.",
"gettransactionresult-blockhash": "The hash of the block this transaction is mined in, or the empty string if unmined.",
"gettransactionresult-blockindex": "Unset.",
"gettransactionresult-blocktime": "The Unix time of the block header this transaction is mined in, or 0 if unmined.",
"gettransactionresult-txid": "The transaction hash.",
"gettransactionresult-walletconflicts": "Unset.",
"gettransactionresult-time": "The earliest Unix time this transaction was known to exist.",
"gettransactionresult-timereceived": "The earliest Unix time this transaction was known to exist.",
"gettransactionresult-details": "Additional details for each recorded wallet credit and debit.",
"gettransactionresult-hex": "The transaction encoded as a hexadecimal string.",
// GetTransactionDetailsResult help.
"gettransactiondetailsresult-account": "The account pertaining to this transaction.",
"gettransactiondetailsresult-address": "The address an output was paid to, or the empty string if the output is nonstandard or this detail is regarding a transaction input.",
"gettransactiondetailsresult-category": `The kind of detail: "send" for sent transactions, "immature" for immature coinbase outputs, "generate" for mature coinbase outputs, or "recv" for all other received outputs.`,
"gettransactiondetailsresult-amount": "The amount of a received output.",
"gettransactiondetailsresult-fee": "The included fee for a sent transaction.",
"gettransactiondetailsresult-vout": "The transaction output index.",
"gettransactiondetailsresult-involveswatchonly": "Unset.",
// HelpCmd help.
"help--synopsis": "Returns a list of all commands or help for a specified command.",
"help-command": "The command to retrieve help for",
"help--condition0": "no command provided",
"help--condition1": "command specified",
"help--result0": "List of commands",
"help--result1": "Help for specified command",
// GetTransactionResult help.
"gettransactionresult-amount": "The total amount this transaction credits to the wallet, valued in bitcoin",
"gettransactionresult-fee": "The total input value minus the total output value, or 0 if 'txid' is not a sent transaction",
"gettransactionresult-confirmations": "The number of block confirmations of the transaction",
"gettransactionresult-blockhash": "The hash of the block this transaction is mined in, or the empty string if unmined",
"gettransactionresult-blockindex": "Unset",
"gettransactionresult-blocktime": "The Unix time of the block header this transaction is mined in, or 0 if unmined",
"gettransactionresult-txid": "The transaction hash",
"gettransactionresult-walletconflicts": "Unset",
"gettransactionresult-time": "The earliest Unix time this transaction was known to exist",
"gettransactionresult-timereceived": "The earliest Unix time this transaction was known to exist",
"gettransactionresult-details": "Additional details for each recorded wallet credit and debit",
"gettransactionresult-hex": "The transaction encoded as a hexadecimal string",
// GetTransactionDetailsResult help.
"gettransactiondetailsresult-account": "DEPRECATED -- Unset",
"gettransactiondetailsresult-address": "The address an output was paid to, or the empty string if the output is nonstandard or this detail is regarding a transaction input",
"gettransactiondetailsresult-category": `The kind of detail: "send" for sent transactions, "immature" for immature coinbase outputs, "generate" for mature coinbase outputs, or "recv" for all other received outputs`,
"gettransactiondetailsresult-amount": "The amount of a received output",
"gettransactiondetailsresult-fee": "The included fee for a sent transaction",
"gettransactiondetailsresult-vout": "The transaction output index",
"gettransactiondetailsresult-involveswatchonly": "Unset",
"help-command": "The command to retrieve help for.",
"help--condition0": "no command provided.",
"help--condition1": "command specified.",
"help--result0": "List of commands.",
"help--result1": "Help for specified command.",
// ImportPrivKeyCmd help.
"importprivkey--synopsis": "Imports a WIF-encoded private key to the 'imported' account.",
"importprivkey-privkey": "The WIF-encoded private key",
"importprivkey-label": "Unused (must be unset or 'imported')",
"importprivkey-rescan": "Rescan the blockchain (since the genesis block) for outputs controlled by the imported key",
"importprivkey-privkey": "The WIF-encoded private key.",
"importprivkey-label": "Unused (must be unset or 'imported').",
"importprivkey-rescan": "Rescan the blockchain (since the genesis block) for outputs controlled by the imported key.",
// InfoWalletResult help.
"infowalletresult-version": "The version of the server.",
"infowalletresult-protocolversion": "The latest supported protocol version.",
"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-relayfee": "The minimum relay fee for non-free transactions in LBC/KB.",
"infowalletresult-errors": "Any current errors.",
"infowalletresult-paytxfee": "The increment used each time more fee is required for an authored transaction.",
"infowalletresult-balance": "The non-staked balance of all accounts calculated with one block confirmation.",
"infowalletresult-staked": "The staked balance of all accounts calculated with one block confirmation.",
"infowalletresult-walletversion": "The version of the address manager database.",
"infowalletresult-unlocked_until": "Unset.",
"infowalletresult-keypoolsize": "Unset.",
"infowalletresult-keypoololdest": "Unset.",
// KeypoolRefillCmd help.
"keypoolrefill--synopsis": "DEPRECATED -- This request does nothing since no keypool is maintained.",
"keypoolrefill-newsize": "Unused",
"keypoolrefill-newsize": "Unused.",
// ListAccountsCmd help.
"listaccounts--synopsis": "DEPRECATED -- Returns a JSON object of all accounts and their balances.",
"listaccounts-minconf": "Minimum number of block confirmations required before an unspent output's value is included in the balance",
"listaccounts--result0--desc": "JSON object with account names as keys and bitcoin amounts as values",
"listaccounts--result0--key": "The account name",
"listaccounts--result0--value": "The account balance valued in bitcoin",
"listaccounts--synopsis": "Returns a JSON object of all accounts and their balances.",
"listaccounts-minconf": "Minimum number of block confirmations required before an unspent output's value is included in the balance.",
"listaccounts-addresstype": "Address type filter. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.",
"listaccounts--result0--desc": "JSON object with account names as keys and LBC amounts as values.",
"listaccounts--result0--key": "Account name",
"listaccounts--result0--value": "Total balance and each scope respectively, valued in LBC.",
// ListAddressTransactionsCmd help.
"listaddresstransactions--synopsis": "Returns a JSON array of objects containing verbose details for wallet transactions pertaining some addresses.",
"listaddresstransactions-addresses": "Addresses to filter transaction results by.",
"listaddresstransactions-account": "Account to filter transactions results by. Defaults to 'default'.",
// ListAllTransactionsCmd help.
"listalltransactions--synopsis": "Returns a JSON array of objects in the same format as 'listtransactions' without limiting the number of returned objects.",
"listalltransactions-account": "Account to filter transactions results by. Defaults to 'default'.",
// ListLockUnspentCmd help.
"listlockunspent--synopsis": "Returns a JSON array of outpoints marked as locked (with lockunspent) for this wallet session.",
// TransactionInput help.
"transactioninput-txid": "The transaction hash of the referenced output",
"transactioninput-vout": "The output index of the referenced output",
"transactioninput-txid": "The transaction hash of the referenced output.",
"transactioninput-vout": "The output index of the referenced output.",
// ListReceivedByAccountCmd help.
"listreceivedbyaccount--synopsis": "DEPRECATED -- Returns a JSON array of objects listing all accounts and the total amount received by each account.",
"listreceivedbyaccount-minconf": "Minimum number of block confirmations required before a transaction is considered",
"listreceivedbyaccount-includeempty": "Unused",
"listreceivedbyaccount-includewatchonly": "Unused",
"listreceivedbyaccount--synopsis": "Returns a JSON array of objects listing all accounts and the total amount received by each account.",
"listreceivedbyaccount-minconf": "Minimum number of block confirmations required before a transaction is considered.",
"listreceivedbyaccount-includeempty": "Unused.",
"listreceivedbyaccount-includewatchonly": "Unused.",
// ListReceivedByAccountResult help.
"listreceivedbyaccountresult-account": "The name of the account",
"listreceivedbyaccountresult-amount": "Total amount received by payment addresses of the account valued in bitcoin",
"listreceivedbyaccountresult-confirmations": "Number of block confirmations of the most recent transaction relevant to the account",
"listreceivedbyaccountresult-account": "Account name.",
"listreceivedbyaccountresult-amount": "Total amount received by payment addresses of the account valued in LBC.",
"listreceivedbyaccountresult-confirmations": "Number of block confirmations of the most recent transaction relevant to the account.",
// ListReceivedByAddressCmd help.
"listreceivedbyaddress--synopsis": "Returns a JSON array of objects listing wallet payment addresses and their total received amounts.",
"listreceivedbyaddress-minconf": "Minimum number of block confirmations required before a transaction is considered",
"listreceivedbyaddress-includeempty": "Unused",
"listreceivedbyaddress-includewatchonly": "Unused",
"listreceivedbyaddress-minconf": "Minimum number of block confirmations required before a transaction is considered.",
"listreceivedbyaddress-includeempty": "Unused.",
"listreceivedbyaddress-includewatchonly": "Unused.",
// ListReceivedByAddressResult help.
"listreceivedbyaddressresult-account": "DEPRECATED -- Unset",
"listreceivedbyaddressresult-address": "The payment address",
"listreceivedbyaddressresult-amount": "Total amount received by the payment address valued in bitcoin",
"listreceivedbyaddressresult-confirmations": "Number of block confirmations of the most recent transaction relevant to the address",
"listreceivedbyaddressresult-txids": "Transaction hashes of all transactions involving this address",
"listreceivedbyaddressresult-involvesWatchonly": "Unset",
"listreceivedbyaddressresult-address": "The payment address.",
"listreceivedbyaddressresult-amount": "Total amount received by the payment address valued in LBC.",
"listreceivedbyaddressresult-confirmations": "Number of block confirmations of the most recent transaction relevant to the address.",
"listreceivedbyaddressresult-txids": "Transaction hashes of all transactions involving this address.",
"listreceivedbyaddressresult-involvesWatchonly": "Unset.",
// ListSinceBlockCmd help.
"listsinceblock--synopsis": "Returns a JSON array of objects listing details of all wallet transactions after some block.",
"listsinceblock-blockhash": "Hash of the parent block of the first block to consider transactions from, or unset to list all transactions",
"listsinceblock-targetconfirmations": "Minimum number of block confirmations of the last block in the result object. Must be 1 or greater. Note: The transactions array in the result object is not affected by this parameter",
"listsinceblock-includewatchonly": "Unused",
"listsinceblock--condition0": "blockhash specified",
"listsinceblock--condition1": "no blockhash specified",
"listsinceblock--result0": "Lists all transactions, including unmined transactions, since the specified block",
"listsinceblock--result1": "Lists all transactions since the genesis block",
"listsinceblock-blockhash": "Hash of the parent block of the first block to consider transactions from, or unset to list all transactions.",
"listsinceblock-targetconfirmations": "Minimum number of block confirmations of the last block in the result object. Must be 1 or greater. Note: The transactions array in the result object is not affected by this parameter.",
"listsinceblock-includewatchonly": "Unused.",
"listsinceblock--condition0": "blockhash specified.",
"listsinceblock--condition1": "no blockhash specified.",
"listsinceblock--result0": "Lists all transactions, including unmined transactions, since the specified block.",
"listsinceblock--result1": "Lists all transactions since the genesis block.",
// ListSinceBlockResult help.
"listsinceblockresult-transactions": "JSON array of objects containing verbose details of the each transaction",
"listsinceblockresult-lastblock": "Hash of the latest-synced block to be used in later calls to listsinceblock",
// ListTransactionsResult help.
"listtransactionsresult-account": "DEPRECATED -- Unset",
"listtransactionsresult-address": "Payment address for a transaction output",
"listtransactionsresult-category": `The kind of transaction: "send" for sent transactions, "immature" for immature coinbase outputs, "generate" for mature coinbase outputs, or "recv" for all other received outputs. Note: A single output may be included multiple times under different categories`,
"listtransactionsresult-amount": "The value of the transaction output valued in bitcoin",
"listtransactionsresult-fee": "The total input value minus the total output value for sent transactions",
"listtransactionsresult-confirmations": "The number of block confirmations of the transaction",
"listtransactionsresult-generated": "Whether the transaction output is a coinbase output",
"listtransactionsresult-blockhash": "The hash of the block this transaction is mined in, or the empty string if unmined",
"listtransactionsresult-blockindex": "Unset",
"listtransactionsresult-blocktime": "The Unix time of the block header this transaction is mined in, or 0 if unmined",
"listtransactionsresult-txid": "The hash of the transaction",
"listtransactionsresult-vout": "The transaction output index",
"listtransactionsresult-walletconflicts": "Unset",
"listtransactionsresult-time": "The earliest Unix time this transaction was known to exist",
"listtransactionsresult-timereceived": "The earliest Unix time this transaction was known to exist",
"listtransactionsresult-involveswatchonly": "Unset",
"listtransactionsresult-comment": "Unset",
"listtransactionsresult-otheraccount": "Unset",
"listtransactionsresult-trusted": "Unset",
"listtransactionsresult-bip125-replaceable": "Unset",
"listtransactionsresult-abandoned": "Unset",
"listsinceblockresult-transactions": "JSON array of objects containing verbose details of the each transaction.",
"listsinceblockresult-lastblock": "Hash of the latest-synced block to be used in later calls to listsinceblock.",
// ListTransactionsCmd help.
"listtransactions--synopsis": "Returns a JSON array of objects containing verbose details for wallet transactions.",
"listtransactions-account": "DEPRECATED -- Unused (must be unset or \"*\")",
"listtransactions-count": "Maximum number of transactions to create results from",
"listtransactions-from": "Number of transactions to skip before results are created",
"listtransactions-includewatchonly": "Unused",
"listtransactions-account": "Account to filter transactions results by. Defaults to 'default'.",
"listtransactions-count": "Maximum number of transactions to create results from. Defaults to 10",
"listtransactions-from": "Number of transactions to skip before results are created.",
"listtransactions-includewatchonly": "Unused.",
// ListTransactionsResult help.
"listtransactionsresult-account": "The account name associated with the transaction.",
"listtransactionsresult-address": "Payment address for a transaction output.",
"listtransactionsresult-category": `The kind of transaction: "send" for sent transactions, "immature" for immature coinbase outputs, "generate" for mature coinbase outputs, or "recv" for all other received outputs. Note: A single output may be included multiple times under different categories`,
"listtransactionsresult-amount": "The value of the transaction output valued in LBC.",
"listtransactionsresult-fee": "The total input value minus the total output value for sent transactions.",
"listtransactionsresult-confirmations": "The number of block confirmations of the transaction.",
"listtransactionsresult-generated": "Whether the transaction output is a coinbase output.",
"listtransactionsresult-blockhash": "The hash of the block this transaction is mined in, or the empty string if unmined.",
"listtransactionsresult-blockheight": "The block height containing the transaction.",
"listtransactionsresult-blockindex": "Unset.",
"listtransactionsresult-blocktime": "The Unix time of the block header this transaction is mined in, or 0 if unmined.",
"listtransactionsresult-label": "A comment for the address/transaction, if any.",
"listtransactionsresult-txid": "The hash of the transaction.",
"listtransactionsresult-vout": "The transaction output index.",
"listtransactionsresult-walletconflicts": "Unset.",
"listtransactionsresult-time": "The earliest Unix time this transaction was known to exist.",
"listtransactionsresult-timereceived": "The earliest Unix time this transaction was known to exist.",
"listtransactionsresult-involveswatchonly": "Unset.",
"listtransactionsresult-comment": "Unset.",
"listtransactionsresult-otheraccount": "Unset.",
"listtransactionsresult-trusted": "Unset.",
"listtransactionsresult-bip125-replaceable": "Unset.",
"listtransactionsresult-abandoned": "Unset.",
// ListUnspentCmd help.
"listunspent--synopsis": "Returns a JSON array of objects representing unlocked unspent outputs controlled by wallet keys.",
"listunspent-minconf": "Minimum number of block confirmations required before a transaction output is considered",
"listunspent-maxconf": "Maximum number of block confirmations required before a transaction output is excluded",
"listunspent-addresses": "If set, limits the returned details to unspent outputs received by any of these payment addresses",
"listunspent-minconf": "Minimum number of block confirmations required before a transaction output is considered.",
"listunspent-maxconf": "Maximum number of block confirmations required before a transaction output is excluded.",
"listunspent-addresses": "If set, limits the returned details to unspent outputs received by any of these payment addresses.",
// ListUnspentResult help.
"listunspentresult-txid": "The transaction hash of the referenced output",
"listunspentresult-vout": "The output index of the referenced output",
"listunspentresult-address": "The payment address that received the output",
"listunspentresult-account": "The account associated with the receiving payment address",
"listunspentresult-scriptPubKey": "The output script encoded as a hexadecimal string",
"listunspentresult-redeemScript": "Unset",
"listunspentresult-amount": "The amount of the output valued in bitcoin",
"listunspentresult-confirmations": "The number of block confirmations of the transaction",
"listunspentresult-spendable": "Whether the output is entirely controlled by wallet keys/scripts (false for partially controlled multisig outputs or outputs to watch-only addresses)",
"listunspentresult-txid": "The transaction hash of the referenced output.",
"listunspentresult-vout": "The output index of the referenced output.",
"listunspentresult-address": "The payment address that received the output.",
"listunspentresult-account": "The account associated with the receiving payment address.",
"listunspentresult-scriptPubKey": "The output script encoded as a hexadecimal string.",
"listunspentresult-redeemScript": "Unset.",
"listunspentresult-amount": "The amount of the output valued in LBC.",
"listunspentresult-confirmations": "The number of block confirmations of the transaction.",
"listunspentresult-solvable": "Whether the output is solvable.",
"listunspentresult-spendable": "Whether the output is entirely controlled by wallet keys/scripts (false for partially controlled multisig outputs or outputs to watch-only addresses).",
"listunspentresult-isstake": "Whether the output is staked.",
// LockUnspentCmd help.
"lockunspent--synopsis": "Locks or unlocks an unspent output.\n" +
"Locked outputs are not chosen for transaction inputs of authored transactions and are not included in 'listunspent' results.\n" +
"Locked outputs are volatile and are not saved across wallet restarts.\n" +
"If unlock is true and no transaction outputs are specified, all locked outputs are marked unlocked.",
"lockunspent-unlock": "True to unlock outputs, false to lock",
"lockunspent-transactions": "Transaction outputs to lock or unlock",
"lockunspent--result0": "The boolean 'true'",
"lockunspent-unlock": "True to unlock outputs, false to lock.",
"lockunspent-transactions": "Transaction outputs to lock or unlock.",
"lockunspent--result0": "The boolean 'true'.",
// RenameAccountCmd help.
"renameaccount--synopsis": "Renames an account.",
"renameaccount-oldaccount": "The old account name to rename.",
"renameaccount-newaccount": "The new name for the account.",
// RescanBlockchainCmd help.
"rescanblockchain--synopsis": "Renames an account.",
"rescanblockchain-startheight": "Block height where the rescan should start.",
"rescanblockchain-stopheight": "The last block height that should be scanned. If none is provided it will rescan up to the tip at return time of this call.",
// RescanblockchainResult help.
"rescanblockchainresult-start_height": "The block height where the rescan started (the requested height or 0)",
"rescanblockchainresult-stop_height": "The height of the last rescanned block.",
// SendFromCmd help.
"sendfrom--synopsis": "DEPRECATED -- Authors, signs, and sends a transaction that outputs some amount to a payment address.\n" +
"sendfrom--synopsis": "Authors, signs, and sends a transaction that outputs some amount to a payment address.\n" +
"A change output is automatically included to send extra output value back to the original account.",
"sendfrom-fromaccount": "Account to pick unspent outputs from",
"sendfrom-toaddress": "Address to pay",
"sendfrom-amount": "Amount to send to the payment address valued in bitcoin",
"sendfrom-minconf": "Minimum number of block confirmations required before a transaction output is eligible to be spent",
"sendfrom-comment": "Unused",
"sendfrom-commentto": "Unused",
"sendfrom--result0": "The transaction hash of the sent transaction",
"sendfrom-fromaccount": "Account to pick unspent outputs from.",
"sendfrom-toaddress": "Address to pay.",
"sendfrom-amount": "Amount to send to the payment address valued in LBC.",
"sendfrom-minconf": "Minimum number of block confirmations required before a transaction output is eligible to be spent.",
"sendfrom-addresstype": "Address type filter for UTXOs to spent from. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.",
"sendfrom-comment": "Unused.",
"sendfrom-commentto": "Unused.",
"sendfrom--result0": "The transaction hash of the sent transaction.",
// SendManyCmd help.
"sendmany--synopsis": "Authors, signs, and sends a transaction that outputs to many payment addresses.\n" +
"A change output is automatically included to send extra output value back to the original account.",
"sendmany-fromaccount": "DEPRECATED -- Account to pick unspent outputs from",
"sendmany-amounts": "Pairs of payment addresses and the output amount to pay each",
"sendmany-amounts--desc": "JSON object using payment addresses as keys and output amounts valued in bitcoin to send to each address",
"sendmany-amounts--key": "Address to pay",
"sendmany-amounts--value": "Amount to send to the payment address valued in bitcoin",
"sendmany-minconf": "Minimum number of block confirmations required before a transaction output is eligible to be spent",
"sendmany-comment": "Unused",
"sendmany--result0": "The transaction hash of the sent transaction",
"sendmany-fromaccount": "Account to pick unspent outputs from.",
"sendmany-amounts": "Pairs of payment addresses and the output amount to pay each.",
"sendmany-amounts--desc": "JSON object using payment addresses as keys and output amounts valued in LBC to send to each address.",
"sendmany-amounts--key": "Address to pay.",
"sendmany-amounts--value": "Amount to send to the payment address valued in LBC.",
"sendmany-minconf": "Minimum number of block confirmations required before a transaction output is eligible to be spent.",
"sendmany-addresstype": "Address type filter for UTXOs to spent from. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.",
"sendmany-comment": "Unused.",
"sendmany--result0": "The transaction hash of the sent transaction.",
// SendToAddressCmd help.
"sendtoaddress--synopsis": "Authors, signs, and sends a transaction that outputs some amount to a payment address.\n" +
"Unlike sendfrom, outputs are always chosen from the default account.\n" +
"A change output is automatically included to send extra output value back to the original account.",
"sendtoaddress-address": "Address to pay",
"sendtoaddress-amount": "Amount to send to the payment address valued in bitcoin",
"sendtoaddress-comment": "Unused",
"sendtoaddress-commentto": "Unused",
"sendtoaddress--result0": "The transaction hash of the sent transaction",
"sendtoaddress-address": "Address to pay.",
"sendtoaddress-amount": "Amount to send to the payment address valued in LBC.",
"sendtoaddress-addresstype": "Address type filter for UTXOs to spent from. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.",
"sendtoaddress-comment": "Unused.",
"sendtoaddress-commentto": "Unused.",
"sendtoaddress--result0": "The transaction hash of the sent transaction.",
// SetTxFeeCmd help.
"settxfee--synopsis": "Modify the increment used each time more fee is required for an authored transaction.",
"settxfee-amount": "The new fee increment valued in bitcoin",
"settxfee--result0": "The boolean 'true'",
"settxfee-amount": "The new fee increment valued in LBC.",
"settxfee--result0": "The boolean 'true'.",
// SignMessageCmd help.
"signmessage--synopsis": "Signs a message using the private key of a payment address.",
"signmessage-address": "Payment address of private key used to sign the message with",
"signmessage-message": "Message to sign",
"signmessage--result0": "The signed message encoded as a base64 string",
"signmessage-address": "Payment address of private key used to sign the message with.",
"signmessage-message": "Message to sign.",
"signmessage--result0": "The signed message encoded as a base64 string.",
// SignRawTransactionCmd help.
"signrawtransaction--synopsis": "Signs transaction inputs using private keys from this wallet and request.\n" +
"The valid flags options are ALL, NONE, SINGLE, ALL|ANYONECANPAY, NONE|ANYONECANPAY, and SINGLE|ANYONECANPAY.",
"signrawtransaction-rawtx": "Unsigned or partially unsigned transaction to sign encoded as a hexadecimal string",
"signrawtransaction-inputs": "Additional data regarding inputs that this wallet may not be tracking",
"signrawtransaction-privkeys": "Additional WIF-encoded private keys to use when creating signatures",
"signrawtransaction-flags": "Sighash flags",
"signrawtransaction-rawtx": "Unsigned or partially unsigned transaction to sign encoded as a hexadecimal string.",
"signrawtransaction-inputs": "Additional data regarding inputs that this wallet may not be tracking.",
"signrawtransaction-privkeys": "Additional WIF-encoded private keys to use when creating signatures.",
"signrawtransaction-flags": "Sighash flags.",
// SignRawTransactionResult help.
"signrawtransactionresult-hex": "The resulting transaction encoded as a hexadecimal string",
"signrawtransactionresult-complete": "Whether all input signatures have been created",
"signrawtransactionresult-errors": "Script verification errors (if exists)",
"signrawtransactionresult-hex": "The resulting transaction encoded as a hexadecimal string.",
"signrawtransactionresult-complete": "Whether all input signatures have been created.",
"signrawtransactionresult-errors": "Script verification errors (if exists).",
// SignRawTransactionError help.
"signrawtransactionerror-error": "Verification or signing error related to the input",
"signrawtransactionerror-sequence": "Script sequence number",
"signrawtransactionerror-scriptSig": "The hex-encoded signature script",
"signrawtransactionerror-txid": "The transaction hash of the referenced previous output",
"signrawtransactionerror-vout": "The output index of the referenced previous output",
"signrawtransactionerror-error": "Verification or signing error related to the input.",
"signrawtransactionerror-sequence": "Script sequence number.",
"signrawtransactionerror-scriptSig": "The hex-encoded signature script.",
"signrawtransactionerror-txid": "The transaction hash of the referenced previous output.",
"signrawtransactionerror-vout": "The output index of the referenced previous output.",
// ValidateAddressCmd help.
"validateaddress--synopsis": "Verify that an address is valid.\n" +
@@ -330,80 +431,43 @@ var helpDescsEnUS = map[string]string{
"The following fields are only valid when address has an associated public key: pubkey, iscompressed.\n" +
"The following fields are only valid when address is a pay-to-script-hash address: addresses, hex, and script.\n" +
"If the address is a multisig address controlled by this wallet, the multisig fields will be left unset if the wallet is locked since the redeem script cannot be decrypted.",
"validateaddress-address": "Address to validate",
"validateaddress-address": "Address to validate.",
// ValidateAddressWalletResult help.
"validateaddresswalletresult-isvalid": "Whether or not the address is valid",
"validateaddresswalletresult-address": "The payment address (only when isvalid is true)",
"validateaddresswalletresult-ismine": "Whether this address is controlled by the wallet (only when isvalid is true)",
"validateaddresswalletresult-iswatchonly": "Unset",
"validateaddresswalletresult-isscript": "Whether the payment address is a pay-to-script-hash address (only when isvalid is true)",
"validateaddresswalletresult-pubkey": "The associated public key of the payment address, if any (only when isvalid is true)",
"validateaddresswalletresult-iscompressed": "Whether the address was created by hashing a compressed public key, if any (only when isvalid is true)",
"validateaddresswalletresult-account": "The account this payment address belongs to (only when isvalid is true)",
"validateaddresswalletresult-addresses": "All associated payment addresses of the script if address is a multisig address (only when isvalid is true)",
"validateaddresswalletresult-hex": "The redeem script ",
"validateaddresswalletresult-script": "The class of redeem script for a multisig address",
"validateaddresswalletresult-sigsrequired": "The number of required signatures to redeem outputs to the multisig address",
"validateaddresswalletresult-isvalid": "Whether or not the address is valid.",
"validateaddresswalletresult-address": "The payment address (only when isvalid is true).",
"validateaddresswalletresult-ismine": "Whether this address is controlled by the wallet (only when isvalid is true).",
"validateaddresswalletresult-iswatchonly": "Unset.",
"validateaddresswalletresult-isscript": "Whether the payment address is a pay-to-script-hash address (only when isvalid is true).",
"validateaddresswalletresult-pubkey": "The associated public key of the payment address, if any (only when isvalid is true).",
"validateaddresswalletresult-iscompressed": "Whether the address was created by hashing a compressed public key, if any (only when isvalid is true).",
"validateaddresswalletresult-account": "The account this payment address belongs to (only when isvalid is true).",
"validateaddresswalletresult-addresses": "All associated payment addresses of the script if address is a multisig address (only when isvalid is true).",
"validateaddresswalletresult-hex": "The redeem script .",
"validateaddresswalletresult-script": "The class of redeem script for a multisig address.",
"validateaddresswalletresult-sigsrequired": "The number of required signatures to redeem outputs to the multisig address.",
// VerifyMessageCmd help.
"verifymessage--synopsis": "Verify a message was signed with the associated private key of some address.",
"verifymessage-address": "Address used to sign message",
"verifymessage-signature": "The signature to verify",
"verifymessage-message": "The message to verify",
"verifymessage--result0": "Whether the message was signed with the private key of 'address'",
"verifymessage-address": "Address used to sign message.",
"verifymessage-signature": "The signature to verify.",
"verifymessage-message": "The message to verify.",
"verifymessage--result0": "Whether the message was signed with the private key of 'address'.",
// WalletIsLockedCmd help.
"walletislocked--synopsis": "Returns whether or not the wallet is locked.",
"walletislocked--result0": "Whether the wallet is locked.",
// WalletLockCmd help.
"walletlock--synopsis": "Lock the wallet.",
// WalletPassphraseCmd help.
"walletpassphrase--synopsis": "Unlock the wallet.",
"walletpassphrase-passphrase": "The wallet passphrase",
"walletpassphrase-timeout": "The number of seconds to wait before the wallet automatically locks",
"walletpassphrase-passphrase": "The wallet passphrase.",
"walletpassphrase-timeout": "The number of seconds to wait before the wallet automatically locks.",
// WalletPassphraseChangeCmd help.
"walletpassphrasechange--synopsis": "Change the wallet passphrase.",
"walletpassphrasechange-oldpassphrase": "The old wallet passphrase",
"walletpassphrasechange-newpassphrase": "The new wallet passphrase",
// CreateNewAccountCmd help.
"createnewaccount--synopsis": "Creates a new account.\n" +
"The wallet must be unlocked for this request to succeed.",
"createnewaccount-account": "Name of the new account",
// ExportWatchingWalletCmd help.
"exportwatchingwallet--synopsis": "Creates and returns a duplicate of the wallet database without any private keys to be used as a watching-only wallet.",
"exportwatchingwallet-account": "Unused (must be unset or \"*\")",
"exportwatchingwallet-download": "Unused",
"exportwatchingwallet--result0": "The watching-only database encoded as a base64 string",
// GetBestBlockCmd help.
"getbestblock--synopsis": "Returns the hash and height of the newest block in the best chain that wallet has finished syncing with.",
// GetBestBlockResult help.
"getbestblockresult-hash": "The hash of the block",
"getbestblockresult-height": "The blockchain height of the block",
// GetUnconfirmedBalanceCmd help.
"getunconfirmedbalance--synopsis": "Calculates the unspent output value of all unmined transaction outputs for an account.",
"getunconfirmedbalance-account": "The account to query the unconfirmed balance for (default=\"default\")",
"getunconfirmedbalance--result0": "Total amount of all unmined unspent outputs of the account valued in bitcoin.",
// ListAddressTransactionsCmd help.
"listaddresstransactions--synopsis": "Returns a JSON array of objects containing verbose details for wallet transactions pertaining some addresses.",
"listaddresstransactions-addresses": "Addresses to filter transaction results by",
"listaddresstransactions-account": "Unused (must be unset or \"*\")",
// ListAllTransactionsCmd help.
"listalltransactions--synopsis": "Returns a JSON array of objects in the same format as 'listtransactions' without limiting the number of returned objects.",
"listalltransactions-account": "Unused (must be unset or \"*\")",
// RenameAccountCmd help.
"renameaccount--synopsis": "Renames an account.",
"renameaccount-oldaccount": "The old account name to rename",
"renameaccount-newaccount": "The new name for the account",
// WalletIsLockedCmd help.
"walletislocked--synopsis": "Returns whether or not the wallet is locked.",
"walletislocked--result0": "Whether the wallet is locked",
"walletpassphrasechange-oldpassphrase": "The old wallet passphrase.",
"walletpassphrasechange-newpassphrase": "The new wallet passphrase.",
}
+8 -4
View File
@@ -2,11 +2,14 @@
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
//+build !generate
//go:build !generate
// +build !generate
package rpchelp
import "github.com/btcsuite/btcd/btcjson"
import (
"github.com/lbryio/lbcd/btcjson"
)
// Common return types.
var (
@@ -29,7 +32,8 @@ var Methods = []struct {
{"getaccount", returnsString},
{"getaccountaddress", returnsString},
{"getaddressesbyaccount", returnsStringArray},
{"getbalance", append(returnsNumber, returnsNumber[0])},
{"getaddressinfo", []interface{}{(*btcjson.GetAddressInfoResult)(nil)}},
{"getbalance", returnsNumber},
{"getbestblockhash", returnsString},
{"getblockcount", returnsNumber},
{"getinfo", []interface{}{(*btcjson.InfoWalletResult)(nil)}},
@@ -61,12 +65,12 @@ var Methods = []struct {
{"walletpassphrase", nil},
{"walletpassphrasechange", nil},
{"createnewaccount", nil},
{"exportwatchingwallet", returnsString},
{"getbestblock", []interface{}{(*btcjson.GetBestBlockResult)(nil)}},
{"getunconfirmedbalance", returnsNumber},
{"listaddresstransactions", returnsLTRArray},
{"listalltransactions", returnsLTRArray},
{"renameaccount", nil},
{"rescanblockchain", []interface{}{(*btcjson.RescanBlockchainResult)(nil)}},
{"walletislocked", returnsBool},
}
+1 -1
View File
@@ -7,7 +7,7 @@ package zero_test
import (
"testing"
. "github.com/btcsuite/btcwallet/internal/zero"
. "github.com/lbryio/lbcwallet/internal/zero"
)
var (
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"strings"
"testing"
. "github.com/btcsuite/btcwallet/internal/zero"
. "github.com/lbryio/lbcwallet/internal/zero"
)
func makeOneBytes(n int) []byte {
+29 -74
View File
@@ -10,15 +10,14 @@ import (
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"runtime"
"sync"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/rpc/legacyrpc"
"github.com/btcsuite/btcwallet/wallet"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lightninglabs/neutrino"
"github.com/lbryio/lbcwallet/chain"
"github.com/lbryio/lbcwallet/rpc/legacyrpc"
"github.com/lbryio/lbcwallet/wallet"
"github.com/lbryio/lbcd/version"
)
var (
@@ -55,7 +54,7 @@ func walletMain() error {
}()
// Show version at startup.
log.Infof("Version %s", version())
log.Infof("Version %s", version.Full())
if cfg.Profile != "" {
go func() {
@@ -69,35 +68,34 @@ func walletMain() error {
}
dbDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
loader := wallet.NewLoader(activeNet.Params, dbDir, true, 250)
loader := wallet.NewLoader(
activeNet.Params, dbDir, true, cfg.DBTimeout, 250,
)
// Create and start HTTP server to serve wallet client connections.
// This will be updated with the wallet and chain server RPC client
// created below after each is created.
rpcs, legacyRPCServer, err := startRPCServers(loader)
legacyRPCServer, err := startRPCServers(loader)
if err != nil {
log.Errorf("Unable to create RPC servers: %v", err)
return err
}
// Create and start chain RPC client so it's ready to connect to
// the wallet when loaded later.
if !cfg.NoInitialLoad {
go rpcClientConnectLoop(legacyRPCServer, loader)
}
go rpcClientConnectLoop(legacyRPCServer, loader)
loader.RunAfterLoad(func(w *wallet.Wallet) {
startWalletRPCServices(w, rpcs, legacyRPCServer)
startWalletRPCServices(w, legacyRPCServer)
log.Infof("Unlocking wallet with the default or specified passphrase...")
err = w.Unlock([]byte(cfg.Passphrase), nil)
if err != nil {
log.Infof("Unable to unlock wallet: %v", err)
}
})
if !cfg.NoInitialLoad {
// Load the wallet database. It must have been created already
// or this will return an appropriate error.
_, err = loader.OpenExistingWallet([]byte(cfg.WalletPass), true)
if err != nil {
log.Error(err)
return err
}
_, err = loader.OpenExistingWallet()
if err != nil {
log.Error(err)
return err
}
// Add interrupt handlers to shutdown the various process components
@@ -109,15 +107,6 @@ func walletMain() error {
log.Errorf("Failed to close wallet: %v", err)
}
})
if rpcs != nil {
addInterruptHandler(func() {
// TODO: Does this need to wait for the grpc server to
// finish up any requests?
log.Warn("Stopping RPC server...")
rpcs.Stop()
log.Info("RPC server shutdown")
})
}
if legacyRPCServer != nil {
addInterruptHandler(func() {
log.Warn("Stopping legacy RPC server...")
@@ -143,10 +132,7 @@ func walletMain() error {
// associated with the server for RPC passthrough and to enable additional
// methods.
func rpcClientConnectLoop(legacyRPCServer *legacyrpc.Server, loader *wallet.Loader) {
var certs []byte
if !cfg.UseSPV {
certs = readCAFile()
}
certs := readCAFile()
for {
var (
@@ -154,42 +140,10 @@ func rpcClientConnectLoop(legacyRPCServer *legacyrpc.Server, loader *wallet.Load
err error
)
if cfg.UseSPV {
var (
chainService *neutrino.ChainService
spvdb walletdb.DB
)
netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
spvdb, err = walletdb.Create("bdb",
filepath.Join(netDir, "neutrino.db"))
defer spvdb.Close()
if err != nil {
log.Errorf("Unable to create Neutrino DB: %s", err)
continue
}
chainService, err = neutrino.NewChainService(
neutrino.Config{
DataDir: netDir,
Database: spvdb,
ChainParams: *activeNet.Params,
ConnectPeers: cfg.ConnectPeers,
AddPeers: cfg.AddPeers,
})
if err != nil {
log.Errorf("Couldn't create Neutrino ChainService: %s", err)
continue
}
chainClient = chain.NewNeutrinoClient(activeNet.Params, chainService)
err = chainClient.Start()
if err != nil {
log.Errorf("Couldn't start Neutrino client: %s", err)
}
} else {
chainClient, err = startChainRPC(certs)
if err != nil {
log.Errorf("Unable to open connection to consensus RPC server: %v", err)
continue
}
chainClient, err = startChainRPC(certs)
if err != nil {
log.Errorf("Unable to open connection to consensus RPC server: %v", err)
continue
}
// Rather than inlining this logic directly into the loader
@@ -258,14 +212,15 @@ func readCAFile() []byte {
return certs
}
// startChainRPC opens a RPC client connection to a btcd server for blockchain
// startChainRPC opens a RPC client connection to a server for blockchain
// services. This function uses the RPC options from the global config and
// there is no recovery in case the server is not available or if there is an
// authentication error. Instead, all requests to the client will simply error.
func startChainRPC(certs []byte) (*chain.RPCClient, error) {
log.Infof("Attempting RPC client connection to %v", cfg.RPCConnect)
rpcc, err := chain.NewRPCClient(activeNet.Params, cfg.RPCConnect,
cfg.BtcdUsername, cfg.BtcdPassword, certs, cfg.DisableClientTLS, 0)
cfg.RPCUser, cfg.RPCPass, certs, cfg.DisableClientTLS,
cfg.SkipVerify, 0)
if err != nil {
return nil, err
}
+8 -21
View File
@@ -10,15 +10,13 @@ import (
"os"
"path/filepath"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btclog"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/rpc/legacyrpc"
"github.com/btcsuite/btcwallet/rpc/rpcserver"
"github.com/btcsuite/btcwallet/wallet"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/jrick/logrotate/rotator"
"github.com/lightninglabs/neutrino"
"github.com/lbryio/lbcd/rpcclient"
"github.com/lbryio/lbcwallet/chain"
"github.com/lbryio/lbcwallet/rpc/legacyrpc"
"github.com/lbryio/lbcwallet/wallet"
"github.com/lbryio/lbcwallet/wtxmgr"
)
// logWriter implements an io.Writer that outputs to both standard output and
@@ -26,8 +24,8 @@ import (
type logWriter struct{}
func (logWriter) Write(p []byte) (n int, err error) {
os.Stdout.Write(p)
logRotatorPipe.Write(p)
_, _ = os.Stdout.Write(p)
_, _ = logRotatorPipe.Write(p)
return len(p), nil
}
@@ -68,9 +66,7 @@ func init() {
wtxmgr.UseLogger(txmgrLog)
chain.UseLogger(chainLog)
rpcclient.UseLogger(chainLog)
rpcserver.UseLogger(grpcLog)
legacyrpc.UseLogger(legacyRPCLog)
neutrino.UseLogger(btcnLog)
}
// subsystemLoggers maps each subsystem identifier to its associated logger.
@@ -101,7 +97,7 @@ func initLogRotator(logFile string) {
}
pr, pw := io.Pipe()
go r.Run(pr)
go func() { _ = r.Run(pr) }()
logRotator = r
logRotatorPipe = pw
@@ -132,12 +128,3 @@ func setLogLevels(logLevel string) {
setLogLevel(subsystemID, logLevel)
}
}
// pickNoun returns the singular or plural form of a noun depending
// on the count n.
func pickNoun(n int, singular, plural string) string {
if n == 1 {
return singular
}
return plural
}
+19 -15
View File
@@ -4,7 +4,9 @@
package netparams
import "github.com/btcsuite/btcd/chaincfg"
import (
"github.com/lbryio/lbcd/chaincfg"
)
// Params is used to group parameters for various networks such as the main
// network and test networks.
@@ -14,26 +16,28 @@ type Params struct {
RPCServerPort string
}
// MainNetParams contains parameters specific running btcwallet and
// btcd on the main network (wire.MainNet).
// MainNetParams contains parameters specific running lbcwallet and
//
// on the main network (wire.MainNet).
var MainNetParams = Params{
Params: &chaincfg.MainNetParams,
RPCClientPort: "8334",
RPCServerPort: "8332",
RPCClientPort: "9245",
RPCServerPort: "9244",
}
// TestNet3Params contains parameters specific running btcwallet and
// btcd on the test network (version 3) (wire.TestNet3).
// TestNet3Params contains parameters specific running lbcwallet and
//
// on the test network (version 3) (wire.TestNet3).
var TestNet3Params = Params{
Params: &chaincfg.TestNet3Params,
RPCClientPort: "18334",
RPCServerPort: "18332",
RPCClientPort: "19245",
RPCServerPort: "19244",
}
// SimNetParams contains parameters specific to the simulation test network
// (wire.SimNet).
var SimNetParams = Params{
Params: &chaincfg.SimNetParams,
RPCClientPort: "18556",
RPCServerPort: "18554",
// RegNetParams contains parameters specific to the regression test network
// (wire.RegNet).
var RegTestParams = Params{
Params: &chaincfg.RegressionNetParams,
RPCClientPort: "29245",
RPCServerPort: "29244",
}
+1 -1
View File
@@ -4,6 +4,6 @@
package main
import "github.com/btcsuite/btcwallet/netparams"
import "github.com/lbryio/lbcwallet/netparams"
var activeNet = &netparams.MainNetParams
-317
View File
@@ -1,317 +0,0 @@
syntax = "proto3";
package walletrpc;
service VersionService {
rpc Version (VersionRequest) returns (VersionResponse);
}
message VersionRequest {}
message VersionResponse {
string version_string = 1;
uint32 major = 2;
uint32 minor = 3;
uint32 patch = 4;
string prerelease = 5;
string build_metadata = 6;
}
service WalletService {
// Queries
rpc Ping (PingRequest) returns (PingResponse);
rpc Network (NetworkRequest) returns (NetworkResponse);
rpc AccountNumber (AccountNumberRequest) returns (AccountNumberResponse);
rpc Accounts (AccountsRequest) returns (AccountsResponse);
rpc Balance (BalanceRequest) returns (BalanceResponse);
rpc GetTransactions (GetTransactionsRequest) returns (GetTransactionsResponse);
// Notifications
rpc TransactionNotifications (TransactionNotificationsRequest) returns (stream TransactionNotificationsResponse);
rpc SpentnessNotifications (SpentnessNotificationsRequest) returns (stream SpentnessNotificationsResponse);
rpc AccountNotifications (AccountNotificationsRequest) returns (stream AccountNotificationsResponse);
// Control
rpc ChangePassphrase (ChangePassphraseRequest) returns (ChangePassphraseResponse);
rpc RenameAccount (RenameAccountRequest) returns (RenameAccountResponse);
rpc NextAccount (NextAccountRequest) returns (NextAccountResponse);
rpc NextAddress (NextAddressRequest) returns (NextAddressResponse);
rpc ImportPrivateKey (ImportPrivateKeyRequest) returns (ImportPrivateKeyResponse);
rpc FundTransaction (FundTransactionRequest) returns (FundTransactionResponse);
rpc SignTransaction (SignTransactionRequest) returns (SignTransactionResponse);
rpc PublishTransaction (PublishTransactionRequest) returns (PublishTransactionResponse);
}
service WalletLoaderService {
rpc WalletExists (WalletExistsRequest) returns (WalletExistsResponse);
rpc CreateWallet (CreateWalletRequest) returns (CreateWalletResponse);
rpc OpenWallet (OpenWalletRequest) returns (OpenWalletResponse);
rpc CloseWallet (CloseWalletRequest) returns (CloseWalletResponse);
rpc StartConsensusRpc (StartConsensusRpcRequest) returns (StartConsensusRpcResponse);
}
message TransactionDetails {
message Input {
uint32 index = 1;
uint32 previous_account = 2;
int64 previous_amount = 3;
}
message Output {
uint32 index = 1;
uint32 account = 2;
bool internal = 3;
}
bytes hash = 1;
bytes transaction = 2;
repeated Input debits = 3;
repeated Output credits = 4;
int64 fee = 5;
int64 timestamp = 6; // May be earlier than a block timestamp, but never later.
}
message BlockDetails {
bytes hash = 1;
int32 height = 2;
int64 timestamp = 3;
repeated TransactionDetails transactions = 4;
}
message AccountBalance {
uint32 account = 1;
int64 total_balance = 2;
}
message PingRequest {}
message PingResponse {}
message NetworkRequest {}
message NetworkResponse {
uint32 active_network = 1;
}
message AccountNumberRequest {
string account_name = 1;
}
message AccountNumberResponse {
uint32 account_number = 1;
}
message AccountsRequest {}
message AccountsResponse {
message Account {
uint32 account_number = 1;
string account_name = 2;
int64 total_balance = 3;
uint32 external_key_count = 4;
uint32 internal_key_count = 5;
uint32 imported_key_count = 6;
}
repeated Account accounts = 1;
bytes current_block_hash = 2;
int32 current_block_height = 3;
}
message RenameAccountRequest {
uint32 account_number = 1;
string new_name = 2;
}
message RenameAccountResponse {}
message NextAccountRequest {
bytes passphrase = 1;
string account_name = 2;
}
message NextAccountResponse {
uint32 account_number = 1;
}
message NextAddressRequest {
uint32 account = 1;
enum Kind {
BIP0044_EXTERNAL = 0;
BIP0044_INTERNAL = 1;
}
Kind kind = 2;
}
message NextAddressResponse {
string address = 1;
}
message ImportPrivateKeyRequest {
bytes passphrase = 1;
uint32 account = 2;
string private_key_wif = 3;
bool rescan = 4;
}
message ImportPrivateKeyResponse {
}
message BalanceRequest {
uint32 account_number = 1;
int32 required_confirmations = 2;
}
message BalanceResponse {
int64 total = 1;
int64 spendable = 2;
int64 immature_reward = 3;
}
message GetTransactionsRequest {
// Optionally specify the starting block from which to begin including all transactions.
// Either the starting block hash or height may be specified, but not both.
// If a block height is specified and is negative, the absolute value becomes the number of
// last blocks to include. That is, given a current chain height of 1000 and a starting block
// height of -3, transaction notifications will be created for blocks 998, 999, and 1000.
// If both options are excluded, transaction results are created for transactions since the
// genesis block.
bytes starting_block_hash = 1;
sint32 starting_block_height = 2;
// Optionally specify the last block that transaction results may appear in.
// Either the ending block hash or height may be specified, but not both.
// If both are excluded, transaction results are created for all transactions
// through the best block, and include all unmined transactions.
bytes ending_block_hash = 3;
int32 ending_block_height = 4;
// Include at least this many of the newest transactions if they exist.
// Cannot be used when the ending block hash is specified.
//
// TODO: remove until spec adds it back in some way.
int32 minimum_recent_transactions = 5;
// TODO: limit max number of txs?
}
message GetTransactionsResponse {
repeated BlockDetails mined_transactions = 1;
repeated TransactionDetails unmined_transactions = 2;
}
message ChangePassphraseRequest {
enum Key {
PRIVATE = 0;
PUBLIC = 1;
}
Key key = 1;
bytes old_passphrase = 2;
bytes new_passphrase = 3;
}
message ChangePassphraseResponse {}
message FundTransactionRequest {
uint32 account = 1;
int64 target_amount = 2;
int32 required_confirmations = 3;
bool include_immature_coinbases = 4;
bool include_change_script = 5;
}
message FundTransactionResponse {
message PreviousOutput {
bytes transaction_hash = 1;
uint32 output_index = 2;
int64 amount = 3;
bytes pk_script = 4;
int64 receive_time = 5;
bool from_coinbase = 6;
}
repeated PreviousOutput selected_outputs = 1;
int64 total_amount = 2;
bytes change_pk_script = 3;
}
message SignTransactionRequest {
bytes passphrase = 1;
bytes serialized_transaction = 2;
// If no indexes are specified, signatures scripts will be added for
// every input. If any input indexes are specified, only those inputs
// will be signed. Rather than returning an incompletely signed
// transaction if any of the inputs to be signed can not be, the RPC
// immediately errors.
repeated uint32 input_indexes = 3;
}
message SignTransactionResponse {
bytes transaction = 1;
repeated uint32 unsigned_input_indexes = 2;
}
message PublishTransactionRequest {
bytes signed_transaction = 1;
}
message PublishTransactionResponse {}
message TransactionNotificationsRequest {}
message TransactionNotificationsResponse {
// Sorted by increasing height. This is a repeated field so many new blocks
// in a new best chain can be notified at once during a reorganize.
repeated BlockDetails attached_blocks = 1;
// If there was a chain reorganize, there may have been blocks with wallet
// transactions that are no longer in the best chain. These are those
// block's hashes.
repeated bytes detached_blocks = 2;
// Any new unmined transactions are included here. These unmined transactions
// refer to the current best chain, so transactions from detached blocks may
// be moved to mempool and included here if they are not mined or double spent
// in the new chain. Additonally, if no new blocks were attached but a relevant
// unmined transaction is seen by the wallet, it will be reported here.
repeated TransactionDetails unmined_transactions = 3;
// Instead of notifying all of the removed unmined transactions,
// just send all of the current hashes.
repeated bytes unmined_transaction_hashes = 4;
}
message SpentnessNotificationsRequest {
uint32 account = 1;
bool no_notify_unspent = 2;
bool no_notify_spent = 3;
}
message SpentnessNotificationsResponse {
bytes transaction_hash = 1;
uint32 output_index = 2;
message Spender {
bytes transaction_hash = 1;
uint32 input_index = 2;
}
Spender spender = 3;
}
message AccountNotificationsRequest {}
message AccountNotificationsResponse {
uint32 account_number = 1;
string account_name = 2;
uint32 external_key_count = 3;
uint32 internal_key_count = 4;
uint32 imported_key_count = 5;
}
message CreateWalletRequest {
bytes public_passphrase = 1;
bytes private_passphrase = 2;
bytes seed = 3;
}
message CreateWalletResponse {}
message OpenWalletRequest {
bytes public_passphrase = 1;
}
message OpenWalletResponse {}
message CloseWalletRequest {}
message CloseWalletResponse {}
message WalletExistsRequest {}
message WalletExistsResponse {
bool exists = 1;
}
message StartConsensusRpcRequest {
string network_address = 1;
string username = 2;
bytes password = 3;
bytes certificate = 4;
}
message StartConsensusRpcResponse {}
-16
View File
@@ -1,16 +0,0 @@
# RPC Documentation
This project provides a [gRPC](http://www.grpc.io/) server for Remote Procedure
Call (RPC) access from other processes. This is intended to be the primary
means by which users, through other client programs, interact with the wallet.
These documents cover the documentation for both consumers of the server and
developers who must make changes or additions to the API and server
implementation:
- [API specification](./api.md)
- [Client usage](./clientusage.md)
- [Making API changes](./serverchanges.md)
A legacy RPC server based on the JSON-RPC API of Bitcoin Core's wallet is also
available, but documenting its usage is out of scope for these documents.
-983
View File
@@ -1,983 +0,0 @@
# RPC API Specification
Version: 2.0.1
=======
**Note:** This document assumes the reader is familiar with gRPC concepts.
Refer to the [gRPC Concepts documentation](http://www.grpc.io/docs/guides/concepts.html)
for any unfamiliar terms.
**Note:** The naming style used for autogenerated identifiers may differ
depending on the language being used. This document follows the naming style
used by Google in their Protocol Buffers and gRPC documentation as well as this
project's `.proto` files. That is, CamelCase is used for services, methods, and
messages, lower_snake_case for message fields, and SCREAMING_SNAKE_CASE for
enums.
**Note:** The entierty of the RPC API is currently considered unstable and may
change anytime. Stability will be gradually added based on correctness,
perceived usefulness and ease-of-use over alternatives, and user feedback.
This document is the authoritative source on the RPC API's definitions and
semantics. Any divergence from this document is an implementation error. API
fixes and additions require a version increase according to the rules of
[Semantic Versioning 2.0.0](http://semver.org/).
Only optional proto3 message fields are used (the `required` keyword is never
used in the `.proto` file). If a message field must be set to something other
than the default value, or any other values are invalid, the error must occur in
the application's message handling. This prevents accidentally introducing
parsing errors if a previously optional field is missing or a new required field
is added.
Functionality is grouped into gRPC services. Depending on what functions are
currently callable, different services will be running. As an example, the
server may be running without a loaded wallet, in which case the Wallet service
is not running and the Loader service must be used to create a new or load an
existing wallet.
- [`VersionService`](#versionservice)
- [`LoaderService`](#loaderservice)
- [`WalletService`](#walletservice)
## `VersionService`
The `VersionService` service provides the caller with versioning information
regarding the RPC server. It has no dependencies and is always running.
**Methods:**
- [`Version`](#version)
### Methods
#### `Version`
The `Version` method returns the RPC server version. Versioning follows the
rules of Semantic Versioning (SemVer) 2.0.0.
**Request:** `VersionRequest`
**Response:** `VersionResponse`
- `string version_string`: The version encoded as a string.
- `uint32 major`: The SemVer major version number.
- `uint32 minor`: The SemVer minor version number.
- `uint32 patch`: The SemVer patch version number.
- `string prerelease`: The SemVer pre-release version identifier, if any.
- `string build_metadata`: Extra SemVer build metadata, if any.
**Expected errors:** None
**Stability:** Stable
## `LoaderService`
The `LoaderService` service provides the caller with functions related to the
management of the wallet and its connection to the Bitcoin network. It has no
dependencies and is always running.
**Methods:**
- [`WalletExists`](#walletexists)
- [`CreateWallet`](#createwallet)
- [`OpenWallet`](#openwallet)
- [`CloseWallet`](#closewallet)
- [`StartConsensusRpc`](#startconsensusrpc)
**Shared messages:**
- [`BlockDetails`](#blockdetails)
- [`TransactionDetails`](#transactiondetails)
### Methods
#### `WalletExists`
The `WalletExists` method returns whether a file at the wallet database's file
path exists. Clients that must load wallets with this service are expected to
call this RPC to query whether `OpenWallet` should be used to open an existing
wallet, or `CreateWallet` to create a new wallet.
**Request:** `WalletExistsRequest`
**Response:** `WalletExistsResponse`
- `bool exists`: Whether the wallet file exists.
**Expected errors:** None
**Stability:** Unstable
___
#### `CreateWallet`
The `CreateWallet` method is used to create a wallet that is protected by two
levels of encryption: the public passphrase (for data that is made public on the
blockchain) and the private passphrase (for private keys). Since the seed is
not saved in the wallet database and clients should make their users backup the
seed, it needs to be passed as part of the request.
After creating a wallet, the `WalletService` service begins running.
**Request:** `CreateWalletRequest`
- `bytes public_passphrase`: The passphrase used for the outer wallet
encryption. This passphrase protects data that is made public on the
blockchain. If this passphrase has zero length, an insecure default is used
instead.
- `bytes private_passphrase`: The passphrase used for the inner wallet
encryption. This is the passphrase used for data that must always remain
private, such as private keys. The length of this field must not be zero.
- `bytes seed`: The BIP0032 seed used to derive all wallet keys. The length of
this field must be between 16 and 64 bytes, inclusive.
**Response:** `CreateWalletReponse`
**Expected errors:**
- `FailedPrecondition`: The wallet is currently open.
- `AlreadyExists`: A file already exists at the wallet database file path.
- `InvalidArgument`: A private passphrase was not included in the request, or
the seed is of incorrect length.
**Stability:** Unstable: There needs to be a way to recover all keys and
transactions of a wallet being recovered by its seed. It is unclear whether
it should be part of this method or a `WalletService` method.
___
#### `OpenWallet`
The `OpenWallet` method is used to open an existing wallet database. If the
wallet is protected by a public passphrase, it can not be successfully opened if
the public passphrase parameter is missing or incorrect.
After opening a wallet, the `WalletService` service begins running.
**Request:** `OpenWalletRequest`
- `bytes public_passphrase`: The passphrase used for the outer wallet
encryption. This passphrase protects data that is made public on the
blockchain. If this passphrase has zero length, an insecure default is used
instead.
**Response:** `OpenWalletResponse`
**Expected errors:**
- `FailedPrecondition`: The wallet is currently open.
- `NotFound`: The wallet database file does not exist.
- `InvalidArgument`: The public encryption passphrase was missing or incorrect.
**Stability:** Unstable
___
#### `CloseWallet`
The `CloseWallet` method is used to cleanly stop all wallet operations on a
loaded wallet and close the database. After closing, the `WalletService`
service will remain running but any operations that require the database will be
unusable.
**Request:** `CloseWalletRequest`
**Response:** `CloseWalletResponse`
**Expected errors:**
- `FailedPrecondition`: The wallet is not currently open.
**Stability:** Unstable: It would be preferable to stop the `WalletService`
after closing, but there does not appear to be any way to do so currently. It
may also be a good idea to limit under what conditions a wallet can be closed,
such as only closing wallets loaded by `LoaderService` and/or using a secret
to authenticate the operation.
___
#### `StartConsensusRpc`
The `StartConsensusRpc` method is used to provide clients the ability to dynamically
start the btcd RPC client. This RPC client is used for wallet syncing and
publishing transactions to the Bitcoin network.
**Request:** `StartConsensusRpcRequest`
- `string network_address`: The host/IP and optional port of the RPC server to
connect to. IP addresses may be IPv4 or IPv6. If the port is missing, a
default port is chosen corresponding to the default btcd RPC port of the
active Bitcoin network.
- `string username`: The RPC username required to authenticate to the RPC
server.
- `bytes password`: The RPC password required to authenticate to the RPC server.
- `bytes certificate`: The consensus RPC server's TLS certificate. If this
field has zero length and the network address describes a loopback connection
(`localhost`, `127.0.0.1`, or `::1`) TLS will be disabled.
**Response:** `StartConsensusRpcResponse`
**Expected errors:**
- `FailedPrecondition`: A consensus RPC client is already active.
- `InvalidArgument`: The network address is ill-formatted or does not contain a
valid IP address.
- `NotFound`: The consensus RPC server is unreachable. This condition may not
return `Unavailable` as that refers to `LoaderService` itself being
unavailable.
- `InvalidArgument`: The username, password, or certificate are invalid. This
condition may not be return `Unauthenticated` as that refers to the client not
having the credentials to call this method.
**Stability:** Unstable: It is unknown if the consensus RPC client will remain
used after the project gains SPV support.
## `WalletService`
The WalletService service provides RPCs for the wallet itself. The service
depends on a loaded wallet and does not run when the wallet has not been created
or opened yet.
The service provides the following methods:
- [`Ping`](#ping)
- [`Network`](#network)
- [`AccountNumber`](#accountnumber)
- [`Accounts`](#accounts)
- [`Balance`](#balance)
- [`GetTransactions`](#gettransactions)
- [`ChangePassphrase`](#changepassphrase)
- [`RenameAccount`](#renameaccount)
- [`NextAccount`](#nextaccount)
- [`NextAddress`](#nextaddress)
- [`ImportPrivateKey`](#importprivatekey)
- [`FundTransaction`](#fundtransaction)
- [`SignTransaction`](#signtransaction)
- [`PublishTransaction`](#publishtransaction)
- [`TransactionNotifications`](#transactionnotifications)
- [`SpentnessNotifications`](#spentnessnotifications)
- [`AccountNotifications`](#accountnotifications)
#### `Ping`
The `Ping` method checks whether the service is active.
**Request:** `PingRequest`
**Response:** `PingResponse`
**Expected errors:** None
**Stability:** Unstable: This may be moved to another service as it does not
depend on the wallet.
___
#### `Network`
The `Network` method returns the network identifier constant describing the
server's active network.
**Request:** `NetworkRequest`
**Response:** `NetworkResponse`
- `uint32 active_network`: The network identifier.
**Expected errors:** None
**Stability:** Unstable: This may be moved to another service as it does not
depend on the wallet.
___
#### `AccountNumber`
The `AccountNumber` method looks up a BIP0044 account number by an account's
unique name.
**Request:** `AccountNumberRequest`
- `string account_name`: The name of the account being queried.
**Response:** `AccountNumberResponse`
- `uint32 account_number`: The BIP0044 account number.
**Expected errors:**
- `Aborted`: The wallet database is closed.
- `NotFound`: No accounts exist by the name in the request.
**Stability:** Unstable
___
#### `Accounts`
The `Accounts` method returns the current properties of all accounts managed in
the wallet.
**Request:** `AccountsRequest`
**Response:** `AccountsResponse`
- `repeated Account accounts`: Account properties grouped into `Account` nested
message types, one per account, ordered by increasing account numbers.
**Nested message:** `Account`
- `uint32 account_number`: The BIP0044 account number.
- `string account_name`: The name of the account.
- `int64 total_balance`: The total (zero-conf and immature) balance, counted
in Satoshis.
- `uint32 external_key_count`: The number of derived keys in the external
key chain.
- `uint32 internal_key_count`: The number of derived keys in the internal
key chain.
- `uint32 imported_key_count`: The number of imported keys.
- `bytes current_block_hash`: The hash of the block wallet is considered to
be synced with.
- `int32 current_block_height`: The height of the block wallet is considered
to be synced with.
**Expected errors:**
- `Aborted`: The wallet database is closed.
**Stability:** Unstable
___
#### `Balance`
The `Balance` method queries the wallet for an account's balance. Balances are
returned as combination of total, spendable (by consensus and request policy),
and unspendable immature coinbase balances.
**Request:** `BalanceRequest`
- `uint32 account_number`: The account number to query.
- `int32 required_confirmations`: The number of confirmations required before an
unspent transaction output's value is included in the spendable balance. This
may not be negative.
**Response:** `BalanceResponse`
- `int64 total`: The total (zero-conf and immature) balance, counted in
Satoshis.
- `int64 spendable`: The spendable balance, given some number of required
confirmations, counted in Satoshis. This equals the total balance when the
required number of confirmations is zero and there are no immature coinbase
outputs.
- `int64 immature_reward`: The total value of all immature coinbase outputs,
counted in Satoshis.
**Expected errors:**
- `InvalidArgument`: The required number of confirmations is negative.
- `Aborted`: The wallet database is closed.
- `NotFound`: The account does not exist.
**Stability:** Unstable: It may prove useful to modify this RPC to query
multiple accounts together.
___
#### `GetTransactions`
The `GetTransactions` method queries the wallet for relevant transactions. The
query set may be specified using a block range, inclusive, with the heights or
hashes of the minimum and maximum block. Transaction results are grouped
grouped by the block they are mined in, or grouped together with other unmined
transactions.
**Request:** `GetTransactionsRequest`
- `bytes starting_block_hash`: The block hash of the block to begin including
transactions from. If this field is set to the default, the
`starting_block_height` field is used instead. If changed, the byte array
must have length 32 and `starting_block_height` must be zero.
- `sint32 starting_block_height`: The block height to begin including
transactions from. If this field is non-zero, `starting_block_hash` must be
set to its default value to avoid ambiguity. If positive, the field is
interpreted as a block height. If negative, the height is subtracted from the
block wallet considers itself in sync with.
- `bytes ending_block_hash`: The block hash of the last block to include
transactions from. If this default is set to the default, the
`ending_block_height` field is used instead. If changed, the byte array must
have length 32 and `ending_block_height` must be zero.
- `int32 ending_block_height`: The block height of the last block to include
transactions from. If non-zero, the `ending_block_hash` field must be set to
its default value to avoid ambiguity. If both this field and
`ending_block_hash` are set to their default values, no upper block limit is
used and transactions through the best block and all unmined transactions are
included.
**Response:** `GetTransactionsResponse`
- `repeated BlockDetails mined_transactions`: All mined transactions, organized
by blocks in the order they appear in the blockchain.
The `BlockDetails` message is used by other methods and is documented
[here](#blockdetails).
- `repeated TransactionDetails unmined_transactions`: All unmined transactions.
The ordering is unspecified.
The `TransactionDetails` message is used by other methods and is documented
[here](#transactiondetails).
**Expected errors:**
- `InvalidArgument`: A non-default block hash field did not have the correct length.
- `Aborted`: The wallet database is closed.
- `NotFound`: A block, specified by its height or hash, is unknown to the
wallet.
**Stability:** Unstable
- There is currently no way to get only unmined transactions due to the way
the block range is specified.
- It would be useful to ignore the block range and return some minimum number of
the most recent transaction, but it is unclear if that should be added to this
method's request object, or to make a new method.
- A specified ordering (such as dependency order) for all returned unmined
transactions would be useful.
___
#### `ChangePassphrase`
The `ChangePassphrase` method requests a change to either the public (outer) or
private (inner) encryption passphrases.
**Request:** `ChangePassphraseRequest`
- `Key key`: The key being changed.
**Nested enum:** `Key`
- `PRIVATE`: The request specifies to change the private (inner) encryption
passphrase.
- `PUBLIC`: The request specifies to change the public (outer) encryption
passphrase.
- `bytes old_passphrase`: The current passphrase for the encryption key. This
is the value being modified. If the public passphrase is being modified and
this value is the default value, an insecure default is used instead.
- `bytes new_passphrase`: The replacement passphrase. This field may only have
zero length if the public passphrase is being changed, in which case an
insecure default will be used instead.
**Response:** `ChangePassphraseResponse`
**Expected errors:**
- `InvalidArgument`: A zero length passphrase was specified when changing the
private passphrase, or the old passphrase was incorrect.
- `Aborted`: The wallet database is closed.
**Stability:** Unstable
___
#### `RenameAccount`
The `RenameAccount` method requests a change to an account's name property.
**Request:** `RenameAccountRequest`
- `uint32 account_number`: The number of the account being modified.
- `string new_name`: The new name for the account.
**Response:** `RenameAccountResponse`
**Expected errors:**
- `Aborted`: The wallet database is closed.
- `InvalidArgument`: The new account name is a reserved name.
- `NotFound`: The account does not exist.
- `AlreadyExists`: An account by the same name already exists.
**Stability:** Unstable: There should be a way to specify a starting block or
time to begin the rescan at. Additionally, since the client is expected to be
able to do asynchronous RPC, it may be useful for the response to block on the
rescan finishing before returning.
___
#### `NextAccount`
The `NextAccount` method generates the next BIP0044 account for the wallet.
**Request:** `NextAccountRequest`
- `bytes passphrase`: The private passphrase required to derive the next
account's key.
- `string account_name`: The name to give the new account.
**Response:** `NextAccountResponse`
- `uint32 account_number`: The number of the newly-created account.
**Expected errors:**
- `Aborted`: The wallet database is closed.
- `InvalidArgument`: The private passphrase is incorrect.
- `InvalidArgument`: The new account name is a reserved name.
- `AlreadyExists`: An account by the same name already exists.
**Stability:** Unstable
___
#### `NextAddress`
The `NextAddress` method generates the next deterministic address for the
wallet.
**Request:** `NextAddressRequest`
- `uint32 account`: The number of the account to derive the next address for.
- `Kind kind`: The type of address to generate.
**Nested enum:** `Kind`
- `BIP0044_EXTERNAL`: The request specifies to generate the next address for
the account's BIP0044 external key chain.
- `BIP0044_INTERNAL`: The request specifies to generate the next address for
the account's BIP0044 internal key chain.
**Response:** `NextAddressResponse`
- `string address`: The payment address string.
**Expected errors:**
- `Aborted`: The wallet database is closed.
- `NotFound`: The account does not exist.
**Stability:** Unstable
___
#### `ImportPrivateKey`
The `ImportPrivateKey` method imports a private key in Wallet Import Format
(WIF) encoding to a wallet account. A rescan may optionally be started to
search for transactions involving the private key's associated payment address.
**Request:** `ImportPrivateKeyRequest`
- `bytes passphrase`: The wallet's private passphrase.
- `uint32 account`: The account number to associate the imported key with.
- `string private_key_wif`: The private key, encoded using WIF.
- `bool rescan`: Whether or not to perform a blockchain rescan for the imported
key.
**Response:** `ImportPrivateKeyResponse`
**Expected errors:**
- `InvalidArgument`: The private key WIF string is not a valid WIF encoding.
- `Aborted`: The wallet database is closed.
- `InvalidArgument`: The private passphrase is incorrect.
- `NotFound`: The account does not exist.
**Stability:** Unstable
___
#### `FundTransaction`
The `FundTransaction` method queries the wallet for unspent transaction outputs
controlled by some account. Results may be refined by setting a target output
amount and limiting the required confirmations. The selection algorithm is
unspecified.
Output results are always created even if a minimum target output amount could
not be reached. This allows this method to behave similar to the `Balance`
method while also including the outputs that make up that balance.
Change outputs can optionally be returned by this method as well. This can
provide the caller with everything necessary to construct an unsigned
transaction paying to already known addresses or scripts.
**Request:** `FundTransactionRequest`
- `uint32 account`: Account number containing the keys controlling the output
set to query.
- `int64 target_amount`: If positive, the service may limit output results to
those that sum to at least this amount (counted in Satoshis). If zero, all
outputs not excluded by other arguments are returned. This may not be
negative.
- `int32 required_confirmations`: The minimum number of block confirmations
needed to consider including an output in the return set. This may not be
negative.
- `bool include_immature_coinbases`: If true, immature coinbase outputs will
also be included.
- `bool include_change_script`: If true, a change script is included in the
response object.
**Response:** `FundTransactionResponse`
- `repeated PreviousOutput selected_outputs`: The output set returned as a list
of `PreviousOutput` nested message objects.
**Nested message:** `PreviousOutput`
- `bytes transaction_hash`: The hash of the transaction this output originates
from.
- `uint32 output_index`: The output index of the transaction this output
originates from.
- `int64 amount`: The output value (counted in Satoshis) of the unspent
transaction output.
- `bytes pk_script`: The output script of the unspent transaction output.
- `int64 receive_time`: The earliest Unix time the wallet became aware of the
transaction containing this output.
- `bool from_coinbase`: Whether the output is a coinbase output.
- `int64 total_amount`: The sum of all returned output amounts. This may be
less than a positive target amount if there were not enough eligible outputs
available.
- `bytes change_pk_script`: A transaction output script used to pay the
remaining amount to a newly-generated change address for the account. This is
null if `include_change_script` was false or the target amount was not
exceeded.
**Expected errors:**
- `InvalidArgument`: The target amount is negative.
- `InvalidArgument`: The required confirmations is negative.
- `Aborted`: The wallet database is closed.
- `NotFound`: The account does not exist.
**Stability:** Unstable
___
#### `SignTransaction`
The `SignTransaction` method adds transaction input signatures to a serialized
transaction using a wallet private keys.
**Request:** `SignTransactionRequest`
- `bytes passphrase`: The wallet's private passphrase.
- `bytes serialized_transaction`: The transaction to add input signatures to.
- `repeated uint32 input_indexes`: The input indexes that signature scripts must
be created for. If there are no indexes, input scripts are created for every
input that is missing an input script.
**Response:** `SignTransactionResponse`
- `bytes transaction`: The serialized transaction with added input scripts.
- `repeated uint32 unsigned_input_indexes`: The indexes of every input that an
input script could not be created for.
**Expected errors:**
- `InvalidArgument`: The serialized transaction can not be decoded.
- `Aborted`: The wallet database is closed.
- `InvalidArgument`: The private passphrase is incorrect.
**Stability:** Unstable: It is unclear if the request should include an account,
and only secrets of that account are used when creating input scripts. It's
also missing options similar to Core's signrawtransaction, such as the sighash
flags and additional keys.
___
#### `PublishTransaction`
The `PublishTransaction` method publishes a signed, serialized transaction to
the Bitcoin network. If the transaction spends any of the wallet's unspent
outputs or creates a new output controlled by the wallet, it is saved by the
wallet and republished later if it or a double spend are not mined.
**Request:** `PublishTransactionRequest`
- `bytes signed_transaction`: The signed transaction to publish.
**Response:** `PublishTransactionResponse`
**Expected errors:**
- `InvalidArgument`: The serialized transaction can not be decoded or is missing
input scripts.
- `Aborted`: The wallet database is closed.
**Stability:** Unstable
___
#### `TransactionNotifications`
The `TransactionNotifications` method returns a stream of notifications
regarding changes to the blockchain and transactions relevant to the wallet.
**Request:** `TransactionNotificationsRequest`
**Response:** `stream TransactionNotificationsResponse`
- `repeated BlockDetails attached_blocks`: A list of blocks attached to the main
chain, sorted by increasing height. All newly mined transactions are included
in these messages, in the message corresponding to the block that contains
them. If this field has zero length, the notification is due to an unmined
transaction being added to the wallet.
The `BlockDetails` message is used by other methods and is documented
[here](#blockdetails).
- `repeated bytes detached_blocks`: The hashes of every block that was
reorganized out of the main chain. These are sorted by heights in decreasing
order (newest blocks first).
- `repeated TransactionDetails unmined_transactions`: All newly added unmined
transactions. When relevant transactions are reorganized out and not included
in (or double-spent by) the new chain, they are included here.
The `TransactionDetails` message is used by other methods and is documented
[here](#transactiondetails).
- `repeated bytes unmined_transaction_hashes`: The hashes of every
currently-unmined transaction. This differs from the `unmined_transactions`
field by including every unmined transaction, rather than those newly added to
the unmined set.
**Expected errors:**
- `Aborted`: The wallet database is closed.
**Stability:** Unstable: This method could use a better name.
___
#### `SpentnessNotifications`
The `SpentnessNotifications` method returns a stream of notifications regarding
the spending of unspent outputs and/or the discovery of new unspent outputs for
an account.
**Request:** `SpentnessNotificationsRequest`
- `uint32 account`: The account to create notifications for.
- `bool no_notify_unspent`: If true, do not send any notifications for
newly-discovered unspent outputs controlled by the account.
- `bool no_notify_spent`: If true, do not send any notifications for newly-spent
transactions controlled by the account.
**Response:** `stream SpentnessNotificationsResponse`
- `bytes transaction_hash`: The hash of the serialized transaction containing
the output being reported.
- `uint32 output_index`: The output index of the output being reported.
- `Spender spender`: If null, the output is a newly-discovered unspent output.
If not null, the message records the transaction input that spends the
previously-unspent output.
**Nested message:** `Spender`
- `bytes transaction_hash`: The hash of the serialized transaction that spends
the reported output.
- `uint32 input_index`: The index of the input that spends the reported
output.
**Expected errors:**
- `InvalidArgument`: The `no_notify_unspent` and `no_notify_spent` request
fields are both true.
- `Aborted`: The wallet database is closed.
**Stability:** Unstable
___
#### `AccountNotifications`
The `AccountNotifications` method returns a stream of notifications for account
property changes, such as name and key counts.
**Request:** `AccountNotificationsRequest`
**Response:** `stream AccountNotificationsResponse`
- `uint32 account_number`: The BIP0044 account being reported.
- `string account_name`: The current account name.
- `uint32 external_key_count`: The current number of BIP0032 external keys
derived for the account.
- `uint32 internal_key_count`: The current number of BIP0032 internal keys
derived for the account.
- `uint32 imported_key_count`: The current number of private keys imported into
the account.
**Expected errors:**
- `Aborted`: The wallet database is closed.
**Stability:** Unstable: This should probably share a message with the
`Accounts` method.
___
### Shared messages
The following messages are used by multiple methods. To avoid unnecessary
duplication, they are documented once here.
#### `BlockDetails`
The `BlockDetails` message is included in responses to report a block and the
wallet's relevant transactions contained therein.
- `bytes hash`: The hash of the block being reported.
- `int32 height`: The height of the block being reported.
- `int64 timestamp`: The Unix time included in the block header.
- `repeated TransactionDetails transactions`: All transactions relevant to the
wallet that are mined in this block. Transactions are sorted by their block
index in increasing order.
The `TransactionDetails` message is used by other methods and is documented
[here](#transactiondetails).
**Stability**: Unstable: This should probably include the block version.
___
#### `TransactionDetails`
The `TransactionDetails` message is included in responses to report transactions
relevant to the wallet. The message includes details such as which previous
wallet inputs are spent by this transaction, whether each output is controlled
by the wallet or not, the total fee (if calculable), and the earlist time the
transaction was seen.
- `bytes hash`: The hash of the serialized transaction.
- `bytes transaction`: The serialized transaction.
- `repeated Input debits`: Properties for every previously-unspent wallet output
spent by this transaction.
**Nested message:** `Input`
- `uint32 index`: The transaction input index of the input being reported.
- `uint32 previous_account`: The account that controlled the now-spent output.
- `int64 previous_amount`: The previous output value.
- `repeated Output credits`: Properties for every output controlled by the wallet.
**Nested message:** `Output`
- `uint32 index`: The transaction output index of the output being reported.
- `uint32 account`: The account number of the controlled output.
- `bool internal`: Whether the output pays to an address derived from the
account's internal key series. This often means the output is a change
output.
- `int64 fee`: The transaction fee, if calculable. The fee is only calculable
when every previous output spent by this transaction is also recorded by
wallet. Otherwise, this field is zero.
- `int64 timestamp`: The Unix time of the earliest time this transaction was
seen.
**Stability**: Unstable: Since the caller is expected to decode the serialized
transaction, and would have access to every output script, the output
properties could be changed to only include outputs controlled by the wallet.
-438
View File
@@ -1,438 +0,0 @@
# Client usage
Clients use RPC to interact with the wallet. A client may be implemented in any
language directly supported by [gRPC](http://www.grpc.io/), languages capable of
performing [FFI](https://en.wikipedia.org/wiki/Foreign_function_interface) with
these, and languages that share a common runtime (e.g. Scala, Kotlin, and Ceylon
for the JVM, F# for the CLR, etc.). Exact instructions differ slightly
depending on the language being used, but the general process is the same for
each. In short summary, to call RPC server methods, a client must:
1. Generate client bindings specific for the [wallet RPC server API](./api.md)
2. Import or include the gRPC dependency
3. (Optional) Wrap the client bindings with application-specific types
4. Open a gRPC channel using the wallet server's self-signed TLS certificate
The only exception to these steps is if the client is being written in Go. In
that case, the first step may be omitted by importing the bindings from
btcwallet itself.
The rest of this document provides short examples of how to quickly get started
by implementing a basic client that fetches the balance of the default account
(account 0) from a testnet3 wallet listening on `localhost:18332` in several
different languages:
- [Go](#go)
- [C++](#cpp)
- [C#](#csharp)
- [Node.js](#nodejs)
- [Python](#python)
Unless otherwise stated under the language example, it is assumed that
gRPC is already already installed. The gRPC installation procedure
can vary greatly depending on the operating system being used and
whether a gRPC source install is required. Follow the [gRPC install
instructions](https://github.com/grpc/grpc/blob/master/INSTALL) if
gRPC is not already installed. A full gRPC install also includes
[Protocol Buffers](https://github.com/google/protobuf) (compiled with
support for the proto3 language version), which contains the protoc
tool and language plugins used to compile this project's `.proto`
files to language-specific bindings.
## Go
The native gRPC library (gRPC Core) is not required for Go clients (a
pure Go implementation is used instead) and no additional setup is
required to generate Go bindings.
```Go
package main
import (
"fmt"
"path/filepath"
pb "github.com/btcsuite/btcwallet/rpc/walletrpc"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/btcsuite/btcutil"
)
var certificateFile = filepath.Join(btcutil.AppDataDir("btcwallet", false), "rpc.cert")
func main() {
creds, err := credentials.NewClientTLSFromFile(certificateFile, "localhost")
if err != nil {
fmt.Println(err)
return
}
conn, err := grpc.Dial("localhost:18332", grpc.WithTransportCredentials(creds))
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
c := pb.NewWalletServiceClient(conn)
balanceRequest := &pb.BalanceRequest{
AccountNumber: 0,
RequiredConfirmations: 1,
}
balanceResponse, err := c.Balance(context.Background(), balanceRequest)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Spendable balance: ", btcutil.Amount(balanceResponse.Spendable))
}
```
<a name="cpp"/>
## C++
**Note:** Protocol Buffers and gRPC require at least C++11. The example client
is written using C++14.
**Note:** The following instructions assume the client is being written on a
Unix-like platform (with instructions using the `sh` shell and Unix-isms in the
example source code) with a source gRPC install in `/usr/local`.
First, generate the C++ language bindings by compiling the `.proto`:
```bash
$ protoc -I/path/to/btcwallet/rpc --cpp_out=. --grpc_out=. \
--plugin=protoc-gen-grpc=$(which grpc_cpp_plugin) \
/path/to/btcwallet/rpc/api.proto
```
Once the `.proto` file has been compiled, the example client can be completed.
Note that the following code uses synchronous calls which will block the main
thread on all gRPC IO.
```C++
// example.cc
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <grpc++/grpc++.h>
#include "api.grpc.pb.h"
using namespace std::string_literals;
struct NoHomeDirectoryException : std::exception {
char const* what() const noexcept override {
return "Failed to lookup home directory";
}
};
auto read_file(std::string const& file_path) -> std::string {
std::ifstream in{file_path};
std::stringstream ss{};
ss << in.rdbuf();
return ss.str();
}
auto main() -> int {
// Before the gRPC native library (gRPC Core) is lazily loaded and
// initialized, an environment variable must be set so BoringSSL is
// configured to use ECDSA TLS certificates (required by btcwallet).
setenv("GRPC_SSL_CIPHER_SUITES", "HIGH+ECDSA", 1);
// Note: This path is operating system-dependent. This can be created
// portably using boost::filesystem or the experimental filesystem class
// expected to ship in C++17.
auto wallet_tls_cert_file = []{
auto pw = getpwuid(getuid());
if (pw == nullptr || pw->pw_dir == nullptr) {
throw NoHomeDirectoryException{};
}
return pw->pw_dir + "/.btcwallet/rpc.cert"s;
}();
grpc::SslCredentialsOptions cred_options{
.pem_root_certs = read_file(wallet_tls_cert_file),
};
auto creds = grpc::SslCredentials(cred_options);
auto channel = grpc::CreateChannel("localhost:18332", creds);
auto stub = walletrpc::WalletService::NewStub(channel);
grpc::ClientContext context{};
walletrpc::BalanceRequest request{};
request.set_account_number(0);
request.set_required_confirmations(1);
walletrpc::BalanceResponse response{};
auto status = stub->Balance(&context, request, &response);
if (!status.ok()) {
std::cout << status.error_message() << std::endl;
} else {
std::cout << "Spendable balance: " << response.spendable() << " Satoshis" << std::endl;
}
}
```
The example can then be built with the following commands:
```bash
$ c++ -std=c++14 -I/usr/local/include -pthread -c -o api.pb.o api.pb.cc
$ c++ -std=c++14 -I/usr/local/include -pthread -c -o api.grpc.pb.o api.grpc.pb.cc
$ c++ -std=c++14 -I/usr/local/include -pthread -c -o example.o example.cc
$ c++ *.o -L/usr/local/lib -lgrpc++ -lgrpc -lgpr -lprotobuf -lpthread -ldl -o example
```
<a name="csharp"/>
## C&#35;
The quickest way of generating client bindings in a Windows .NET environment is
by using the protoc binary included in the gRPC NuGet package. From the NuGet
package manager PowerShell console, this can be performed with:
```
PM> Install-Package Grpc
```
The protoc and C# plugin binaries can then be found in the packages directory.
For example, `.\packages\Google.Protobuf.x.x.x\tools\protoc.exe` and
`.\packages\Grpc.Tools.x.x.x\tools\grpc_csharp_plugin.exe`.
When writing a client on other platforms (e.g. Mono on OS X), or when doing a
full gRPC source install on Windows, protoc and the C# plugin must be installed
by other means. Consult the [official documentation](https://github.com/grpc/grpc/blob/master/src/csharp/README.md)
for these steps.
Once protoc and the C# plugin have been obtained, client bindings can be
generated. The following command generates the files `Api.cs` and `ApiGrpc.cs`
in the `Example` project directory using the `Walletrpc` namespace:
```PowerShell
PS> & protoc.exe -I \Path\To\btcwallet\rpc --csharp_out=Example --grpc_out=Example `
--plugin=protoc-gen-grpc=\Path\To\grpc_csharp_plugin.exe `
\Path\To\btcwallet\rpc\api.proto
```
Once references have been added to the project for the `Google.Protobuf` and
`Grpc.Core` assemblies, the example client can be implemented.
```C#
using Grpc.Core;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Walletrpc;
namespace Example
{
static class Program
{
static void Main(string[] args)
{
ExampleAsync().Wait();
}
static async Task ExampleAsync()
{
// Before the gRPC native library (gRPC Core) is lazily loaded and initialized,
// an environment variable must be set so BoringSSL is configured to use ECDSA TLS
// certificates (required by btcwallet).
Environment.SetEnvironmentVariable("GRPC_SSL_CIPHER_SUITES", "HIGH+ECDSA");
var walletAppData = Portability.LocalAppData(Environment.OSVersion.Platform, "Btcwallet");
var walletTlsCertFile = Path.Combine(walletAppData, "rpc.cert");
var cert = await FileUtils.ReadFileAsync(walletTlsCertFile);
var channel = new Channel("localhost:18332", new SslCredentials(cert));
try
{
var c = WalletService.NewClient(channel);
var balanceRequest = new BalanceRequest
{
AccountNumber = 0,
RequiredConfirmations = 1,
};
var balanceResponse = await c.BalanceAsync(balanceRequest);
Console.WriteLine($"Spendable balance: {balanceResponse.Spendable} Satoshis");
}
finally
{
await channel.ShutdownAsync();
}
}
}
static class FileUtils
{
public static async Task<string> ReadFileAsync(string filePath)
{
using (var r = new StreamReader(filePath, Encoding.UTF8))
{
return await r.ReadToEndAsync();
}
}
}
static class Portability
{
public static string LocalAppData(PlatformID platform, string processName)
{
if (processName == null)
throw new ArgumentNullException(nameof(processName));
if (processName.Length == 0)
throw new ArgumentException(nameof(processName) + " may not have zero length");
switch (platform)
{
case PlatformID.Win32NT:
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
ToUpper(processName));
case PlatformID.MacOSX:
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"Library", "Application Support", ToUpper(processName));
case PlatformID.Unix:
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),
ToDotLower(processName));
default:
throw new PlatformNotSupportedException($"PlatformID={platform}");
}
}
private static string ToUpper(string value)
{
var firstChar = value[0];
if (char.IsUpper(firstChar))
return value;
else
return char.ToUpper(firstChar) + value.Substring(1);
}
private static string ToDotLower(string value)
{
var firstChar = value[0];
return "." + char.ToLower(firstChar) + value.Substring(1);
}
}
}
```
## Node.js
First, install gRPC (either by building the latest source release, or
by installing a gRPC binary development package through your operating
system's package manager). This is required to install the npm module
as it wraps the native C library (gRPC Core) with C++ bindings.
Installing the [grpc module](https://www.npmjs.com/package/grpc) to
your project can then be done by executing:
```
npm install grpc
```
A Node.js client does not require generating JavaScript stub files for
the wallet's API from the `.proto`. Instead, a call to `grpc.load`
with the `.proto` file path dynamically loads the Protobuf descriptor
and generates bindings for each service. Either copy the `.proto` to
the client project directory, or reference the file from the
`btcwallet` project directory.
```JavaScript
// Before the gRPC native library (gRPC Core) is lazily loaded and
// initialized, an environment variable must be set so BoringSSL is
// configured to use ECDSA TLS certificates (required by btcwallet).
process.env['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA';
var fs = require('fs');
var path = require('path');
var os = require('os');
var grpc = require('grpc');
var protoDescriptor = grpc.load('./api.proto');
var walletrpc = protoDescriptor.walletrpc;
var certPath = path.join(process.env.HOME, '.btcwallet', 'rpc.cert');
if (os.platform == 'win32') {
certPath = path.join(process.env.LOCALAPPDATA, 'Btcwallet', 'rpc.cert');
} else if (os.platform == 'darwin') {
certPath = path.join(process.env.HOME, 'Library', 'Application Support',
'Btcwallet', 'rpc.cert');
}
var cert = fs.readFileSync(certPath);
var creds = grpc.credentials.createSsl(cert);
var client = new walletrpc.WalletService('localhost:18332', creds);
var request = {
account_number: 0,
required_confirmations: 1
};
client.balance(request, function(err, response) {
if (err) {
console.error(err);
} else {
console.log('Spendable balance:', response.spendable, 'Satoshis');
}
});
```
## Python
**Note:** gRPC requires Python 2.7.
After installing gRPC Core and Python development headers, `pip`
should be used to install the `grpc` module and its dependencies.
Full instructions for this procedure can be found
[here](https://github.com/grpc/grpc/blob/master/src/python/README.md).
Generate Python stubs from the `.proto`:
```bash
$ protoc -I /path/to/btcsuite/btcwallet/rpc --python_out=. --grpc_out=. \
--plugin=protoc-gen-grpc=$(which grpc_python_plugin) \
/path/to/btcwallet/rpc/api.proto
```
Implement the client:
```Python
import os
import platform
from grpc.beta import implementations
import api_pb2 as walletrpc
timeout = 1 # seconds
def main():
# Before the gRPC native library (gRPC Core) is lazily loaded and
# initialized, an environment variable must be set so BoringSSL is
# configured to use ECDSA TLS certificates (required by btcwallet).
os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
cert_file_path = os.path.join(os.environ['HOME'], '.btcwallet', 'rpc.cert')
if platform.system() == 'Windows':
cert_file_path = os.path.join(os.environ['LOCALAPPDATA'], "Btcwallet", "rpc.cert")
elif platform.system() == 'Darwin':
cert_file_path = os.path.join(os.environ['HOME'], 'Library', 'Application Support',
'Btcwallet', 'rpc.cert')
with open(cert_file_path, 'r') as f:
cert = f.read()
creds = implementations.ssl_client_credentials(cert, None, None)
channel = implementations.secure_channel('localhost', 18332, creds)
stub = walletrpc.beta_create_WalletService_stub(channel)
request = walletrpc.BalanceRequest(account_number = 0, required_confirmations = 1)
response = stub.Balance(request, timeout)
print 'Spendable balance: %d Satoshis' % response.spendable
if __name__ == '__main__':
main()
```
-94
View File
@@ -1,94 +0,0 @@
# Making API Changes
This document describes the process of how btcwallet developers must make
changes to the RPC API and server. Due to the use of gRPC and Protocol Buffers
for the RPC implementation, changes to this API require extra dependencies and
steps before changes to the server can be implemented.
## Requirements
- The Protocol Buffer compiler `protoc` installed with support for the `proto3`
language
The `protoc` tool is part of the Protocol Buffers project. This can be
installed [from source](https://github.com/google/protobuf/blob/master/INSTALL.txt),
from an [official binary release](https://github.com/google/protobuf/releases),
or through an operating system's package manager.
- The gRPC `protoc` plugin for Go
This plugin is written in Go and can be installed using `go get`:
```
go get github.com/golang/protobuf/protoc-gen-go
```
- Knowledge of Protocol Buffers version 3 (proto3)
Note that a full installation of gRPC Core is not required, and only the
`protoc` compiler and Go plugins are necessary. This is due to the project
using a pure Go gRPC implementation instead of wrapping the C library from gRPC
Core.
## Step 1: Modify the `.proto`
Once the developer dependencies have been met, changes can be made to the API by
modifying the Protocol Buffers descriptor file [`api.proto`](../api.proto).
The API is versioned according to the rules of [Semantic Versioning
2.0](http://semver.org/). After any changes, bump the API version in the [API
specification](./api.md) and add the changes to the spec.
Unless backwards compatibility is broken (and the version is bumped to represent
this change), message fields must never be removed or changed, and new fields
must always be appended.
It is forbidden to use the `required` attribute on a message field as this can
cause errors during parsing when the new API is used by an older client.
Instead, the (implicit) optional attribute is used, and the server
implementation must return an appropriate error if the new request field is not
set to a valid value.
## Step 2: Compile the `.proto`
Once changes to the descriptor file and API specification have been made, the
`protoc` compiler must be used to compile the descriptor into a Go package.
This code contains interfaces (stubs) for each service (to be implemented by the
wallet) and message types used for each RPC. This same code can also be
imported by a Go client that then calls same interface methods to perform RPC
with the wallet.
By committing the autogenerated package to the project repo, the `proto3`
compiler and plugin are not needed by users installing the project by source or
by other developers not making changes to the RPC API.
A `sh` shell script is included to compile the Protocol Buffers descriptor. It
must be run from the `rpc` directory.
```bash
$ sh regen.sh
```
If a `sh` shell is unavailable, the command can be run manually instead (again
from the `rpc` directory).
```
protoc -I. api.proto --go_out=plugins=grpc:walletrpc
```
TODO(jrick): This step could be simplified and be more portable by putting the
commands in a Go source file and executing them with `go generate`. It should,
however, only be run when API changes are performed (not with `go generate
./...` in the project root) since not all developers are expected to have
`protoc` installed.
## Step 3: Implement the API change in the RPC server
After the Go code for the API has been regenated, the necessary changes can be
implemented in the [`rpcserver`](../rpcserver/) package.
## Additional Resources
- [Protocol Buffers Language Guide (proto3)](https://developers.google.com/protocol-buffers/docs/proto3)
- [Protocol Buffers Basics: Go](https://developers.google.com/protocol-buffers/docs/gotutorial)
- [gRPC Basics: Go](http://www.grpc.io/docs/tutorials/basic/go.html)
+2 -2
View File
@@ -7,11 +7,11 @@ package legacyrpc
import (
"errors"
"github.com/btcsuite/btcd/btcjson"
"github.com/lbryio/lbcd/btcjson"
)
// TODO(jrick): There are several error paths which 'replace' various errors
// with a more appropiate error from the btcjson package. Create a map of
// with a more appropriate error from the btcjson package. Create a map of
// these replacements so they can be handled once after an RPC handler has
// returned and before the error is marshaled.
+525 -222
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -18,8 +18,8 @@ import (
"strings"
"testing"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcwallet/internal/rpchelp"
"github.com/lbryio/lbcd/btcjson"
"github.com/lbryio/lbcwallet/internal/rpchelp"
)
func serverMethods() map[string]struct{} {
+3 -1
View File
@@ -26,9 +26,11 @@ func TestThrottle(t *testing.T) {
go func() {
res, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
t.Log(err)
return
}
codes <- res.StatusCode
_ = res.Body.Close()
}()
}
+46 -45
View File
@@ -4,51 +4,52 @@ package legacyrpc
func helpDescsEnUS() map[string]string {
return map[string]string{
"addmultisigaddress": "addmultisigaddress nrequired [\"key\",...] (\"account\")\n\nGenerates and imports a multisig address and redeeming script to the 'imported' account.\n\nArguments:\n1. nrequired (numeric, required) The number of signatures required to redeem outputs paid to this address\n2. keys (array of string, required) Pubkeys and/or pay-to-pubkey-hash addresses to partially control the multisig address\n3. account (string, optional) DEPRECATED -- Unused (all imported addresses belong to the imported account)\n\nResult:\n\"value\" (string) The imported pay-to-script-hash address\n",
"createmultisig": "createmultisig nrequired [\"key\",...]\n\nGenerate a multisig address and redeem script.\n\nArguments:\n1. nrequired (numeric, required) The number of signatures required to redeem outputs paid to this address\n2. keys (array of string, required) Pubkeys and/or pay-to-pubkey-hash addresses to partially control the multisig address\n\nResult:\n{\n \"address\": \"value\", (string) The generated pay-to-script-hash address\n \"redeemScript\": \"value\", (string) The script required to redeem outputs paid to the multisig address\n} \n",
"dumpprivkey": "dumpprivkey \"address\"\n\nReturns the private key in WIF encoding that controls some wallet address.\n\nArguments:\n1. address (string, required) The address to return a private key for\n\nResult:\n\"value\" (string) The WIF-encoded private key\n",
"getaccount": "getaccount \"address\"\n\nDEPRECATED -- Lookup the account name that some wallet address belongs to.\n\nArguments:\n1. address (string, required) The address to query the account for\n\nResult:\n\"value\" (string) The name of the account that 'address' belongs to\n",
"getaccountaddress": "getaccountaddress \"account\"\n\nDEPRECATED -- Returns the most recent external payment address for an account that has not been seen publicly.\nA new address is generated for the account if the most recently generated address has been seen on the blockchain or in mempool.\n\nArguments:\n1. account (string, required) The account of the returned address\n\nResult:\n\"value\" (string) The unused address for 'account'\n",
"getaddressesbyaccount": "getaddressesbyaccount \"account\"\n\nDEPRECATED -- Returns all addresses strings controlled by a single account.\n\nArguments:\n1. account (string, required) Account name to fetch addresses for\n\nResult:\n[\"value\",...] (array of string) All addresses controlled by 'account'\n",
"getbalance": "getbalance (\"account\" minconf=1)\n\nCalculates and returns the balance of one or all accounts.\n\nArguments:\n1. account (string, optional) DEPRECATED -- The account name to query the balance for, or \"*\" to consider all accounts (default=\"*\")\n2. minconf (numeric, optional, default=1) Minimum number of block confirmations required before an unspent output's value is included in the balance\n\nResult (account != \"*\"):\nn.nnn (numeric) The balance of 'account' valued in bitcoin\n\nResult (account = \"*\"):\nn.nnn (numeric) The balance of all accounts valued in bitcoin\n",
"getbestblockhash": "getbestblockhash\n\nReturns the hash of the newest block in the best chain that wallet has finished syncing with.\n\nArguments:\nNone\n\nResult:\n\"value\" (string) The hash of the most recent synced-to block\n",
"getblockcount": "getblockcount\n\nReturns the blockchain height of the newest block in the best chain that wallet has finished syncing with.\n\nArguments:\nNone\n\nResult:\nn.nnn (numeric) The blockchain height of the most recent synced-to block\n",
"getinfo": "getinfo\n\nReturns a JSON object containing various state info.\n\nArguments:\nNone\n\nResult:\n{\n \"version\": n, (numeric) The version of the server\n \"protocolversion\": n, (numeric) The latest supported protocol version\n \"walletversion\": n, (numeric) The version of the address manager database\n \"balance\": n.nnn, (numeric) The balance of all accounts calculated with one block confirmation\n \"blocks\": n, (numeric) The number of blocks processed\n \"timeoffset\": n, (numeric) The time offset\n \"connections\": n, (numeric) The number of connected peers\n \"proxy\": \"value\", (string) The proxy used by the server\n \"difficulty\": n.nnn, (numeric) The current target difficulty\n \"testnet\": true|false, (boolean) Whether or not server is using testnet\n \"keypoololdest\": n, (numeric) Unset\n \"keypoolsize\": n, (numeric) Unset\n \"unlocked_until\": n, (numeric) Unset\n \"paytxfee\": n.nnn, (numeric) The increment used each time more fee is required for an authored transaction\n \"relayfee\": n.nnn, (numeric) The minimum relay fee for non-free transactions in BTC/KB\n \"errors\": \"value\", (string) Any current errors\n} \n",
"getnewaddress": "getnewaddress (\"account\")\n\nGenerates and returns a new payment address.\n\nArguments:\n1. account (string, optional) DEPRECATED -- Account name the new address will belong to (default=\"default\")\n\nResult:\n\"value\" (string) The payment address\n",
"getrawchangeaddress": "getrawchangeaddress (\"account\")\n\nGenerates and returns a new internal payment address for use as a change address in raw transactions.\n\nArguments:\n1. account (string, optional) Account name the new internal address will belong to (default=\"default\")\n\nResult:\n\"value\" (string) The internal payment address\n",
"getreceivedbyaccount": "getreceivedbyaccount \"account\" (minconf=1)\n\nDEPRECATED -- Returns the total amount received by addresses of some account, including spent outputs.\n\nArguments:\n1. account (string, required) Account name to query total received amount for\n2. minconf (numeric, optional, default=1) Minimum number of block confirmations required before an output's value is included in the total\n\nResult:\nn.nnn (numeric) The total received amount valued in bitcoin\n",
"getreceivedbyaddress": "getreceivedbyaddress \"address\" (minconf=1)\n\nReturns the total amount received by a single address, including spent outputs.\n\nArguments:\n1. address (string, required) Payment address which received outputs to include in total\n2. minconf (numeric, optional, default=1) Minimum number of block confirmations required before an output's value is included in the total\n\nResult:\nn.nnn (numeric) The total received amount valued in bitcoin\n",
"gettransaction": "gettransaction \"txid\" (includewatchonly=false)\n\nReturns a JSON object with details regarding a transaction relevant to this wallet.\n\nArguments:\n1. txid (string, required) Hash of the transaction to query\n2. includewatchonly (boolean, optional, default=false) Also consider transactions involving watched addresses\n\nResult:\n{\n \"amount\": n.nnn, (numeric) The total amount this transaction credits to the wallet, valued in bitcoin\n \"fee\": n.nnn, (numeric) The total input value minus the total output value, or 0 if 'txid' is not a sent transaction\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined\n \"blockindex\": n, (numeric) Unset\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined\n \"txid\": \"value\", (string) The transaction hash\n \"walletconflicts\": [\"value\",...], (array of string) Unset\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"details\": [{ (array of object) Additional details for each recorded wallet credit and debit\n \"account\": \"value\", (string) DEPRECATED -- Unset\n \"address\": \"value\", (string) The address an output was paid to, or the empty string if the output is nonstandard or this detail is regarding a transaction input\n \"amount\": n.nnn, (numeric) The amount of a received output\n \"category\": \"value\", (string) The kind of detail: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs\n \"involveswatchonly\": true|false, (boolean) Unset\n \"fee\": n.nnn, (numeric) The included fee for a sent transaction\n \"vout\": n, (numeric) The transaction output index\n },...], \n \"hex\": \"value\", (string) The transaction encoded as a hexadecimal string\n} \n",
"help": "help (\"command\")\n\nReturns a list of all commands or help for a specified command.\n\nArguments:\n1. command (string, optional) The command to retrieve help for\n\nResult (no command provided):\n\"value\" (string) List of commands\n\nResult (command specified):\n\"value\" (string) Help for specified command\n",
"importprivkey": "importprivkey \"privkey\" (\"label\" rescan=true)\n\nImports a WIF-encoded private key to the 'imported' account.\n\nArguments:\n1. privkey (string, required) The WIF-encoded private key\n2. label (string, optional) Unused (must be unset or 'imported')\n3. rescan (boolean, optional, default=true) Rescan the blockchain (since the genesis block) for outputs controlled by the imported key\n\nResult:\nNothing\n",
"keypoolrefill": "keypoolrefill (newsize=100)\n\nDEPRECATED -- This request does nothing since no keypool is maintained.\n\nArguments:\n1. newsize (numeric, optional, default=100) Unused\n\nResult:\nNothing\n",
"listaccounts": "listaccounts (minconf=1)\n\nDEPRECATED -- Returns a JSON object of all accounts and their balances.\n\nArguments:\n1. minconf (numeric, optional, default=1) Minimum number of block confirmations required before an unspent output's value is included in the balance\n\nResult:\n{\n \"The account name\": The account balance valued in bitcoin, (object) JSON object with account names as keys and bitcoin amounts as values\n ...\n}\n",
"listlockunspent": "listlockunspent\n\nReturns a JSON array of outpoints marked as locked (with lockunspent) for this wallet session.\n\nArguments:\nNone\n\nResult:\n[{\n \"txid\": \"value\", (string) The transaction hash of the referenced output\n \"vout\": n, (numeric) The output index of the referenced output\n},...]\n",
"listreceivedbyaccount": "listreceivedbyaccount (minconf=1 includeempty=false includewatchonly=false)\n\nDEPRECATED -- Returns a JSON array of objects listing all accounts and the total amount received by each account.\n\nArguments:\n1. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction is considered\n2. includeempty (boolean, optional, default=false) Unused\n3. includewatchonly (boolean, optional, default=false) Unused\n\nResult:\n[{\n \"account\": \"value\", (string) The name of the account\n \"amount\": n.nnn, (numeric) Total amount received by payment addresses of the account valued in bitcoin\n \"confirmations\": n, (numeric) Number of block confirmations of the most recent transaction relevant to the account\n},...]\n",
"listreceivedbyaddress": "listreceivedbyaddress (minconf=1 includeempty=false includewatchonly=false)\n\nReturns a JSON array of objects listing wallet payment addresses and their total received amounts.\n\nArguments:\n1. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction is considered\n2. includeempty (boolean, optional, default=false) Unused\n3. includewatchonly (boolean, optional, default=false) Unused\n\nResult:\n[{\n \"account\": \"value\", (string) DEPRECATED -- Unset\n \"address\": \"value\", (string) The payment address\n \"amount\": n.nnn, (numeric) Total amount received by the payment address valued in bitcoin\n \"confirmations\": n, (numeric) Number of block confirmations of the most recent transaction relevant to the address\n \"txids\": [\"value\",...], (array of string) Transaction hashes of all transactions involving this address\n \"involvesWatchonly\": true|false, (boolean) Unset\n},...]\n",
"listsinceblock": "listsinceblock (\"blockhash\" targetconfirmations=1 includewatchonly=false)\n\nReturns a JSON array of objects listing details of all wallet transactions after some block.\n\nArguments:\n1. blockhash (string, optional) Hash of the parent block of the first block to consider transactions from, or unset to list all transactions\n2. targetconfirmations (numeric, optional, default=1) Minimum number of block confirmations of the last block in the result object. Must be 1 or greater. Note: The transactions array in the result object is not affected by this parameter\n3. includewatchonly (boolean, optional, default=false) Unused\n\nResult:\n{\n \"transactions\": [{ (array of object) JSON array of objects containing verbose details of the each transaction\n \"abandoned\": true|false, (boolean) Unset\n \"account\": \"value\", (string) DEPRECATED -- Unset\n \"address\": \"value\", (string) Payment address for a transaction output\n \"amount\": n.nnn, (numeric) The value of the transaction output valued in bitcoin\n \"bip125-replaceable\": \"value\", (string) Unset\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined\n \"blockindex\": n, (numeric) Unset\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined\n \"category\": \"value\", (string) The kind of transaction: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs. Note: A single output may be included multiple times under different categories\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction\n \"fee\": n.nnn, (numeric) The total input value minus the total output value for sent transactions\n \"generated\": true|false, (boolean) Whether the transaction output is a coinbase output\n \"involveswatchonly\": true|false, (boolean) Unset\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"trusted\": true|false, (boolean) Unset\n \"txid\": \"value\", (string) The hash of the transaction\n \"vout\": n, (numeric) The transaction output index\n \"walletconflicts\": [\"value\",...], (array of string) Unset\n \"comment\": \"value\", (string) Unset\n \"otheraccount\": \"value\", (string) Unset\n },...], \n \"lastblock\": \"value\", (string) Hash of the latest-synced block to be used in later calls to listsinceblock\n} \n",
"listtransactions": "listtransactions (\"account\" count=10 from=0 includewatchonly=false)\n\nReturns a JSON array of objects containing verbose details for wallet transactions.\n\nArguments:\n1. account (string, optional) DEPRECATED -- Unused (must be unset or \"*\")\n2. count (numeric, optional, default=10) Maximum number of transactions to create results from\n3. from (numeric, optional, default=0) Number of transactions to skip before results are created\n4. includewatchonly (boolean, optional, default=false) Unused\n\nResult:\n[{\n \"abandoned\": true|false, (boolean) Unset\n \"account\": \"value\", (string) DEPRECATED -- Unset\n \"address\": \"value\", (string) Payment address for a transaction output\n \"amount\": n.nnn, (numeric) The value of the transaction output valued in bitcoin\n \"bip125-replaceable\": \"value\", (string) Unset\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined\n \"blockindex\": n, (numeric) Unset\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined\n \"category\": \"value\", (string) The kind of transaction: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs. Note: A single output may be included multiple times under different categories\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction\n \"fee\": n.nnn, (numeric) The total input value minus the total output value for sent transactions\n \"generated\": true|false, (boolean) Whether the transaction output is a coinbase output\n \"involveswatchonly\": true|false, (boolean) Unset\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"trusted\": true|false, (boolean) Unset\n \"txid\": \"value\", (string) The hash of the transaction\n \"vout\": n, (numeric) The transaction output index\n \"walletconflicts\": [\"value\",...], (array of string) Unset\n \"comment\": \"value\", (string) Unset\n \"otheraccount\": \"value\", (string) Unset\n},...]\n",
"listunspent": "listunspent (minconf=1 maxconf=9999999 [\"address\",...])\n\nReturns a JSON array of objects representing unlocked unspent outputs controlled by wallet keys.\n\nArguments:\n1. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction output is considered\n2. maxconf (numeric, optional, default=9999999) Maximum number of block confirmations required before a transaction output is excluded\n3. addresses (array of string, optional) If set, limits the returned details to unspent outputs received by any of these payment addresses\n\nResult:\n{\n \"txid\": \"value\", (string) The transaction hash of the referenced output\n \"vout\": n, (numeric) The output index of the referenced output\n \"address\": \"value\", (string) The payment address that received the output\n \"account\": \"value\", (string) The account associated with the receiving payment address\n \"scriptPubKey\": \"value\", (string) The output script encoded as a hexadecimal string\n \"redeemScript\": \"value\", (string) Unset\n \"amount\": n.nnn, (numeric) The amount of the output valued in bitcoin\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction\n \"spendable\": true|false, (boolean) Whether the output is entirely controlled by wallet keys/scripts (false for partially controlled multisig outputs or outputs to watch-only addresses)\n} \n",
"lockunspent": "lockunspent unlock [{\"txid\":\"value\",\"vout\":n},...]\n\nLocks or unlocks an unspent output.\nLocked outputs are not chosen for transaction inputs of authored transactions and are not included in 'listunspent' results.\nLocked outputs are volatile and are not saved across wallet restarts.\nIf unlock is true and no transaction outputs are specified, all locked outputs are marked unlocked.\n\nArguments:\n1. unlock (boolean, required) True to unlock outputs, false to lock\n2. transactions (array of object, required) Transaction outputs to lock or unlock\n[{\n \"txid\": \"value\", (string) The transaction hash of the referenced output\n \"vout\": n, (numeric) The output index of the referenced output\n},...]\n\nResult:\ntrue|false (boolean) The boolean 'true'\n",
"sendfrom": "sendfrom \"fromaccount\" \"toaddress\" amount (minconf=1 \"comment\" \"commentto\")\n\nDEPRECATED -- Authors, signs, and sends a transaction that outputs some amount to a payment address.\nA change output is automatically included to send extra output value back to the original account.\n\nArguments:\n1. fromaccount (string, required) Account to pick unspent outputs from\n2. toaddress (string, required) Address to pay\n3. amount (numeric, required) Amount to send to the payment address valued in bitcoin\n4. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction output is eligible to be spent\n5. comment (string, optional) Unused\n6. commentto (string, optional) Unused\n\nResult:\n\"value\" (string) The transaction hash of the sent transaction\n",
"sendmany": "sendmany \"fromaccount\" {\"address\":amount,...} (minconf=1 \"comment\")\n\nAuthors, signs, and sends a transaction that outputs to many payment addresses.\nA change output is automatically included to send extra output value back to the original account.\n\nArguments:\n1. fromaccount (string, required) DEPRECATED -- Account to pick unspent outputs from\n2. amounts (object, required) Pairs of payment addresses and the output amount to pay each\n{\n \"Address to pay\": Amount to send to the payment address valued in bitcoin, (object) JSON object using payment addresses as keys and output amounts valued in bitcoin to send to each address\n ...\n}\n3. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction output is eligible to be spent\n4. comment (string, optional) Unused\n\nResult:\n\"value\" (string) The transaction hash of the sent transaction\n",
"sendtoaddress": "sendtoaddress \"address\" amount (\"comment\" \"commentto\")\n\nAuthors, signs, and sends a transaction that outputs some amount to a payment address.\nUnlike sendfrom, outputs are always chosen from the default account.\nA change output is automatically included to send extra output value back to the original account.\n\nArguments:\n1. address (string, required) Address to pay\n2. amount (numeric, required) Amount to send to the payment address valued in bitcoin\n3. comment (string, optional) Unused\n4. commentto (string, optional) Unused\n\nResult:\n\"value\" (string) The transaction hash of the sent transaction\n",
"settxfee": "settxfee amount\n\nModify the increment used each time more fee is required for an authored transaction.\n\nArguments:\n1. amount (numeric, required) The new fee increment valued in bitcoin\n\nResult:\ntrue|false (boolean) The boolean 'true'\n",
"signmessage": "signmessage \"address\" \"message\"\n\nSigns a message using the private key of a payment address.\n\nArguments:\n1. address (string, required) Payment address of private key used to sign the message with\n2. message (string, required) Message to sign\n\nResult:\n\"value\" (string) The signed message encoded as a base64 string\n",
"signrawtransaction": "signrawtransaction \"rawtx\" ([{\"txid\":\"value\",\"vout\":n,\"scriptpubkey\":\"value\",\"redeemscript\":\"value\"},...] [\"privkey\",...] flags=\"ALL\")\n\nSigns transaction inputs using private keys from this wallet and request.\nThe valid flags options are ALL, NONE, SINGLE, ALL|ANYONECANPAY, NONE|ANYONECANPAY, and SINGLE|ANYONECANPAY.\n\nArguments:\n1. rawtx (string, required) Unsigned or partially unsigned transaction to sign encoded as a hexadecimal string\n2. inputs (array of object, optional) Additional data regarding inputs that this wallet may not be tracking\n3. privkeys (array of string, optional) Additional WIF-encoded private keys to use when creating signatures\n4. flags (string, optional, default=\"ALL\") Sighash flags\n\nResult:\n{\n \"hex\": \"value\", (string) The resulting transaction encoded as a hexadecimal string\n \"complete\": true|false, (boolean) Whether all input signatures have been created\n \"errors\": [{ (array of object) Script verification errors (if exists)\n \"txid\": \"value\", (string) The transaction hash of the referenced previous output\n \"vout\": n, (numeric) The output index of the referenced previous output\n \"scriptSig\": \"value\", (string) The hex-encoded signature script\n \"sequence\": n, (numeric) Script sequence number\n \"error\": \"value\", (string) Verification or signing error related to the input\n },...], \n} \n",
"validateaddress": "validateaddress \"address\"\n\nVerify that an address is valid.\nExtra details are returned if the address is controlled by this wallet.\nThe following fields are valid only when the address is controlled by this wallet (ismine=true): isscript, pubkey, iscompressed, account, addresses, hex, script, and sigsrequired.\nThe following fields are only valid when address has an associated public key: pubkey, iscompressed.\nThe following fields are only valid when address is a pay-to-script-hash address: addresses, hex, and script.\nIf the address is a multisig address controlled by this wallet, the multisig fields will be left unset if the wallet is locked since the redeem script cannot be decrypted.\n\nArguments:\n1. address (string, required) Address to validate\n\nResult:\n{\n \"isvalid\": true|false, (boolean) Whether or not the address is valid\n \"address\": \"value\", (string) The payment address (only when isvalid is true)\n \"ismine\": true|false, (boolean) Whether this address is controlled by the wallet (only when isvalid is true)\n \"iswatchonly\": true|false, (boolean) Unset\n \"isscript\": true|false, (boolean) Whether the payment address is a pay-to-script-hash address (only when isvalid is true)\n \"pubkey\": \"value\", (string) The associated public key of the payment address, if any (only when isvalid is true)\n \"iscompressed\": true|false, (boolean) Whether the address was created by hashing a compressed public key, if any (only when isvalid is true)\n \"account\": \"value\", (string) The account this payment address belongs to (only when isvalid is true)\n \"addresses\": [\"value\",...], (array of string) All associated payment addresses of the script if address is a multisig address (only when isvalid is true)\n \"hex\": \"value\", (string) The redeem script \n \"script\": \"value\", (string) The class of redeem script for a multisig address\n \"sigsrequired\": n, (numeric) The number of required signatures to redeem outputs to the multisig address\n} \n",
"verifymessage": "verifymessage \"address\" \"signature\" \"message\"\n\nVerify a message was signed with the associated private key of some address.\n\nArguments:\n1. address (string, required) Address used to sign message\n2. signature (string, required) The signature to verify\n3. message (string, required) The message to verify\n\nResult:\ntrue|false (boolean) Whether the message was signed with the private key of 'address'\n",
"addmultisigaddress": "addmultisigaddress nrequired [\"key\",...] (\"account\")\n\nGenerates and imports a multisig address and redeeming script to the 'imported' account.\n\nArguments:\n1. nrequired (numeric, required) The number of signatures required to redeem outputs paid to this address.\n2. keys (array of string, required) Pubkeys and/or pay-to-pubkey-hash addresses to partially control the multisig address.\n3. account (string, optional) DEPRECATED -- Unused (all imported addresses belong to the imported account).\n\nResult:\n\"value\" (string) The imported pay-to-script-hash address.\n",
"createmultisig": "createmultisig nrequired [\"key\",...]\n\nGenerate a multisig address and redeem script.\n\nArguments:\n1. nrequired (numeric, required) The number of signatures required to redeem outputs paid to this address.\n2. keys (array of string, required) Pubkeys and/or pay-to-pubkey-hash addresses to partially control the multisig address.\n\nResult:\n{\n \"address\": \"value\", (string) The generated pay-to-script-hash address.\n \"redeemScript\": \"value\", (string) The script required to redeem outputs paid to the multisig address.\n} \n",
"dumpprivkey": "dumpprivkey \"address\"\n\nReturns the private key in WIF encoding that controls some wallet address.\n\nArguments:\n1. address (string, required) The address to return a private key for.\n\nResult:\n\"value\" (string) The WIF-encoded private key.\n",
"getaccount": "getaccount \"address\"\n\nLookup the account name that some wallet address belongs to.\n\nArguments:\n1. address (string, required) The address to query the account for.\n\nResult:\n\"value\" (string) The name of the account that 'address' belongs to.\n",
"getaccountaddress": "getaccountaddress (account=\"default\" addresstype=\"legacy\")\n\nReturns the most recent external payment address for an account that has not been seen publicly.\nA new address is generated for the account if the most recently generated address has been seen on the blockchain or in mempool.\n\nArguments:\n1. account (string, optional, default=\"default\") The account of the returned address. Defaults to 'default'\n2. addresstype (string, optional, default=\"legacy\") Address type. Must be one of 'legacy', 'p2sh-segwit', or 'bech32'. Default to 'legacy'.\n\nResult:\n\"value\" (string) The unused address for 'account'.\n",
"getaddressesbyaccount": "getaddressesbyaccount (account=\"default\" addresstype=\"*\")\n\nReturns all addresses controlled by a single account.\n\nArguments:\n1. account (string, optional, default=\"default\") Account name to fetch addresses for. Defaults to 'default'\n2. addresstype (string, optional, default=\"*\") Address type filter. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.\n\nResult:\n[\"value\",...] (array of string) All addresses controlled by 'account' filtered by 'addresstype'.\n",
"getaddressinfo": "getaddressinfo \"address\"\n\nGenerates and returns a new payment address.\n\nArguments:\n1. address (string, required) The address to get the information of.\n\nResult:\n{\n \"address\": \"value\", (string) The address validatedi.\n \"scriptPubKey\": \"value\", (string) The hex-encoded scriptPubKey generated by the address.\n \"desc\": \"value\", (string) A descriptor for spending coins sent to this address (only when solvable).\n \"isscript\": true|false, (boolean) If the key is a script.\n \"ischange\": true|false, (boolean) If the address was used for change output.\n \"iswitness\": true|false, (boolean) If the address is a witness address.\n \"witness_version\": n, (numeric) The version number of the witness program.\n \"witness_program\": \"value\", (string) The hex value of the witness program.\n \"script\": n, (numeric) The output script type. Only if isscript is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown.\n \"hex\": \"value\", (string) The redeemscript for the p2sh address.\n \"pubkeys\": [\"value\",...], (array of string) The hex value of the raw public key for single-key addresses (possibly embedded in P2SH or P2WSH).\n \"sigsrequired\": n, (numeric) The number of signatures required to spend multisig output (only if script is multisig).\n \"pubkey\": \"value\", (string) Array of pubkeys associated with the known redeemscript (only if script is multisig).\n \"iscompressed\": true|false, (boolean) If the pubkey is compressed.\n \"hdmasterfingerprint\": \"value\", (string) The fingerprint of the master key.\n \"labels\": [\"value\",...], (array of string) Array of labels associated with the address. Currently limited to one label but returned.\n \"ismine\": true|false, (boolean) If the address is yours.\n \"iswatchonly\": true|false, (boolean) If the address is watchonly.\n \"timestamp\": n, (numeric) The creation time of the key, if available, expressed in UNIX epoch time.\n \"hdkeypath\": \"value\", (string) The HD keypath, if the key is HD and available.\n \"hdseedid\": \"value\", (string) The Hash160 of the HD seed.\n \"embedded\": { (object) Information about the address embedded in P2SH or P2WSH, if relevant and known.\n \"address\": \"value\", (string) The address validated.\n \"scriptPubKey\": \"value\", (string) The hex-encoded scriptPubKey generated by the address.\n \"desc\": \"value\", (string) A descriptor for spending coins sent to this address (only when solvable).\n \"isscript\": true|false, (boolean) If the key is a script.\n \"ischange\": true|false, (boolean) If the address was used for change output.\n \"iswitness\": true|false, (boolean) If the address is a witness address.\n \"witness_version\": n, (numeric) The version number of the witness program.\n \"witness_program\": \"value\", (string) The hex value of the witness program.\n \"script\": n, (numeric) The output script type. Only if isscript is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown.\n \"hex\": \"value\", (string) The redeemscript for the p2sh address.\n \"pubkeys\": [\"value\",...], (array of string) The hex value of the raw public key for single-key addresses (possibly embedded in P2SH or P2WSH).\n \"sigsrequired\": n, (numeric) The number of signatures required to spend multisig output (only if script is multisig).\n \"pubkey\": \"value\", (string) Array of pubkeys associated with the known redeemscript (only if script is multisig).\n \"iscompressed\": true|false, (boolean) If the pubkey is compressed.\n \"hdmasterfingerprint\": \"value\", (string) The fingerprint of the master key.\n \"labels\": [\"value\",...], (array of string) Array of labels associated with the address. Currently limited to one label but returned.\n }, \n} \n",
"getbalance": "getbalance (account=\"default\" minconf=1 addresstype=\"*\")\n\nCalculates and returns the balance of one or all accounts.\n\nArguments:\n1. account (string, optional, default=\"default\") Account name or '*' for all accounts to query the balance for. Default to 'default'.\n2. minconf (numeric, optional, default=1) Minimum number of block confirmations required before an unspent output's value is included in the balance.\n3. addresstype (string, optional, default=\"*\") Address type filter. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Default to '*'.\n\nResult:\nn.nnn (numeric) The balance valued in LBC.\n",
"getbestblockhash": "getbestblockhash\n\nReturns the hash of the newest block in the best chain that wallet has finished syncing with.\n\nArguments:\nNone\n\nResult:\n\"value\" (string) The hash of the most recent synced-to block.\n",
"getblockcount": "getblockcount\n\nReturns the blockchain height of the newest block in the best chain that wallet has finished syncing with.\n\nArguments:\nNone\n\nResult:\nn.nnn (numeric) The blockchain height of the most recent synced-to block.\n",
"getinfo": "getinfo\n\nReturns a JSON object containing various state info.\n\nArguments:\nNone\n\nResult:\n{\n \"version\": n, (numeric) The version of the server.\n \"protocolversion\": n, (numeric) The latest supported protocol version.\n \"walletversion\": n, (numeric) The version of the address manager database.\n \"balance\": n.nnn, (numeric) The non-staked balance of all accounts calculated with one block confirmation.\n \"blocks\": n, (numeric) The number of blocks processed.\n \"timeoffset\": n, (numeric) The time offset.\n \"connections\": n, (numeric) The number of connected peers.\n \"proxy\": \"value\", (string) The proxy used by the server.\n \"difficulty\": n.nnn, (numeric) The current target difficulty.\n \"testnet\": true|false, (boolean) Whether or not server is using testnet.\n \"keypoololdest\": n, (numeric) Unset.\n \"keypoolsize\": n, (numeric) Unset.\n \"unlocked_until\": n, (numeric) Unset.\n \"paytxfee\": n.nnn, (numeric) The increment used each time more fee is required for an authored transaction.\n \"relayfee\": n.nnn, (numeric) The minimum relay fee for non-free transactions in LBC/KB.\n \"errors\": \"value\", (string) Any current errors.\n \"staked\": n.nnn, (numeric) The staked balance of all accounts calculated with one block confirmation.\n} \n",
"getnewaddress": "getnewaddress (account=\"default\" addresstype=\"legacy\")\n\nGenerates and returns a new payment address.\n\nArguments:\n1. account (string, optional, default=\"default\") Account name the new address will belong to. Defaults to 'default'.\n2. addresstype (string, optional, default=\"legacy\") Address type. Must be one of 'legacy', 'p2sh-segwit', or 'bech32'. Default to 'legacy'.\n\nResult:\n\"value\" (string) The payment address.\n",
"getrawchangeaddress": "getrawchangeaddress (account=\"default\" addresstype=\"legacy\")\n\nGenerates and returns a new internal payment address for use as a change address in raw transactions.\n\nArguments:\n1. account (string, optional, default=\"default\") Account name the new internal address will belong to. Defaults to 'default'.\n2. addresstype (string, optional, default=\"legacy\") Address type. Must be one of 'legacy', 'p2sh-segwit', or 'bech32'. Default to 'legacy'.\n\nResult:\n\"value\" (string) The internal payment address.\n",
"getreceivedbyaccount": "getreceivedbyaccount (account=\"default\" minconf=1)\n\nReturns the total amount received by addresses of some account, including spent outputs.\n\nArguments:\n1. account (string, optional, default=\"default\") Account name to query total received amount for. Defaults to 'default'\n2. minconf (numeric, optional, default=1) Minimum number of block confirmations required before an output's value is included in the total. Defaults to 0\n\nResult:\nn.nnn (numeric) The total received amount valued in LBC.\n",
"getreceivedbyaddress": "getreceivedbyaddress \"address\" (minconf=1)\n\nReturns the total amount received by a single address, including spent outputs.\n\nArguments:\n1. address (string, required) Payment address which received outputs to include in total.\n2. minconf (numeric, optional, default=1) Minimum number of block confirmations required before an output's value is included in the total. Defaults to 1\n\nResult:\nn.nnn (numeric) The total received amount valued in LBC.\n",
"gettransaction": "gettransaction \"txid\" (includewatchonly=false)\n\nReturns a JSON object with details regarding a transaction relevant to this wallet.\n\nArguments:\n1. txid (string, required) Hash of the transaction to query.\n2. includewatchonly (boolean, optional, default=false) Also consider transactions involving watched addresses.\n\nResult:\n{\n \"amount\": n.nnn, (numeric) The total amount this transaction credits to the wallet, valued in LBC.\n \"fee\": n.nnn, (numeric) The total input value minus the total output value, or 0 if 'txid' is not a sent transaction.\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction.\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined.\n \"blockindex\": n, (numeric) Unset.\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined.\n \"txid\": \"value\", (string) The transaction hash.\n \"walletconflicts\": [\"value\",...], (array of string) Unset.\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"details\": [{ (array of object) Additional details for each recorded wallet credit and debit.\n \"account\": \"value\", (string) The account pertaining to this transaction.\n \"address\": \"value\", (string) The address an output was paid to, or the empty string if the output is nonstandard or this detail is regarding a transaction input.\n \"amount\": n.nnn, (numeric) The amount of a received output.\n \"category\": \"value\", (string) The kind of detail: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs.\n \"involveswatchonly\": true|false, (boolean) Unset.\n \"fee\": n.nnn, (numeric) The included fee for a sent transaction.\n \"vout\": n, (numeric) The transaction output index.\n },...], \n \"hex\": \"value\", (string) The transaction encoded as a hexadecimal string.\n \"generated\": true|false, (boolean) Only present if transaction only input is a coinbase one.\n} \n",
"help": "help (\"command\")\n\nReturns a list of all commands or help for a specified command.\n\nArguments:\n1. command (string, optional) The command to retrieve help for.\n\nResult (no command provided.):\n\"value\" (string) List of commands.\n\nResult (command specified.):\n\"value\" (string) Help for specified command.\n",
"importprivkey": "importprivkey \"privkey\" (\"label\" rescan=true)\n\nImports a WIF-encoded private key to the 'imported' account.\n\nArguments:\n1. privkey (string, required) The WIF-encoded private key.\n2. label (string, optional) Unused (must be unset or 'imported').\n3. rescan (boolean, optional, default=true) Rescan the blockchain (since the genesis block) for outputs controlled by the imported key.\n\nResult:\nNothing\n",
"keypoolrefill": "keypoolrefill (newsize=100)\n\nDEPRECATED -- This request does nothing since no keypool is maintained.\n\nArguments:\n1. newsize (numeric, optional, default=100) Unused.\n\nResult:\nNothing\n",
"listaccounts": "listaccounts (minconf=1 addresstype=\"*\")\n\nReturns a JSON object of all accounts and their balances.\n\nArguments:\n1. minconf (numeric, optional, default=1) Minimum number of block confirmations required before an unspent output's value is included in the balance.\n2. addresstype (string, optional, default=\"*\") Address type filter. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.\n\nResult:\n{\n \"Account name\": Total balance and each scope respectively, valued in LBC., (object) JSON object with account names as keys and LBC amounts as values.\n ...\n}\n",
"listlockunspent": "listlockunspent\n\nReturns a JSON array of outpoints marked as locked (with lockunspent) for this wallet session.\n\nArguments:\nNone\n\nResult:\n[{\n \"txid\": \"value\", (string) The transaction hash of the referenced output.\n \"vout\": n, (numeric) The output index of the referenced output.\n},...]\n",
"listreceivedbyaccount": "listreceivedbyaccount (minconf=1 includeempty=false includewatchonly=false)\n\nReturns a JSON array of objects listing all accounts and the total amount received by each account.\n\nArguments:\n1. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction is considered.\n2. includeempty (boolean, optional, default=false) Unused.\n3. includewatchonly (boolean, optional, default=false) Unused.\n\nResult:\n[{\n \"account\": \"value\", (string) Account name.\n \"amount\": n.nnn, (numeric) Total amount received by payment addresses of the account valued in LBC.\n \"confirmations\": n, (numeric) Number of block confirmations of the most recent transaction relevant to the account.\n},...]\n",
"listreceivedbyaddress": "listreceivedbyaddress (minconf=1 includeempty=false includewatchonly=false)\n\nReturns a JSON array of objects listing wallet payment addresses and their total received amounts.\n\nArguments:\n1. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction is considered.\n2. includeempty (boolean, optional, default=false) Unused.\n3. includewatchonly (boolean, optional, default=false) Unused.\n\nResult:\n[{\n \"address\": \"value\", (string) The payment address.\n \"amount\": n.nnn, (numeric) Total amount received by the payment address valued in LBC.\n \"confirmations\": n, (numeric) Number of block confirmations of the most recent transaction relevant to the address.\n \"txids\": [\"value\",...], (array of string) Transaction hashes of all transactions involving this address.\n \"involvesWatchonly\": true|false, (boolean) Unset.\n},...]\n",
"listsinceblock": "listsinceblock (\"blockhash\" targetconfirmations=1 includewatchonly=false)\n\nReturns a JSON array of objects listing details of all wallet transactions after some block.\n\nArguments:\n1. blockhash (string, optional) Hash of the parent block of the first block to consider transactions from, or unset to list all transactions.\n2. targetconfirmations (numeric, optional, default=1) Minimum number of block confirmations of the last block in the result object. Must be 1 or greater. Note: The transactions array in the result object is not affected by this parameter.\n3. includewatchonly (boolean, optional, default=false) Unused.\n\nResult:\n{\n \"transactions\": [{ (array of object) JSON array of objects containing verbose details of the each transaction.\n \"abandoned\": true|false, (boolean) Unset.\n \"account\": \"value\", (string) The account name associated with the transaction.\n \"address\": \"value\", (string) Payment address for a transaction output.\n \"amount\": n.nnn, (numeric) The value of the transaction output valued in LBC.\n \"bip125-replaceable\": \"value\", (string) Unset.\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined.\n \"blockheight\": n, (numeric) The block height containing the transaction.\n \"blockindex\": n, (numeric) Unset.\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined.\n \"category\": \"value\", (string) The kind of transaction: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs. Note: A single output may be included multiple times under different categories\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction.\n \"fee\": n.nnn, (numeric) The total input value minus the total output value for sent transactions.\n \"generated\": true|false, (boolean) Whether the transaction output is a coinbase output.\n \"involveswatchonly\": true|false, (boolean) Unset.\n \"label\": \"value\", (string) A comment for the address/transaction, if any.\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"trusted\": true|false, (boolean) Unset.\n \"txid\": \"value\", (string) The hash of the transaction.\n \"vout\": n, (numeric) The transaction output index.\n \"walletconflicts\": [\"value\",...], (array of string) Unset.\n \"comment\": \"value\", (string) Unset.\n \"otheraccount\": \"value\", (string) Unset.\n },...], \n \"lastblock\": \"value\", (string) Hash of the latest-synced block to be used in later calls to listsinceblock.\n} \n",
"listtransactions": "listtransactions (account=\"default\" count=10 from=0 includewatchonly=false)\n\nReturns a JSON array of objects containing verbose details for wallet transactions.\n\nArguments:\n1. account (string, optional, default=\"default\") Account to filter transactions results by. Defaults to 'default'.\n2. count (numeric, optional, default=10) Maximum number of transactions to create results from. Defaults to 10\n3. from (numeric, optional, default=0) Number of transactions to skip before results are created.\n4. includewatchonly (boolean, optional, default=false) Unused.\n\nResult:\n[{\n \"abandoned\": true|false, (boolean) Unset.\n \"account\": \"value\", (string) The account name associated with the transaction.\n \"address\": \"value\", (string) Payment address for a transaction output.\n \"amount\": n.nnn, (numeric) The value of the transaction output valued in LBC.\n \"bip125-replaceable\": \"value\", (string) Unset.\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined.\n \"blockheight\": n, (numeric) The block height containing the transaction.\n \"blockindex\": n, (numeric) Unset.\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined.\n \"category\": \"value\", (string) The kind of transaction: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs. Note: A single output may be included multiple times under different categories\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction.\n \"fee\": n.nnn, (numeric) The total input value minus the total output value for sent transactions.\n \"generated\": true|false, (boolean) Whether the transaction output is a coinbase output.\n \"involveswatchonly\": true|false, (boolean) Unset.\n \"label\": \"value\", (string) A comment for the address/transaction, if any.\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"trusted\": true|false, (boolean) Unset.\n \"txid\": \"value\", (string) The hash of the transaction.\n \"vout\": n, (numeric) The transaction output index.\n \"walletconflicts\": [\"value\",...], (array of string) Unset.\n \"comment\": \"value\", (string) Unset.\n \"otheraccount\": \"value\", (string) Unset.\n},...]\n",
"listunspent": "listunspent (minconf=1 maxconf=9999999 [\"address\",...])\n\nReturns a JSON array of objects representing unlocked unspent outputs controlled by wallet keys.\n\nArguments:\n1. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction output is considered.\n2. maxconf (numeric, optional, default=9999999) Maximum number of block confirmations required before a transaction output is excluded.\n3. addresses (array of string, optional) If set, limits the returned details to unspent outputs received by any of these payment addresses.\n\nResult:\n{\n \"txid\": \"value\", (string) The transaction hash of the referenced output.\n \"vout\": n, (numeric) The output index of the referenced output.\n \"address\": \"value\", (string) The payment address that received the output.\n \"account\": \"value\", (string) The account associated with the receiving payment address.\n \"scriptPubKey\": \"value\", (string) The output script encoded as a hexadecimal string.\n \"redeemScript\": \"value\", (string) Unset.\n \"amount\": n.nnn, (numeric) The amount of the output valued in LBC.\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction.\n \"solvable\": true|false, (boolean) Whether the output is solvable.\n \"spendable\": true|false, (boolean) Whether the output is entirely controlled by wallet keys/scripts (false for partially controlled multisig outputs or outputs to watch-only addresses).\n \"isstake\": true|false, (boolean) Whether the output is staked.\n} \n",
"lockunspent": "lockunspent unlock [{\"txid\":\"value\",\"vout\":n},...]\n\nLocks or unlocks an unspent output.\nLocked outputs are not chosen for transaction inputs of authored transactions and are not included in 'listunspent' results.\nLocked outputs are volatile and are not saved across wallet restarts.\nIf unlock is true and no transaction outputs are specified, all locked outputs are marked unlocked.\n\nArguments:\n1. unlock (boolean, required) True to unlock outputs, false to lock.\n2. transactions (array of object, required) Transaction outputs to lock or unlock.\n[{\n \"txid\": \"value\", (string) The transaction hash of the referenced output.\n \"vout\": n, (numeric) The output index of the referenced output.\n},...]\n\nResult:\ntrue|false (boolean) The boolean 'true'.\n",
"sendfrom": "sendfrom \"fromaccount\" \"toaddress\" amount (minconf=1 addresstype=\"*\" \"comment\" \"commentto\")\n\nAuthors, signs, and sends a transaction that outputs some amount to a payment address.\nA change output is automatically included to send extra output value back to the original account.\n\nArguments:\n1. fromaccount (string, required) Account to pick unspent outputs from.\n2. toaddress (string, required) Address to pay.\n3. amount (numeric, required) Amount to send to the payment address valued in LBC.\n4. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction output is eligible to be spent.\n5. addresstype (string, optional, default=\"*\") Address type filter for UTXOs to spent from. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.\n6. comment (string, optional) Unused.\n7. commentto (string, optional) Unused.\n\nResult:\n\"value\" (string) The transaction hash of the sent transaction.\n",
"sendmany": "sendmany \"fromaccount\" {\"address\":amount,...} (minconf=1 addresstype=\"*\" \"comment\")\n\nAuthors, signs, and sends a transaction that outputs to many payment addresses.\nA change output is automatically included to send extra output value back to the original account.\n\nArguments:\n1. fromaccount (string, required) Account to pick unspent outputs from.\n2. amounts (object, required) Pairs of payment addresses and the output amount to pay each.\n{\n \"Address to pay.\": Amount to send to the payment address valued in LBC., (object) JSON object using payment addresses as keys and output amounts valued in LBC to send to each address.\n ...\n}\n3. minconf (numeric, optional, default=1) Minimum number of block confirmations required before a transaction output is eligible to be spent.\n4. addresstype (string, optional, default=\"*\") Address type filter for UTXOs to spent from. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.\n5. comment (string, optional) Unused.\n\nResult:\n\"value\" (string) The transaction hash of the sent transaction.\n",
"sendtoaddress": "sendtoaddress \"address\" amount (addresstype=\"*\" \"comment\" \"commentto\")\n\nAuthors, signs, and sends a transaction that outputs some amount to a payment address.\nUnlike sendfrom, outputs are always chosen from the default account.\nA change output is automatically included to send extra output value back to the original account.\n\nArguments:\n1. address (string, required) Address to pay.\n2. amount (numeric, required) Amount to send to the payment address valued in LBC.\n3. addresstype (string, optional, default=\"*\") Address type filter for UTXOs to spent from. Must be one of 'legacy', 'p2sh-segwit', 'bech32', or '*'. Defaults to '*'.\n4. comment (string, optional) Unused.\n5. commentto (string, optional) Unused.\n\nResult:\n\"value\" (string) The transaction hash of the sent transaction.\n",
"settxfee": "settxfee amount\n\nModify the increment used each time more fee is required for an authored transaction.\n\nArguments:\n1. amount (numeric, required) The new fee increment valued in LBC.\n\nResult:\ntrue|false (boolean) The boolean 'true'.\n",
"signmessage": "signmessage \"address\" \"message\"\n\nSigns a message using the private key of a payment address.\n\nArguments:\n1. address (string, required) Payment address of private key used to sign the message with.\n2. message (string, required) Message to sign.\n\nResult:\n\"value\" (string) The signed message encoded as a base64 string.\n",
"signrawtransaction": "signrawtransaction \"rawtx\" ([{\"txid\":\"value\",\"vout\":n,\"scriptpubkey\":\"value\",\"redeemscript\":\"value\"},...] [\"privkey\",...] flags=\"ALL\")\n\nSigns transaction inputs using private keys from this wallet and request.\nThe valid flags options are ALL, NONE, SINGLE, ALL|ANYONECANPAY, NONE|ANYONECANPAY, and SINGLE|ANYONECANPAY.\n\nArguments:\n1. rawtx (string, required) Unsigned or partially unsigned transaction to sign encoded as a hexadecimal string.\n2. inputs (array of object, optional) Additional data regarding inputs that this wallet may not be tracking.\n3. privkeys (array of string, optional) Additional WIF-encoded private keys to use when creating signatures.\n4. flags (string, optional, default=\"ALL\") Sighash flags.\n\nResult:\n{\n \"hex\": \"value\", (string) The resulting transaction encoded as a hexadecimal string.\n \"complete\": true|false, (boolean) Whether all input signatures have been created.\n \"errors\": [{ (array of object) Script verification errors (if exists).\n \"txid\": \"value\", (string) The transaction hash of the referenced previous output.\n \"vout\": n, (numeric) The output index of the referenced previous output.\n \"scriptSig\": \"value\", (string) The hex-encoded signature script.\n \"sequence\": n, (numeric) Script sequence number.\n \"error\": \"value\", (string) Verification or signing error related to the input.\n },...], \n} \n",
"validateaddress": "validateaddress \"address\"\n\nVerify that an address is valid.\nExtra details are returned if the address is controlled by this wallet.\nThe following fields are valid only when the address is controlled by this wallet (ismine=true): isscript, pubkey, iscompressed, account, addresses, hex, script, and sigsrequired.\nThe following fields are only valid when address has an associated public key: pubkey, iscompressed.\nThe following fields are only valid when address is a pay-to-script-hash address: addresses, hex, and script.\nIf the address is a multisig address controlled by this wallet, the multisig fields will be left unset if the wallet is locked since the redeem script cannot be decrypted.\n\nArguments:\n1. address (string, required) Address to validate.\n\nResult:\n{\n \"isvalid\": true|false, (boolean) Whether or not the address is valid.\n \"address\": \"value\", (string) The payment address (only when isvalid is true).\n \"ismine\": true|false, (boolean) Whether this address is controlled by the wallet (only when isvalid is true).\n \"iswatchonly\": true|false, (boolean) Unset.\n \"isscript\": true|false, (boolean) Whether the payment address is a pay-to-script-hash address (only when isvalid is true).\n \"pubkey\": \"value\", (string) The associated public key of the payment address, if any (only when isvalid is true).\n \"iscompressed\": true|false, (boolean) Whether the address was created by hashing a compressed public key, if any (only when isvalid is true).\n \"account\": \"value\", (string) The account this payment address belongs to (only when isvalid is true).\n \"addresses\": [\"value\",...], (array of string) All associated payment addresses of the script if address is a multisig address (only when isvalid is true).\n \"hex\": \"value\", (string) The redeem script .\n \"script\": \"value\", (string) The class of redeem script for a multisig address.\n \"sigsrequired\": n, (numeric) The number of required signatures to redeem outputs to the multisig address.\n} \n",
"verifymessage": "verifymessage \"address\" \"signature\" \"message\"\n\nVerify a message was signed with the associated private key of some address.\n\nArguments:\n1. address (string, required) Address used to sign message.\n2. signature (string, required) The signature to verify.\n3. message (string, required) The message to verify.\n\nResult:\ntrue|false (boolean) Whether the message was signed with the private key of 'address'.\n",
"walletlock": "walletlock\n\nLock the wallet.\n\nArguments:\nNone\n\nResult:\nNothing\n",
"walletpassphrase": "walletpassphrase \"passphrase\" timeout\n\nUnlock the wallet.\n\nArguments:\n1. passphrase (string, required) The wallet passphrase\n2. timeout (numeric, required) The number of seconds to wait before the wallet automatically locks\n\nResult:\nNothing\n",
"walletpassphrasechange": "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n\nChange the wallet passphrase.\n\nArguments:\n1. oldpassphrase (string, required) The old wallet passphrase\n2. newpassphrase (string, required) The new wallet passphrase\n\nResult:\nNothing\n",
"createnewaccount": "createnewaccount \"account\"\n\nCreates a new account.\nThe wallet must be unlocked for this request to succeed.\n\nArguments:\n1. account (string, required) Name of the new account\n\nResult:\nNothing\n",
"exportwatchingwallet": "exportwatchingwallet (\"account\" download=false)\n\nCreates and returns a duplicate of the wallet database without any private keys to be used as a watching-only wallet.\n\nArguments:\n1. account (string, optional) Unused (must be unset or \"*\")\n2. download (boolean, optional, default=false) Unused\n\nResult:\n\"value\" (string) The watching-only database encoded as a base64 string\n",
"getbestblock": "getbestblock\n\nReturns the hash and height of the newest block in the best chain that wallet has finished syncing with.\n\nArguments:\nNone\n\nResult:\n{\n \"hash\": \"value\", (string) The hash of the block\n \"height\": n, (numeric) The blockchain height of the block\n} \n",
"getunconfirmedbalance": "getunconfirmedbalance (\"account\")\n\nCalculates the unspent output value of all unmined transaction outputs for an account.\n\nArguments:\n1. account (string, optional) The account to query the unconfirmed balance for (default=\"default\")\n\nResult:\nn.nnn (numeric) Total amount of all unmined unspent outputs of the account valued in bitcoin.\n",
"listaddresstransactions": "listaddresstransactions [\"address\",...] (\"account\")\n\nReturns a JSON array of objects containing verbose details for wallet transactions pertaining some addresses.\n\nArguments:\n1. addresses (array of string, required) Addresses to filter transaction results by\n2. account (string, optional) Unused (must be unset or \"*\")\n\nResult:\n[{\n \"abandoned\": true|false, (boolean) Unset\n \"account\": \"value\", (string) DEPRECATED -- Unset\n \"address\": \"value\", (string) Payment address for a transaction output\n \"amount\": n.nnn, (numeric) The value of the transaction output valued in bitcoin\n \"bip125-replaceable\": \"value\", (string) Unset\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined\n \"blockindex\": n, (numeric) Unset\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined\n \"category\": \"value\", (string) The kind of transaction: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs. Note: A single output may be included multiple times under different categories\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction\n \"fee\": n.nnn, (numeric) The total input value minus the total output value for sent transactions\n \"generated\": true|false, (boolean) Whether the transaction output is a coinbase output\n \"involveswatchonly\": true|false, (boolean) Unset\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"trusted\": true|false, (boolean) Unset\n \"txid\": \"value\", (string) The hash of the transaction\n \"vout\": n, (numeric) The transaction output index\n \"walletconflicts\": [\"value\",...], (array of string) Unset\n \"comment\": \"value\", (string) Unset\n \"otheraccount\": \"value\", (string) Unset\n},...]\n",
"listalltransactions": "listalltransactions (\"account\")\n\nReturns a JSON array of objects in the same format as 'listtransactions' without limiting the number of returned objects.\n\nArguments:\n1. account (string, optional) Unused (must be unset or \"*\")\n\nResult:\n[{\n \"abandoned\": true|false, (boolean) Unset\n \"account\": \"value\", (string) DEPRECATED -- Unset\n \"address\": \"value\", (string) Payment address for a transaction output\n \"amount\": n.nnn, (numeric) The value of the transaction output valued in bitcoin\n \"bip125-replaceable\": \"value\", (string) Unset\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined\n \"blockindex\": n, (numeric) Unset\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined\n \"category\": \"value\", (string) The kind of transaction: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs. Note: A single output may be included multiple times under different categories\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction\n \"fee\": n.nnn, (numeric) The total input value minus the total output value for sent transactions\n \"generated\": true|false, (boolean) Whether the transaction output is a coinbase output\n \"involveswatchonly\": true|false, (boolean) Unset\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist\n \"trusted\": true|false, (boolean) Unset\n \"txid\": \"value\", (string) The hash of the transaction\n \"vout\": n, (numeric) The transaction output index\n \"walletconflicts\": [\"value\",...], (array of string) Unset\n \"comment\": \"value\", (string) Unset\n \"otheraccount\": \"value\", (string) Unset\n},...]\n",
"renameaccount": "renameaccount \"oldaccount\" \"newaccount\"\n\nRenames an account.\n\nArguments:\n1. oldaccount (string, required) The old account name to rename\n2. newaccount (string, required) The new name for the account\n\nResult:\nNothing\n",
"walletislocked": "walletislocked\n\nReturns whether or not the wallet is locked.\n\nArguments:\nNone\n\nResult:\ntrue|false (boolean) Whether the wallet is locked\n",
"walletpassphrase": "walletpassphrase \"passphrase\" timeout\n\nUnlock the wallet.\n\nArguments:\n1. passphrase (string, required) The wallet passphrase.\n2. timeout (numeric, required) The number of seconds to wait before the wallet automatically locks.\n\nResult:\nNothing\n",
"walletpassphrasechange": "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n\nChange the wallet passphrase.\n\nArguments:\n1. oldpassphrase (string, required) The old wallet passphrase.\n2. newpassphrase (string, required) The new wallet passphrase.\n\nResult:\nNothing\n",
"createnewaccount": "createnewaccount \"account\"\n\nCreates a new account.\n\nArguments:\n1. account (string, required) Account name.\n\nResult:\nNothing\n",
"getbestblock": "getbestblock\n\nReturns the hash and height of the newest block in the best chain that wallet has finished syncing with.\n\nArguments:\nNone\n\nResult:\n{\n \"hash\": \"value\", (string) The hash of the block.\n \"height\": n, (numeric) The blockchain height of the block.\n} \n",
"getunconfirmedbalance": "getunconfirmedbalance (account=\"default\")\n\nCalculates the unspent output value of all unmined transaction outputs.\n\nArguments:\n1. account (string, optional, default=\"default\") The account name to query the unconfirmed balance for. Default to 'default'.\n\nResult:\nn.nnn (numeric) Total amount of all unmined unspent outputs of the account valued in LBC.\n",
"listaddresstransactions": "listaddresstransactions [\"address\",...] (account=\"default\")\n\nReturns a JSON array of objects containing verbose details for wallet transactions pertaining some addresses.\n\nArguments:\n1. addresses (array of string, required) Addresses to filter transaction results by.\n2. account (string, optional, default=\"default\") Account to filter transactions results by. Defaults to 'default'.\n\nResult:\n[{\n \"abandoned\": true|false, (boolean) Unset.\n \"account\": \"value\", (string) The account name associated with the transaction.\n \"address\": \"value\", (string) Payment address for a transaction output.\n \"amount\": n.nnn, (numeric) The value of the transaction output valued in LBC.\n \"bip125-replaceable\": \"value\", (string) Unset.\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined.\n \"blockheight\": n, (numeric) The block height containing the transaction.\n \"blockindex\": n, (numeric) Unset.\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined.\n \"category\": \"value\", (string) The kind of transaction: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs. Note: A single output may be included multiple times under different categories\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction.\n \"fee\": n.nnn, (numeric) The total input value minus the total output value for sent transactions.\n \"generated\": true|false, (boolean) Whether the transaction output is a coinbase output.\n \"involveswatchonly\": true|false, (boolean) Unset.\n \"label\": \"value\", (string) A comment for the address/transaction, if any.\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"trusted\": true|false, (boolean) Unset.\n \"txid\": \"value\", (string) The hash of the transaction.\n \"vout\": n, (numeric) The transaction output index.\n \"walletconflicts\": [\"value\",...], (array of string) Unset.\n \"comment\": \"value\", (string) Unset.\n \"otheraccount\": \"value\", (string) Unset.\n},...]\n",
"listalltransactions": "listalltransactions (account=\"default\")\n\nReturns a JSON array of objects in the same format as 'listtransactions' without limiting the number of returned objects.\n\nArguments:\n1. account (string, optional, default=\"default\") Account to filter transactions results by. Defaults to 'default'.\n\nResult:\n[{\n \"abandoned\": true|false, (boolean) Unset.\n \"account\": \"value\", (string) The account name associated with the transaction.\n \"address\": \"value\", (string) Payment address for a transaction output.\n \"amount\": n.nnn, (numeric) The value of the transaction output valued in LBC.\n \"bip125-replaceable\": \"value\", (string) Unset.\n \"blockhash\": \"value\", (string) The hash of the block this transaction is mined in, or the empty string if unmined.\n \"blockheight\": n, (numeric) The block height containing the transaction.\n \"blockindex\": n, (numeric) Unset.\n \"blocktime\": n, (numeric) The Unix time of the block header this transaction is mined in, or 0 if unmined.\n \"category\": \"value\", (string) The kind of transaction: \"send\" for sent transactions, \"immature\" for immature coinbase outputs, \"generate\" for mature coinbase outputs, or \"recv\" for all other received outputs. Note: A single output may be included multiple times under different categories\n \"confirmations\": n, (numeric) The number of block confirmations of the transaction.\n \"fee\": n.nnn, (numeric) The total input value minus the total output value for sent transactions.\n \"generated\": true|false, (boolean) Whether the transaction output is a coinbase output.\n \"involveswatchonly\": true|false, (boolean) Unset.\n \"label\": \"value\", (string) A comment for the address/transaction, if any.\n \"time\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"timereceived\": n, (numeric) The earliest Unix time this transaction was known to exist.\n \"trusted\": true|false, (boolean) Unset.\n \"txid\": \"value\", (string) The hash of the transaction.\n \"vout\": n, (numeric) The transaction output index.\n \"walletconflicts\": [\"value\",...], (array of string) Unset.\n \"comment\": \"value\", (string) Unset.\n \"otheraccount\": \"value\", (string) Unset.\n},...]\n",
"renameaccount": "renameaccount \"oldaccount\" \"newaccount\"\n\nRenames an account.\n\nArguments:\n1. oldaccount (string, required) The old account name to rename.\n2. newaccount (string, required) The new name for the account.\n\nResult:\nNothing\n",
"rescanblockchain": "rescanblockchain (startheight=0 stopheight)\n\nRenames an account.\n\nArguments:\n1. startheight (numeric, optional, default=0) Block height where the rescan should start.\n2. stopheight (numeric, optional) The last block height that should be scanned. If none is provided it will rescan up to the tip at return time of this call.\n\nResult:\n{\n \"start_height\": n, (numeric) The block height where the rescan started (the requested height or 0)\n \"stop_height\": n, (numeric) The height of the last rescanned block.\n} \n",
"walletislocked": "walletislocked\n\nReturns whether or not the wallet is locked.\n\nArguments:\nNone\n\nResult:\ntrue|false (boolean) Whether the wallet is locked.\n",
}
}
@@ -56,4 +57,4 @@ var localeHelpDescs = map[string]func() map[string]string{
"en_US": helpDescsEnUS,
}
var requestUsages = "addmultisigaddress nrequired [\"key\",...] (\"account\")\ncreatemultisig nrequired [\"key\",...]\ndumpprivkey \"address\"\ngetaccount \"address\"\ngetaccountaddress \"account\"\ngetaddressesbyaccount \"account\"\ngetbalance (\"account\" minconf=1)\ngetbestblockhash\ngetblockcount\ngetinfo\ngetnewaddress (\"account\")\ngetrawchangeaddress (\"account\")\ngetreceivedbyaccount \"account\" (minconf=1)\ngetreceivedbyaddress \"address\" (minconf=1)\ngettransaction \"txid\" (includewatchonly=false)\nhelp (\"command\")\nimportprivkey \"privkey\" (\"label\" rescan=true)\nkeypoolrefill (newsize=100)\nlistaccounts (minconf=1)\nlistlockunspent\nlistreceivedbyaccount (minconf=1 includeempty=false includewatchonly=false)\nlistreceivedbyaddress (minconf=1 includeempty=false includewatchonly=false)\nlistsinceblock (\"blockhash\" targetconfirmations=1 includewatchonly=false)\nlisttransactions (\"account\" count=10 from=0 includewatchonly=false)\nlistunspent (minconf=1 maxconf=9999999 [\"address\",...])\nlockunspent unlock [{\"txid\":\"value\",\"vout\":n},...]\nsendfrom \"fromaccount\" \"toaddress\" amount (minconf=1 \"comment\" \"commentto\")\nsendmany \"fromaccount\" {\"address\":amount,...} (minconf=1 \"comment\")\nsendtoaddress \"address\" amount (\"comment\" \"commentto\")\nsettxfee amount\nsignmessage \"address\" \"message\"\nsignrawtransaction \"rawtx\" ([{\"txid\":\"value\",\"vout\":n,\"scriptpubkey\":\"value\",\"redeemscript\":\"value\"},...] [\"privkey\",...] flags=\"ALL\")\nvalidateaddress \"address\"\nverifymessage \"address\" \"signature\" \"message\"\nwalletlock\nwalletpassphrase \"passphrase\" timeout\nwalletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\ncreatenewaccount \"account\"\nexportwatchingwallet (\"account\" download=false)\ngetbestblock\ngetunconfirmedbalance (\"account\")\nlistaddresstransactions [\"address\",...] (\"account\")\nlistalltransactions (\"account\")\nrenameaccount \"oldaccount\" \"newaccount\"\nwalletislocked"
var requestUsages = "addmultisigaddress nrequired [\"key\",...] (\"account\")\ncreatemultisig nrequired [\"key\",...]\ndumpprivkey \"address\"\ngetaccount \"address\"\ngetaccountaddress (account=\"default\" addresstype=\"legacy\")\ngetaddressesbyaccount (account=\"default\" addresstype=\"*\")\ngetaddressinfo \"address\"\ngetbalance (account=\"default\" minconf=1 addresstype=\"*\")\ngetbestblockhash\ngetblockcount\ngetinfo\ngetnewaddress (account=\"default\" addresstype=\"legacy\")\ngetrawchangeaddress (account=\"default\" addresstype=\"legacy\")\ngetreceivedbyaccount (account=\"default\" minconf=1)\ngetreceivedbyaddress \"address\" (minconf=1)\ngettransaction \"txid\" (includewatchonly=false)\nhelp (\"command\")\nimportprivkey \"privkey\" (\"label\" rescan=true)\nkeypoolrefill (newsize=100)\nlistaccounts (minconf=1 addresstype=\"*\")\nlistlockunspent\nlistreceivedbyaccount (minconf=1 includeempty=false includewatchonly=false)\nlistreceivedbyaddress (minconf=1 includeempty=false includewatchonly=false)\nlistsinceblock (\"blockhash\" targetconfirmations=1 includewatchonly=false)\nlisttransactions (account=\"default\" count=10 from=0 includewatchonly=false)\nlistunspent (minconf=1 maxconf=9999999 [\"address\",...])\nlockunspent unlock [{\"txid\":\"value\",\"vout\":n},...]\nsendfrom \"fromaccount\" \"toaddress\" amount (minconf=1 addresstype=\"*\" \"comment\" \"commentto\")\nsendmany \"fromaccount\" {\"address\":amount,...} (minconf=1 addresstype=\"*\" \"comment\")\nsendtoaddress \"address\" amount (addresstype=\"*\" \"comment\" \"commentto\")\nsettxfee amount\nsignmessage \"address\" \"message\"\nsignrawtransaction \"rawtx\" ([{\"txid\":\"value\",\"vout\":n,\"scriptpubkey\":\"value\",\"redeemscript\":\"value\"},...] [\"privkey\",...] flags=\"ALL\")\nvalidateaddress \"address\"\nverifymessage \"address\" \"signature\" \"message\"\nwalletlock\nwalletpassphrase \"passphrase\" timeout\nwalletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\ncreatenewaccount \"account\"\ngetbestblock\ngetunconfirmedbalance (account=\"default\")\nlistaddresstransactions [\"address\",...] (account=\"default\")\nlistalltransactions (account=\"default\")\nrenameaccount \"oldaccount\" \"newaccount\"\nrescanblockchain (startheight=0 stopheight)\nwalletislocked"
+29 -40
View File
@@ -10,7 +10,6 @@ import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
@@ -19,10 +18,10 @@ import (
"sync/atomic"
"time"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/wallet"
"github.com/btcsuite/websocket"
"github.com/lbryio/lbcd/btcjson"
"github.com/lbryio/lbcwallet/chain"
"github.com/lbryio/lbcwallet/wallet"
)
type websocketClient struct {
@@ -58,12 +57,11 @@ func (c *websocketClient) send(b []byte) error {
// Server holds the items the RPC server may need to access (auth,
// config, shutdown, etc.)
type Server struct {
httpServer http.Server
wallet *wallet.Wallet
walletLoader *wallet.Loader
chainClient chain.Interface
handlerLookup func(string) (requestHandler, bool)
handlerMu sync.Mutex
httpServer http.Server
wallet *wallet.Wallet
walletLoader *wallet.Loader
chainClient chain.Interface
handlerMu sync.Mutex
listeners []net.Listener
authsha [sha256.Size]byte
@@ -81,7 +79,7 @@ type Server struct {
// jsonAuthFail sends a message back to the client if the http auth is rejected.
func jsonAuthFail(w http.ResponseWriter) {
w.Header().Add("WWW-Authenticate", `Basic realm="btcwallet RPC"`)
w.Header().Add("WWW-Authenticate", `Basic realm="lbcwallet RPC"`)
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
}
@@ -167,7 +165,7 @@ func NewServer(opts *Options, walletLoader *wallet.Loader, listeners []net.Liste
// httpBasicAuth returns the UTF-8 bytes of the HTTP Basic authentication
// string:
//
// "Basic " + base64(username + ":" + password)
// "Basic " + base64(username + ":" + password)
func httpBasicAuth(username, password string) []byte {
const header = "Basic "
base64 := base64.StdEncoding
@@ -265,8 +263,8 @@ func (s *Server) SetChainServer(chainClient chain.Interface) {
}
// handlerClosure creates a closure function for handling requests of the given
// method. This may be a request that is handled directly by btcwallet, or
// a chain server request that is handled by passing the request down to btcd.
// method. This may be a request that is handled directly by lbcwallet, or
// a chain server request that is handled by passing the request down to .
//
// NOTE: These handlers do not handle special cases, such as the authenticate
// method. Each of these must be checked beforehand (the method is already
@@ -326,7 +324,7 @@ func throttled(threshold int64, h http.Handler) http.Handler {
if current-1 >= threshold {
log.Warnf("Reached threshold of %d concurrent active clients", threshold)
http.Error(w, "429 Too Many Requests", 429)
http.Error(w, "429 Too Many Requests", http.StatusTooManyRequests)
return
}
@@ -334,24 +332,6 @@ func throttled(threshold int64, h http.Handler) http.Handler {
})
}
// sanitizeRequest returns a sanitized string for the request which may be
// safely logged. It is intended to strip private keys, passphrases, and any
// other secrets from request parameters before they may be saved to a log file.
func sanitizeRequest(r *btcjson.Request) string {
// These are considered unsafe to log, so sanitize parameters.
switch r.Method {
case "encryptwallet", "importprivkey", "importwallet",
"signrawtransaction", "walletpassphrase",
"walletpassphrasechange":
return fmt.Sprintf(`{"id":%v,"method":"%s","params":SANITIZED %d parameters}`,
r.ID, r.Method, len(r.Params))
}
return fmt.Sprintf(`{"id":%v,"method":"%s","params":%v}`, r.ID,
r.Method, r.Params)
}
// idPointer returns a pointer to the passed ID, or nil if the interface is nil.
// Interface pointers are usually a red flag of doing something incorrectly,
// but this is only implemented here to work around an oddity with btcjson,
@@ -462,7 +442,7 @@ out:
switch req.Method {
case "stop":
resp := makeResponse(req.ID,
"btcwallet stopping.", nil)
"lbcwallet stopping.", nil)
mresp, err := json.Marshal(resp)
// Expected to never fail.
if err != nil {
@@ -473,7 +453,7 @@ out:
break out
}
s.requestProcessShutdown()
break
break out
default:
req := req // Copy for the closure
@@ -481,9 +461,13 @@ out:
wsc.wg.Add(1)
go func() {
resp, jsonErr := f()
mresp, err := btcjson.MarshalResponse(req.ID, resp, jsonErr)
mresp, err := btcjson.MarshalResponse(
btcjson.RpcVersion1, req.ID,
resp, jsonErr,
)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
log.Errorf("Unable to marshal "+
"response: %v", err)
} else {
_ = wsc.send(mresp)
}
@@ -580,7 +564,10 @@ func (s *Server) postClientRPC(w http.ResponseWriter, r *http.Request) {
var req btcjson.Request
err = json.Unmarshal(rpcRequest, &req)
if err != nil {
resp, err := btcjson.MarshalResponse(req.ID, nil, btcjson.ErrRPCInvalidRequest)
resp, err := btcjson.MarshalResponse(
btcjson.RpcVersion1, req.ID, nil,
btcjson.ErrRPCInvalidRequest,
)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error",
@@ -606,13 +593,15 @@ func (s *Server) postClientRPC(w http.ResponseWriter, r *http.Request) {
return
case "stop":
stop = true
res = "btcwallet stopping"
res = "lbcwallet stopping"
default:
res, jsonErr = s.handlerClosure(&req)()
}
// Marshal and send.
mresp, err := btcjson.MarshalResponse(req.ID, res, jsonErr)
mresp, err := btcjson.MarshalResponse(
btcjson.RpcVersion1, req.ID, res, jsonErr,
)
if err != nil {
log.Errorf("Unable to marshal response: %v", err)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
-3
View File
@@ -1,3 +0,0 @@
#!/bin/sh
protoc -I. api.proto --go_out=plugins=grpc:walletrpc
-81
View File
@@ -1,81 +0,0 @@
// Copyright (c) 2015-2016 The btcsuite developers
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package rpcserver
import (
"os"
"strings"
"google.golang.org/grpc/grpclog"
"github.com/btcsuite/btclog"
)
// UseLogger sets the logger to use for the gRPC server.
func UseLogger(l btclog.Logger) {
grpclog.SetLogger(logger{l})
}
// logger uses a btclog.Logger to implement the grpclog.Logger interface.
type logger struct {
btclog.Logger
}
// stripGrpcPrefix removes the package prefix for all logs made to the grpc
// logger, since these are already included as the btclog subsystem name.
func stripGrpcPrefix(logstr string) string {
return strings.TrimPrefix(logstr, "grpc: ")
}
// stripGrpcPrefixArgs removes the package prefix from the first argument, if it
// exists and is a string, returning the same arg slice after reassigning the
// first arg.
func stripGrpcPrefixArgs(args ...interface{}) []interface{} {
if len(args) == 0 {
return args
}
firstArgStr, ok := args[0].(string)
if ok {
args[0] = stripGrpcPrefix(firstArgStr)
}
return args
}
func (l logger) Fatal(args ...interface{}) {
l.Critical(stripGrpcPrefixArgs(args)...)
os.Exit(1)
}
func (l logger) Fatalf(format string, args ...interface{}) {
l.Criticalf(stripGrpcPrefix(format), args...)
os.Exit(1)
}
func (l logger) Fatalln(args ...interface{}) {
l.Critical(stripGrpcPrefixArgs(args)...)
os.Exit(1)
}
func (l logger) Print(args ...interface{}) {
l.Info(stripGrpcPrefixArgs(args)...)
}
func (l logger) Printf(format string, args ...interface{}) {
l.Infof(stripGrpcPrefix(format), args...)
}
func (l logger) Println(args ...interface{}) {
l.Info(stripGrpcPrefixArgs(args)...)
}
-837
View File
@@ -1,837 +0,0 @@
// Copyright (c) 2015-2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
// Package rpcserver implements the RPC API and is used by the main package to
// start gRPC services.
//
// Full documentation of the API implemented by this package is maintained in a
// language-agnostic document:
//
// https://github.com/btcsuite/btcwallet/blob/master/rpc/documentation/api.md
//
// Any API changes must be performed according to the steps listed here:
//
// https://github.com/btcsuite/btcwallet/blob/master/rpc/documentation/serverchanges.md
package rpcserver
import (
"bytes"
"errors"
"sync"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/internal/cfgutil"
"github.com/btcsuite/btcwallet/internal/zero"
"github.com/btcsuite/btcwallet/netparams"
pb "github.com/btcsuite/btcwallet/rpc/walletrpc"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wallet"
"github.com/btcsuite/btcwallet/walletdb"
)
// Public API version constants
const (
semverString = "2.0.1"
semverMajor = 2
semverMinor = 0
semverPatch = 1
)
// translateError creates a new gRPC error with an appropiate error code for
// recognized errors.
//
// This function is by no means complete and should be expanded based on other
// known errors. Any RPC handler not returning a gRPC error (with grpc.Errorf)
// should return this result instead.
func translateError(err error) error {
code := errorCode(err)
return grpc.Errorf(code, "%s", err.Error())
}
func errorCode(err error) codes.Code {
// waddrmgr.IsError is convenient, but not granular enough when the
// underlying error has to be checked. Unwrap the underlying error
// if it exists.
if e, ok := err.(waddrmgr.ManagerError); ok {
// For these waddrmgr error codes, the underlying error isn't
// needed to determine the grpc error code.
switch e.ErrorCode {
case waddrmgr.ErrWrongPassphrase: // public and private
return codes.InvalidArgument
case waddrmgr.ErrAccountNotFound:
return codes.NotFound
case waddrmgr.ErrInvalidAccount: // reserved account
return codes.InvalidArgument
case waddrmgr.ErrDuplicateAccount:
return codes.AlreadyExists
}
err = e.Err
}
switch err {
case wallet.ErrLoaded:
return codes.FailedPrecondition
case walletdb.ErrDbNotOpen:
return codes.Aborted
case walletdb.ErrDbExists:
return codes.AlreadyExists
case walletdb.ErrDbDoesNotExist:
return codes.NotFound
case hdkeychain.ErrInvalidSeedLen:
return codes.InvalidArgument
default:
return codes.Unknown
}
}
// versionServer provides RPC clients with the ability to query the RPC server
// version.
type versionServer struct {
}
// walletServer provides wallet services for RPC clients.
type walletServer struct {
wallet *wallet.Wallet
}
// loaderServer provides RPC clients with the ability to load and close wallets,
// as well as establishing a RPC connection to a btcd consensus server.
type loaderServer struct {
loader *wallet.Loader
activeNet *netparams.Params
rpcClient *chain.RPCClient
mu sync.Mutex
}
// StartVersionService creates an implementation of the VersionService and
// registers it with the gRPC server.
func StartVersionService(server *grpc.Server) {
pb.RegisterVersionServiceServer(server, &versionServer{})
}
func (*versionServer) Version(ctx context.Context, req *pb.VersionRequest) (*pb.VersionResponse, error) {
return &pb.VersionResponse{
VersionString: semverString,
Major: semverMajor,
Minor: semverMinor,
Patch: semverPatch,
}, nil
}
// StartWalletService creates an implementation of the WalletService and
// registers it with the gRPC server.
func StartWalletService(server *grpc.Server, wallet *wallet.Wallet) {
service := &walletServer{wallet}
pb.RegisterWalletServiceServer(server, service)
}
func (s *walletServer) Ping(ctx context.Context, req *pb.PingRequest) (*pb.PingResponse, error) {
return &pb.PingResponse{}, nil
}
func (s *walletServer) Network(ctx context.Context, req *pb.NetworkRequest) (
*pb.NetworkResponse, error) {
return &pb.NetworkResponse{ActiveNetwork: uint32(s.wallet.ChainParams().Net)}, nil
}
func (s *walletServer) AccountNumber(ctx context.Context, req *pb.AccountNumberRequest) (
*pb.AccountNumberResponse, error) {
accountNum, err := s.wallet.AccountNumber(waddrmgr.KeyScopeBIP0044, req.AccountName)
if err != nil {
return nil, translateError(err)
}
return &pb.AccountNumberResponse{AccountNumber: accountNum}, nil
}
func (s *walletServer) Accounts(ctx context.Context, req *pb.AccountsRequest) (
*pb.AccountsResponse, error) {
resp, err := s.wallet.Accounts(waddrmgr.KeyScopeBIP0044)
if err != nil {
return nil, translateError(err)
}
accounts := make([]*pb.AccountsResponse_Account, len(resp.Accounts))
for i := range resp.Accounts {
a := &resp.Accounts[i]
accounts[i] = &pb.AccountsResponse_Account{
AccountNumber: a.AccountNumber,
AccountName: a.AccountName,
TotalBalance: int64(a.TotalBalance),
ExternalKeyCount: a.ExternalKeyCount,
InternalKeyCount: a.InternalKeyCount,
ImportedKeyCount: a.ImportedKeyCount,
}
}
return &pb.AccountsResponse{
Accounts: accounts,
CurrentBlockHash: resp.CurrentBlockHash[:],
CurrentBlockHeight: resp.CurrentBlockHeight,
}, nil
}
func (s *walletServer) RenameAccount(ctx context.Context, req *pb.RenameAccountRequest) (
*pb.RenameAccountResponse, error) {
err := s.wallet.RenameAccount(waddrmgr.KeyScopeBIP0044, req.AccountNumber, req.NewName)
if err != nil {
return nil, translateError(err)
}
return &pb.RenameAccountResponse{}, nil
}
func (s *walletServer) NextAccount(ctx context.Context, req *pb.NextAccountRequest) (
*pb.NextAccountResponse, error) {
defer zero.Bytes(req.Passphrase)
if req.AccountName == "" {
return nil, grpc.Errorf(codes.InvalidArgument, "account name may not be empty")
}
lock := make(chan time.Time, 1)
defer func() {
lock <- time.Time{} // send matters, not the value
}()
err := s.wallet.Unlock(req.Passphrase, lock)
if err != nil {
return nil, translateError(err)
}
account, err := s.wallet.NextAccount(waddrmgr.KeyScopeBIP0044, req.AccountName)
if err != nil {
return nil, translateError(err)
}
return &pb.NextAccountResponse{AccountNumber: account}, nil
}
func (s *walletServer) NextAddress(ctx context.Context, req *pb.NextAddressRequest) (
*pb.NextAddressResponse, error) {
var (
addr btcutil.Address
err error
)
switch req.Kind {
case pb.NextAddressRequest_BIP0044_EXTERNAL:
addr, err = s.wallet.NewAddress(req.Account, waddrmgr.KeyScopeBIP0044)
case pb.NextAddressRequest_BIP0044_INTERNAL:
addr, err = s.wallet.NewChangeAddress(req.Account, waddrmgr.KeyScopeBIP0044)
default:
return nil, grpc.Errorf(codes.InvalidArgument, "kind=%v", req.Kind)
}
if err != nil {
return nil, translateError(err)
}
return &pb.NextAddressResponse{Address: addr.EncodeAddress()}, nil
}
func (s *walletServer) ImportPrivateKey(ctx context.Context, req *pb.ImportPrivateKeyRequest) (
*pb.ImportPrivateKeyResponse, error) {
defer zero.Bytes(req.Passphrase)
wif, err := btcutil.DecodeWIF(req.PrivateKeyWif)
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Invalid WIF-encoded private key: %v", err)
}
lock := make(chan time.Time, 1)
defer func() {
lock <- time.Time{} // send matters, not the value
}()
err = s.wallet.Unlock(req.Passphrase, lock)
if err != nil {
return nil, translateError(err)
}
// At the moment, only the special-cased import account can be used to
// import keys.
if req.Account != waddrmgr.ImportedAddrAccount {
return nil, grpc.Errorf(codes.InvalidArgument,
"Only the imported account accepts private key imports")
}
_, err = s.wallet.ImportPrivateKey(waddrmgr.KeyScopeBIP0044, wif, nil, req.Rescan)
if err != nil {
return nil, translateError(err)
}
return &pb.ImportPrivateKeyResponse{}, nil
}
func (s *walletServer) Balance(ctx context.Context, req *pb.BalanceRequest) (
*pb.BalanceResponse, error) {
account := req.AccountNumber
reqConfs := req.RequiredConfirmations
bals, err := s.wallet.CalculateAccountBalances(account, reqConfs)
if err != nil {
return nil, translateError(err)
}
// TODO: Spendable currently includes multisig outputs that may not
// actually be spendable without additional keys.
resp := &pb.BalanceResponse{
Total: int64(bals.Total),
Spendable: int64(bals.Spendable),
ImmatureReward: int64(bals.ImmatureReward),
}
return resp, nil
}
// confirmed checks whether a transaction at height txHeight has met minconf
// confirmations for a blockchain at height curHeight.
func confirmed(minconf, txHeight, curHeight int32) bool {
return confirms(txHeight, curHeight) >= minconf
}
// confirms returns the number of confirmations for a transaction in a block at
// height txHeight (or -1 for an unconfirmed tx) given the chain height
// curHeight.
func confirms(txHeight, curHeight int32) int32 {
switch {
case txHeight == -1, txHeight > curHeight:
return 0
default:
return curHeight - txHeight + 1
}
}
func (s *walletServer) FundTransaction(ctx context.Context, req *pb.FundTransactionRequest) (
*pb.FundTransactionResponse, error) {
policy := wallet.OutputSelectionPolicy{
Account: req.Account,
RequiredConfirmations: req.RequiredConfirmations,
}
unspentOutputs, err := s.wallet.UnspentOutputs(policy)
if err != nil {
return nil, translateError(err)
}
selectedOutputs := make([]*pb.FundTransactionResponse_PreviousOutput, 0, len(unspentOutputs))
var totalAmount btcutil.Amount
for _, output := range unspentOutputs {
selectedOutputs = append(selectedOutputs, &pb.FundTransactionResponse_PreviousOutput{
TransactionHash: output.OutPoint.Hash[:],
OutputIndex: output.OutPoint.Index,
Amount: output.Output.Value,
PkScript: output.Output.PkScript,
ReceiveTime: output.ReceiveTime.Unix(),
FromCoinbase: output.OutputKind == wallet.OutputKindCoinbase,
})
totalAmount += btcutil.Amount(output.Output.Value)
if req.TargetAmount != 0 && totalAmount > btcutil.Amount(req.TargetAmount) {
break
}
}
var changeScript []byte
if req.IncludeChangeScript && totalAmount > btcutil.Amount(req.TargetAmount) {
changeAddr, err := s.wallet.NewChangeAddress(req.Account, waddrmgr.KeyScopeBIP0044)
if err != nil {
return nil, translateError(err)
}
changeScript, err = txscript.PayToAddrScript(changeAddr)
if err != nil {
return nil, translateError(err)
}
}
return &pb.FundTransactionResponse{
SelectedOutputs: selectedOutputs,
TotalAmount: int64(totalAmount),
ChangePkScript: changeScript,
}, nil
}
func marshalGetTransactionsResult(wresp *wallet.GetTransactionsResult) (
*pb.GetTransactionsResponse, error) {
resp := &pb.GetTransactionsResponse{
MinedTransactions: marshalBlocks(wresp.MinedTransactions),
UnminedTransactions: marshalTransactionDetails(wresp.UnminedTransactions),
}
return resp, nil
}
// BUGS:
// - MinimumRecentTransactions is ignored.
// - Wrong error codes when a block height or hash is not recognized
func (s *walletServer) GetTransactions(ctx context.Context, req *pb.GetTransactionsRequest) (
resp *pb.GetTransactionsResponse, err error) {
var startBlock, endBlock *wallet.BlockIdentifier
if req.StartingBlockHash != nil && req.StartingBlockHeight != 0 {
return nil, errors.New(
"starting block hash and height may not be specified simultaneously")
} else if req.StartingBlockHash != nil {
startBlockHash, err := chainhash.NewHash(req.StartingBlockHash)
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument, "%s", err.Error())
}
startBlock = wallet.NewBlockIdentifierFromHash(startBlockHash)
} else if req.StartingBlockHeight != 0 {
startBlock = wallet.NewBlockIdentifierFromHeight(req.StartingBlockHeight)
}
if req.EndingBlockHash != nil && req.EndingBlockHeight != 0 {
return nil, grpc.Errorf(codes.InvalidArgument,
"ending block hash and height may not be specified simultaneously")
} else if req.EndingBlockHash != nil {
endBlockHash, err := chainhash.NewHash(req.EndingBlockHash)
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument, "%s", err.Error())
}
endBlock = wallet.NewBlockIdentifierFromHash(endBlockHash)
} else if req.EndingBlockHeight != 0 {
endBlock = wallet.NewBlockIdentifierFromHeight(req.EndingBlockHeight)
}
var minRecentTxs int
if req.MinimumRecentTransactions != 0 {
if endBlock != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"ending block and minimum number of recent transactions "+
"may not be specified simultaneously")
}
minRecentTxs = int(req.MinimumRecentTransactions)
if minRecentTxs < 0 {
return nil, grpc.Errorf(codes.InvalidArgument,
"minimum number of recent transactions may not be negative")
}
}
_ = minRecentTxs
gtr, err := s.wallet.GetTransactions(startBlock, endBlock, ctx.Done())
if err != nil {
return nil, translateError(err)
}
return marshalGetTransactionsResult(gtr)
}
func (s *walletServer) ChangePassphrase(ctx context.Context, req *pb.ChangePassphraseRequest) (
*pb.ChangePassphraseResponse, error) {
defer func() {
zero.Bytes(req.OldPassphrase)
zero.Bytes(req.NewPassphrase)
}()
var err error
switch req.Key {
case pb.ChangePassphraseRequest_PRIVATE:
err = s.wallet.ChangePrivatePassphrase(req.OldPassphrase, req.NewPassphrase)
case pb.ChangePassphraseRequest_PUBLIC:
err = s.wallet.ChangePublicPassphrase(req.OldPassphrase, req.NewPassphrase)
default:
return nil, grpc.Errorf(codes.InvalidArgument, "Unknown key type (%d)", req.Key)
}
if err != nil {
return nil, translateError(err)
}
return &pb.ChangePassphraseResponse{}, nil
}
// BUGS:
// - InputIndexes request field is ignored.
func (s *walletServer) SignTransaction(ctx context.Context, req *pb.SignTransactionRequest) (
*pb.SignTransactionResponse, error) {
defer zero.Bytes(req.Passphrase)
var tx wire.MsgTx
err := tx.Deserialize(bytes.NewReader(req.SerializedTransaction))
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Bytes do not represent a valid raw transaction: %v", err)
}
lock := make(chan time.Time, 1)
defer func() {
lock <- time.Time{} // send matters, not the value
}()
err = s.wallet.Unlock(req.Passphrase, lock)
if err != nil {
return nil, translateError(err)
}
invalidSigs, err := s.wallet.SignTransaction(&tx, txscript.SigHashAll, nil, nil, nil)
if err != nil {
return nil, translateError(err)
}
invalidInputIndexes := make([]uint32, len(invalidSigs))
for i, e := range invalidSigs {
invalidInputIndexes[i] = e.InputIndex
}
var serializedTransaction bytes.Buffer
serializedTransaction.Grow(tx.SerializeSize())
err = tx.Serialize(&serializedTransaction)
if err != nil {
return nil, translateError(err)
}
resp := &pb.SignTransactionResponse{
Transaction: serializedTransaction.Bytes(),
UnsignedInputIndexes: invalidInputIndexes,
}
return resp, nil
}
// BUGS:
// - The transaction is not inspected to be relevant before publishing using
// sendrawtransaction, so connection errors to btcd could result in the tx
// never being added to the wallet database.
// - Once the above bug is fixed, wallet will require a way to purge invalid
// transactions from the database when they are rejected by the network, other
// than double spending them.
func (s *walletServer) PublishTransaction(ctx context.Context, req *pb.PublishTransactionRequest) (
*pb.PublishTransactionResponse, error) {
var msgTx wire.MsgTx
err := msgTx.Deserialize(bytes.NewReader(req.SignedTransaction))
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Bytes do not represent a valid raw transaction: %v", err)
}
err = s.wallet.PublishTransaction(&msgTx)
if err != nil {
return nil, translateError(err)
}
return &pb.PublishTransactionResponse{}, nil
}
func marshalTransactionInputs(v []wallet.TransactionSummaryInput) []*pb.TransactionDetails_Input {
inputs := make([]*pb.TransactionDetails_Input, len(v))
for i := range v {
input := &v[i]
inputs[i] = &pb.TransactionDetails_Input{
Index: input.Index,
PreviousAccount: input.PreviousAccount,
PreviousAmount: int64(input.PreviousAmount),
}
}
return inputs
}
func marshalTransactionOutputs(v []wallet.TransactionSummaryOutput) []*pb.TransactionDetails_Output {
outputs := make([]*pb.TransactionDetails_Output, len(v))
for i := range v {
output := &v[i]
outputs[i] = &pb.TransactionDetails_Output{
Index: output.Index,
Account: output.Account,
Internal: output.Internal,
}
}
return outputs
}
func marshalTransactionDetails(v []wallet.TransactionSummary) []*pb.TransactionDetails {
txs := make([]*pb.TransactionDetails, len(v))
for i := range v {
tx := &v[i]
txs[i] = &pb.TransactionDetails{
Hash: tx.Hash[:],
Transaction: tx.Transaction,
Debits: marshalTransactionInputs(tx.MyInputs),
Credits: marshalTransactionOutputs(tx.MyOutputs),
Fee: int64(tx.Fee),
Timestamp: tx.Timestamp,
}
}
return txs
}
func marshalBlocks(v []wallet.Block) []*pb.BlockDetails {
blocks := make([]*pb.BlockDetails, len(v))
for i := range v {
block := &v[i]
blocks[i] = &pb.BlockDetails{
Hash: block.Hash[:],
Height: block.Height,
Timestamp: block.Timestamp,
Transactions: marshalTransactionDetails(block.Transactions),
}
}
return blocks
}
func marshalHashes(v []*chainhash.Hash) [][]byte {
hashes := make([][]byte, len(v))
for i, hash := range v {
hashes[i] = hash[:]
}
return hashes
}
func marshalAccountBalances(v []wallet.AccountBalance) []*pb.AccountBalance {
balances := make([]*pb.AccountBalance, len(v))
for i := range v {
balance := &v[i]
balances[i] = &pb.AccountBalance{
Account: balance.Account,
TotalBalance: int64(balance.TotalBalance),
}
}
return balances
}
func (s *walletServer) TransactionNotifications(req *pb.TransactionNotificationsRequest,
svr pb.WalletService_TransactionNotificationsServer) error {
n := s.wallet.NtfnServer.TransactionNotifications()
defer n.Done()
ctxDone := svr.Context().Done()
for {
select {
case v := <-n.C:
resp := pb.TransactionNotificationsResponse{
AttachedBlocks: marshalBlocks(v.AttachedBlocks),
DetachedBlocks: marshalHashes(v.DetachedBlocks),
UnminedTransactions: marshalTransactionDetails(v.UnminedTransactions),
UnminedTransactionHashes: marshalHashes(v.UnminedTransactionHashes),
}
err := svr.Send(&resp)
if err != nil {
return translateError(err)
}
case <-ctxDone:
return nil
}
}
}
func (s *walletServer) SpentnessNotifications(req *pb.SpentnessNotificationsRequest,
svr pb.WalletService_SpentnessNotificationsServer) error {
if req.NoNotifyUnspent && req.NoNotifySpent {
return grpc.Errorf(codes.InvalidArgument,
"no_notify_unspent and no_notify_spent may not both be true")
}
n := s.wallet.NtfnServer.AccountSpentnessNotifications(req.Account)
defer n.Done()
ctxDone := svr.Context().Done()
for {
select {
case v := <-n.C:
spenderHash, spenderIndex, spent := v.Spender()
if (spent && req.NoNotifySpent) || (!spent && req.NoNotifyUnspent) {
continue
}
index := v.Index()
resp := pb.SpentnessNotificationsResponse{
TransactionHash: v.Hash()[:],
OutputIndex: index,
}
if spent {
resp.Spender = &pb.SpentnessNotificationsResponse_Spender{
TransactionHash: spenderHash[:],
InputIndex: spenderIndex,
}
}
err := svr.Send(&resp)
if err != nil {
return translateError(err)
}
case <-ctxDone:
return nil
}
}
}
func (s *walletServer) AccountNotifications(req *pb.AccountNotificationsRequest,
svr pb.WalletService_AccountNotificationsServer) error {
n := s.wallet.NtfnServer.AccountNotifications()
defer n.Done()
ctxDone := svr.Context().Done()
for {
select {
case v := <-n.C:
resp := pb.AccountNotificationsResponse{
AccountNumber: v.AccountNumber,
AccountName: v.AccountName,
ExternalKeyCount: v.ExternalKeyCount,
InternalKeyCount: v.InternalKeyCount,
ImportedKeyCount: v.ImportedKeyCount,
}
err := svr.Send(&resp)
if err != nil {
return translateError(err)
}
case <-ctxDone:
return nil
}
}
}
// StartWalletLoaderService creates an implementation of the WalletLoaderService
// and registers it with the gRPC server.
func StartWalletLoaderService(server *grpc.Server, loader *wallet.Loader,
activeNet *netparams.Params) {
service := &loaderServer{loader: loader, activeNet: activeNet}
pb.RegisterWalletLoaderServiceServer(server, service)
}
func (s *loaderServer) CreateWallet(ctx context.Context, req *pb.CreateWalletRequest) (
*pb.CreateWalletResponse, error) {
defer func() {
zero.Bytes(req.PrivatePassphrase)
zero.Bytes(req.Seed)
}()
// Use an insecure public passphrase when the request's is empty.
pubPassphrase := req.PublicPassphrase
if len(pubPassphrase) == 0 {
pubPassphrase = []byte(wallet.InsecurePubPassphrase)
}
wallet, err := s.loader.CreateNewWallet(
pubPassphrase, req.PrivatePassphrase, req.Seed, time.Now(),
)
if err != nil {
return nil, translateError(err)
}
s.mu.Lock()
if s.rpcClient != nil {
wallet.SynchronizeRPC(s.rpcClient)
}
s.mu.Unlock()
return &pb.CreateWalletResponse{}, nil
}
func (s *loaderServer) OpenWallet(ctx context.Context, req *pb.OpenWalletRequest) (
*pb.OpenWalletResponse, error) {
// Use an insecure public passphrase when the request's is empty.
pubPassphrase := req.PublicPassphrase
if len(pubPassphrase) == 0 {
pubPassphrase = []byte(wallet.InsecurePubPassphrase)
}
wallet, err := s.loader.OpenExistingWallet(pubPassphrase, false)
if err != nil {
return nil, translateError(err)
}
s.mu.Lock()
if s.rpcClient != nil {
wallet.SynchronizeRPC(s.rpcClient)
}
s.mu.Unlock()
return &pb.OpenWalletResponse{}, nil
}
func (s *loaderServer) WalletExists(ctx context.Context, req *pb.WalletExistsRequest) (
*pb.WalletExistsResponse, error) {
exists, err := s.loader.WalletExists()
if err != nil {
return nil, translateError(err)
}
return &pb.WalletExistsResponse{Exists: exists}, nil
}
func (s *loaderServer) CloseWallet(ctx context.Context, req *pb.CloseWalletRequest) (
*pb.CloseWalletResponse, error) {
err := s.loader.UnloadWallet()
if err == wallet.ErrNotLoaded {
return nil, grpc.Errorf(codes.FailedPrecondition, "wallet is not loaded")
}
if err != nil {
return nil, translateError(err)
}
return &pb.CloseWalletResponse{}, nil
}
func (s *loaderServer) StartConsensusRpc(ctx context.Context, req *pb.StartConsensusRpcRequest) (
*pb.StartConsensusRpcResponse, error) {
defer zero.Bytes(req.Password)
defer s.mu.Unlock()
s.mu.Lock()
if s.rpcClient != nil {
return nil, grpc.Errorf(codes.FailedPrecondition, "RPC client already created")
}
networkAddress, err := cfgutil.NormalizeAddress(req.NetworkAddress,
s.activeNet.RPCClientPort)
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Network address is ill-formed: %v", err)
}
// Error if the wallet is already syncing with the network.
wallet, walletLoaded := s.loader.LoadedWallet()
if walletLoaded && wallet.SynchronizingToNetwork() {
return nil, grpc.Errorf(codes.FailedPrecondition,
"wallet is loaded and already synchronizing")
}
rpcClient, err := chain.NewRPCClient(s.activeNet.Params, networkAddress, req.Username,
string(req.Password), req.Certificate, len(req.Certificate) == 0, 1)
if err != nil {
return nil, translateError(err)
}
err = rpcClient.Start()
if err != nil {
if err == rpcclient.ErrInvalidAuth {
return nil, grpc.Errorf(codes.InvalidArgument,
"Invalid RPC credentials: %v", err)
}
return nil, grpc.Errorf(codes.NotFound,
"Connection to RPC server failed: %v", err)
}
s.rpcClient = rpcClient
if walletLoaded {
wallet.SynchronizeRPC(rpcClient)
}
return &pb.StartConsensusRpcResponse{}, nil
}
File diff suppressed because it is too large. Load diff
+16 -46
View File
@@ -16,12 +16,9 @@ import (
"strings"
"time"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/rpc/legacyrpc"
"github.com/btcsuite/btcwallet/rpc/rpcserver"
"github.com/btcsuite/btcwallet/wallet"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/rpc/legacyrpc"
"github.com/lbryio/lbcwallet/wallet"
)
// openRPCKeyPair creates or loads the RPC TLS keypair specified by the
@@ -70,7 +67,7 @@ func generateRPCKeyPair(writeKey bool) (tls.Certificate, error) {
}
// Generate cert pair.
org := "btcwallet autogenerated cert"
org := "lbcwallet autogenerated cert"
validUntil := time.Now().Add(time.Hour * 24 * 365 * 10)
cert, key, err := btcutil.NewTLSCertPair(org, validUntil, nil)
if err != nil {
@@ -102,9 +99,8 @@ func generateRPCKeyPair(writeKey bool) (tls.Certificate, error) {
return keyPair, nil
}
func startRPCServers(walletLoader *wallet.Loader) (*grpc.Server, *legacyrpc.Server, error) {
func startRPCServers(walletLoader *wallet.Loader) (*legacyrpc.Server, error) {
var (
server *grpc.Server
legacyServer *legacyrpc.Server
legacyListen = net.Listen
keyPair tls.Certificate
@@ -115,7 +111,7 @@ func startRPCServers(walletLoader *wallet.Loader) (*grpc.Server, *legacyrpc.Serv
} else {
keyPair, err = openRPCKeyPair()
if err != nil {
return nil, nil, err
return nil, err
}
// Change the standard net.Listen function to the tls one.
@@ -128,40 +124,19 @@ func startRPCServers(walletLoader *wallet.Loader) (*grpc.Server, *legacyrpc.Serv
return tls.Listen(net, laddr, tlsConfig)
}
if len(cfg.ExperimentalRPCListeners) != 0 {
listeners := makeListeners(cfg.ExperimentalRPCListeners, net.Listen)
if len(listeners) == 0 {
err := errors.New("failed to create listeners for RPC server")
return nil, nil, err
}
creds := credentials.NewServerTLSFromCert(&keyPair)
server = grpc.NewServer(grpc.Creds(creds))
rpcserver.StartVersionService(server)
rpcserver.StartWalletLoaderService(server, walletLoader, activeNet)
for _, lis := range listeners {
lis := lis
go func() {
log.Infof("Experimental RPC server listening on %s",
lis.Addr())
err := server.Serve(lis)
log.Tracef("Finished serving expimental RPC: %v",
err)
}()
}
}
}
if cfg.Username == "" || cfg.Password == "" {
log.Info("Legacy RPC server disabled (requires username and password)")
if cfg.RPCUser == "" || cfg.RPCPass == "" {
log.Info("RPC server disabled (requires rpcuser and rpcpass)")
} else if len(cfg.LegacyRPCListeners) != 0 {
listeners := makeListeners(cfg.LegacyRPCListeners, legacyListen)
if len(listeners) == 0 {
err := errors.New("failed to create listeners for legacy RPC server")
return nil, nil, err
return nil, err
}
opts := legacyrpc.Options{
Username: cfg.Username,
Password: cfg.Password,
Username: cfg.RPCUser,
Password: cfg.RPCPass,
MaxPOSTClients: cfg.LegacyRPCMaxClients,
MaxWebsocketClients: cfg.LegacyRPCMaxWebsockets,
}
@@ -169,11 +144,11 @@ func startRPCServers(walletLoader *wallet.Loader) (*grpc.Server, *legacyrpc.Serv
}
// Error when neither the GRPC nor legacy RPC servers can be started.
if server == nil && legacyServer == nil {
return nil, nil, errors.New("no suitable RPC services can be started")
if legacyServer == nil {
return nil, errors.New("no suitable RPC services can be started")
}
return server, legacyServer, nil
return legacyServer, nil
}
type listenFunc func(net string, laddr string) (net.Listener, error)
@@ -244,11 +219,6 @@ func makeListeners(normalizedListenAddrs []string, listen listenFunc) []net.List
// with a wallet to enable remote wallet access. For the GRPC server, this
// registers the WalletService service, and for the legacy JSON-RPC server it
// enables methods that require a loaded wallet.
func startWalletRPCServices(wallet *wallet.Wallet, server *grpc.Server, legacyServer *legacyrpc.Server) {
if server != nil {
rpcserver.StartWalletService(server, wallet)
}
if legacyServer != nil {
legacyServer.RegisterWallet(wallet)
}
func startWalletRPCServices(wallet *wallet.Wallet, legacyServer *legacyrpc.Server) {
legacyServer.RegisterWallet(wallet)
}
+17 -27
View File
@@ -4,16 +4,13 @@
; Bitcoin wallet settings
; ------------------------------------------------------------------------------
; Use testnet (cannot be used with simnet=1).
; Use testnet
; testnet=0
; Use simnet (cannot be used with testnet=1).
; simnet=0
; The directory to open and save wallet, transaction, and unspent transaction
; output files. Two directories, `mainnet` and `testnet` are used in this
; directory for mainnet and testnet wallets, respectively.
; appdata=~/.btcwallet
; appdata=~/.lbcwallet
; ------------------------------------------------------------------------------
@@ -27,11 +24,11 @@
; proxyuser=
; proxypass=
; The server and port used for btcd websocket connections.
; rpcconnect=localhost:18334
; The server and port used for lbcd websocket connections.
; rpcconnect=localhost:19245
; File containing root certificates to authenticate a TLS connections with btcd
; cafile=~/.btcwallet/btcd.cert
; File containing root certificates to authenticate a TLS connections with
; cafile=~/.lbcwallet/.cert
@@ -40,8 +37,8 @@
; ------------------------------------------------------------------------------
; TLS certificate and key file locations
; rpccert=~/.btcwallet/rpc.cert
; rpckey=~/.btcwallet/rpc.key
; rpccert=~/.lbcwallet/rpc.cert
; rpckey=~/.lbcwallet/rpc.key
; Enable one time TLS keys. This option results in the process generating
; a new certificate pair each startup, writing only the certificate file
@@ -61,11 +58,11 @@
; rpclisten= ; all interfaces on default port
; rpclisten=0.0.0.0 ; all ipv4 interfaces on default port
; rpclisten=:: ; all ipv6 interfaces on default port
; rpclisten=:8332 ; all interfaces on port 8332
; rpclisten=0.0.0.0:8332 ; all ipv4 interfaces on port 8332
; rpclisten=[::]:8332 ; all ipv6 interfaces on port 8332
; rpclisten=127.0.0.1:8332 ; only ipv4 localhost on port 8332 (this is a default)
; rpclisten=[::1]:8332 ; only ipv6 localhost on port 8332 (this is a default)
; rpclisten=:9244 ; all interfaces on port 9244
; rpclisten=0.0.0.0:9244 ; all ipv4 interfaces on port 9244
; rpclisten=[::]:9244 ; all ipv6 interfaces on port 9244
; rpclisten=127.0.0.1:9244 ; only ipv4 localhost on port 9244 (this is a default)
; rpclisten=[::1]:9244 ; only ipv6 localhost on port 9244 (this is a default)
; rpclisten=127.0.0.1:8337 ; only ipv4 localhost on non-standard port 8337
; rpclisten=:8337 ; all interfaces on non-standard port 8337
; rpclisten=0.0.0.0:8337 ; all ipv4 interfaces on non-standard port 8337
@@ -86,17 +83,10 @@
; RPC settings (both client and server)
; ------------------------------------------------------------------------------
; Username and password to authenticate to btcd a RPC server and authenticate
; Username and password to authenticate to lbcd a RPC server and authenticate
; new client connections
; username=
; password=
; Alternative username and password for btcd. If set, these will be used
; instead of the username and password set above for authentication to a
; btcd RPC server.
; btcdusername=
; btcdpassword=
; rpcuser=
; rpcpass=
; ------------------------------------------------------------------------------
; Debug
@@ -106,7 +96,7 @@
; Valid options are {trace, debug, info, warn, error, critical}
; debuglevel=info
; The port used to listen for HTTP profile requests. The profile server will
; The port used to listen for HTTP profile requests. The profile server will
; be disabled if this option is not specified. The profile information can be
; accessed at http://localhost:<profileport>/debug/pprof once running.
; profile=6062
+1
View File
@@ -2,6 +2,7 @@
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
package main
+2 -2
View File
@@ -13,7 +13,7 @@ import (
"io"
"runtime/debug"
"github.com/btcsuite/btcwallet/internal/zero"
"github.com/lbryio/lbcwallet/internal/zero"
"golang.org/x/crypto/nacl/secretbox"
"golang.org/x/crypto/scrypt"
)
@@ -222,7 +222,7 @@ func (sk *SecretKey) Decrypt(in []byte) ([]byte, error) {
}
// NewSecretKey returns a SecretKey structure based on the passed parameters.
func NewSecretKey(password *[]byte, N, r, p int) (*SecretKey, error) {
func NewSecretKey(password *[]byte, N, r, p int) (*SecretKey, error) { // nolint:gocritic
sk := SecretKey{
Key: (*CryptoKey)(&[KeySize]byte{}),
}
+8
View File
@@ -0,0 +1,8 @@
//go:build tools
// +build tools
package tools
import (
_ "golang.org/x/tools/cmd/goimports"
)
-77
View File
@@ -1,77 +0,0 @@
// Copyright (c) 2013-2014 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 (
"bytes"
"fmt"
"strings"
)
// semanticAlphabet
const semanticAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"
// These constants define the application version and follow the semantic
// versioning 2.0.0 spec (http://semver.org/).
const (
appMajor uint = 0
appMinor uint = 11
appPatch uint = 0
// appPreRelease MUST only contain characters from semanticAlphabet
// per the semantic versioning spec.
appPreRelease = "alpha"
)
// appBuild is defined as a variable so it can be overridden during the build
// process with '-ldflags "-X main.appBuild foo' if needed. It MUST only
// contain characters from semanticAlphabet per the semantic versioning spec.
var appBuild string
// version returns the application version as a properly formed string per the
// semantic versioning 2.0.0 spec (http://semver.org/).
func version() string {
// Start with the major, minor, and path versions.
version := fmt.Sprintf("%d.%d.%d", appMajor, appMinor, appPatch)
// Append pre-release version if there is one. The hyphen called for
// by the semantic versioning spec is automatically appended and should
// not be contained in the pre-release string. The pre-release version
// is not appended if it contains invalid characters.
preRelease := normalizeVerString(appPreRelease)
if preRelease != "" {
version = fmt.Sprintf("%s-%s", version, preRelease)
}
// Append build metadata if there is any. The plus called for
// by the semantic versioning spec is automatically appended and should
// not be contained in the build metadata string. The build metadata
// string is not appended if it contains invalid characters.
build := normalizeVerString(appBuild)
if build != "" {
version = fmt.Sprintf("%s+%s", version, build)
}
return version
}
// normalizeVerString returns the passed string stripped of all characters which
// are not valid according to the semantic versioning guidelines for pre-release
// version and build metadata strings. In particular they MUST only contain
// characters in semanticAlphabet.
func normalizeVerString(str string) string {
result := bytes.Buffer{}
for _, r := range str {
if strings.ContainsRune(semanticAlphabet, r) {
_, err := result.WriteRune(r)
// Writing to a bytes.Buffer panics on OOM, and all
// errors are unexpected.
if err != nil {
panic(err)
}
}
}
return result.String()
}
+9 -8
View File
@@ -1,8 +1,8 @@
waddrmgr
========
[![Build Status](https://travis-ci.org/btcsuite/btcwallet.png?branch=master)]
(https://travis-ci.org/btcsuite/btcwallet)
[![Build Status](https://travis-ci.org/lbryio/lbcwallet.png?branch=master)]
(https://travis-ci.org/lbryio/lbcwallet)
Package waddrmgr provides a secure hierarchical deterministic wallet address
manager.
@@ -32,8 +32,9 @@ report. Package waddrmgr is licensed under the liberal ISC license.
- Import WIF keys
- Import pay-to-script-hash scripts for things such as multi-signature
transactions
- Ability to export a watching-only version which does not contain any private
- Ability to start in watching-only mode which does not contain any private
key material
- Ability to convert to watching-only mode
- Programmatically detectable errors, including encapsulation of errors from
packages it relies on
- Address synchronization capabilities
@@ -41,21 +42,21 @@ report. Package waddrmgr is licensed under the liberal ISC license.
## Documentation
[![GoDoc](https://godoc.org/github.com/btcsuite/btcwallet/waddrmgr?status.png)]
(http://godoc.org/github.com/btcsuite/btcwallet/waddrmgr)
[![GoDoc](https://godoc.org/github.com/lbryio/lbcwallet/waddrmgr?status.png)]
(http://godoc.org/github.com/lbryio/lbcwallet/waddrmgr)
Full `go doc` style documentation for the project can be viewed online without
installing this package by using the GoDoc site here:
http://godoc.org/github.com/btcsuite/btcwallet/waddrmgr
http://godoc.org/github.com/lbryio/lbcwallet/waddrmgr
You can also view the documentation locally once the package is installed with
the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to
http://localhost:6060/pkg/github.com/btcsuite/btcwallet/waddrmgr
http://localhost:6060/pkg/github.com/lbryio/lbcwallet/waddrmgr
## Installation
```bash
$ go get github.com/btcsuite/btcwallet/waddrmgr
$ go get github.com/lbryio/lbcwallet/waddrmgr
```
Package waddrmgr is licensed under the [copyfree](http://copyfree.org) ISC
+187 -67
View File
@@ -9,12 +9,12 @@ import (
"fmt"
"sync"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/btcsuite/btcwallet/internal/zero"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lbryio/lbcd/btcec"
"github.com/lbryio/lbcd/txscript"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcutil/hdkeychain"
"github.com/lbryio/lbcwallet/internal/zero"
"github.com/lbryio/lbcwallet/walletdb"
)
// AddressType represents the various address types waddrmgr is currently able
@@ -47,15 +47,20 @@ const (
// WitnessPubKey represents a p2wkh (pay-to-witness-key-hash) address
// type.
WitnessPubKey
// WitnessScript represents a p2wsh (pay-to-witness-script-hash) address
// type.
WitnessScript
)
// ManagedAddress is an interface that provides acces to information regarding
// ManagedAddress is an interface that provides access to information regarding
// an address managed by an address manager. Concrete implementations of this
// type may provide further fields to provide information specific to that type
// of address.
type ManagedAddress interface {
// Account returns the account the address is associated with.
Account() uint32
// InternalAccount returns the internal account the address is
// associated with.
InternalAccount() uint32
// Address returns a btcutil.Address for the backing address.
Address() btcutil.Address
@@ -96,8 +101,7 @@ type ManagedPubKeyAddress interface {
ExportPubKey() string
// PrivKey returns the private key for the address. It can fail if the
// address manager is watching-only or locked, or the address does not
// have any keys.
// address manager is locked, or the address does not have any keys.
PrivKey() (*btcec.PrivateKey, error)
// ExportPrivKey returns the private key associated with the address
@@ -130,10 +134,9 @@ type managedAddress struct {
imported bool
internal bool
compressed bool
used bool
addrType AddressType
pubKey *btcec.PublicKey
privKeyEncrypted []byte
privKeyEncrypted []byte // nil if part of watch-only account
privKeyCT []byte // non-nil if unlocked
privKeyMutex sync.Mutex
}
@@ -177,11 +180,12 @@ func (a *managedAddress) lock() {
a.privKeyMutex.Unlock()
}
// Account returns the account number the address is associated with.
// InternalAccount returns the internal account number the address is associated
// with.
//
// This is part of the ManagedAddress interface implementation.
func (a *managedAddress) Account() uint32 {
return a.derivationPath.Account
func (a *managedAddress) InternalAccount() uint32 {
return a.derivationPath.InternalAccount
}
// AddrType returns the address type of the managed address. This can be used
@@ -273,14 +277,10 @@ func (a *managedAddress) ExportPubKey() string {
}
// PrivKey returns the private key for the address. It can fail if the address
// manager is watching-only or locked, or the address does not have any keys.
// manager is locked, or the address does not have any keys.
//
// This is part of the ManagedPubKeyAddress interface implementation.
func (a *managedAddress) PrivKey() (*btcec.PrivateKey, error) {
// No private keys are available for a watching-only address manager.
if a.manager.rootManager.WatchOnly() {
return nil, managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
a.manager.mtx.Lock()
defer a.manager.mtx.Unlock()
@@ -316,7 +316,7 @@ func (a *managedAddress) ExportPrivKey() (*btcutil.WIF, error) {
return btcutil.NewWIF(pk, a.manager.rootManager.chainParams, a.compressed)
}
// Derivationinfo contains the information required to derive the key that
// DerivationInfo contains the information required to derive the key that
// backs the address via traditional methods from the HD root. For imported
// keys, the first value will be set to false to indicate that we don't know
// exactly how the key was derived.
@@ -360,7 +360,7 @@ func newManagedAddressWithoutPrivKey(m *ScopedKeyManager,
case NestedWitnessPubKey:
// For this address type we'l generate an address which is
// backwards compatible to Bitcoin nodes running 0.6.0 onwards, but
// allows us to take advantage of segwit's scripting improvments,
// allows us to take advantage of segwit's scripting improvements,
// and malleability fixes.
// First, we'll generate a normal p2wkh address from the pubkey hash.
@@ -496,30 +496,27 @@ func newManagedAddressFromExtKey(s *ScopedKeyManager,
return managedAddr, nil
}
// scriptAddress represents a pay-to-script-hash address.
type scriptAddress struct {
// baseScriptAddress represents the common fields of a pay-to-script-hash and
// a pay-to-witness-script-hash address.
type baseScriptAddress struct {
manager *ScopedKeyManager
account uint32
address *btcutil.AddressScriptHash
scriptEncrypted []byte
scriptCT []byte
scriptClearText []byte
scriptMutex sync.Mutex
used bool
}
// Enforce scriptAddress satisfies the ManagedScriptAddress interface.
var _ ManagedScriptAddress = (*scriptAddress)(nil)
// unlock decrypts and stores the associated script. It will fail if the key is
// invalid or the encrypted script is not available. The returned clear text
// script will always be a copy that may be safely used by the caller without
// worrying about it being zeroed during an address lock.
func (a *scriptAddress) unlock(key EncryptorDecryptor) ([]byte, error) {
func (a *baseScriptAddress) unlock(key EncryptorDecryptor) ([]byte, error) {
// Protect concurrent access to clear text script.
a.scriptMutex.Lock()
defer a.scriptMutex.Unlock()
if len(a.scriptCT) == 0 {
if len(a.scriptClearText) == 0 {
script, err := key.Decrypt(a.scriptEncrypted)
if err != nil {
str := fmt.Sprintf("failed to decrypt script for %s",
@@ -527,31 +524,53 @@ func (a *scriptAddress) unlock(key EncryptorDecryptor) ([]byte, error) {
return nil, managerError(ErrCrypto, str, err)
}
a.scriptCT = script
a.scriptClearText = script
}
scriptCopy := make([]byte, len(a.scriptCT))
copy(scriptCopy, a.scriptCT)
scriptCopy := make([]byte, len(a.scriptClearText))
copy(scriptCopy, a.scriptClearText)
return scriptCopy, nil
}
// lock zeroes the associated clear text private key.
func (a *scriptAddress) lock() {
// lock zeroes the associated clear text script.
func (a *baseScriptAddress) lock() {
// Zero and nil the clear text script associated with this address.
a.scriptMutex.Lock()
zero.Bytes(a.scriptCT)
a.scriptCT = nil
zero.Bytes(a.scriptClearText)
a.scriptClearText = nil
a.scriptMutex.Unlock()
}
// Account returns the account the address is associated with. This will always
// be the ImportedAddrAccount constant for script addresses.
// InternalAccount returns the account the address is associated with. This will
// always be the ImportedAddrAccount constant for script addresses.
//
// This is part of the ManagedAddress interface implementation.
func (a *scriptAddress) Account() uint32 {
func (a *baseScriptAddress) InternalAccount() uint32 {
return a.account
}
// Imported always returns true since script addresses are always imported
// addresses and not part of any chain.
//
// This is part of the ManagedAddress interface implementation.
func (a *baseScriptAddress) Imported() bool {
return true
}
// Internal always returns false since script addresses are always imported
// addresses and not part of any chain in order to be for internal use.
//
// This is part of the ManagedAddress interface implementation.
func (a *baseScriptAddress) Internal() bool {
return false
}
// scriptAddress represents a pay-to-script-hash address.
type scriptAddress struct {
baseScriptAddress
address *btcutil.AddressScriptHash
}
// AddrType returns the address type of the managed address. This can be used
// to quickly discern the address type without further processing
//
@@ -575,22 +594,6 @@ func (a *scriptAddress) AddrHash() []byte {
return a.address.Hash160()[:]
}
// Imported always returns true since script addresses are always imported
// addresses and not part of any chain.
//
// This is part of the ManagedAddress interface implementation.
func (a *scriptAddress) Imported() bool {
return true
}
// Internal always returns false since script addresses are always imported
// addresses and not part of any chain in order to be for internal use.
//
// This is part of the ManagedAddress interface implementation.
func (a *scriptAddress) Internal() bool {
return false
}
// Compressed returns false since script addresses are never compressed.
//
// This is part of the ManagedAddress interface implementation.
@@ -607,12 +610,8 @@ func (a *scriptAddress) Used(ns walletdb.ReadBucket) bool {
// Script returns the script associated with the address.
//
// This implements the ScriptAddress interface.
// This is part of the ManagedAddress interface implementation.
func (a *scriptAddress) Script() ([]byte, error) {
// No script is available for a watching-only address manager.
if a.manager.rootManager.WatchOnly() {
return nil, managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
a.manager.mtx.Lock()
defer a.manager.mtx.Unlock()
@@ -628,6 +627,9 @@ func (a *scriptAddress) Script() ([]byte, error) {
return a.unlock(a.manager.rootManager.cryptoKeyScript)
}
// Enforce scriptAddress satisfies the ManagedScriptAddress interface.
var _ ManagedScriptAddress = (*scriptAddress)(nil)
// newScriptAddress initializes and returns a new pay-to-script-hash address.
func newScriptAddress(m *ScopedKeyManager, account uint32, scriptHash,
scriptEncrypted []byte) (*scriptAddress, error) {
@@ -640,9 +642,127 @@ func newScriptAddress(m *ScopedKeyManager, account uint32, scriptHash,
}
return &scriptAddress{
manager: m,
account: account,
address: address,
scriptEncrypted: scriptEncrypted,
baseScriptAddress: baseScriptAddress{
manager: m,
account: account,
scriptEncrypted: scriptEncrypted,
},
address: address,
}, nil
}
// witnessScriptAddress represents a pay-to-witness-script-hash address.
type witnessScriptAddress struct {
baseScriptAddress
address btcutil.Address
// witnessVersion is the version of the witness script.
witnessVersion byte
// isSecretScript denotes whether the script is considered to be "secret"
// and encrypted with the script encryption key or "public" and
// therefore only encrypted with the public encryption key.
isSecretScript bool
}
// AddrType returns the address type of the managed address. This can be used
// to quickly discern the address type without further processing
//
// This is part of the ManagedAddress interface implementation.
func (a *witnessScriptAddress) AddrType() AddressType {
return WitnessScript
}
// Address returns the btcutil.Address which represents the managed address.
// This will be a pay-to-witness-script-hash address.
//
// This is part of the ManagedAddress interface implementation.
func (a *witnessScriptAddress) Address() btcutil.Address {
return a.address
}
// AddrHash returns the script hash for the address.
//
// This is part of the ManagedAddress interface implementation.
func (a *witnessScriptAddress) AddrHash() []byte {
return a.address.ScriptAddress()
}
// Compressed returns true since witness script addresses are always compressed.
//
// This is part of the ManagedAddress interface implementation.
func (a *witnessScriptAddress) Compressed() bool {
return true
}
// Used returns true if the address has been used in a transaction.
//
// This is part of the ManagedAddress interface implementation.
func (a *witnessScriptAddress) Used(ns walletdb.ReadBucket) bool {
return a.manager.fetchUsed(ns, a.AddrHash())
}
// Script returns the script associated with the address.
//
// This is part of the ManagedAddress interface implementation.
func (a *witnessScriptAddress) Script() ([]byte, error) {
a.manager.mtx.Lock()
defer a.manager.mtx.Unlock()
// Account manager must be unlocked to decrypt the script.
if a.isSecretScript && a.manager.rootManager.IsLocked() {
return nil, managerError(ErrLocked, errLocked, nil)
}
cryptoKey := a.manager.rootManager.cryptoKeyScript
if !a.isSecretScript {
cryptoKey = a.manager.rootManager.cryptoKeyPub
}
// Decrypt the script as needed. Also, make sure it's a copy since the
// script stored in memory can be cleared at any time. Otherwise,
// the returned script could be invalidated from under the caller.
return a.unlock(cryptoKey)
}
// Enforce witnessScriptAddress satisfies the ManagedScriptAddress interface.
var _ ManagedScriptAddress = (*witnessScriptAddress)(nil)
// newWitnessScriptAddress initializes and returns a new
// pay-to-witness-script-hash address.
func newWitnessScriptAddress(m *ScopedKeyManager, account uint32, scriptHash,
scriptEncrypted []byte, witnessVersion byte,
isSecretScript bool) (*witnessScriptAddress, error) {
var (
address btcutil.Address
err error
)
switch witnessVersion {
case 0x00:
address, err = btcutil.NewAddressWitnessScriptHash(
scriptHash, m.rootManager.chainParams,
)
case 0x01:
address, err = btcutil.NewAddressTaproot(
scriptHash, m.rootManager.chainParams,
)
}
if err != nil {
return nil, err
}
return &witnessScriptAddress{
baseScriptAddress: baseScriptAddress{
manager: m,
account: account,
scriptEncrypted: scriptEncrypted,
},
address: address,
witnessVersion: witnessVersion,
isSecretScript: isSecretScript,
}, nil
}
+57 -46
View File
@@ -12,9 +12,10 @@ import (
"testing"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcwallet/walletdb"
_ "github.com/btcsuite/btcwallet/walletdb/bdb"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcutil/hdkeychain"
"github.com/lbryio/lbcwallet/walletdb"
_ "github.com/lbryio/lbcwallet/walletdb/bdb"
)
var (
@@ -26,18 +27,14 @@ var (
0xb6, 0xc4, 0x40, 0xc0, 0x64,
}
pubPassphrase = []byte("_DJr{fL4H0O}*-0\n:V1izc)(6BomK")
privPassphrase = []byte("81lUHXnOMZ@?XXd7O9xyDIWIbXX-lj")
pubPassphrase2 = []byte("-0NV4P~VSJBWbunw}%<Z]fuGpbN[ZI")
rootKey, _ = hdkeychain.NewMaster(seed, &chaincfg.MainNetParams)
passphrase = []byte("81lUHXnOMZ@?XXd7O9xyDIWIbXX-lj")
privPassphrase2 = []byte("~{<]08%6!-?2s<$(8$8:f(5[4/!/{Y")
// fastScrypt are parameters used throughout the tests to speed up the
// scrypt operations.
fastScrypt = &ScryptOptions{
N: 16,
R: 8,
P: 1,
}
fastScrypt = &FastScryptOptions
// waddrmgrNamespaceKey is the namespace key for the waddrmgr package.
waddrmgrNamespaceKey = []byte("waddrmgrNamespace")
@@ -55,9 +52,10 @@ var (
privKey: hexToBytes("c27d6581b92785834b381fa697c4b0ffc4574b495743722e0acb7601b1b68b99"),
privKeyWIF: "L3jmpy54Pc7MLXTN2mL8Xas7BJziwKaUGmgnXXzgGbVRdiAniXZk",
derivationInfo: DerivationPath{
Account: 0,
Branch: 0,
Index: 0,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 0,
Index: 0,
},
},
{
@@ -70,9 +68,10 @@ var (
privKey: hexToBytes("18f3b191019e83878a81557abebb2afda199e31d22e150d8bf4df4561671be6c"),
privKeyWIF: "Kx4DNid19W8sjNFN3uPqQE7UYnCqyEp7unCvdkf2LrVUFpnDtwpB",
derivationInfo: DerivationPath{
Account: 0,
Branch: 0,
Index: 1,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 0,
Index: 1,
},
},
{
@@ -85,9 +84,10 @@ var (
privKey: hexToBytes("ccb8f6305b73136b363644b647f6efc0fd27b6b7d9c11c7e560662ed38db7b34"),
privKeyWIF: "L45fWF6Yd736fDohuB97vwRRLdQQJr3ZGvbokk9ubiT7aNrg7tTn",
derivationInfo: DerivationPath{
Account: 0,
Branch: 0,
Index: 2,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 0,
Index: 2,
},
},
{
@@ -100,9 +100,10 @@ var (
privKey: hexToBytes("d6bc8ff768814fede2adcdb74826bd846924341b3862e3b6e31cdc084e992940"),
privKeyWIF: "L4R8XyxYQyPSpTwj8w96tM86a6j3QA9jbRPj3RA7DVTVWk71ndeP",
derivationInfo: DerivationPath{
Account: 0,
Branch: 0,
Index: 3,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 0,
Index: 3,
},
},
{
@@ -115,9 +116,10 @@ var (
privKey: hexToBytes("8563ade061110e03aee50695ffc5cb1c06c8310bde0a3674257c853c966968c0"),
privKeyWIF: "L1h16Hunxomww4FrpyQP2iFmWNgG7U1u3awp6Vd3s2uGf7v5VU8c",
derivationInfo: DerivationPath{
Account: 0,
Branch: 0,
Index: 4,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 0,
Index: 4,
},
},
{
@@ -130,9 +132,10 @@ var (
privKey: hexToBytes("fe4f855fcf059ec6ddf7b25f63b19aa49c771d1fcb9850b68ae3d65e20657a60"),
privKeyWIF: "L5k4HivqXvohxBMpuwD38iUgi6uewffwZny91ZNYfM39RXH2x3QR",
derivationInfo: DerivationPath{
Account: 0,
Branch: 1,
Index: 0,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 1,
Index: 0,
},
},
{
@@ -145,9 +148,10 @@ var (
privKey: hexToBytes("bfef521317c65b018ae7e6d7ecc3aa700d5d0f7ea84d567be9270382d0b5e3e6"),
privKeyWIF: "L3eomUajnTDM3Pc8GU47qqXUFuCjvpqY7NYN9mH3x1ZFjDgiY4BU",
derivationInfo: DerivationPath{
Account: 0,
Branch: 1,
Index: 1,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 1,
Index: 1,
},
},
{
@@ -160,9 +164,10 @@ var (
privKey: hexToBytes("f506dffd4494c24006df7a35f3291f7ca0297a1a431557a1339bfed6f48738ca"),
privKeyWIF: "L5S1bVQUPqQb1Su82fLoSpnGCjcPfdAQE1pJxWRopJSBdYNDHESv",
derivationInfo: DerivationPath{
Account: 0,
Branch: 1,
Index: 2,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 1,
Index: 2,
},
},
{
@@ -175,9 +180,10 @@ var (
privKey: hexToBytes("b3629de8ef6a275b4ffae41aa2bbbc2952eb92282ea6402435abbb010ecc1fb8"),
privKeyWIF: "L3EQsGeEnyXmKaux54cG4DQeCSQDvGuvEuy3W2ss4geum7AtWaHw",
derivationInfo: DerivationPath{
Account: 0,
Branch: 1,
Index: 3,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 1,
Index: 3,
},
},
{
@@ -190,9 +196,10 @@ var (
privKey: hexToBytes("ca747a7ef815ea0dbe68655272cecbfbd65f2a109019a9ed28e0d3dcaffe05c3"),
privKeyWIF: "L41Frac75RPbTELKzw1EGC2qCkdveiVumpmsyX4daAvyyCMxit1W",
derivationInfo: DerivationPath{
Account: 0,
Branch: 1,
Index: 4,
InternalAccount: 0,
Account: hdkeychain.HardenedKeyStart,
Branch: 1,
Index: 4,
},
},
}
@@ -204,6 +211,10 @@ var (
// expectedInternalAddrs is the list of expected internal addresses
// generated from the seed
expectedInternalAddrs = expectedAddrs[5:]
// defaultDBTimeout specifies the timeout value when opening the wallet
// database.
defaultDBTimeout = 10 * time.Second
)
// checkManagerError ensures the passed error is a ManagerError with an error
@@ -242,7 +253,7 @@ func emptyDB(t *testing.T) (tearDownFunc func(), db walletdb.DB) {
t.Fatalf("Failed to create db temp dir: %v", err)
}
dbPath := filepath.Join(dirName, "mgrtest.db")
db, err = walletdb.Create("bdb", dbPath, true)
db, err = walletdb.Create("bdb", dbPath, true, defaultDBTimeout)
if err != nil {
_ = os.RemoveAll(dirName)
t.Fatalf("createDbNamespace: unexpected error: %v", err)
@@ -263,7 +274,7 @@ func setupManager(t *testing.T) (tearDownFunc func(), db walletdb.DB, mgr *Manag
t.Fatalf("Failed to create db temp dir: %v", err)
}
dbPath := filepath.Join(dirName, "mgrtest.db")
db, err = walletdb.Create("bdb", dbPath, true)
db, err = walletdb.Create("bdb", dbPath, true, defaultDBTimeout)
if err != nil {
_ = os.RemoveAll(dirName)
t.Fatalf("createDbNamespace: unexpected error: %v", err)
@@ -274,13 +285,13 @@ func setupManager(t *testing.T) (tearDownFunc func(), db walletdb.DB, mgr *Manag
return err
}
err = Create(
ns, seed, pubPassphrase, privPassphrase,
&chaincfg.MainNetParams, fastScrypt, time.Time{},
ns, rootKey, passphrase, &chaincfg.MainNetParams,
fastScrypt, time.Time{},
)
if err != nil {
return err
}
mgr, err = Open(ns, pubPassphrase, &chaincfg.MainNetParams)
mgr, err = Open(ns, &chaincfg.MainNetParams)
return err
})
if err != nil {
-17
View File
@@ -1,17 +0,0 @@
#!/bin/sh
# This script uses gocov to generate a test coverage report.
# The gocov tool my be obtained with the following command:
# go get github.com/axw/gocov/gocov
#
# It will be installed to $GOPATH/bin, so ensure that location is in your $PATH.
# Check for gocov.
type gocov >/dev/null 2>&1
if [ $? -ne 0 ]; then
echo >&2 "This script requires the gocov tool."
echo >&2 "You may obtain it with the following command:"
echo >&2 "go get github.com/axw/gocov/gocov"
exit 1
fi
gocov test | gocov report
+206 -120
View File
@@ -12,8 +12,8 @@ import (
"fmt"
"time"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcwallet/walletdb"
)
const (
@@ -34,7 +34,7 @@ var (
// ObtainUserInputFunc is a function that reads a user input and returns it as
// a byte stream. It is used to accept data required during upgrades, for e.g.
// wallet seed and private passphrase.
// wallet seed and passphrase.
type ObtainUserInputFunc func() ([]byte, error)
// maybeConvertDbError converts the passed error to a ManagerError with an
@@ -60,7 +60,7 @@ type syncStatus uint8
// of supporting sync status on a per-address basis.
const (
ssNone syncStatus = 0 // not iota as they need to be stable for db
ssPartial syncStatus = 1
ssPartial syncStatus = 1 // nolint:varcheck,deadcode,unused
ssFull syncStatus = 2
)
@@ -69,9 +69,10 @@ type addressType uint8
// These constants define the various supported address types.
const (
adtChain addressType = 0
adtImport addressType = 1 // not iota as they need to be stable for db
adtScript addressType = 2
adtChain addressType = 0
adtImport addressType = 1 // not iota as they need to be stable for db
adtScript addressType = 2
adtWitnessScript addressType = 3
)
// accountType represents a type of address stored in the database.
@@ -136,6 +137,27 @@ type dbScriptAddressRow struct {
encryptedScript []byte
}
// dbWitnessScriptAddressRow houses additional information stored about a
// witness script address in the database.
type dbWitnessScriptAddressRow struct {
dbAddressRow
// witnessVersion is the version of the witness script.
witnessVersion byte
// isSecretScript denotes whether the script is considered to be
// "secret" and encrypted with the script encryption key or "public" and
// therefore only encrypted with the public encryption key.
isSecretScript bool
encryptedHash []byte
// encryptedScript is the actual payload of the script address and
// represents the script itself. The encoding of the script is up to the
// actual implementation, it is not parsed or interpreted in any way by
// the database code. So it can be a plain script or a TLV encoded MAST.
encryptedScript []byte
}
// Key names for various database fields.
var (
// nullVall is null byte used as a flag value in a bucket entry
@@ -257,7 +279,6 @@ var (
cryptoPrivKeyName = []byte("cpriv")
cryptoPubKeyName = []byte("cpub")
cryptoScriptKeyName = []byte("cscript")
watchingOnlyName = []byte("watchonly")
// Sync related key names (sync bucket).
syncedToName = []byte("syncedto")
@@ -275,14 +296,6 @@ func uint32ToBytes(number uint32) []byte {
return buf
}
// uint64ToBytes converts a 64 bit unsigned integer into a 8-byte slice in
// little-endian order: 1 -> [1 0 0 0 0 0 0 0].
func uint64ToBytes(number uint64) []byte {
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, number)
return buf
}
// stringToBytes converts a string into a variable length byte slice in
// little-endian order: "abc" -> [3 0 0 0 61 62 63]
func stringToBytes(s string) []byte {
@@ -311,15 +324,6 @@ func scopeToBytes(scope *KeyScope) [scopeKeySize]byte {
return scopeBytes
}
// scopeFromBytes decodes a serializes manager scope into its concrete manager
// scope struct.
func scopeFromBytes(scopeBytes []byte) KeyScope {
return KeyScope{
Purpose: binary.LittleEndian.Uint32(scopeBytes[:]),
Coin: binary.LittleEndian.Uint32(scopeBytes[4:]),
}
}
// scopeSchemaToBytes encodes the passed scope schema as a set of bytes
// suitable for storage within the database.
func scopeSchemaToBytes(schema *ScopeAddrSchema) []byte {
@@ -361,22 +365,6 @@ func fetchScopeAddrSchema(ns walletdb.ReadBucket,
return scopeSchemaFromBytes(schemaBytes), nil
}
// putScopeAddrSchema attempts to store the passed addr scehma for the given
// manager scope.
func putScopeAddrTypes(ns walletdb.ReadWriteBucket, scope *KeyScope,
schema *ScopeAddrSchema) error {
scopeSchemaBucket := ns.NestedReadWriteBucket(scopeSchemaBucketName)
if scopeSchemaBucket == nil {
str := fmt.Sprintf("unable to find scope schema bucket")
return managerError(ErrScopeNotFound, str, nil)
}
scopeKey := scopeToBytes(scope)
schemaBytes := scopeSchemaToBytes(schema)
return scopeSchemaBucket.Put(scopeKey[:], schemaBytes)
}
func fetchReadScopeBucket(ns walletdb.ReadBucket, scope *KeyScope) (walletdb.ReadBucket, error) {
rootScopeBucket := ns.NestedReadBucket(scopeBucketName)
@@ -431,9 +419,7 @@ func putManagerVersion(ns walletdb.ReadWriteBucket, version uint32) error {
}
// fetchMasterKeyParams loads the master key parameters needed to derive them
// (when given the correct user-supplied passphrase) from the database. Either
// returned value can be nil, but in practice only the private key params will
// be nil for a watching-only database.
// (when given the correct user-supplied passphrase) from the database.
func fetchMasterKeyParams(ns walletdb.ReadBucket) ([]byte, []byte, error) {
bucket := ns.NestedReadBucket(mainBucketName)
@@ -571,7 +557,7 @@ func putMasterHDKeys(ns walletdb.ReadWriteBucket, masterHDPrivEnc, masterHDPubEn
// fetchMasterHDKeys attempts to fetch both the master HD private and public
// keys from the database. If this is a watch only wallet, then it's possible
// that the master private key isn't stored.
func fetchMasterHDKeys(ns walletdb.ReadBucket) ([]byte, []byte, error) {
func fetchMasterHDKeys(ns walletdb.ReadBucket) ([]byte, []byte) {
bucket := ns.NestedReadBucket(mainBucketName)
var masterHDPrivEnc, masterHDPubEnc []byte
@@ -582,22 +568,21 @@ func fetchMasterHDKeys(ns walletdb.ReadBucket) ([]byte, []byte, error) {
key := bucket.Get(masterHDPrivName)
if key != nil {
masterHDPrivEnc = make([]byte, len(key))
copy(masterHDPrivEnc[:], key)
copy(masterHDPrivEnc, key)
}
key = bucket.Get(masterHDPubName)
if key != nil {
masterHDPubEnc = make([]byte, len(key))
copy(masterHDPubEnc[:], key)
copy(masterHDPubEnc, key)
}
return masterHDPrivEnc, masterHDPubEnc, nil
return masterHDPrivEnc, masterHDPubEnc
}
// fetchCryptoKeys loads the encrypted crypto keys which are in turn used to
// protect the extended keys, imported keys, and scripts. Any of the returned
// values can be nil, but in practice only the crypto private and script keys
// will be nil for a watching-only database.
// values can be nil
func fetchCryptoKeys(ns walletdb.ReadBucket) ([]byte, []byte, []byte, error) {
bucket := ns.NestedReadBucket(mainBucketName)
@@ -664,35 +649,6 @@ func putCryptoKeys(ns walletdb.ReadWriteBucket, pubKeyEncrypted, privKeyEncrypte
return nil
}
// fetchWatchingOnly loads the watching-only flag from the database.
func fetchWatchingOnly(ns walletdb.ReadBucket) (bool, error) {
bucket := ns.NestedReadBucket(mainBucketName)
buf := bucket.Get(watchingOnlyName)
if len(buf) != 1 {
str := "malformed watching-only flag stored in database"
return false, managerError(ErrDatabase, str, nil)
}
return buf[0] != 0, nil
}
// putWatchingOnly stores the watching-only flag to the database.
func putWatchingOnly(ns walletdb.ReadWriteBucket, watchingOnly bool) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
var encoded byte
if watchingOnly {
encoded = 1
}
if err := bucket.Put(watchingOnlyName, []byte{encoded}); err != nil {
str := "failed to store watching only flag"
return managerError(ErrDatabase, str, err)
}
return nil
}
// deserializeAccountRow deserializes the passed serialized account information.
// This is used as a common base for the various account types to deserialize
// the common parts.
@@ -821,7 +777,7 @@ func forEachKeyScope(ns walletdb.ReadBucket, fn func(KeyScope) error) error {
}
scope := KeyScope{
Purpose: binary.LittleEndian.Uint32(k[:]),
Purpose: binary.LittleEndian.Uint32(k),
Coin: binary.LittleEndian.Uint32(k[4:]),
}
@@ -850,6 +806,7 @@ func forEachAccount(ns walletdb.ReadBucket, scope *KeyScope,
}
// fetchLastAccount retrieves the last account from the database.
// If no accounts, returns twos-complement representation of -1, so that the next account is zero
func fetchLastAccount(ns walletdb.ReadBucket, scope *KeyScope) (uint32, error) {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
if err != nil {
@@ -859,6 +816,9 @@ func fetchLastAccount(ns walletdb.ReadBucket, scope *KeyScope) (uint32, error) {
metaBucket := scopedBucket.NestedReadBucket(metaBucketName)
val := metaBucket.Get(lastAccountName)
if val == nil {
return (1 << 32) - 1, nil
}
if len(val) != 4 {
str := fmt.Sprintf("malformed metadata '%s' stored in database",
lastAccountName)
@@ -1083,8 +1043,9 @@ func putAccountRow(ns walletdb.ReadWriteBucket, scope *KeyScope,
return nil
}
// putAccountInfo stores the provided account information to the database.
func putAccountInfo(ns walletdb.ReadWriteBucket, scope *KeyScope,
// putDefaultAccountInfo stores the provided default account information to the
// database.
func putDefaultAccountInfo(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, encryptedPubKey, encryptedPrivKey []byte,
nextExternalIndex, nextInternalIndex uint32, name string) error {
@@ -1099,7 +1060,14 @@ func putAccountInfo(ns walletdb.ReadWriteBucket, scope *KeyScope,
acctType: accountDefault,
rawData: rawData,
}
if err := putAccountRow(ns, scope, account, &acctRow); err != nil {
return putAccountInfo(ns, scope, account, &acctRow, name)
}
// putAccountInfo stores the provided account information to the database.
func putAccountInfo(ns walletdb.ReadWriteBucket, scope *KeyScope,
account uint32, acctRow *dbAccountRow, name string) error {
if err := putAccountRow(ns, scope, account, acctRow); err != nil {
return err
}
@@ -1109,11 +1077,7 @@ func putAccountInfo(ns walletdb.ReadWriteBucket, scope *KeyScope,
}
// Update account name index.
if err := putAccountNameIndex(ns, scope, account, name); err != nil {
return err
}
return nil
return putAccountNameIndex(ns, scope, account, name)
}
// putLastAccount stores the provided metadata - last account - to the
@@ -1324,6 +1288,74 @@ func serializeScriptAddress(encryptedHash, encryptedScript []byte) []byte {
return rawData
}
// deserializeWitnessScriptAddress deserializes the raw data from the passed
// address row as a witness script address.
func deserializeWitnessScriptAddress(
row *dbAddressRow) (*dbWitnessScriptAddressRow, error) {
// The serialized witness script address raw data format is:
// <witness_version><is_secret_script><encscripthashlen>
// <encscripthash><encscriptlen><encscript>
//
// 1 byte witness version + 1 byte boolean + 4 bytes encrypted script
// hash len + encrypted script hash + 4 bytes encrypted script len +
// encrypted script
const minLength = 1 + 1 + 4 + 4
// Given the above, the length of the entry must be at a minimum
// the constant value sizes.
if len(row.rawData) < minLength {
str := "malformed serialized witness script address"
return nil, managerError(ErrDatabase, str, nil)
}
retRow := dbWitnessScriptAddressRow{
dbAddressRow: *row,
witnessVersion: row.rawData[0],
isSecretScript: row.rawData[1] == 1,
}
hashLen := binary.LittleEndian.Uint32(row.rawData[2:6])
retRow.encryptedHash = make([]byte, hashLen)
copy(retRow.encryptedHash, row.rawData[6:6+hashLen])
offset := 6 + hashLen
scriptLen := binary.LittleEndian.Uint32(row.rawData[offset : offset+4])
offset += 4
retRow.encryptedScript = make([]byte, scriptLen)
copy(retRow.encryptedScript, row.rawData[offset:offset+scriptLen])
return &retRow, nil
}
// serializeWitnessScriptAddress returns the serialization of the raw data field
// for a witness script address.
func serializeWitnessScriptAddress(witnessVersion uint8, isSecretScript bool,
encryptedHash, encryptedScript []byte) []byte {
// The serialized witness script address raw data format is:
// <witness_version><is_secret_script><encscripthashlen>
// <encscripthash><encscriptlen><encscript>
//
// 1 byte witness version + 1 byte boolean + 4 bytes encrypted script
// hash len + encrypted script hash + 4 bytes encrypted script len +
// encrypted script
hashLen := uint32(len(encryptedHash))
scriptLen := uint32(len(encryptedScript))
rawData := make([]byte, 10+hashLen+scriptLen)
rawData[0] = witnessVersion
if isSecretScript {
rawData[1] = 1
}
binary.LittleEndian.PutUint32(rawData[2:6], hashLen)
copy(rawData[6:6+hashLen], encryptedHash)
offset := 6 + hashLen
binary.LittleEndian.PutUint32(rawData[offset:offset+4], scriptLen)
offset += 4
copy(rawData[offset:offset+scriptLen], encryptedScript)
return rawData
}
// fetchAddressByHash loads address information for the provided address hash
// from the database. The returned value is one of the address rows for the
// specific address type. The caller should use type assertions to ascertain
@@ -1339,7 +1371,7 @@ func fetchAddressByHash(ns walletdb.ReadBucket, scope *KeyScope,
bucket := scopedBucket.NestedReadBucket(addrBucketName)
serializedRow := bucket.Get(addrHash[:])
serializedRow := bucket.Get(addrHash)
if serializedRow == nil {
str := "address not found"
return nil, managerError(ErrAddressNotFound, str, nil)
@@ -1357,6 +1389,8 @@ func fetchAddressByHash(ns walletdb.ReadBucket, scope *KeyScope,
return deserializeImportedAddress(row)
case adtScript:
return deserializeScriptAddress(row)
case adtWitnessScript:
return deserializeWitnessScriptAddress(row)
}
str := fmt.Sprintf("unsupported address type '%d'", row.addrType)
@@ -1475,32 +1509,38 @@ func putChainedAddress(ns walletdb.ReadWriteBucket, scope *KeyScope,
if err != nil {
return err
}
arow, err := deserializeDefaultAccountRow(accountID, row)
if err != nil {
return err
switch row.acctType {
case accountDefault:
arow, err := deserializeDefaultAccountRow(accountID, row)
if err != nil {
return err
}
// Increment the appropriate next index depending on whether the
// branch is internal or external.
nextExternalIndex := arow.nextExternalIndex
nextInternalIndex := arow.nextInternalIndex
if branch == InternalBranch {
nextInternalIndex = index + 1
} else {
nextExternalIndex = index + 1
}
// Reserialize the account with the updated index and store it.
row.rawData = serializeDefaultAccountRow(
arow.pubKeyEncrypted, arow.privKeyEncrypted,
nextExternalIndex, nextInternalIndex, arow.name,
)
}
// Increment the appropriate next index depending on whether the branch
// is internal or external.
nextExternalIndex := arow.nextExternalIndex
nextInternalIndex := arow.nextInternalIndex
if branch == InternalBranch {
nextInternalIndex = index + 1
} else {
nextExternalIndex = index + 1
}
// Reserialize the account with the updated index and store it.
row.rawData = serializeDefaultAccountRow(
arow.pubKeyEncrypted, arow.privKeyEncrypted, nextExternalIndex,
nextInternalIndex, arow.name,
)
err = bucket.Put(accountID, serializeAccountRow(row))
if err != nil {
str := fmt.Sprintf("failed to update next index for "+
"address %x, account %d", addressID, account)
return managerError(ErrDatabase, str, err)
}
return nil
}
@@ -1542,6 +1582,30 @@ func putScriptAddress(ns walletdb.ReadWriteBucket, scope *KeyScope,
return nil
}
// putWitnessScriptAddress stores the provided witness script address
// information to the database.
func putWitnessScriptAddress(ns walletdb.ReadWriteBucket, scope *KeyScope,
addressID []byte, account uint32, status syncStatus,
witnessVersion uint8, isSecretScript bool, encryptedHash,
encryptedScript []byte) error {
rawData := serializeWitnessScriptAddress(
witnessVersion, isSecretScript, encryptedHash, encryptedScript,
)
addrRow := dbAddressRow{
addrType: adtWitnessScript,
account: account,
addTime: uint64(time.Now().Unix()),
syncStatus: status,
rawData: rawData,
}
if err := putAddress(ns, scope, addressID, &addrRow); err != nil {
return err
}
return nil
}
// existsAddress returns whether or not the address id exists in the database.
func existsAddress(ns walletdb.ReadBucket, scope *KeyScope, addressID []byte) bool {
scopedBucket, err := fetchReadScopeBucket(ns, scope)
@@ -1661,12 +1725,6 @@ func forEachActiveAddress(ns walletdb.ReadBucket, scope *KeyScope,
}
// deletePrivateKeys removes all private key material from the database.
//
// NOTE: Care should be taken when calling this function. It is primarily
// intended for use in converting to a watching-only copy. Removing the private
// keys from the main database without also marking it watching-only will result
// in an unusable database. It will also make any imported scripts and private
// keys unrecoverable unless there is a backup copy available.
func deletePrivateKeys(ns walletdb.ReadWriteBucket) error {
bucket := ns.NestedReadWriteBucket(mainBucketName)
@@ -1792,6 +1850,30 @@ func deletePrivateKeys(ns walletdb.ReadWriteBucket) error {
str := "failed to delete imported script"
return managerError(ErrDatabase, str, err)
}
case adtWitnessScript:
srow, err := deserializeWitnessScriptAddress(row)
if err != nil {
return err
}
// If the script is considered to be public, we
// don't need to do anything.
if !srow.isSecretScript {
return nil
}
// Re-serialize the script address without the
// script and store it.
row.rawData = serializeWitnessScriptAddress(
srow.witnessVersion, srow.isSecretScript,
srow.encryptedHash, nil,
)
err = bucket.Put(k, serializeAddressRow(row))
if err != nil {
str := "failed to delete imported script"
return managerError(ErrDatabase, str, err)
}
}
return nil
@@ -2035,9 +2117,10 @@ func putBirthday(ns walletdb.ReadWriteBucket, t time.Time) error {
// FetchBirthdayBlock retrieves the birthday block from the database.
//
// The block is serialized as follows:
// [0:4] block height
// [4:36] block hash
// [36:44] block timestamp
//
// [0:4] block height
// [4:36] block hash
// [36:44] block timestamp
func FetchBirthdayBlock(ns walletdb.ReadBucket) (BlockStamp, error) {
var block BlockStamp
@@ -2075,9 +2158,10 @@ func DeleteBirthdayBlock(ns walletdb.ReadWriteBucket) error {
// PutBirthdayBlock stores the provided birthday block to the database.
//
// The block is serialized as follows:
// [0:4] block height
// [4:36] block hash
// [36:44] block timestamp
//
// [0:4] block height
// [4:36] block hash
// [36:44] block timestamp
//
// NOTE: This does not alter the birthday block verification state.
func PutBirthdayBlock(ns walletdb.ReadWriteBucket, block BlockStamp) error {
@@ -2108,7 +2192,7 @@ func fetchBirthdayBlockVerification(ns walletdb.ReadBucket) bool {
}
// Otherwise, we'll determine if it's verified by the value stored.
verified := binary.BigEndian.Uint16(verifiedValue[:])
verified := binary.BigEndian.Uint16(verifiedValue)
return verified != 0
}
@@ -2242,6 +2326,8 @@ func createManagerNS(ns walletdb.ReadWriteBucket,
// Next, we'll create the namespace for each of the relevant default
// manager scopes.
for scope, scopeSchema := range defaultScopes {
scope, scopeSchema := scope, scopeSchema
// Before we create the entire namespace of this scope, we'll
// update the schema mapping to note what types of addresses it
// prefers.
+4 -4
View File
@@ -5,18 +5,18 @@ import (
"fmt"
"testing"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcwallet/walletdb"
)
// TestStoreMaxReorgDepth ensures that we can only store up to MaxReorgDepth
// blocks at any given time.
func TestStoreMaxReorgDepth(t *testing.T) {
t.Parallel()
teardown, db, _ := setupManager(t)
defer teardown()
t.Parallel()
// We'll start the test by simulating a synced chain where we start from
// 1000 and end at 109999.
const (
+17 -17
View File
@@ -6,7 +6,7 @@
Package waddrmgr provides a secure hierarchical deterministic wallet address
manager.
Overview
# Overview
One of the fundamental jobs of a wallet is to manage addresses, private keys,
and script data associated with them. At a high level, this package provides
@@ -52,14 +52,14 @@ used to decrypt private keys and scripts on demand. Relocking the address
manager actively zeros all private material from memory. In addition, temp
private key material used internally is zeroed as soon as it's used.
Locking and Unlocking
# Locking and Unlocking
As previously mentioned, this package provide facilities for locking and
unlocking the address manager to protect access to private material and remove
it from memory when locked. The Lock, Unlock, and IsLocked functions are used
for this purpose.
Creating a New Address Manager
# Creating a New Address Manager
A new address manager is created via the Create function. This function accepts
a wallet database namespace, passphrases, network, and perhaps most importantly,
@@ -69,28 +69,28 @@ to be recovered with only the seed. The GenerateSeed function in the hdkeychain
package can be used as a convenient way to create a random seed for use with
this function. The address manager is locked immediately upon being created.
Opening an Existing Address Manager
# Opening an Existing Address Manager
An existing address manager is opened via the Open function. This function
accepts an existing wallet database namespace, the public passphrase, and
network. The address manager is opened locked as expected since the open
function does not take the private passphrase to unlock it.
Closing the Address Manager
# Closing the Address Manager
The Close method should be called on the address manager when the caller is done
with it. While it is not required, it is recommended because it sanely shuts
down the database and ensures all private and public key material is purged from
memory.
Managed Addresses
# Managed Addresses
Each address returned by the address manager satisifies the ManagedAddress
interface as well as either the ManagedPubKeyAddress or ManagedScriptAddress
interfaces. These interfaces provide the means to obtain relevant information
about the addresses such as their private keys and scripts.
Chained Addresses
# Chained Addresses
Most callers will make use of the chained addresses for normal operations.
Internal addresses are intended for internal wallet uses such as change outputs,
@@ -101,13 +101,13 @@ been provided. In addition, the LastInternalAddress and LastExternalAddress
functions can be used to get the most recently provided internal and external
address, respectively.
Requesting Existing Addresses
# Requesting Existing Addresses
In addition to generating new addresses, access to old addresses is often
required. Most notably, to sign transactions in order to redeem them. The
Address function provides this capability and returns a ManagedAddress.
Importing Addresses
# Importing Addresses
While the recommended approach is to use the chained addresses discussed above
because they can be deterministically regenerated to avoid losing funds as long
@@ -116,27 +116,27 @@ and as a result, this package provides the ability to import existing private
keys in Wallet Import Format (WIF) and hence the associated public key and
address.
Importing Scripts
# Importing Scripts
In order to support pay-to-script-hash transactions, the script must be securely
stored as it is needed to redeem the transaction. This can be useful for a
variety of scenarios, however the most common use is currently multi-signature
transactions.
Syncing
# Syncing
The address manager also supports storing and retrieving a block hash and height
which the manager is known to have all addresses synced through. The manager
itself does not have any notion of which addresses are synced or not. It only
provides the storage as a convenience for the caller.
Network
# Network
The address manager must be associated with a given network in order to provide
appropriate addresses and reject imported addresses and scripts which don't
apply to the associated network.
Errors
# Errors
All errors returned from this package are of type ManagerError. This allows the
caller to programmatically ascertain the specific reasons for failure by
@@ -144,12 +144,12 @@ examining the ErrorCode field of the type asserted ManagerError. For certain
error codes, as documented by the specific error codes, the underlying error
will be contained in the Err field.
Bitcoin Improvement Proposals
# Bitcoin Improvement Proposals
This package includes concepts outlined by the following BIPs:
BIP0032 (https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)
BIP0043 (https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki)
BIP0044 (https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)
BIP0032 (https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)
BIP0043 (https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki)
BIP0044 (https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)
*/
package waddrmgr
+6 -11
View File
@@ -8,7 +8,7 @@ import (
"fmt"
"strconv"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/lbryio/lbcutil/hdkeychain"
)
var (
@@ -29,10 +29,6 @@ var (
// errLocked is the common error description used for the ErrLocked
// error code.
errLocked = "address manager is locked"
// errWatchingOnly is the common error description used for the
// ErrWatchingOnly error code.
errWatchingOnly = "address manager is watching-only"
)
// ErrorCode identifies a kind of error.
@@ -86,11 +82,6 @@ const (
// manager to be unlocked, was requested on a locked account manager.
ErrLocked
// ErrWatchingOnly indicates that an operation, which requires the
// account manager to have access to private data, was requested on
// a watching-only account manager.
ErrWatchingOnly
// ErrInvalidAccount indicates that the requested account is not valid.
ErrInvalidAccount
@@ -139,6 +130,10 @@ const (
// ErrBlockNotFound is returned when we attempt to retrieve the hash for
// a block that we do not know of.
ErrBlockNotFound
// ErrAccountNotCached is returned when we attempt to perform an
// operation that relies on an account begin cached but it isn't.
ErrAccountNotCached
)
// Map of ErrorCode values back to their constant names for pretty printing.
@@ -153,7 +148,6 @@ var errorCodeStrings = map[ErrorCode]string{
ErrCoinTypeTooHigh: "ErrCoinTypeTooHigh",
ErrAccountNumTooHigh: "ErrAccountNumTooHigh",
ErrLocked: "ErrLocked",
ErrWatchingOnly: "ErrWatchingOnly",
ErrInvalidAccount: "ErrInvalidAccount",
ErrAddressNotFound: "ErrAddressNotFound",
ErrAccountNotFound: "ErrAccountNotFound",
@@ -165,6 +159,7 @@ var errorCodeStrings = map[ErrorCode]string{
ErrCallBackBreak: "ErrCallBackBreak",
ErrEmptyPassphrase: "ErrEmptyPassphrase",
ErrScopeNotFound: "ErrScopeNotFound",
ErrAccountNotCached: "ErrAccountNotCached",
}
// String returns the ErrorCode as a human-readable name.
+1 -2
View File
@@ -9,7 +9,7 @@ import (
"fmt"
"testing"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/waddrmgr"
)
// TestErrorCodeStringer tests the stringized output for the ErrorCode type.
@@ -28,7 +28,6 @@ func TestErrorCodeStringer(t *testing.T) {
{waddrmgr.ErrCoinTypeTooHigh, "ErrCoinTypeTooHigh"},
{waddrmgr.ErrAccountNumTooHigh, "ErrAccountNumTooHigh"},
{waddrmgr.ErrLocked, "ErrLocked"},
{waddrmgr.ErrWatchingOnly, "ErrWatchingOnly"},
{waddrmgr.ErrInvalidAccount, "ErrInvalidAccount"},
{waddrmgr.ErrAddressNotFound, "ErrAddressNotFound"},
{waddrmgr.ErrAccountNotFound, "ErrAccountNotFound"},
-17
View File
@@ -24,20 +24,3 @@ func DisableLog() {
func UseLogger(logger btclog.Logger) {
log = logger
}
// LogClosure is a closure that can be printed with %v to be used to
// generate expensive-to-create data for a detailed log level and avoid doing
// the work if the data isn't printed.
type logClosure func() string
// String invokes the log closure and returns the results string.
func (c logClosure) String() string {
return c()
}
// newLogClosure returns a new closure over the passed function which allows
// it to be used as a parameter in a logging function that is only invoked when
// the logging level is such that the message will actually be logged.
func newLogClosure(c func() string) logClosure {
return logClosure(c)
}
+396 -439
View File
File diff suppressed because it is too large. Load diff
+464 -509
View File
File diff suppressed because it is too large. Load diff
+4 -8
View File
@@ -5,9 +5,9 @@ import (
"fmt"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/btcsuite/btcwallet/walletdb/migration"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcwallet/walletdb"
"github.com/lbryio/lbcwallet/walletdb/migration"
)
// versions is a list of the different database versions. The last entry should
@@ -93,7 +93,7 @@ func (m *MigrationManager) SetVersion(ns walletdb.ReadWriteBucket,
if ns == nil {
ns = m.ns
}
return putManagerVersion(m.ns, version)
return putManagerVersion(ns, version)
}
// Versions returns all of the available database versions of the service.
@@ -318,10 +318,6 @@ func populateBirthdayBlock(ns walletdb.ReadWriteBucket) error {
genesisTimestamp =
chaincfg.RegressionNetParams.GenesisBlock.Header.Timestamp
case *chaincfg.SimNetParams.GenesisHash:
genesisTimestamp =
chaincfg.SimNetParams.GenesisBlock.Header.Timestamp
default:
return fmt.Errorf("unknown genesis hash %v", genesisHash)
}
+6 -5
View File
@@ -8,9 +8,9 @@ import (
"testing"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcwallet/walletdb"
)
// applyMigration is a helper function that allows us to assert the state of the
@@ -327,6 +327,7 @@ func TestMigrationStoreMaxReorgDepth(t *testing.T) {
}
for _, testCase := range testCases {
testCase := testCase
success := t.Run(testCase.name, func(t *testing.T) {
// We'll start the test by creating the number of blocks
// we'll add to the chain. We start from height 1 as the
@@ -387,13 +388,13 @@ func TestMigrationStoreMaxReorgDepth(t *testing.T) {
return err
}
expectedBlock := blocks[len(blocks)-1]
if block.Height != block.Height {
if expectedBlock.Height != block.Height {
return fmt.Errorf("expected synced to "+
"block height %v, got %v",
expectedBlock.Height,
block.Height)
}
if block.Hash != block.Hash {
if expectedBlock.Hash != block.Hash {
return fmt.Errorf("expected synced to "+
"block hash %v, got %v",
expectedBlock.Hash,
+830 -398
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -7,8 +7,8 @@ package waddrmgr
import (
"time"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcwallet/walletdb"
)
// BlockStamp defines a block (by height and a unique hash) and is used to mark
-126
View File
@@ -1,126 +0,0 @@
github.com/conformal/btcwallet/waddrmgr/db.go serializeBIP0044AccountRow 100.00% (19/19)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.lock 100.00% (12/12)
github.com/conformal/btcwallet/waddrmgr/db.go serializeScriptAddress 100.00% (10/10)
github.com/conformal/btcwallet/waddrmgr/db.go serializeImportedAddress 100.00% (10/10)
github.com/conformal/btcwallet/waddrmgr/db.go serializeAddressRow 100.00% (9/9)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.Address 100.00% (8/8)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.Lock 100.00% (8/8)
github.com/conformal/btcwallet/waddrmgr/address.go scriptAddress.Script 100.00% (7/7)
github.com/conformal/btcwallet/waddrmgr/db.go serializeAccountRow 100.00% (6/6)
github.com/conformal/btcwallet/waddrmgr/sync.go BlockIterator.Prev 100.00% (6/6)
github.com/conformal/btcwallet/waddrmgr/address.go zeroBigInt 100.00% (5/5)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.zeroSensitivePublicData 100.00% (5/5)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.lock 100.00% (4/4)
github.com/conformal/btcwallet/waddrmgr/address.go scriptAddress.lock 100.00% (4/4)
github.com/conformal/btcwallet/waddrmgr/db.go serializeChainedAddress 100.00% (4/4)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.ExportPrivKey 100.00% (4/4)
github.com/conformal/btcwallet/waddrmgr/manager.go fileExists 100.00% (4/4)
github.com/conformal/btcwallet/waddrmgr/error.go ManagerError.Error 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/error.go ErrorCode.String 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.pubKeyBytes 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/sync.go Manager.NewIterateRecentBlocks 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/sync.go BlockIterator.BlockStamp 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/db.go accountKey 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/sync.go Manager.SyncedTo 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutAccountInfo 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.IsLocked 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutImportedAddress 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.ExistsAddress 100.00% (3/3)
github.com/conformal/btcwallet/waddrmgr/address.go zero 100.00% (2/2)
github.com/conformal/btcwallet/waddrmgr/address.go scriptAddress.Account 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go scriptAddress.Compressed 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/sync.go newSyncState 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go scriptAddress.Internal 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/manager.go cryptoKey.CopyBytes 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/manager.go newManager 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.AddrHash 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/manager.go defaultNewSecretKey 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go scriptAddress.Imported 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go scriptAddress.AddrHash 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go scriptAddress.Address 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.Account 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.Internal 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.Net 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.ExportPubKey 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/error.go managerError 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.PubKey 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/manager.go cryptoKey.Bytes 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.Compressed 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.Address 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.Imported 100.00% (1/1)
github.com/conformal/btcwallet/waddrmgr/sync.go Manager.SetSyncedTo 93.94% (31/33)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.PrivKey 91.67% (11/12)
github.com/conformal/btcwallet/waddrmgr/db.go deserializeBIP0044AccountRow 90.48% (19/21)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.keyToManaged 90.00% (9/10)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchCryptoKeys 88.89% (16/18)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.Close 88.89% (8/9)
github.com/conformal/btcwallet/waddrmgr/address.go newManagedAddressWithoutPrivKey 87.50% (7/8)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutRecentBlocks 85.71% (12/14)
github.com/conformal/btcwallet/waddrmgr/manager.go Open 85.71% (6/7)
github.com/conformal/btcwallet/waddrmgr/db.go deserializeScriptAddress 84.62% (11/13)
github.com/conformal/btcwallet/waddrmgr/db.go deserializeImportedAddress 84.62% (11/13)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchRecentBlocks 84.62% (11/13)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchMasterKeyParams 84.62% (11/13)
github.com/conformal/btcwallet/waddrmgr/db.go deserializeAddressRow 83.33% (10/12)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.loadAndCacheAddress 83.33% (10/12)
github.com/conformal/btcwallet/waddrmgr/address.go managedAddress.unlock 81.82% (9/11)
github.com/conformal/btcwallet/waddrmgr/address.go scriptAddress.unlock 81.82% (9/11)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.nextAddresses 80.00% (52/65)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutScriptAddress 80.00% (4/5)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.ChangePassphrase 79.10% (53/67)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutChainedAddress 78.26% (18/23)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchSyncedTo 77.78% (7/9)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutStartBlock 77.78% (7/9)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchStartBlock 77.78% (7/9)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutSyncedTo 77.78% (7/9)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.existsAddress 77.78% (7/9)
github.com/conformal/btcwallet/waddrmgr/db.go deserializeAccountRow 77.78% (7/9)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.ExportWatchingOnly 75.00% (12/16)
github.com/conformal/btcwallet/waddrmgr/address.go newManagedAddressFromExtKey 75.00% (12/16)
github.com/conformal/btcwallet/waddrmgr/address.go newManagedAddress 75.00% (9/12)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutWatchingOnly 75.00% (6/8)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutNumAccounts 75.00% (6/8)
github.com/conformal/btcwallet/waddrmgr/address.go newScriptAddress 75.00% (3/4)
github.com/conformal/btcwallet/waddrmgr/manager.go defaultNewCryptoKey 75.00% (3/4)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.chainAddressRowToManaged 75.00% (3/4)
github.com/conformal/btcwallet/waddrmgr/manager.go checkBranchKeys 75.00% (3/4)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.deriveKeyFromPath 75.00% (3/4)
github.com/conformal/btcwallet/waddrmgr/manager.go loadManager 72.55% (37/51)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.putAddress 71.43% (5/7)
github.com/conformal/btcwallet/waddrmgr/db.go deserializeChainedAddress 71.43% (5/7)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.deriveKey 69.23% (9/13)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.ImportScript 67.44% (29/43)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.Unlock 67.35% (33/49)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchAddress 66.67% (10/15)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.importedAddressRowToManaged 66.67% (10/15)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutMasterKeyParams 66.67% (8/12)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.LastInternalAddress 66.67% (6/9)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.LastExternalAddress 66.67% (6/9)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.putAccountRow 66.67% (4/6)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.rowInterfaceToManaged 66.67% (4/6)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.NextExternalAddresses 66.67% (4/6)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.NextInternalAddresses 66.67% (4/6)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchWatchingOnly 66.67% (4/6)
github.com/conformal/btcwallet/waddrmgr/sync.go syncState.iter 66.67% (2/3)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.DeletePrivateKeys 66.04% (35/53)
github.com/conformal/btcwallet/waddrmgr/db.go openOrCreateDB 66.04% (35/53)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.ImportPrivateKey 64.71% (33/51)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.PutCryptoKeys 64.71% (11/17)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.loadAccountInfo 62.96% (34/54)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchAccountInfo 61.54% (8/13)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.scriptAddressRowToManaged 60.00% (3/5)
github.com/conformal/btcwallet/waddrmgr/manager.go Create 58.59% (58/99)
github.com/conformal/btcwallet/waddrmgr/manager.go deriveAccountKey 53.85% (7/13)
github.com/conformal/btcwallet/waddrmgr/db.go managerDB.Update 50.00% (4/8)
github.com/conformal/btcwallet/waddrmgr/db.go managerDB.View 50.00% (4/8)
github.com/conformal/btcwallet/waddrmgr/db.go managerDB.Close 50.00% (2/4)
github.com/conformal/btcwallet/waddrmgr/db.go managerDB.CopyDB 45.45% (5/11)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchAllAddresses 0.00% (0/20)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.AllActiveAddresses 0.00% (0/16)
github.com/conformal/btcwallet/waddrmgr/db.go managerDB.WriteTo 0.00% (0/11)
github.com/conformal/btcwallet/waddrmgr/sync.go BlockIterator.Next 0.00% (0/6)
github.com/conformal/btcwallet/waddrmgr/db.go managerTx.FetchNumAccounts 0.00% (0/6)
github.com/conformal/btcwallet/waddrmgr/manager.go Manager.Export 0.00% (0/3)
github.com/conformal/btcwallet/waddrmgr ----------------------------------- 72.59% (1030/1419)
+7 -7
View File
@@ -1,8 +1,8 @@
wallet
======
[![Build Status](https://travis-ci.org/btcsuite/btcwallet.png?branch=master)]
(https://travis-ci.org/btcsuite/btcwallet)
[![Build Status](https://travis-ci.org/lbryio/lbcwallet.png?branch=master)]
(https://travis-ci.org/lbryio/lbcwallet)
## Feature Overview
@@ -10,21 +10,21 @@ TODO: Flesh out this section
## Documentation
[![GoDoc](https://godoc.org/github.com/btcsuite/btcwallet/wallet?status.png)]
(http://godoc.org/github.com/btcsuite/btcwallet/wallet)
[![GoDoc](https://godoc.org/github.com/lbryio/lbcwallet/wallet?status.png)]
(http://godoc.org/github.com/lbryio/lbcwallet/wallet)
Full `go doc` style documentation for the project can be viewed online without
installing this package by using the GoDoc site here:
http://godoc.org/github.com/btcsuite/btcwallet/wallet
http://godoc.org/github.com/lbryio/lbcwallet/wallet
You can also view the documentation locally once the package is installed with
the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to
http://localhost:6060/pkg/github.com/btcsuite/btcwallet/wallet
http://localhost:6060/pkg/github.com/lbryio/lbcwallet/wallet
## Installation
```bash
$ go get github.com/btcsuite/btcwallet/wallet
$ go get github.com/lbryio/lbcwallet/wallet
```
Package wallet is licensed under the [copyfree](http://copyfree.org) ISC
+21 -13
View File
@@ -9,13 +9,13 @@ import (
"fmt"
"time"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/txscript"
"github.com/lbryio/lbcd/wire"
"github.com/lbryio/lbcwallet/chain"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/walletdb"
"github.com/lbryio/lbcwallet/wtxmgr"
)
const (
@@ -36,10 +36,10 @@ func (w *Wallet) handleChainNotifications() {
catchUpHashes := func(w *Wallet, client chain.Interface,
height int32) error {
// TODO(aakselrod): There's a race conditon here, which
// TODO(aakselrod): There's a race condition here, which
// happens when a reorg occurs between the
// rescanProgress notification and the last GetBlockHash
// call. The solution when using btcd is to make btcd
// call. The solution when using is to make
// send blockconnected notifications with each block
// the way Neutrino does, and get rid of the loop. The
// other alternative is to check the final hash and,
@@ -107,14 +107,14 @@ func (w *Wallet) handleChainNotifications() {
chainClient, birthdayStore,
)
if err != nil && !waddrmgr.IsError(err, waddrmgr.ErrBirthdayBlockNotSet) {
panic(fmt.Errorf("Unable to sanity "+
panic(fmt.Errorf("unable to sanity "+
"check wallet birthday block: %v",
err))
}
err = w.syncWithChain(birthdayBlock)
if err != nil && !w.ShuttingDown() {
panic(fmt.Errorf("Unable to synchronize "+
panic(fmt.Errorf("unable to synchronize "+
"wallet to chain: %v", err))
}
case chain.BlockConnected:
@@ -245,7 +245,7 @@ func (w *Wallet) disconnectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta)
if err != nil {
return err
}
b.Hash = *hash
bs.Hash = *hash
client := w.ChainClient()
header, err := client.GetBlockHeader(hash)
@@ -280,11 +280,19 @@ func (w *Wallet) addRelevantTx(dbtx walletdb.ReadWriteTx, rec *wtxmgr.TxRecord,
// relevant. This assumption will not hold true when SPV support is
// added, but until then, simply insert the transaction because there
// should either be one or more relevant inputs or outputs.
err := w.TxStore.InsertTx(txmgrNs, rec, block)
exists, err := w.TxStore.InsertTxCheckIfExists(txmgrNs, rec, block)
if err != nil {
return err
}
// If the transaction has already been recorded, we can return early.
// Note: Returning here is safe as we're within the context of an atomic
// database transaction, so we don't need to worry about the MarkUsed
// calls below.
if exists {
return nil
}
// Check every output to determine whether it is controlled by a wallet
// key. If so, mark the output as a credit.
for i, output := range rec.MsgTx.TxOut {
+6 -6
View File
@@ -6,17 +6,17 @@ import (
"testing"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/waddrmgr"
_ "github.com/btcsuite/btcwallet/walletdb/bdb"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/wire"
"github.com/lbryio/lbcwallet/waddrmgr"
_ "github.com/lbryio/lbcwallet/walletdb/bdb"
)
const (
// defaultBlockInterval is the default time interval between any two
// blocks in a mocked chain.
defaultBlockInterval = 10 * time.Minute
defaultBlockInterval = 150 * time.Second
)
var (
+14 -3
View File
@@ -8,9 +8,10 @@ package wallet
import (
"time"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/txscript"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
)
// Note: The following common types should never reference the Wallet type.
@@ -41,8 +42,18 @@ type OutputKind byte
const (
OutputKindNormal OutputKind = iota
OutputKindCoinbase
OutputKindStake
)
func isStake(pkScript []byte) bool {
if len(pkScript) > 0 &&
(pkScript[0] == txscript.OP_CLAIMNAME || pkScript[0] == txscript.OP_SUPPORTCLAIM ||
pkScript[0] == txscript.OP_UPDATECLAIM) {
return true
}
return false
}
// TransactionOutput describes an output that was or is at least partially
// controlled by the wallet. Depending on context, this could refer to an
// unspent output, or a spent one.
+234 -102
View File
@@ -7,16 +7,18 @@ package wallet
import (
"fmt"
"math/rand"
"sort"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wallet/txauthor"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/lbryio/lbcd/btcec"
"github.com/lbryio/lbcd/txscript"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/wallet/txauthor"
"github.com/lbryio/lbcwallet/wallet/txsizes"
"github.com/lbryio/lbcwallet/walletdb"
"github.com/lbryio/lbcwallet/wtxmgr"
)
// byAmount defines the methods needed to satisify sort.Interface to
@@ -28,10 +30,6 @@ func (s byAmount) Less(i, j int) bool { return s[i].Amount < s[j].Amount }
func (s byAmount) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func makeInputSource(eligible []wtxmgr.Credit) txauthor.InputSource {
// Pick largest outputs first. This is only done for compatibility with
// previous tx creation code, not because it's a good idea.
sort.Sort(sort.Reverse(byAmount(eligible)))
// Current inputs and their total value. These are closed over by the
// returned input source and reused across multiple calls.
currentTotal := btcutil.Amount(0)
@@ -97,119 +95,160 @@ func (s secretSource) GetScript(addr btcutil.Address) ([]byte, error) {
}
// txToOutputs creates a signed transaction which includes each output from
// outputs. Previous outputs to reedeem are chosen from the passed account's
// outputs. Previous outputs to redeem are chosen from the passed account's
// UTXO set and minconf policy. An additional output may be added to return
// change to the wallet. An appropriate fee is included based on the wallet's
// current relay fee. The wallet must be unlocked to create the transaction.
// change to the wallet. This output will have an address generated from the
// given key scope and account. If a key scope is not specified, the address
// will always be generated from the P2WKH key scope. An appropriate fee is
// included based on the wallet's current relay fee. The wallet must be
// unlocked to create the transaction.
//
// NOTE: The dryRun argument can be set true to create a tx that doesn't alter
// the database. A tx created with this set to true will intentionally have no
// input scripts added and SHOULD NOT be broadcasted.
func (w *Wallet) txToOutputs(outputs []*wire.TxOut, account uint32,
minconf int32, feeSatPerKb btcutil.Amount, dryRun bool) (
tx *txauthor.AuthoredTx, err error) {
func (w *Wallet) txToOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope,
account uint32, minconf int32, feeSatPerKb btcutil.Amount,
coinSelectionStrategy CoinSelectionStrategy, dryRun bool) (
*txauthor.AuthoredTx, error) {
chainClient, err := w.requireChainClient()
if err != nil {
return nil, err
}
dbtx, err := w.db.BeginReadWriteTx()
if err != nil {
return nil, err
}
defer dbtx.Rollback()
addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
// Get current block's height and hash.
bs, err := chainClient.BlockStamp()
if err != nil {
return nil, err
}
eligible, err := w.findEligibleOutputs(dbtx, account, minconf, bs)
if err != nil {
return nil, err
}
inputSource := makeInputSource(eligible)
changeSource := func() ([]byte, error) {
// Derive the change output script. As a hack to allow
// spending from the imported account, change addresses are
// created from account 0.
var changeAddr btcutil.Address
var err error
if account == waddrmgr.ImportedAddrAccount {
changeAddr, err = w.newChangeAddress(addrmgrNs, 0)
} else {
changeAddr, err = w.newChangeAddress(addrmgrNs, account)
}
if err != nil {
return nil, err
}
return txscript.PayToAddrScript(changeAddr)
}
tx, err = txauthor.NewUnsignedTransaction(outputs, feeSatPerKb,
inputSource, changeSource)
if err != nil {
return nil, err
}
// Randomize change position, if change exists, before signing. This
// doesn't affect the serialize size, so the change amount will still
// be valid.
if tx.ChangeIndex >= 0 {
tx.RandomizeChangePosition()
}
// If a dry run was requested, we return now before adding the input
// scripts, and don't commit the database transaction. The DB will be
// rolled back when this method returns to ensure the dry run didn't
// alter the DB in any way.
if dryRun {
return tx, nil
}
err = tx.AddAllInputScripts(secretSource{w.Manager, addrmgrNs})
if err != nil {
return nil, err
}
err = validateMsgTx(tx.Tx, tx.PrevScripts, tx.PrevInputValues)
if err != nil {
return nil, err
}
if err := dbtx.Commit(); err != nil {
return nil, err
}
if tx.ChangeIndex >= 0 && account == waddrmgr.ImportedAddrAccount {
changeAmount := btcutil.Amount(tx.Tx.TxOut[tx.ChangeIndex].Value)
log.Warnf("Spend from imported account produced change: moving"+
" %v from imported account into default account.", changeAmount)
}
// Finally, we'll request the backend to notify us of the transaction
// that pays to the change address, if there is one, when it confirms.
if tx.ChangeIndex >= 0 {
changePkScript := tx.Tx.TxOut[tx.ChangeIndex].PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
changePkScript, w.chainParams,
var tx *txauthor.AuthoredTx
err = walletdb.Update(w.db, func(dbtx walletdb.ReadWriteTx) error {
addrmgrNs, changeSource, err := w.addrMgrWithChangeSource(
dbtx, keyScope, account,
)
if err != nil {
return nil, err
return err
}
if err := chainClient.NotifyReceived(addrs); err != nil {
return nil, err
eligible, err := w.findEligibleOutputs(
dbtx, keyScope, account, minconf, bs,
)
if err != nil {
return err
}
var inputSource txauthor.InputSource
switch coinSelectionStrategy {
// Pick largest outputs first.
case CoinSelectionLargest:
sort.Sort(sort.Reverse(byAmount(eligible)))
inputSource = makeInputSource(eligible)
// Select coins at random. This prevents the creation of ever
// smaller utxos over time that may never become economical to
// spend.
case CoinSelectionRandom:
// Skip inputs that do not raise the total transaction
// output value at the requested fee rate.
var positivelyYielding []wtxmgr.Credit
for _, output := range eligible {
output := output
if !inputYieldsPositively(&output, feeSatPerKb) {
continue
}
positivelyYielding = append(
positivelyYielding, output,
)
}
rand.Shuffle(len(positivelyYielding), func(i, j int) {
positivelyYielding[i], positivelyYielding[j] =
positivelyYielding[j], positivelyYielding[i]
})
inputSource = makeInputSource(positivelyYielding)
}
tx, err = txauthor.NewUnsignedTransaction(
outputs, feeSatPerKb, inputSource, changeSource,
)
if err != nil {
return err
}
// Randomize change position, if change exists, before signing.
// This doesn't affect the serialize size, so the change amount
// will still be valid.
if tx.ChangeIndex >= 0 {
tx.RandomizeChangePosition()
}
// If a dry run was requested, we return now before adding the
// input scripts, and don't commit the database transaction.
// By returning an error, we make sure the walletdb.Update call
// rolls back the transaction. But we'll react to this specific
// error outside of the DB transaction so we can still return
// the produced chain TX.
if dryRun {
return walletdb.ErrDryRunRollBack
}
err = tx.AddAllInputScripts(
secretSource{w.Manager, addrmgrNs},
)
if err != nil {
return err
}
err = validateMsgTx(
tx.Tx, tx.PrevScripts, tx.PrevInputValues,
)
if err != nil {
return err
}
if tx.ChangeIndex >= 0 && account == waddrmgr.ImportedAddrAccount {
changeAmount := btcutil.Amount(
tx.Tx.TxOut[tx.ChangeIndex].Value,
)
log.Warnf("Spend from imported account produced "+
"change: moving %v from imported account into "+
"default account.", changeAmount)
}
// Finally, we'll request the backend to notify us of the
// transaction that pays to the change address, if there is one,
// when it confirms.
if tx.ChangeIndex >= 0 {
changePkScript := tx.Tx.TxOut[tx.ChangeIndex].PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
changePkScript, w.chainParams,
)
if err != nil {
return err
}
if err := chainClient.NotifyReceived(addrs); err != nil {
return err
}
}
return nil
})
if err != nil && err != walletdb.ErrDryRunRollBack {
return nil, err
}
return tx, nil
}
func (w *Wallet) findEligibleOutputs(dbtx walletdb.ReadTx, account uint32, minconf int32, bs *waddrmgr.BlockStamp) ([]wtxmgr.Credit, error) {
func (w *Wallet) findEligibleOutputs(dbtx walletdb.ReadTx,
keyScope *waddrmgr.KeyScope, account uint32, minconf int32,
bs *waddrmgr.BlockStamp) ([]wtxmgr.Credit, error) {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
@@ -222,7 +261,7 @@ func (w *Wallet) findEligibleOutputs(dbtx walletdb.ReadTx, account uint32, minco
// should be handled by the call to UnspentOutputs (or similar).
// Because one of these filters requires matching the output script to
// the desired account, this change depends on making wtxmgr a waddrmgr
// dependancy and requesting unspent outputs for a single account.
// dependency and requesting unspent outputs for a single account.
eligible := make([]wtxmgr.Credit, 0, len(unspent))
for i := range unspent {
output := &unspent[i]
@@ -255,8 +294,19 @@ func (w *Wallet) findEligibleOutputs(dbtx walletdb.ReadTx, account uint32, minco
if err != nil || len(addrs) != 1 {
continue
}
_, addrAcct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])
if err != nil || addrAcct != account {
if isStake(output.PkScript) {
continue
}
scopedMgr, addrAcct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])
if err != nil {
continue
}
if keyScope != nil && scopedMgr.Scope() != *keyScope {
continue
}
if addrAcct != account {
continue
}
eligible = append(eligible, *output)
@@ -264,6 +314,88 @@ func (w *Wallet) findEligibleOutputs(dbtx walletdb.ReadTx, account uint32, minco
return eligible, nil
}
// inputYieldsPositively returns a boolean indicating whether this input yields
// positively if added to a transaction. This determination is based on the
// best-case added virtual size. For edge cases this function can return true
// while the input is yielding slightly negative as part of the final
// transaction.
func inputYieldsPositively(credit *wtxmgr.Credit, feeRatePerKb btcutil.Amount) bool {
inputSize := txsizes.GetMinInputVirtualSize(credit.PkScript)
inputFee := feeRatePerKb * btcutil.Amount(inputSize) / 1000
return inputFee < credit.Amount
}
// addrMgrWithChangeSource returns the address manager bucket and a change
// source that returns change addresses from said address manager. The change
// addresses will come from the specified key scope and account, unless a key
// scope is not specified. In that case, change addresses will always come from
// the P2WKH key scope.
func (w *Wallet) addrMgrWithChangeSource(dbtx walletdb.ReadWriteTx,
changeKeyScope *waddrmgr.KeyScope, account uint32) (
walletdb.ReadWriteBucket, *txauthor.ChangeSource, error) {
// Determine the address type for change addresses of the given account.
if changeKeyScope == nil {
changeKeyScope = &waddrmgr.KeyScopeBIP0084
}
addrType := waddrmgr.ScopeAddrMap[*changeKeyScope].InternalAddrType
// It's possible for the account to have an address schema override, so
// prefer that if it exists.
addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
scopeMgr, err := w.Manager.FetchScopedKeyManager(*changeKeyScope)
if err != nil {
return nil, nil, err
}
accountInfo, err := scopeMgr.AccountProperties(addrmgrNs, account)
if err != nil {
return nil, nil, err
}
if accountInfo.AddrSchema != nil {
addrType = accountInfo.AddrSchema.InternalAddrType
}
// Compute the expected size of the script for the change address type.
var scriptSize int
switch addrType {
case waddrmgr.PubKeyHash:
scriptSize = txsizes.P2PKHPkScriptSize
case waddrmgr.NestedWitnessPubKey:
scriptSize = txsizes.NestedP2WPKHPkScriptSize
case waddrmgr.WitnessPubKey:
scriptSize = txsizes.P2WPKHPkScriptSize
}
newChangeScript := func() ([]byte, error) {
// Derive the change output script. As a hack to allow spending
// from the imported account, change addresses are created from
// account 0.
var (
changeAddr btcutil.Address
err error
)
if account == waddrmgr.ImportedAddrAccount {
changeAddr, err = w.newChangeAddress(
addrmgrNs, 0, *changeKeyScope,
)
} else {
changeAddr, err = w.newChangeAddress(
addrmgrNs, account, *changeKeyScope,
)
}
if err != nil {
return nil, err
}
return txscript.PayToAddrScript(changeAddr)
}
return addrmgrNs, &txauthor.ChangeSource{
ScriptSize: scriptSize,
NewScript: newChangeScript,
}, nil
}
// validateMsgTx verifies transaction input scripts for tx. All previous output
// scripts from outputs redeemed by the transaction, in the same order they are
// spent, must be passed in the prevScripts slice.
+175 -78
View File
@@ -6,54 +6,40 @@ package wallet
import (
"bytes"
"io/ioutil"
"os"
"testing"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/walletdb"
_ "github.com/btcsuite/btcwallet/walletdb/bdb"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/txscript"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/wallet/txauthor"
"github.com/lbryio/lbcwallet/walletdb"
_ "github.com/lbryio/lbcwallet/walletdb/bdb"
"github.com/lbryio/lbcwallet/wtxmgr"
"github.com/stretchr/testify/require"
)
var (
testBlockHash, _ = chainhash.NewHashFromStr(
"00000000000000017188b968a371bab95aa43522665353b646e41865abae" +
"02a4",
)
testBlockHeight int32 = 276425
)
// TestTxToOutput checks that no new address is added to he database if we
// request a dry run of the txToOutputs call. It also makes sure a subsequent
// non-dry run call produces a similar transaction to the dry-run.
func TestTxToOutputsDryRun(t *testing.T) {
// Set up a wallet.
dir, err := ioutil.TempDir("", "createtx_test")
if err != nil {
t.Fatalf("Failed to create db dir: %v", err)
}
defer os.RemoveAll(dir)
seed, err := hdkeychain.GenerateSeed(hdkeychain.MinSeedBytes)
if err != nil {
t.Fatalf("unable to create seed: %v", err)
}
pubPass := []byte("hello")
privPass := []byte("world")
loader := NewLoader(&chaincfg.TestNet3Params, dir, true, 250)
w, err := loader.CreateNewWallet(pubPass, privPass, seed, time.Now())
if err != nil {
t.Fatalf("unable to create wallet: %v", err)
}
chainClient := &mockChainClient{}
w.chainClient = chainClient
if err := w.Unlock(privPass, time.After(10*time.Minute)); err != nil {
t.Fatalf("unable to unlock wallet: %v", err)
}
w, cleanup := testWallet(t)
defer cleanup()
// Create an address we can use to send some coins to.
addr, err := w.CurrentAddress(0, waddrmgr.KeyScopeBIP0044)
keyScope := waddrmgr.KeyScopeBIP0049
addr, err := w.CurrentAddress(0, keyScope)
if err != nil {
t.Fatalf("unable to get current address: %v", addr)
}
@@ -72,41 +58,7 @@ func TestTxToOutputsDryRun(t *testing.T) {
txOut,
},
}
var b bytes.Buffer
if err := incomingTx.Serialize(&b); err != nil {
t.Fatalf("unable to serialize tx: %v", err)
}
txBytes := b.Bytes()
rec, err := wtxmgr.NewTxRecord(txBytes, time.Now())
if err != nil {
t.Fatalf("unable to create tx record: %v", err)
}
// The block meta will be inserted to tell the wallet this is a
// confirmed transaction.
blockHash, _ := chainhash.NewHashFromStr(
"00000000000000017188b968a371bab95aa43522665353b646e41865abae02a4")
block := &wtxmgr.BlockMeta{
Block: wtxmgr.Block{Hash: *blockHash, Height: 276425},
Time: time.Unix(1387737310, 0),
}
if err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(wtxmgrNamespaceKey)
err = w.TxStore.InsertTx(ns, rec, block)
if err != nil {
return err
}
err = w.TxStore.AddCredit(ns, rec, block, 0, false)
if err != nil {
return err
}
return nil
}); err != nil {
t.Fatalf("failed inserting tx: %v", err)
}
addUtxo(t, w, incomingTx)
// Now tell the wallet to create a transaction paying to the specified
// outputs.
@@ -123,13 +75,15 @@ func TestTxToOutputsDryRun(t *testing.T) {
// First do a few dry-runs, making sure the number of addresses in the
// database us not inflated.
dryRunTx, err := w.txToOutputs(txOuts, 0, 1, 1000, true)
dryRunTx, err := w.txToOutputs(
txOuts, nil, 0, 1, 1000, CoinSelectionLargest, true,
)
if err != nil {
t.Fatalf("unable to author tx: %v", err)
}
change := dryRunTx.Tx.TxOut[dryRunTx.ChangeIndex]
addresses, err := w.AccountAddresses(0)
addresses, err := w.AccountAddresses(0, nil)
if err != nil {
t.Fatalf("unable to get addresses: %v", err)
}
@@ -138,13 +92,15 @@ func TestTxToOutputsDryRun(t *testing.T) {
t.Fatalf("expected 1 address, found %v", len(addresses))
}
dryRunTx2, err := w.txToOutputs(txOuts, 0, 1, 1000, true)
dryRunTx2, err := w.txToOutputs(
txOuts, nil, 0, 1, 1000, CoinSelectionLargest, true,
)
if err != nil {
t.Fatalf("unable to author tx: %v", err)
}
change2 := dryRunTx2.Tx.TxOut[dryRunTx2.ChangeIndex]
addresses, err = w.AccountAddresses(0)
addresses, err = w.AccountAddresses(0, nil)
if err != nil {
t.Fatalf("unable to get addresses: %v", err)
}
@@ -171,13 +127,15 @@ func TestTxToOutputsDryRun(t *testing.T) {
// Now we do a proper, non-dry run. This should add a change address
// to the database.
tx, err := w.txToOutputs(txOuts, 0, 1, 1000, false)
tx, err := w.txToOutputs(
txOuts, nil, 0, 1, 1000, CoinSelectionLargest, false,
)
if err != nil {
t.Fatalf("unable to author tx: %v", err)
}
change3 := tx.Tx.TxOut[tx.ChangeIndex]
addresses, err = w.AccountAddresses(0)
addresses, err = w.AccountAddresses(0, nil)
if err != nil {
t.Fatalf("unable to get addresses: %v", err)
}
@@ -202,3 +160,142 @@ func TestTxToOutputsDryRun(t *testing.T) {
"than wet run")
}
}
// addUtxo add the given transaction to the wallet's database marked as a
// confirmed UTXO .
func addUtxo(t *testing.T, w *Wallet, incomingTx *wire.MsgTx) {
var b bytes.Buffer
if err := incomingTx.Serialize(&b); err != nil {
t.Fatalf("unable to serialize tx: %v", err)
}
txBytes := b.Bytes()
rec, err := wtxmgr.NewTxRecord(txBytes, time.Now())
if err != nil {
t.Fatalf("unable to create tx record: %v", err)
}
// The block meta will be inserted to tell the wallet this is a
// confirmed transaction.
block := &wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Hash: *testBlockHash,
Height: testBlockHeight,
},
Time: time.Unix(1387737310, 0),
}
if err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(wtxmgrNamespaceKey)
err = w.TxStore.InsertTx(ns, rec, block)
if err != nil {
return err
}
// Add all tx outputs as credits.
for i := 0; i < len(incomingTx.TxOut); i++ {
err = w.TxStore.AddCredit(
ns, rec, block, uint32(i), false,
)
if err != nil {
return err
}
}
return nil
}); err != nil {
t.Fatalf("failed inserting tx: %v", err)
}
}
// TestInputYield verifies the functioning of the inputYieldsPositively.
func _TestInputYield(t *testing.T) {
addr, _ := btcutil.DecodeAddress("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4", &chaincfg.MainNetParams)
pkScript, err := txscript.PayToAddrScript(addr)
require.NoError(t, err)
credit := &wtxmgr.Credit{
Amount: 1000,
PkScript: pkScript,
}
// At 10 sat/b this input is yielding positively.
require.True(t, inputYieldsPositively(credit, 10000))
// At 20 sat/b this input is yielding negatively.
require.False(t, inputYieldsPositively(credit, 20000))
}
// TestTxToOutputsRandom tests random coin selection.
func TestTxToOutputsRandom(t *testing.T) {
w, cleanup := testWallet(t)
defer cleanup()
// Create an address we can use to send some coins to.
keyScope := waddrmgr.KeyScopeBIP0049
addr, err := w.CurrentAddress(0, keyScope)
if err != nil {
t.Fatalf("unable to get current address: %v", addr)
}
p2shAddr, err := txscript.PayToAddrScript(addr)
if err != nil {
t.Fatalf("unable to convert wallet address to p2sh: %v", err)
}
// Add a set of utxos to the wallet.
incomingTx := &wire.MsgTx{
TxIn: []*wire.TxIn{
{},
},
TxOut: []*wire.TxOut{},
}
for amt := int64(5000); amt <= 125000; amt += 10000 {
incomingTx.AddTxOut(wire.NewTxOut(amt, p2shAddr))
}
addUtxo(t, w, incomingTx)
// Now tell the wallet to create a transaction paying to the specified
// outputs.
txOuts := []*wire.TxOut{
{
PkScript: p2shAddr,
Value: 50000,
},
{
PkScript: p2shAddr,
Value: 100000,
},
}
const (
feeSatPerKb = 100000
maxIterations = 100
)
createTx := func() *txauthor.AuthoredTx {
tx, err := w.txToOutputs(
txOuts, nil, 0, 1, feeSatPerKb, CoinSelectionRandom, true,
)
require.NoError(t, err)
return tx
}
firstTx := createTx()
var isRandom bool
for iteration := 0; iteration < maxIterations; iteration++ {
tx := createTx()
// Check to see if we are getting a total input value.
// We consider this proof that the randomization works.
if tx.TotalInput != firstTx.TotalInput {
isRandom = true
}
// At the used fee rate of 100 sat/b, the 5000 sat input is
// negatively yielding. We don't expect it to ever be selected.
for _, inputValue := range tx.PrevInputValues {
require.NotEqual(t, inputValue, btcutil.Amount(5000))
}
}
require.True(t, isRandom)
}
-1
View File
@@ -7,6 +7,5 @@ Package wallet provides ...
TODO: Flesh out this section
Overview
*/
package wallet
+52
View File
@@ -0,0 +1,52 @@
package wallet
import (
"io/ioutil"
"os"
"testing"
"time"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcutil/hdkeychain"
)
// defaultDBTimeout specifies the timeout value when opening the wallet
// database.
var defaultDBTimeout = 10 * time.Second
// testWallet creates a test wallet and unlocks it.
func testWallet(t *testing.T) (*Wallet, func()) {
// Set up a wallet.
dir, err := ioutil.TempDir("", "test_wallet")
if err != nil {
t.Fatalf("Failed to create db dir: %v", err)
}
cleanup := func() {
if err := os.RemoveAll(dir); err != nil {
t.Fatalf("could not cleanup test: %v", err)
}
}
seed, err := hdkeychain.GenerateSeed(hdkeychain.MinSeedBytes)
if err != nil {
t.Fatalf("unable to create seed: %v", err)
}
passphrase := []byte("hello world")
loader := NewLoader(
&chaincfg.TestNet3Params, dir, true, defaultDBTimeout, 250,
)
w, err := loader.CreateNewWallet(passphrase, seed, time.Now())
if err != nil {
t.Fatalf("unable to create wallet: %v", err)
}
chainClient := &mockChainClient{}
w.chainClient = chainClient
if err := w.Unlock(passphrase, time.After(10*time.Minute)); err != nil {
t.Fatalf("unable to unlock wallet: %v", err)
}
return w, cleanup
}
+161
View File
@@ -0,0 +1,161 @@
// Copyright (c) 2015-2020 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wallet
import (
"fmt"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/walletdb"
"github.com/lbryio/lbcwallet/wtxmgr"
)
var (
// bucketTxLabels is the name of the label sub bucket of the wtxmgr
// top level bucket that stores the mapping between a txid and a
// user-defined transaction label.
bucketTxLabels = []byte("l")
)
// DropTransactionHistory completely removes and re-creates the transaction
// manager namespace from the given wallet database. This can be used to force
// a full chain rescan of all wallet transaction and UTXO data. User-defined
// transaction labels can optionally be kept by setting keepLabels to true.
func DropTransactionHistory(db walletdb.DB, keepLabels bool) error {
log.Infof("Dropping lbcwallet transaction history")
err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
// If we want to keep our tx labels, we read them out so we
// can re-add them after we have deleted our wtxmgr.
var (
labels map[chainhash.Hash]string
err error
)
if keepLabels {
labels, err = fetchAllLabels(tx)
if err != nil {
return err
}
}
err = tx.DeleteTopLevelBucket(wtxmgrNamespaceKey)
if err != nil && err != walletdb.ErrBucketNotFound {
return err
}
ns, err := tx.CreateTopLevelBucket(wtxmgrNamespaceKey)
if err != nil {
return err
}
err = wtxmgr.Create(ns)
if err != nil {
return err
}
// If we want to re-add our labels, we do so now.
if keepLabels {
if err := putTxLabels(ns, labels); err != nil {
return err
}
}
ns = tx.ReadWriteBucket(waddrmgrNamespaceKey)
birthdayBlock, err := waddrmgr.FetchBirthdayBlock(ns)
if err != nil {
log.Warnf("Wallet does not have a birthday block " +
"set, falling back to rescan from genesis")
startBlock, err := waddrmgr.FetchStartBlock(ns)
if err != nil {
return err
}
return waddrmgr.PutSyncedTo(ns, startBlock)
}
// We'll need to remove our birthday block first because it
// serves as a barrier when updating our state to detect reorgs
// due to the wallet not storing all block hashes of the chain.
if err := waddrmgr.DeleteBirthdayBlock(ns); err != nil {
return err
}
if err := waddrmgr.PutSyncedTo(ns, &birthdayBlock); err != nil {
return err
}
return waddrmgr.PutBirthdayBlock(ns, birthdayBlock)
})
if err != nil {
return fmt.Errorf("failed to drop and re-create namespace: %v",
err)
}
return nil
}
// fetchAllLabels returns a map of hex-encoded txid to label.
func fetchAllLabels(tx walletdb.ReadWriteTx) (map[chainhash.Hash]string,
error) {
// Get our top level bucket, if it does not exist we just exit.
txBucket := tx.ReadBucket(wtxmgrNamespaceKey)
if txBucket == nil {
return nil, nil
}
// If we do not have a labels bucket, there are no labels so we exit.
labelsBucket := txBucket.NestedReadBucket(bucketTxLabels)
if labelsBucket == nil {
return nil, nil
}
labels := make(map[chainhash.Hash]string)
if err := labelsBucket.ForEach(func(k, v []byte) error {
txid, err := chainhash.NewHash(k)
if err != nil {
return err
}
label, err := wtxmgr.DeserializeLabel(v)
if err != nil {
return err
}
// Add an entry to our map of labels.
labels[*txid] = label
return nil
}); err != nil {
return nil, err
}
return labels, nil
}
// putTxLabels re-adds a nested labels bucket and entries to the bucket provided
// if there are any labels present.
func putTxLabels(ns walletdb.ReadWriteBucket,
labels map[chainhash.Hash]string) error {
// If there are no labels, exit early.
if len(labels) == 0 {
return nil
}
// First, we create a labels bucket which we will add all labels to.
labelBucket, err := ns.CreateBucketIfNotExists(bucketTxLabels)
if err != nil {
return err
}
// Next, we re-add every label to the bucket.
for txid, label := range labels {
err := wtxmgr.PutTxLabel(labelBucket, txid, label)
if err != nil {
return err
}
}
return nil
}
+499
View File
@@ -0,0 +1,499 @@
package wallet
import (
"encoding/binary"
"errors"
"fmt"
"github.com/lbryio/lbcd/btcec"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcutil/hdkeychain"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/walletdb"
)
const (
// accountPubKeyDepth is the maximum depth of an extended key for an
// account public key.
accountPubKeyDepth = 3
// pubKeyDepth is the depth of an extended key for a derived public key.
pubKeyDepth = 5
)
// keyScopeFromPubKey returns the corresponding wallet key scope for the given
// extended public key. The address type can usually be inferred from the key's
// version, but may be required for certain keys to map them into the proper
// scope.
func keyScopeFromPubKey(pubKey *hdkeychain.ExtendedKey,
addrType *waddrmgr.AddressType) (waddrmgr.KeyScope,
*waddrmgr.ScopeAddrSchema, error) {
switch waddrmgr.HDVersion(binary.BigEndian.Uint32(pubKey.Version())) {
// For BIP-0044 keys, an address type must be specified as we intend to
// not support importing BIP-0044 keys into the wallet using the legacy
// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will
// force the standard BIP-0049 derivation scheme (nested witness pubkeys
// everywhere), while a witness address type will force the standard
// BIP-0084 derivation scheme.
case waddrmgr.HDVersionMainNetBIP0044, waddrmgr.HDVersionTestNetBIP0044:
if addrType == nil {
return waddrmgr.KeyScope{}, nil, errors.New("address " +
"type must be specified for account public " +
"key with legacy version")
}
switch *addrType {
case waddrmgr.NestedWitnessPubKey:
return waddrmgr.KeyScopeBIP0049,
&waddrmgr.KeyScopeBIP0049AddrSchema, nil
case waddrmgr.WitnessPubKey:
return waddrmgr.KeyScopeBIP0084, nil, nil
default:
return waddrmgr.KeyScope{}, nil,
fmt.Errorf("unsupported address type %v",
*addrType)
}
// For BIP-0049 keys, we'll need to make a distinction between the
// traditional BIP-0049 address schema (nested witness pubkeys
// everywhere) and our own BIP-0049Plus address schema (nested
// externally, witness internally).
case waddrmgr.HDVersionMainNetBIP0049, waddrmgr.HDVersionTestNetBIP0049:
if addrType == nil {
return waddrmgr.KeyScope{}, nil, errors.New("address " +
"type must be specified for account public " +
"key with BIP-0049 version")
}
switch *addrType {
case waddrmgr.NestedWitnessPubKey:
return waddrmgr.KeyScopeBIP0049,
&waddrmgr.KeyScopeBIP0049AddrSchema, nil
case waddrmgr.WitnessPubKey:
return waddrmgr.KeyScopeBIP0049, nil, nil
default:
return waddrmgr.KeyScope{}, nil,
fmt.Errorf("unsupported address type %v",
*addrType)
}
case waddrmgr.HDVersionMainNetBIP0084, waddrmgr.HDVersionTestNetBIP0084:
if addrType != nil && *addrType != waddrmgr.WitnessPubKey {
return waddrmgr.KeyScope{}, nil,
errors.New("address type mismatch")
}
return waddrmgr.KeyScopeBIP0084, nil, nil
default:
return waddrmgr.KeyScope{}, nil, fmt.Errorf("unknown version %x",
pubKey.Version())
}
}
// isPubKeyForNet determines if the given public key is for the current network
// the wallet is operating under.
func (w *Wallet) isPubKeyForNet(pubKey *hdkeychain.ExtendedKey) bool {
version := waddrmgr.HDVersion(binary.BigEndian.Uint32(pubKey.Version()))
switch w.chainParams.Net {
case wire.MainNet:
return version == waddrmgr.HDVersionMainNetBIP0044 ||
version == waddrmgr.HDVersionMainNetBIP0049 ||
version == waddrmgr.HDVersionMainNetBIP0084
case wire.TestNet, wire.TestNet3:
return version == waddrmgr.HDVersionTestNetBIP0044 ||
version == waddrmgr.HDVersionTestNetBIP0049 ||
version == waddrmgr.HDVersionTestNetBIP0084
default:
return false
}
}
// validateExtendedPubKey ensures a sane derived public key is provided.
func (w *Wallet) validateExtendedPubKey(pubKey *hdkeychain.ExtendedKey,
isAccountKey bool) error {
// Private keys are not allowed.
if pubKey.IsPrivate() {
return errors.New("private keys cannot be imported")
}
// The public key must have a version corresponding to the current
// chain.
if !w.isPubKeyForNet(pubKey) {
return fmt.Errorf("expected extended public key for current "+
"network %v", w.chainParams.Name)
}
// Verify the extended public key's depth and child index based on
// whether it's an account key or not.
if isAccountKey {
if pubKey.Depth() != accountPubKeyDepth {
return errors.New("invalid account key, must be of the " +
"form m/purpose'/coin_type'/account'")
}
if pubKey.ChildIndex() < hdkeychain.HardenedKeyStart {
return errors.New("invalid account key, must be hardened")
}
} else {
if pubKey.Depth() != pubKeyDepth {
return errors.New("invalid account key, must be of the " +
"form m/purpose'/coin_type'/account'/change/" +
"address_index")
}
if pubKey.ChildIndex() >= hdkeychain.HardenedKeyStart {
return errors.New("invalid pulic key, must not be " +
"hardened")
}
}
return nil
}
// ImportAccount imports an account backed by an account extended public key.
// The master key fingerprint denotes the fingerprint of the root key
// corresponding to the account public key (also known as the key with
// derivation path m/). This may be required by some hardware wallets for proper
// identification and signing.
//
// The address type can usually be inferred from the key's version, but may be
// required for certain keys to map them into the proper scope.
//
// For BIP-0044 keys, an address type must be specified as we intend to not
// support importing BIP-0044 keys into the wallet using the legacy
// pay-to-pubkey-hash (P2PKH) scheme. A nested witness address type will force
// the standard BIP-0049 derivation scheme, while a witness address type will
// force the standard BIP-0084 derivation scheme.
//
// For BIP-0049 keys, an address type must also be specified to make a
// distinction between the traditional BIP-0049 address schema (nested witness
// pubkeys everywhere) and our own BIP-0049Plus address schema (nested
// externally, witness internally).
func (w *Wallet) ImportAccount(name string, accountPubKey *hdkeychain.ExtendedKey,
masterKeyFingerprint uint32, addrType *waddrmgr.AddressType) (
*waddrmgr.AccountProperties, error) {
var accountProps *waddrmgr.AccountProperties
err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
accountProps, err = w.importAccount(
ns, name, accountPubKey, masterKeyFingerprint, addrType,
)
return err
})
return accountProps, err
}
// ImportAccountWithScope imports an account backed by an account extended
// public key for a specific key scope which is known in advance.
// The master key fingerprint denotes the fingerprint of the root key
// corresponding to the account public key (also known as the key with
// derivation path m/). This may be required by some hardware wallets for proper
// identification and signing.
func (w *Wallet) ImportAccountWithScope(name string,
accountPubKey *hdkeychain.ExtendedKey, masterKeyFingerprint uint32,
keyScope waddrmgr.KeyScope, addrSchema waddrmgr.ScopeAddrSchema) (
*waddrmgr.AccountProperties, error) {
var accountProps *waddrmgr.AccountProperties
err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
var err error
accountProps, err = w.importAccountScope(
ns, name, accountPubKey, masterKeyFingerprint, keyScope,
&addrSchema,
)
return err
})
return accountProps, err
}
// importAccount is the internal implementation of ImportAccount -- one should
// reference its documentation for this method.
func (w *Wallet) importAccount(ns walletdb.ReadWriteBucket, name string,
accountPubKey *hdkeychain.ExtendedKey, masterKeyFingerprint uint32,
addrType *waddrmgr.AddressType) (*waddrmgr.AccountProperties, error) {
// Ensure we have a valid account public key.
if err := w.validateExtendedPubKey(accountPubKey, true); err != nil {
return nil, err
}
// Determine what key scope the account public key should belong to and
// whether it should use a custom address schema.
keyScope, addrSchema, err := keyScopeFromPubKey(accountPubKey, addrType)
if err != nil {
return nil, err
}
return w.importAccountScope(
ns, name, accountPubKey, masterKeyFingerprint, keyScope,
addrSchema,
)
}
// importAccountScope imports a watch-only account for a given scope.
func (w *Wallet) importAccountScope(ns walletdb.ReadWriteBucket, name string,
accountPubKey *hdkeychain.ExtendedKey, masterKeyFingerprint uint32,
keyScope waddrmgr.KeyScope, addrSchema *waddrmgr.ScopeAddrSchema) (
*waddrmgr.AccountProperties, error) {
scopedMgr, err := w.Manager.FetchScopedKeyManager(keyScope)
if err != nil {
scopedMgr, err = w.Manager.NewScopedKeyManager(
ns, keyScope, *addrSchema,
)
if err != nil {
return nil, err
}
}
// FIXME
// account, err := scopedMgr.NewAccountWatchingOnly(
// ns, name, accountPubKey, masterKeyFingerprint, addrSchema,
// )
// if err != nil {
// return nil, err
// }
var account uint32
return scopedMgr.AccountProperties(ns, account)
}
// ImportAccountDryRun serves as a dry run implementation of ImportAccount. This
// method also returns the first N external and internal addresses, which can be
// presented to users to confirm whether the account has been imported
// correctly.
func (w *Wallet) ImportAccountDryRun(name string,
accountPubKey *hdkeychain.ExtendedKey, masterKeyFingerprint uint32,
addrType *waddrmgr.AddressType, numAddrs uint32) (
*waddrmgr.AccountProperties, []waddrmgr.ManagedAddress,
[]waddrmgr.ManagedAddress, error) {
var (
accountProps *waddrmgr.AccountProperties
externalAddrs []waddrmgr.ManagedAddress
internalAddrs []waddrmgr.ManagedAddress
)
// Start a database transaction that we'll never commit and always
// rollback because we'll return a specific error in the end.
err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
// Import the account as usual.
var err error
accountProps, err = w.importAccount(
ns, name, accountPubKey, masterKeyFingerprint, addrType,
)
if err != nil {
return err
}
// Derive the external and internal addresses. Note that we
// could do this based on the provided accountPubKey alone, but
// we go through the ScopedKeyManager instead to ensure
// addresses will be derived as expected from the wallet's
// point-of-view.
manager, err := w.Manager.FetchScopedKeyManager(
accountProps.KeyScope,
)
if err != nil {
return err
}
// The importAccount method above will cache the imported
// account within the scoped manager. Since this is a dry-run
// attempt, we'll want to invalidate the cache for it.
defer manager.InvalidateAccountCache(accountProps.AccountNumber)
externalAddrs, err = manager.NextAddresses(
ns, accountProps.AccountNumber, waddrmgr.ExternalBranch, numAddrs,
)
if err != nil {
return err
}
internalAddrs, err = manager.NextAddresses(
ns, accountProps.AccountNumber, waddrmgr.InternalBranch, numAddrs,
)
if err != nil {
return err
}
// Refresh the account's properties after generating the
// addresses.
accountProps, err = manager.AccountProperties(
ns, accountProps.AccountNumber,
)
if err != nil {
return err
}
// Make sure we always roll back the dry-run transaction by
// returning an error here.
return walletdb.ErrDryRunRollBack
})
if err != nil && err != walletdb.ErrDryRunRollBack {
return nil, nil, nil, err
}
return accountProps, externalAddrs, internalAddrs, nil
}
// ImportPublicKey imports a single derived public key into the address manager.
// The address type can usually be inferred from the key's version, but in the
// case of legacy versions (xpub, tpub), an address type must be specified as we
// intend to not support importing BIP-44 keys into the wallet using the legacy
// pay-to-pubkey-hash (P2PKH) scheme.
func (w *Wallet) ImportPublicKey(pubKey *btcec.PublicKey,
addrType waddrmgr.AddressType) error {
// Determine what key scope the public key should belong to and import
// it into the key scope's default imported account.
var keyScope waddrmgr.KeyScope
switch addrType {
case waddrmgr.NestedWitnessPubKey:
keyScope = waddrmgr.KeyScopeBIP0049
case waddrmgr.WitnessPubKey:
keyScope = waddrmgr.KeyScopeBIP0084
default:
return fmt.Errorf("address type %v is not supported", addrType)
}
scopedKeyManager, err := w.Manager.FetchScopedKeyManager(keyScope)
if err != nil {
return err
}
// TODO: Perform rescan if requested.
var addr waddrmgr.ManagedAddress
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
addr, err = scopedKeyManager.ImportPublicKey(ns, pubKey, nil)
return err
})
if err != nil {
return err
}
log.Infof("Imported address %v", addr.Address())
err = w.chainClient.NotifyReceived([]btcutil.Address{addr.Address()})
if err != nil {
return fmt.Errorf("unable to subscribe for address "+
"notifications: %v", err)
}
return nil
}
// ImportPrivateKey imports a private key to the wallet and writes the new
// wallet to disk.
//
// NOTE: If a block stamp is not provided, then the wallet's birthday will be
// set to the genesis block of the corresponding chain.
func (w *Wallet) ImportPrivateKey(scope waddrmgr.KeyScope, wif *btcutil.WIF,
bs *waddrmgr.BlockStamp, rescan bool) (string, error) {
manager, err := w.Manager.FetchScopedKeyManager(scope)
if err != nil {
return "", err
}
// The starting block for the key is the genesis block unless otherwise
// specified.
if bs == nil {
bs = &waddrmgr.BlockStamp{
Hash: *w.chainParams.GenesisHash,
Height: 0,
Timestamp: w.chainParams.GenesisBlock.Header.Timestamp,
}
} else if bs.Timestamp.IsZero() {
// Only update the new birthday time from default value if we
// actually have timestamp info in the header.
header, err := w.chainClient.GetBlockHeader(&bs.Hash)
if err == nil {
bs.Timestamp = header.Timestamp
}
}
// Attempt to import private key into wallet.
var addr btcutil.Address
var props *waddrmgr.AccountProperties
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
maddr, err := manager.ImportPrivateKey(addrmgrNs, wif, bs)
if err != nil {
return err
}
addr = maddr.Address()
props, err = manager.AccountProperties(
addrmgrNs, waddrmgr.ImportedAddrAccount,
)
if err != nil {
return err
}
// We'll only update our birthday with the new one if it is
// before our current one. Otherwise, if we do, we can
// potentially miss detecting relevant chain events that
// occurred between them while rescanning.
birthdayBlock, _, err := w.Manager.BirthdayBlock(addrmgrNs)
if err != nil {
return err
}
if bs.Height >= birthdayBlock.Height {
return nil
}
err = w.Manager.SetBirthday(addrmgrNs, bs.Timestamp)
if err != nil {
return err
}
// To ensure this birthday block is correct, we'll mark it as
// unverified to prompt a sanity check at the next restart to
// ensure it is correct as it was provided by the caller.
return w.Manager.SetBirthdayBlock(addrmgrNs, *bs, false)
})
if err != nil {
return "", err
}
// Rescan blockchain for transactions with txout scripts paying to the
// imported address.
if rescan {
job := &RescanJob{
Addrs: []btcutil.Address{addr},
OutPoints: nil,
BlockStamp: *bs,
}
// Submit rescan job and log when the import has completed.
// Do not block on finishing the rescan. The rescan success
// or failure is logged elsewhere, and the channel is not
// required to be read, so discard the return value.
_ = w.SubmitRescan(job)
} else {
err := w.chainClient.NotifyReceived([]btcutil.Address{addr})
if err != nil {
return "", fmt.Errorf("failed to subscribe for address ntfns for "+
"address %s: %s", addr.EncodeAddress(), err)
}
}
addrStr := addr.EncodeAddress()
log.Infof("Imported payment address %s", addrStr)
w.NtfnServer.notifyAccountProperties(props)
// Return the payment address string of the imported private key.
return addrStr, nil
}
+274
View File
@@ -0,0 +1,274 @@
package wallet
import (
"encoding/binary"
"strings"
"testing"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/txscript"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcutil/hdkeychain"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/stretchr/testify/require"
)
func hardenedKey(key uint32) uint32 {
return key + hdkeychain.HardenedKeyStart
}
func deriveAcctPubKey(t *testing.T, root *hdkeychain.ExtendedKey,
scope waddrmgr.KeyScope, paths ...uint32) *hdkeychain.ExtendedKey {
path := []uint32{hardenedKey(scope.Purpose), hardenedKey(scope.Coin)}
path = append(path, paths...)
var (
currentKey = root
err error
)
for _, pathPart := range path {
currentKey, err = currentKey.Derive(pathPart)
require.NoError(t, err)
}
// The Neuter() method checks the version and doesn't know any
// non-standard methods. We need to convert them to standard, neuter,
// then convert them back with the target extended public key version.
pubVersionBytes := make([]byte, 4)
copy(pubVersionBytes, chaincfg.TestNet3Params.HDPublicKeyID[:])
switch {
case strings.HasPrefix(root.String(), "uprv"):
binary.BigEndian.PutUint32(pubVersionBytes, uint32(
waddrmgr.HDVersionTestNetBIP0049,
))
case strings.HasPrefix(root.String(), "vprv"):
binary.BigEndian.PutUint32(pubVersionBytes, uint32(
waddrmgr.HDVersionTestNetBIP0084,
))
}
currentKey, err = currentKey.CloneWithVersion(
chaincfg.TestNet3Params.HDPrivateKeyID[:],
)
require.NoError(t, err)
currentKey, err = currentKey.Neuter()
require.NoError(t, err)
currentKey, err = currentKey.CloneWithVersion(pubVersionBytes)
require.NoError(t, err)
return currentKey
}
type testCase struct {
name string
masterPriv string
accountIndex uint32
addrType waddrmgr.AddressType
expectedScope waddrmgr.KeyScope
expectedAddr string
expectedChangeAddr string
}
var (
testCases = []*testCase{{
name: "bip44 with nested witness address type",
masterPriv: "tprv8ZgxMBicQKsPeWwrFuNjEGTTDSY4mRLwd2KDJAPGa1AY" +
"quw38bZqNMSuB3V1Va3hqJBo9Pt8Sx7kBQer5cNMrb8SYquoWPt9" +
"Y3BZdhdtUcw",
accountIndex: 0,
addrType: waddrmgr.NestedWitnessPubKey,
expectedScope: waddrmgr.KeyScopeBIP0049,
expectedAddr: "2N5YTxG9XtGXx1YyhZb7N2pwEjoZLLMHGKj",
expectedChangeAddr: "2N7wpz5Gy2zEJTvq2MAuU6BCTEBLXNQ8dUw",
}, {
name: "bip44 with witness address type",
masterPriv: "tprv8ZgxMBicQKsPeWwrFuNjEGTTDSY4mRLwd2KDJAPGa1AY" +
"quw38bZqNMSuB3V1Va3hqJBo9Pt8Sx7kBQer5cNMrb8SYquoWPt9" +
"Y3BZdhdtUcw",
accountIndex: 777,
addrType: waddrmgr.WitnessPubKey,
expectedScope: waddrmgr.KeyScopeBIP0084,
expectedAddr: "tb1qllxcutkzsukf8u8c8stkp464j0esu9xq7qju8x",
expectedChangeAddr: "tb1qu6jmqglrthscptjqj3egx54wy8xqvzn5hslgw7",
}, {
name: "traditional bip49",
masterPriv: "uprv8tXDerPXZ1QsVp8y6GAMSMYxPQgWi3LSY8qS5ZH9x1YRu" +
"1kGPFjPzR73CFSbVUhdEwJbtsUgucUJ4hGQoJnNepp3RBcE6Jhdom" +
"FD2KeY6G9",
accountIndex: 9,
addrType: waddrmgr.NestedWitnessPubKey,
expectedScope: waddrmgr.KeyScopeBIP0049,
expectedAddr: "2NBCJ9WzGXZqpLpXGq3Hacybj3c4eHRcqgh",
expectedChangeAddr: "2N3bankFu6F3ZNU41iVJQqyS9MXqp9dvn1M",
}, {
name: "bip49+",
masterPriv: "uprv8tXDerPXZ1QsVp8y6GAMSMYxPQgWi3LSY8qS5ZH9x1YRu" +
"1kGPFjPzR73CFSbVUhdEwJbtsUgucUJ4hGQoJnNepp3RBcE6Jhdom" +
"FD2KeY6G9",
accountIndex: 9,
addrType: waddrmgr.WitnessPubKey,
expectedScope: waddrmgr.KeyScopeBIP0049,
expectedAddr: "2NBCJ9WzGXZqpLpXGq3Hacybj3c4eHRcqgh",
expectedChangeAddr: "tb1qeqn05w2hfq6axpdprhs4y7x65gxkkvfvyxqk4u",
}, {
name: "bip84",
masterPriv: "vprv9DMUxX4ShgxMM7L5vcwyeSeTZNpxefKwTFMerxB3L1vJ" +
"x7ZVdutxcUmBDTQBVPMYeaRQeM5FNGpqwysyX1CPT4VeHXJegDX8" +
"5VJrQvaFaz3",
accountIndex: 1,
addrType: waddrmgr.WitnessPubKey,
expectedScope: waddrmgr.KeyScopeBIP0084,
expectedAddr: "tb1q5vepvcl0z8xj7kps4rsux722r4dvfwlhk6j532",
expectedChangeAddr: "tb1qlwe2kgxcsa8x4huu79yff4rze0l5mwafg5c7xd",
}}
)
// TestImportAccount tests that extended public keys can successfully be
// imported into both watch only and normal wallets.
func _TestImportAccount(t *testing.T) {
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
w, cleanup := testWallet(t)
defer cleanup()
testImportAccount(t, w, tc, tc.name)
})
}
}
func testImportAccount(t *testing.T, w *Wallet, tc *testCase, name string) {
// First derive the master public key of the account we want to import.
root, err := hdkeychain.NewKeyFromString(tc.masterPriv)
require.NoError(t, err)
// Derive the extended private and public key for our target account.
acct1Pub := deriveAcctPubKey(
t, root, tc.expectedScope, hardenedKey(tc.accountIndex),
)
// We want to make sure we can import and handle multiple accounts, so
// we create another one.
acct2Pub := deriveAcctPubKey(
t, root, tc.expectedScope, hardenedKey(tc.accountIndex+1),
)
// And we also want to be able to import loose extended public keys
// without needing to specify an explicit scope.
acct3ExternalExtPub := deriveAcctPubKey(
t, root, tc.expectedScope, hardenedKey(tc.accountIndex+2), 0, 0,
)
acct3ExternalPub, err := acct3ExternalExtPub.ECPubKey()
require.NoError(t, err)
// Do a dry run import first and check that it results in the expected
// addresses being derived.
_, extAddrs, intAddrs, err := w.ImportAccountDryRun(
name+"1", acct1Pub, root.ParentFingerprint(), &tc.addrType, 1,
)
require.NoError(t, err)
require.Len(t, extAddrs, 1)
require.Equal(t, tc.expectedAddr, extAddrs[0].Address().String())
require.Len(t, intAddrs, 1)
require.Equal(t, tc.expectedChangeAddr, intAddrs[0].Address().String())
// Import the extended public keys into new accounts.
acct1, err := w.ImportAccount(
name+"1", acct1Pub, root.ParentFingerprint(), &tc.addrType,
)
require.NoError(t, err)
require.Equal(t, tc.expectedScope, acct1.KeyScope)
acct2, err := w.ImportAccount(
name+"2", acct2Pub, root.ParentFingerprint(), &tc.addrType,
)
require.NoError(t, err)
require.Equal(t, tc.expectedScope, acct2.KeyScope)
err = w.ImportPublicKey(acct3ExternalPub, tc.addrType)
require.NoError(t, err)
// If the wallet is watch only, there is no default account and our
// imported account will be index 0.
firstAccountIndex := uint32(1)
// We should have 3 additional accounts now.
acctResult, err := w.Accounts(tc.expectedScope)
require.NoError(t, err)
require.Len(t, acctResult.Accounts, int(firstAccountIndex*2)+2)
// Validate the state of the accounts.
require.Equal(t, firstAccountIndex, acct1.AccountNumber)
require.Equal(t, name+"1", acct1.AccountName)
require.Equal(t, root.ParentFingerprint(), acct1.MasterKeyFingerprint)
require.NotNil(t, acct1.AccountPubKey)
require.Equal(t, acct1Pub.String(), acct1.AccountPubKey.String())
require.Equal(t, uint32(0), acct1.InternalKeyCount)
require.Equal(t, uint32(0), acct1.ExternalKeyCount)
require.Equal(t, uint32(0), acct1.ImportedKeyCount)
require.Equal(t, firstAccountIndex+1, acct2.AccountNumber)
require.Equal(t, name+"2", acct2.AccountName)
require.Equal(t, root.ParentFingerprint(), acct2.MasterKeyFingerprint)
require.NotNil(t, acct2.AccountPubKey)
require.Equal(t, acct2Pub.String(), acct2.AccountPubKey.String())
require.Equal(t, uint32(0), acct2.InternalKeyCount)
require.Equal(t, uint32(0), acct2.ExternalKeyCount)
require.Equal(t, uint32(0), acct2.ImportedKeyCount)
// Test address derivation.
extAddr, err := w.NewAddress(acct1.AccountNumber, tc.expectedScope)
require.NoError(t, err)
require.Equal(t, tc.expectedAddr, extAddr.String())
intAddr, err := w.NewChangeAddress(acct1.AccountNumber, tc.expectedScope)
require.NoError(t, err)
require.Equal(t, tc.expectedChangeAddr, intAddr.String())
// Make sure the key count was increased.
acct1, err = w.AccountProperties(tc.expectedScope, acct1.AccountNumber)
require.NoError(t, err)
require.Equal(t, uint32(1), acct1.InternalKeyCount)
require.Equal(t, uint32(1), acct1.ExternalKeyCount)
require.Equal(t, uint32(0), acct1.ImportedKeyCount)
// Make sure we can't get private keys for the imported accounts.
_, err = w.DumpWIFPrivateKey(intAddr)
// Get the address info for the single key we imported.
switch tc.addrType {
case waddrmgr.NestedWitnessPubKey:
witnessAddr, err := btcutil.NewAddressWitnessPubKeyHash(
btcutil.Hash160(acct3ExternalPub.SerializeCompressed()),
&chaincfg.TestNet3Params,
)
require.NoError(t, err)
witnessProg, err := txscript.PayToAddrScript(witnessAddr)
require.NoError(t, err)
intAddr, err = btcutil.NewAddressScriptHash(
witnessProg, &chaincfg.TestNet3Params,
)
require.NoError(t, err)
case waddrmgr.WitnessPubKey:
intAddr, err = btcutil.NewAddressWitnessPubKeyHash(
btcutil.Hash160(acct3ExternalPub.SerializeCompressed()),
&chaincfg.TestNet3Params,
)
require.NoError(t, err)
default:
t.Fatalf("unhandled address type %v", tc.addrType)
}
addrManaged, err := w.AddressInfo(intAddr)
require.NoError(t, err)
require.Equal(t, true, addrManaged.Imported())
}
+151 -67
View File
@@ -6,19 +6,24 @@ package wallet
import (
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcwallet/internal/prompt"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcutil/hdkeychain"
"github.com/lbryio/lbcwallet/walletdb"
)
const (
walletDbName = "wallet.db"
// WalletDBName specified the database filename for the wallet.
WalletDBName = "wallet.db"
// DefaultDBTimeout is the default timeout value when opening the wallet
// database.
DefaultDBTimeout = 60 * time.Second
)
var (
@@ -47,8 +52,12 @@ type Loader struct {
chainParams *chaincfg.Params
dbDirPath string
noFreelistSync bool
timeout time.Duration
recoveryWindow uint32
wallet *Wallet
localDB bool
walletExists func() (bool, error)
walletCreated func(db walletdb.ReadWriteTx) error
db walletdb.DB
mu sync.Mutex
}
@@ -57,25 +66,51 @@ type Loader struct {
// recovery window is non-zero, the wallet will attempt to recovery addresses
// starting from the last SyncedTo height.
func NewLoader(chainParams *chaincfg.Params, dbDirPath string,
noFreelistSync bool, recoveryWindow uint32) *Loader {
noFreelistSync bool, timeout time.Duration,
recoveryWindow uint32) *Loader {
return &Loader{
chainParams: chainParams,
dbDirPath: dbDirPath,
noFreelistSync: noFreelistSync,
timeout: timeout,
recoveryWindow: recoveryWindow,
localDB: true,
}
}
// NewLoaderWithDB constructs a Loader with an externally provided DB. This way
// users are free to use their own walletdb implementation (eg. leveldb, etcd)
// to store the wallet. Given that the external DB may be shared an additional
// function is also passed which will override Loader.WalletExists().
func NewLoaderWithDB(chainParams *chaincfg.Params, recoveryWindow uint32,
db walletdb.DB, walletExists func() (bool, error)) (*Loader, error) {
if db == nil {
return nil, fmt.Errorf("no DB provided")
}
if walletExists == nil {
return nil, fmt.Errorf("unable to check if wallet exists")
}
return &Loader{
chainParams: chainParams,
recoveryWindow: recoveryWindow,
localDB: false,
walletExists: walletExists,
db: db,
}, nil
}
// onLoaded executes each added callback and prevents loader from loading any
// additional wallets. Requires mutex to be locked.
func (l *Loader) onLoaded(w *Wallet, db walletdb.DB) {
func (l *Loader) onLoaded(w *Wallet) {
for _, fn := range l.callbacks {
fn(w)
}
l.wallet = w
l.db = db
l.callbacks = nil // not needed anymore
}
@@ -94,12 +129,59 @@ func (l *Loader) RunAfterLoad(fn func(*Wallet)) {
}
}
// CreateNewWallet creates a new wallet using the provided public and private
// passphrases. The seed is optional. If non-nil, addresses are derived from
// this seed. If nil, a secure random seed is generated.
func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte,
// OnWalletCreated adds a function that will be executed the wallet structure
// is initialized in the wallet database. This is useful if users want to add
// extra fields in the same transaction (eg. to flag wallet existence).
func (l *Loader) OnWalletCreated(fn func(walletdb.ReadWriteTx) error) {
l.mu.Lock()
defer l.mu.Unlock()
l.walletCreated = fn
}
// CreateNewWallet creates a new wallet using the provided passphrase.
// The seed is optional. If non-nil, addresses are derived from this seed.
// If nil, a secure random seed is generated.
func (l *Loader) CreateNewWallet(passphrase, seed []byte,
bday time.Time) (*Wallet, error) {
var (
rootKey *hdkeychain.ExtendedKey
err error
)
// If a seed was specified, we check its length now. If no seed is
// passed, the wallet will create a new random one.
if seed != nil {
if len(seed) < hdkeychain.MinSeedBytes ||
len(seed) > hdkeychain.MaxSeedBytes {
return nil, hdkeychain.ErrInvalidSeedLen
}
// Derive the master extended key from the seed.
rootKey, err = hdkeychain.NewMaster(seed, l.chainParams)
if err != nil {
return nil, fmt.Errorf("failed to derive master " +
"extended key")
}
}
return l.createNewWallet(passphrase, rootKey, bday)
}
// CreateNewWalletExtendedKey creates a new wallet from an extended master root
// key using the provided passphrase. The root key is optional.
// If non-nil, addresses are derived from this root key. If nil, a
// secure random seed is generated and the root key is derived from that.
func (l *Loader) CreateNewWalletExtendedKey(passphrase []byte,
rootKey *hdkeychain.ExtendedKey, bday time.Time) (*Wallet, error) {
return l.createNewWallet(passphrase, rootKey, bday)
}
func (l *Loader) createNewWallet(passphrase []byte,
rootKey *hdkeychain.ExtendedKey, bday time.Time) (*Wallet, error) {
defer l.mu.Unlock()
l.mu.Lock()
@@ -107,8 +189,7 @@ func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte,
return nil, ErrLoaded
}
dbPath := filepath.Join(l.dbDirPath, walletDbName)
exists, err := fileExists(dbPath)
exists, err := l.WalletExists()
if err != nil {
return nil, err
}
@@ -116,46 +197,47 @@ func (l *Loader) CreateNewWallet(pubPassphrase, privPassphrase, seed []byte,
return nil, ErrExists
}
// Create the wallet database backed by bolt db.
err = os.MkdirAll(l.dbDirPath, 0700)
if err != nil {
return nil, err
}
db, err := walletdb.Create("bdb", dbPath, l.noFreelistSync)
if err != nil {
return nil, err
if l.localDB {
dbPath := filepath.Join(l.dbDirPath, WalletDBName)
// Create the wallet database backed by bolt db.
err = os.MkdirAll(l.dbDirPath, 0700)
if err != nil {
return nil, err
}
l.db, err = walletdb.Create(
"bdb", dbPath, l.noFreelistSync, l.timeout,
)
if err != nil {
return nil, err
}
}
// Initialize the newly created database for the wallet before opening.
err = Create(
db, pubPassphrase, privPassphrase, seed, l.chainParams, bday,
err = CreateWithCallback(l.db, passphrase, rootKey, l.chainParams,
bday, l.walletCreated,
)
if err != nil {
return nil, err
}
// Open the newly-created wallet.
w, err := Open(db, pubPassphrase, nil, l.chainParams, l.recoveryWindow)
w, err := Open(l.db, l.chainParams, l.recoveryWindow)
if err != nil {
return nil, err
}
w.Start()
l.onLoaded(w, db)
l.onLoaded(w)
return w, nil
}
var errNoConsole = errors.New("db upgrade requires console access for additional input")
func noConsole() ([]byte, error) {
return nil, errNoConsole
}
// OpenExistingWallet opens the wallet from the loader's wallet database path
// and the public passphrase. If the loader is being called by a context where
// standard input prompts may be used during wallet upgrades, setting
// canConsolePrompt will enables these prompts.
func (l *Loader) OpenExistingWallet(pubPassphrase []byte, canConsolePrompt bool) (*Wallet, error) {
// OpenExistingWallet opens the wallet from the loader's wallet database path.
// If the loader is being called by a context where standard input prompts may
// be used during wallet upgrades, setting canConsolePrompt will enables these prompts.
func (l *Loader) OpenExistingWallet() (*Wallet, error) {
defer l.mu.Unlock()
l.mu.Lock()
@@ -163,53 +245,53 @@ func (l *Loader) OpenExistingWallet(pubPassphrase []byte, canConsolePrompt bool)
return nil, ErrLoaded
}
// Ensure that the network directory exists.
if err := checkCreateDir(l.dbDirPath); err != nil {
return nil, err
}
// Open the database using the boltdb backend.
dbPath := filepath.Join(l.dbDirPath, walletDbName)
db, err := walletdb.Open("bdb", dbPath, l.noFreelistSync)
if err != nil {
log.Errorf("Failed to open database: %v", err)
return nil, err
}
var cbs *waddrmgr.OpenCallbacks
if canConsolePrompt {
cbs = &waddrmgr.OpenCallbacks{
ObtainSeed: prompt.ProvideSeed,
ObtainPrivatePass: prompt.ProvidePrivPassphrase,
if l.localDB {
var err error
// Ensure that the network directory exists.
if err = checkCreateDir(l.dbDirPath); err != nil {
return nil, err
}
} else {
cbs = &waddrmgr.OpenCallbacks{
ObtainSeed: noConsole,
ObtainPrivatePass: noConsole,
// Open the database using the boltdb backend.
dbPath := filepath.Join(l.dbDirPath, WalletDBName)
l.db, err = walletdb.Open(
"bdb", dbPath, l.noFreelistSync, l.timeout,
)
if err != nil {
log.Errorf("Failed to open database: %v", err)
return nil, err
}
}
w, err := Open(db, pubPassphrase, cbs, l.chainParams, l.recoveryWindow)
w, err := Open(l.db, l.chainParams, l.recoveryWindow)
if err != nil {
// If opening the wallet fails (e.g. because of wrong
// passphrase), we must close the backing database to
// allow future calls to walletdb.Open().
e := db.Close()
if e != nil {
log.Warnf("Error closing database: %v", e)
if l.localDB {
e := l.db.Close()
if e != nil {
log.Warnf("Error closing database: %v", e)
}
}
return nil, err
}
w.Start()
l.onLoaded(w, db)
l.onLoaded(w)
return w, nil
}
// WalletExists returns whether a file exists at the loader's database path.
// This may return an error for unexpected I/O failures.
func (l *Loader) WalletExists() (bool, error) {
dbPath := filepath.Join(l.dbDirPath, walletDbName)
return fileExists(dbPath)
if l.localDB {
dbPath := filepath.Join(l.dbDirPath, WalletDBName)
return fileExists(dbPath)
}
return l.walletExists()
}
// LoadedWallet returns the loaded wallet, if any, and a bool for whether the
@@ -236,9 +318,11 @@ func (l *Loader) UnloadWallet() error {
l.wallet.Stop()
l.wallet.WaitForShutdown()
err := l.db.Close()
if err != nil {
return err
if l.localDB {
err := l.db.Close()
if err != nil {
return err
}
}
l.wallet = nil
+3 -20
View File
@@ -6,9 +6,9 @@ package wallet
import (
"github.com/btcsuite/btclog"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/walletdb/migration"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/walletdb/migration"
"github.com/lbryio/lbcwallet/wtxmgr"
)
// log is a logger that is initialized with no output filters. This
@@ -38,23 +38,6 @@ func UseLogger(logger btclog.Logger) {
wtxmgr.UseLogger(logger)
}
// LogClosure is a closure that can be printed with %v to be used to
// generate expensive-to-create data for a detailed log level and avoid doing
// the work if the data isn't printed.
type logClosure func() string
// String invokes the log closure and returns the results string.
func (c logClosure) String() string {
return c()
}
// newLogClosure returns a new closure over the passed function which allows
// it to be used as a parameter in a logging function that is only invoked when
// the logging level is such that the message will actually be logged.
func newLogClosure(c func() string) logClosure {
return logClosure(c)
}
// pickNoun returns the singular or plural form of a noun depending
// on the count n.
func pickNoun(n int, singular, plural string) string {
+5 -5
View File
@@ -3,11 +3,11 @@ package wallet
import (
"time"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/chain"
"github.com/lbryio/lbcwallet/waddrmgr"
)
type mockChainClient struct {
+5 -5
View File
@@ -8,10 +8,10 @@ package wallet
import (
"errors"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lbryio/lbcd/txscript"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/walletdb"
)
// MakeMultiSigScript creates a multi-signature script that can be redeemed with
@@ -27,7 +27,7 @@ func (w *Wallet) MakeMultiSigScript(addrs []btcutil.Address, nRequired int) ([]b
var addrmgrNs walletdb.ReadBucket
defer func() {
if dbtx != nil {
dbtx.Rollback()
_ = dbtx.Rollback()
}
}()
+11 -31
View File
@@ -8,13 +8,12 @@ import (
"bytes"
"sync"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/txscript"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/walletdb"
"github.com/lbryio/lbcwallet/wtxmgr"
)
// TODO: It would be good to send errors during notification creation to the rpc
@@ -90,7 +89,7 @@ func lookupOutputChain(dbtx walletdb.ReadTx, w *Wallet, details *wtxmgr.TxDetail
if err != nil {
log.Errorf("Cannot fetch account for wallet output: %v", err)
} else {
account = ma.Account()
account = ma.InternalAccount()
internal = ma.Internal()
}
return
@@ -148,6 +147,7 @@ func makeTxSummary(dbtx walletdb.ReadTx, w *Wallet, details *wtxmgr.TxDetails) T
MyOutputs: outputs,
Fee: fee,
Timestamp: details.Received.Unix(),
Label: details.Label,
}
}
@@ -183,7 +183,7 @@ func flattenBalanceMap(m map[uint32]btcutil.Amount) []AccountBalance {
return s
}
func relevantAccounts(w *Wallet, m map[uint32]btcutil.Amount, txs []TransactionSummary) {
func relevantAccounts(_ *Wallet, m map[uint32]btcutil.Amount, txs []TransactionSummary) {
for _, tx := range txs {
for _, d := range tx.MyInputs {
m[d.PreviousAccount] = 0
@@ -254,7 +254,7 @@ func (s *NotificationServer) notifyMinedTransaction(dbtx walletdb.ReadTx, detail
}
txs := s.currentTxNtfn.AttachedBlocks[n-1].Transactions
s.currentTxNtfn.AttachedBlocks[n-1].Transactions =
append(txs, makeTxSummary(dbtx, s.wallet, details))
append(txs, makeTxSummary(dbtx, s.wallet, details)) // nolint:gocritic
}
func (s *NotificationServer) notifyAttachedBlock(dbtx walletdb.ReadTx, block *wtxmgr.BlockMeta) {
@@ -365,6 +365,7 @@ type TransactionSummary struct {
MyOutputs []TransactionSummaryOutput
Fee btcutil.Amount
Timestamp int64
Label string
}
// TransactionSummaryInput describes a transaction input that is relevant to the
@@ -491,27 +492,6 @@ func (s *NotificationServer) notifyUnspentOutput(account uint32, hash *chainhash
}
}
// notifySpentOutput notifies registered clients that a previously-unspent
// output is now spent, and includes the spender hash and input index in the
// notification.
func (s *NotificationServer) notifySpentOutput(account uint32, op *wire.OutPoint, spenderHash *chainhash.Hash, spenderIndex uint32) {
defer s.mu.Unlock()
s.mu.Lock()
clients := s.spentness[account]
if len(clients) == 0 {
return
}
n := &SpentnessNotifications{
hash: &op.Hash,
index: op.Index,
spenderHash: spenderHash,
spenderIndex: spenderIndex,
}
for _, c := range clients {
c <- n
}
}
// SpentnessNotificationsClient receives SpentnessNotifications from the
// NotificationServer over the channel C.
type SpentnessNotificationsClient struct {
+387
View File
@@ -0,0 +1,387 @@
// Copyright (c) 2020 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wallet
import (
"bytes"
"fmt"
"github.com/lbryio/lbcd/txscript"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcutil/psbt"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/wallet/txauthor"
"github.com/lbryio/lbcwallet/wallet/txrules"
"github.com/lbryio/lbcwallet/walletdb"
"github.com/lbryio/lbcwallet/wtxmgr"
)
// FundPsbt creates a fully populated PSBT packet that contains enough inputs to
// fund the outputs specified in the passed in packet with the specified fee
// rate. If there is change left, a change output from the wallet is added and
// the index of the change output is returned. Otherwise no additional output
// is created and the index -1 is returned.
//
// NOTE: If the packet doesn't contain any inputs, coin selection is performed
// automatically, only selecting inputs from the account based on the given key
// scope and account number. If a key scope is not specified, then inputs from
// accounts matching the account number provided across all key scopes may be
// selected. This is done to handle the default account case, where a user wants
// to fund a PSBT with inputs regardless of their type (NP2WKH, P2WKH, etc.). If
// the packet does contain any inputs, it is assumed that full coin selection
// happened externally and no additional inputs are added. If the specified
// inputs aren't enough to fund the outputs with the given fee rate, an error is
// returned.
//
// NOTE: A caller of the method should hold the global coin selection lock of
// the wallet. However, no UTXO specific lock lease is acquired for any of the
// selected/validated inputs by this method. It is in the caller's
// responsibility to lock the inputs before handing the partial transaction out.
func (w *Wallet) FundPsbt(packet *psbt.Packet, keyScope *waddrmgr.KeyScope,
minConfs int32, account uint32, feeSatPerKB btcutil.Amount,
coinSelectionStrategy CoinSelectionStrategy) (int32, error) {
// Make sure the packet is well formed. We only require there to be at
// least one input or output.
err := psbt.VerifyInputOutputLen(packet, false, false)
if err != nil {
return 0, err
}
if len(packet.UnsignedTx.TxIn) == 0 && len(packet.UnsignedTx.TxOut) == 0 {
return 0, fmt.Errorf("PSBT packet must contain at least one " +
"input or output")
}
txOut := packet.UnsignedTx.TxOut
txIn := packet.UnsignedTx.TxIn
// Make sure none of the outputs are dust.
for _, output := range txOut {
// When checking an output for things like dusty-ness, we'll
// use the default mempool relay fee rather than the target
// effective fee rate to ensure accuracy. Otherwise, we may
// mistakenly mark small-ish, but not quite dust output as
// dust.
err := txrules.CheckOutput(output, txrules.DefaultRelayFeePerKb)
if err != nil {
return 0, err
}
}
// Let's find out the amount to fund first.
amt := int64(0)
for _, output := range txOut {
amt += output.Value
}
// addInputInfo is a helper function that fetches the UTXO information
// of an input and attaches it to the PSBT packet.
addInputInfo := func(inputs []*wire.TxIn) error {
packet.Inputs = make([]psbt.PInput, len(inputs))
for idx, in := range inputs {
tx, utxo, derivationPath, _, err := w.FetchInputInfo(
&in.PreviousOutPoint,
)
if err != nil {
return fmt.Errorf("error fetching UTXO: %v",
err)
}
// As a fix for CVE-2020-14199 we have to always include
// the full non-witness UTXO in the PSBT for segwit v0.
packet.Inputs[idx].NonWitnessUtxo = tx
// To make it more obvious that this is actually a
// witness output being spent, we also add the same
// information as the witness UTXO.
packet.Inputs[idx].WitnessUtxo = &wire.TxOut{
Value: utxo.Value,
PkScript: utxo.PkScript,
}
packet.Inputs[idx].SighashType = txscript.SigHashAll
// Include the derivation path for each input.
packet.Inputs[idx].Bip32Derivation = []*psbt.Bip32Derivation{
derivationPath,
}
// We don't want to include the witness or any script
// on the unsigned TX just yet.
packet.UnsignedTx.TxIn[idx].Witness = wire.TxWitness{}
packet.UnsignedTx.TxIn[idx].SignatureScript = nil
// For nested P2WKH we need to add the redeem script to
// the input, otherwise an offline wallet won't be able
// to sign for it. For normal P2WKH this will be nil.
addr, witnessProgram, _, err := w.ScriptForOutput(utxo)
if err != nil {
return fmt.Errorf("error fetching UTXO "+
"script: %v", err)
}
if addr.AddrType() == waddrmgr.NestedWitnessPubKey {
packet.Inputs[idx].RedeemScript = witnessProgram
}
}
return nil
}
var tx *txauthor.AuthoredTx
switch {
// We need to do coin selection.
case len(txIn) == 0:
// We ask the underlying wallet to fund a TX for us. This
// includes everything we need, specifically fee estimation and
// change address creation.
tx, err = w.CreateSimpleTx(
keyScope, account, packet.UnsignedTx.TxOut, minConfs,
feeSatPerKB, coinSelectionStrategy, false,
)
if err != nil {
return 0, fmt.Errorf("error creating funding TX: %v",
err)
}
// Copy over the inputs now then collect all UTXO information
// that we can and attach them to the PSBT as well. We don't
// include the witness as the resulting PSBT isn't expected not
// should be signed yet.
packet.UnsignedTx.TxIn = tx.Tx.TxIn
err = addInputInfo(tx.Tx.TxIn)
if err != nil {
return 0, err
}
// If there are inputs, we need to check if they're sufficient and add
// a change output if necessary.
default:
// Make sure all inputs provided are actually ours.
err = addInputInfo(txIn)
if err != nil {
return 0, err
}
// We can leverage the fee calculation of the txauthor package
// if we provide the selected UTXOs as a coin source. We just
// need to make sure we always return the full list of user-
// selected UTXOs rather than a subset, otherwise our change
// amount will be off (in case the user selected multiple UTXOs
// that are large enough on their own). That's why we use our
// own static input source creator instead of the more generic
// makeInputSource() that selects a subset that is "large
// enough".
credits := make([]wtxmgr.Credit, len(txIn))
for idx, in := range txIn {
utxo := packet.Inputs[idx].WitnessUtxo
credits[idx] = wtxmgr.Credit{
OutPoint: in.PreviousOutPoint,
Amount: btcutil.Amount(utxo.Value),
PkScript: utxo.PkScript,
}
}
inputSource := constantInputSource(credits)
// We also need a change source which needs to be able to insert
// a new change address into the database.
err = walletdb.Update(w.db, func(dbtx walletdb.ReadWriteTx) error {
_, changeSource, err := w.addrMgrWithChangeSource(
dbtx, keyScope, account,
)
if err != nil {
return err
}
// Ask the txauthor to create a transaction with our
// selected coins. This will perform fee estimation and
// add a change output if necessary.
tx, err = txauthor.NewUnsignedTransaction(
txOut, feeSatPerKB, inputSource, changeSource,
)
if err != nil {
return fmt.Errorf("fee estimation not "+
"successful: %v", err)
}
return nil
})
if err != nil {
return 0, fmt.Errorf("could not add change address to "+
"database: %v", err)
}
}
// If there is a change output, we need to copy it over to the PSBT now.
var changeTxOut *wire.TxOut
if tx.ChangeIndex >= 0 {
changeTxOut = tx.Tx.TxOut[tx.ChangeIndex]
packet.UnsignedTx.TxOut = append(
packet.UnsignedTx.TxOut, changeTxOut,
)
packet.Outputs = append(packet.Outputs, psbt.POutput{})
}
// Now that we have the final PSBT ready, we can sort it according to
// BIP 69. This will sort the wire inputs and outputs and move the
// partial inputs and outputs accordingly.
err = psbt.InPlaceSort(packet)
if err != nil {
return 0, fmt.Errorf("could not sort PSBT: %v", err)
}
// The change output index might have changed after the sorting. We need
// to find our index again.
changeIndex := int32(-1)
if changeTxOut != nil {
for idx, txOut := range packet.UnsignedTx.TxOut {
if psbt.TxOutsEqual(changeTxOut, txOut) {
changeIndex = int32(idx)
break
}
}
}
return changeIndex, nil
}
// FinalizePsbt expects a partial transaction with all inputs and outputs fully
// declared and tries to sign all inputs that belong to the wallet. Our wallet
// must be the last signer of the transaction. That means, if there are any
// unsigned non-witness inputs or inputs without UTXO information attached or
// inputs without witness data that do not belong to the wallet, this method
// will fail. If no error is returned, the PSBT is ready to be extracted and the
// final TX within to be broadcast.
//
// NOTE: This method does NOT publish the transaction after it's been finalized
// successfully.
func (w *Wallet) FinalizePsbt(keyScope *waddrmgr.KeyScope, account uint32,
packet *psbt.Packet) error {
// Let's check that this is actually something we can and want to sign.
// We need at least one input and one output.
err := psbt.VerifyInputOutputLen(packet, true, true)
if err != nil {
return err
}
// Go through each input that doesn't have final witness data attached
// to it already and try to sign it. We do expect that we're the last
// ones to sign. If there is any input without witness data that we
// cannot sign because it's not our UTXO, this will be a hard failure.
tx := packet.UnsignedTx
sigHashes := txscript.NewTxSigHashes(tx)
for idx, txIn := range tx.TxIn {
in := packet.Inputs[idx]
// We can only sign if we have UTXO information available. We
// can just continue here as a later step will fail with a more
// precise error message.
if in.WitnessUtxo == nil && in.NonWitnessUtxo == nil {
continue
}
// Skip this input if it's got final witness data attached.
if len(in.FinalScriptWitness) > 0 {
continue
}
// We can only sign this input if it's ours, so we try to map it
// to a coin we own. If we can't, then we'll continue as it
// isn't our input.
fullTx, txOut, _, _, err := w.FetchInputInfo(
&txIn.PreviousOutPoint,
)
if err != nil {
continue
}
// Find out what UTXO we are signing. Wallets _should_ always
// provide the full non-witness UTXO for segwit v0.
var signOutput *wire.TxOut
if in.NonWitnessUtxo != nil {
prevIndex := txIn.PreviousOutPoint.Index
signOutput = in.NonWitnessUtxo.TxOut[prevIndex]
if !psbt.TxOutsEqual(txOut, signOutput) {
return fmt.Errorf("found UTXO %#v but it "+
"doesn't match PSBT's input %v", txOut,
signOutput)
}
if fullTx.TxHash() != txIn.PreviousOutPoint.Hash {
return fmt.Errorf("found UTXO tx %v but it "+
"doesn't match PSBT's input %v",
fullTx.TxHash(),
txIn.PreviousOutPoint.Hash)
}
}
// Fall back to witness UTXO only for older wallets.
if in.WitnessUtxo != nil {
signOutput = in.WitnessUtxo
if !psbt.TxOutsEqual(txOut, signOutput) {
return fmt.Errorf("found UTXO %#v but it "+
"doesn't match PSBT's input %v", txOut,
signOutput)
}
}
witness, sigScript, err := w.ComputeInputScript(
tx, signOutput, idx, sigHashes, in.SighashType, nil,
)
if err != nil {
return fmt.Errorf("error computing input script for "+
"input %d: %v", idx, err)
}
// Serialize the witness format from the stack representation to
// the wire representation.
var witnessBytes bytes.Buffer
err = psbt.WriteTxWitness(&witnessBytes, witness)
if err != nil {
return fmt.Errorf("error serializing witness: %v", err)
}
packet.Inputs[idx].FinalScriptWitness = witnessBytes.Bytes()
packet.Inputs[idx].FinalScriptSig = sigScript
}
// Make sure the PSBT itself thinks it's finalized and ready to be
// broadcast.
err = psbt.MaybeFinalizeAll(packet)
if err != nil {
return fmt.Errorf("error finalizing PSBT: %v", err)
}
return nil
}
// constantInputSource creates an input source function that always returns the
// static set of user-selected UTXOs.
func constantInputSource(eligible []wtxmgr.Credit) txauthor.InputSource {
// Current inputs and their total value. These won't change over
// different invocations as we want our inputs to remain static since
// they're selected by the user.
currentTotal := btcutil.Amount(0)
currentInputs := make([]*wire.TxIn, 0, len(eligible))
currentScripts := make([][]byte, 0, len(eligible))
currentInputValues := make([]btcutil.Amount, 0, len(eligible))
for _, credit := range eligible {
nextInput := wire.NewTxIn(&credit.OutPoint, nil, nil)
currentTotal += credit.Amount
currentInputs = append(currentInputs, nextInput)
currentScripts = append(currentScripts, credit.PkScript)
currentInputValues = append(currentInputValues, credit.Amount)
}
return func(target btcutil.Amount) (btcutil.Amount, []*wire.TxIn,
[]btcutil.Amount, [][]byte, error) {
return currentTotal, currentInputs, currentInputValues,
currentScripts, nil
}
}
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more