Compare commits

..

29 commits

Author SHA1 Message Date
Roy Lee
cc677ca0c4 go mod: update lbcd version to include rpc commend updates 2022-09-26 22:59:20 -07:00
Roy Lee
ea76f8ce04 multi-scope: update rpc help messages 2022-09-26 11:37:19 -07:00
Roy Lee
4c3f869601 multi-scope: update listaddresstransactions 2022-09-26 11:37:19 -07:00
Roy Lee
a0ecaaa6ee multi-scope: update listsinceblock 2022-09-26 11:37:19 -07:00
Roy Lee
e9159692fb multi-scope: update listalltransactions 2022-09-26 11:37:19 -07:00
Roy Lee
368379d124 multi-scope: update listtransactions 2022-09-26 11:37:19 -07:00
Roy Lee
a49937ac1b multi-scope: update listreceivedbyaddress 2022-09-26 11:37:19 -07:00
Roy Lee
6de6d27f95 multi-scope: update listreceivedbyaccount 2022-09-26 11:37:19 -07:00
Roy Lee
2da50a5e5d multi-scope: update sendtoaddress 2022-09-26 11:37:19 -07:00
Roy Lee
089543f805 multi-scope: update gettransaction 2022-09-26 11:37:19 -07:00
Roy Lee
6a5f65c983 multi-scope: update validateaddress 2022-09-26 11:37:19 -07:00
Roy Lee
b1d25b1c6a multi-scope: update getreceivedbyaccount 2022-09-26 11:37:19 -07:00
Roy Lee
ffd0e0f795 multi-scope: update listaccounts 2022-09-26 11:37:19 -07:00
Roy Lee
8ea43ba508 multi-scope: update sendfrom 2022-09-26 11:37:19 -07:00
Roy Lee
98007d2294 multi-scope: update sendmany 2022-09-26 11:37:19 -07:00
Roy Lee
a5491097ed multi-scope: update getrawchangeaddress 2022-09-26 11:37:19 -07:00
Roy Lee
78584be07e multi-scope: update renameaccount 2022-09-26 11:37:19 -07:00
Roy Lee
b888268cf2 multi-scope: update createNewAccount 2022-09-26 11:37:19 -07:00
Roy Lee
2158c41028 multi-scope: update getunconfirmedbalance 2022-09-26 11:37:19 -07:00
Roy Lee
028f4a7c83 multi-scope: update getaccount 2022-09-26 11:37:19 -07:00
Roy Lee
d54e539700 multi-scope: update getbalance 2022-09-26 11:37:19 -07:00
Roy Lee
8cadd74e47 multi-scope: update getaccountaddress 2022-09-26 11:37:19 -07:00
Roy Lee
743c2fc5c4 multi-scope: update getaddressbyaccount 2022-09-26 11:37:19 -07:00
Roy Lee
64d217712a multi-scope: update getnewaddress 2022-09-26 11:37:19 -07:00
Roy Lee
d5ed29d234 multi-scope: set DefaultScope to KeyScopeBIP0044
By design, all scopes shared the same account name/number space.
2022-09-26 11:37:19 -07:00
Roy Lee
49cb544b54 multi-scope: update sendPairs to take keyscope pointer 2022-09-26 11:37:19 -07:00
Roy Lee
b4fd3e710f multi-scope: add forEachKeyScope uitility iterator 2022-09-26 11:37:19 -07:00
Roy Lee
cd179e0516 multi-account: support BIP44 account discovery 2022-09-26 11:36:25 -07:00
Roy Lee
b774170afd consolidate: merge internal/external branches 2022-09-26 11:36:14 -07:00
36 changed files with 2305 additions and 411 deletions

527
CHANGES Normal file
View file

@ -0,0 +1,527 @@
============================================================================
User visible changes for lbcwallet
A wallet daemon for lbcd, written in Go
============================================================================
Changes in 0.7.0 (Mon Nov 23 2015)
- New features:
- Wallet will now detect network inactivity and reconnect to the lbcd
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 lbcutil.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
lbcd (#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 lbcwallet
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
lbcd 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 lbcd (#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 lbcsuite 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 lbcjson 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 lbcjson 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 lbcd 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 lbcd 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 lbcd 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 lbcd (#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 lbcd 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 lbcd
- 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 lbcd 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 lbcd 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 lbcjson 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 lbcd
- 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. ~/.lbcwallet/logs/testnet3) to match lbcd behavior (#114)
Changes in 0.4.0 (Sun May 25 2014)
- Implement the following standard bitcoin server RPC requests:
- signmessage (https://github.com/lbryio/lbcwallet/issues/58)
- verifymessage (https://github.com/lbryio/lbcwallet/issues/61)
- listunspent (https://github.com/lbryio/lbcwallet/issues/54)
- validateaddress (https://github.com/lbryio/lbcwallet/issues/60)
- addressmultisig (https://github.com/lbryio/lbcwallet/issues/37)
- createmultisig (https://github.com/lbryio/lbcwallet/issues/37)
- signrawtransaction (https://github.com/lbryio/lbcwallet/issues/59)
- Add authenticate extension RPC request to authenticate a websocket
session without requiring the use of the HTTP Authorization header
- Add lbcdusername and lbcdpassword options to allow separate
authentication credentials from wallet clients when authenticating to a
lbcd websocket RPC server
- Fix RPC response passthrough: JSON unmarshaling and marshaling is now
delayed until necessary and JSON result objects from lbcd 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/lbryio/lbcwallet/issues/74)
- Fix listsinceblock request handler to consider the minimum confirmation
parameter (https://github.com/lbryio/lbcwallet/issues/80)
- Fix several RPC handlers which require an unlocked wallet to check
for an unlocked wallet before continuing
(https://github.com/lbryio/lbcwallet/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, lbcd disconnects, etc.) a new rescan can start at the last
synced chain height
- Notify (with an unsolicited notification) websocket clients of lbcd
connection state
- Improve logging:
- Log reason for disconnecting a websocket client
- Updates for lbcd 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 lbcwallet implementations)
- Change websocket endpoint to connect to lbcd 0.6.0-alpha
- Redo server implementation to serialize handling of client requests
- Redo account locking to greatly reduce lbcwallet 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/lbryio/lbcwallet/issues/63)
- getrawchangeaddress (https://github.com/lbryio/lbcwallet/issues/41)
- getreceivedbyaccount (https://github.com/lbryio/lbcwallet/issues/42)
- gettransaction (https://github.com/lbryio/lbcwallet/issues/44)
- keypoolrefill (https://github.com/lbryio/lbcwallet/issues/48)
- listsinceblock (https://github.com/lbryio/lbcwallet/issues/52)
- sendtoaddress (https://github.com/lbryio/lbcwallet/issues/56)
- Add empty (unimplemented) handlers for the following RPC requests so
requests are not passed down to lbcd:
- 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 lbcwallet 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/lbryio/lbcwallet/issues/64)
- Rescan imported private keys in background
(https://github.com/lbryio/lbcwallet/issues/34)
- Do not import duplicate private keys
(https://github.com/lbryio/lbcwallet/issues/35)
- Write all three account files for a new account, rather than just
the wallet (https://github.com/lbryio/lbcwallet/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 lbcwallet 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 lbcd connections. Instead, add a --connect
option to specify the hostname or address and port of a local or
remote lbcd instance
(https://github.com/lbryio/lbcwallet/issues/1)
- Remove --serverport port and replace with --listen. This option works
just like lbcd'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 lbcd performs blockchain
reorganizations while lbcwallet was disconnected
- Add support for the following standard bitcoin JSON-RPC calls:
- dumpprivkey (https://github.com/lbryio/lbcwallet/issues/9)
- getaccount
- getaccountaddress
- importprivkey (https://github.com/lbryio/lbcwallet/issues/2)
- listtransactions (https://github.com/lbryio/lbcwallet/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/lbryio/lbcwallet/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/lbryio/lbcwallet/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/lbryio/lbcwallet/issues/20)
- Move account files to a single directory per bitcoin network to
prevent a future scaling issue
(https://github.com/lbryio/lbcwallet/issues/16)
- Fix several data races and mutex mishandling
- Fix a bug where the RPC server hung on requests requiring lbcd
when a lbcd connection was never established
- Fix a bug where creating account files did not create all necessary
directories (https://github.com/lbryio/lbcwallet/issues/15)
- Fix a bug where '~' did not expand to a home or user directory
(https://github.com/lbryio/lbcwallet/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

180
README.md
View file

@ -1,18 +1,66 @@
# lbcwallet
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).
lbcwallet is a daemon, which provides lbry wallet functionality for a
single user.
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.
lbcwallet 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).
Due to the sensitive nature of public data in a BIP0032 wallet,
lbcwallet 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.
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 lbcwallet, 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).
## Security
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.
## Build from Source Code
## Requirements
Requires [Go](http://golang.org) 1.19 or newer. Install Go according to its [installation instructions](http://golang.org/doc/install).
- [Go](http://golang.org) 1.16 or newer.
- `lbcwallet` is not an SPV client and requires connecting to a local or remote
`lbcd` for asynchronous blockchain queries and notifications over websockets.
Full installation instructions can be found [here](https://github.com/lbryio/lbcd).
## To Build lbcwallet, lbcd, and lbcctl from Source
Install Go according to its [installation instructions](http://golang.org/doc/install).
Build `lbcwallet`
``` sh
git clone https://github.com/lbryio/lbcwallet
@ -20,62 +68,114 @@ cd lbcwallet
go build .
```
## **lbcd** & **lbcwallet**
To make the quick start guide self-contained, here's how we can build the `lbcd` and `lbcctl`
`lbcwallet` is not an SPV client and requires connecting to a `lbcd` node for asynchronous blockchain queries and notifications over websockets.
``` sh
git clone https://github.com/lbryio/lbcd
cd lbcd
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.
# build lbcd
go build .
``` mermaid
sequenceDiagram
actor C as lbcctl
participant W as lbcwallet (port: 9244)
participant D as lbcd (port: 9245)
rect rgb(200,200,200)
Note over C,W: lbcctl --wallet balance
C ->>+ W: getbalance
W -->>- C: response
end
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
# build lbcctl
go build ./cmd/lbcctl
```
## Getting Started
Create a new wallet with a randomly generated seed or an existing one.
The first time running the `lbcwallet` we need to create a new wallet.
``` sh
lbcwallet --create
Do you have an existing wallet seed you want to use? (n/no/y/yes) [no]: no
Your wallet generation seed is: 3d005498ad5e9b7439b857249e328ec34e21845b7d1a7d2a5641d4050c02d0da
./lbcwallet --create
```
The created wallet protects the seed with a default passphrase (`"passphrase"`), which can be override with `-p` option:
Start a local instance of `lbcd` and have the `lbcwallet` connecting to it.
``` sh
lbcwallet --create -p my-passphrase
# Start a lbcd with its RPC credentials
./lbcd --txindex --rpcuser=lbcduser --rpcpass=lbcdpass
# Start a lbcwallet with its RPC credentials along with the lbcd's RPC credentials
# The default lbcd instance to conect to is already localhost:9245 so we don't need to specify it explicitly here.
./lbcwallet --username=rpcuser --password=rpcpass --lbcdusername=lbcduser --lbcdpassword=lbcdpass # --rpcconnect=localhost:9245
#
# rpcuser/rpcpass lbcduser/lbcdpass
# lbcctl <-------------------> lbcwallet <--------------------> lbcd
# RPC port 9244 RPC port 9245
#
```
Start wallet server, and connect it to a lbcd instance.
If the `lbcd` and `lbcwallet` use the same RPC credentials, we can skip the `--lbcdusername` and `--lbcdpassword`
``` sh
lbcwallet --rpcuser=rpcuser --rpcpass=rpcpass # --rpcconnect=localhost:9245
./lbcd --txindex --rpcuser=rpcuser --rpcpass=rpcpass
./lbcwallet --username=rpcuser --password=rpcpass
#
# rpcuser/rpcpass rpcuser/rpcpass
# lbcctl <-------------------> lbcwallet <--------------------> lbcd
# RPC port 9244 RPC port 9245
#
```
At startup, the wallet will try to unlock itself with the default passphrase (`passphrase`) or an user provided one (using `-p` option).
Note:
If the passphrase does not match, the wallet remains locked. User can lock/unlock the wallet using `walletlock` and `walletpassphrase` RPCs.
- `lbcd` and `lbcwallet` implements two disjoint sets of RPCs.
- `lbcd` serves RPC on port 9245 while `lbcwallet` on port 9244.
- `lbcwallet` can proxy non-wallet RPCs to its associated `lbcd`.
Examples of using `lbcctl` to interact with the setup via RPCs:
1. Calling non-wallet RPC directly on lbcd:
``` sh
./lbcctl --rpcuser=rpcuser --rpcpass=rpcpass getblockcount
#
# lbcctl <-- getblockcount() --> lbcd
# RPC port 9245 (handled)
#
```
2. Calling wallet RPC on lbcwallet (using `--wallet`)
``` sh
./lbcctl --rpcuser=rpcuser --rpcpass=rpcpass --wallet getbalance
#
# lbcctl <-- getbalance() --> lbcwallet
# RPC port 9244 (handled)
#
```
3. Calling non-wallet RPC on lbcwallet, which proxies it to lbcd:
``` sh
./lbcctl --rpcuser=rpcuser --rpcpass=rpcpass --wallet getblockcount
#
# lbcctl <-- getblockcount() --> lbcwallet <-- getblockcount() --> lbcd
# RPC port 9244 (proxied) RPC port 9245
#
```
## Default Network and RPC Ports
| Instance | mainnet | testet | regtest |
| ------------- | ------- | ------ | ------- |
| lbcd Network | 9246 | 19246 | 29246 |
| lbcd RPC | 9245 | 19245 | 29245 |
| lbcwallet RPC | 9244 | 19244 | 29244 |
Examples
``` sh
lbcwallet --rpcuser=rpcuser --rpcpass=rpcpass -p my_passphrase
./lbcctl getblockcount # port 9245
./lbcctl --wallet getblockcount # port 9244
./lbcctl --testnet getblockcount # port 19245
./lbcctl --wallet --regtest getblockcount # port 29244
```
## Contributing

View file

@ -282,7 +282,7 @@ func TestBlockFiltererOneInOneOut(t *testing.T) {
req := &chain.FilterBlocksRequest{
WatchedOutPoints: watchedOutPoints,
}
blockFilterer := chain.NewBlockFilterer(&chaincfg.RegressionNetParams, req)
blockFilterer := chain.NewBlockFilterer(&chaincfg.SimNetParams, req)
// Filter block 100000, which should find matches for the watched
// outpoints.

117
cmd/dropwtxmgr/main.go Normal file
View file

@ -0,0 +1,117 @@
// 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"
"time"
"github.com/jessevdk/go-flags"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/wallet"
"github.com/lbryio/lbcwallet/walletdb"
_ "github.com/lbryio/lbcwallet/walletdb/bdb"
)
const defaultNet = "mainnet"
var (
datadir = btcutil.AppDataDir("lbcwallet", false)
)
// Flags.
var opts = struct {
Force bool `short:"f" description:"Force removal without prompt"`
DbPath string `long:"db" description:"Path to wallet database"`
DropLabels bool `long:"droplabels" description:"Drop transaction labels"`
Timeout time.Duration `long:"timeout" description:"Timeout value when opening the wallet database"`
}{
Force: false,
DbPath: filepath.Join(datadir, defaultNet, wallet.WalletDBName),
Timeout: wallet.DefaultDBTimeout,
}
func init() {
_, err := flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
}
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 lbcwallet 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, opts.Timeout)
if err != nil {
fmt.Println("Failed to open database:", err)
return 1
}
defer db.Close()
fmt.Println("Dropping lbcwallet transaction history")
err = wallet.DropTransactionHistory(db, !opts.DropLabels)
if err != nil {
fmt.Println("Failed to drop and re-create namespace:", err)
return 1
}
return 0
}

368
cmd/sweepaccount/main.go Normal file
View file

@ -0,0 +1,368 @@
// 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/jessevdk/go-flags"
"github.com/lbryio/lbcd/btcjson"
"github.com/lbryio/lbcd/chaincfg/chainhash"
"github.com/lbryio/lbcd/rpcclient"
"github.com/lbryio/lbcd/txscript"
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/internal/cfgutil"
"github.com/lbryio/lbcwallet/netparams"
"github.com/lbryio/lbcwallet/wallet/txauthor"
"github.com/lbryio/lbcwallet/wallet/txrules"
"github.com/lbryio/lbcwallet/wallet/txsizes"
)
var (
walletDataDirectory = btcutil.AppDataDir("lbcwallet", 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"`
RegTest bool `long:"regtest" description:"Use the regression test 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,
RegTest: 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
} else if opts.RegTest {
activeNet = &netparams.RegTestParams
}
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 {
output := output
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 {
// GetNewAddress always returns a P2PKH address since it assumes
// BIP-0044.
newChangeScript := func() ([]byte, error) {
destinationAddress, err := rpcClient.GetNewAddress(accountName)
if err != nil {
return nil, err
}
return txscript.PayToAddrScript(destinationAddress)
}
return &txauthor.ChangeSource{
ScriptSize: txsizes.P2PKHPkScriptSize,
NewScript: newChangeScript,
}
}
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
}

171
config.go
View file

@ -5,6 +5,7 @@
package main
import (
"encoding/hex"
"fmt"
"net"
"os"
@ -16,6 +17,7 @@ import (
"time"
flags "github.com/jessevdk/go-flags"
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/version"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcwallet/internal/cfgutil"
@ -31,7 +33,6 @@ const (
defaultLogFilename = "lbcwallet.log"
defaultRPCMaxClients = 10
defaultRPCMaxWebsockets = 25
defaultPassphrase = "password"
)
var (
@ -45,40 +46,68 @@ 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 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."`
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)"`
SimNet bool `long:"simnet" description:"Use the simulation test network (default client port: 39244, server port: 39245)"`
SigNet bool `long:"signet" description:"Use the signet test network (default client port: 49244, server port: 49245)"`
SigNetChallenge string `long:"signetchallenge" description:"Connect to a custom signet network defined by this challenge instead of using the global default signet test network -- Can be specified multiple times"`
SigNetSeedNode []string `long:"signetseednode" description:"Specify a seed node for the signet network instead of using the global default signet network seed nodes"`
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"`
DBTimeout time.Duration `long:"dbtimeout" description:"The timeout value to use when opening the wallet database."`
// Passphrase options
Passphrase string `short:"p" long:"passphrase" default-mask:"-" description:"The wallet passphrase (default: \"passphrase\")"`
// Wallet options
WalletPass string `long:"walletpass" default-mask:"-" description:"The public wallet password -- Only required if the wallet was created with one"`
// RPC client options
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)"`
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 simnet: localhost:39245)"`
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"`
LbcdUsername string `long:"lbcdusername" description:"Username for lbcd authentication"`
LbcdPassword string `long:"lbcdpassword" default-mask:"-" description:"Password for lbcd authentication"`
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"`
LegacyRPCListeners []string `long:"rpclisten" description:"Listen for legacy RPC connections on this interface/port (default port: 9244, testnet: 19244, regtest: 29244)"`
LegacyRPCListeners []string `long:"rpclisten" description:"Listen for legacy RPC connections on this interface/port (default port: 9244, testnet: 19244, regtest: 29244, simnet: 29244)"`
LegacyRPCMaxClients int64 `long:"rpcmaxclients" description:"Max number of legacy RPC clients for standard connections"`
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"`
LegacyRPCMaxWebsockets int64 `long:"rpcmaxwebsockets" description:"Max number of legacy RPC websocket connections"`
Username string `short:"u" long:"username" description:"Username for legacy RPC and lbcd authentication (if lbcdusername is unset)"`
Password string `short:"P" long:"password" default-mask:"-" description:"Password for legacy RPC and lbcd authentication (if lbcdpassword 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"`
// Deprecated options
DataDir *cfgutil.ExplicitString `short:"b" long:"datadir" default-mask:"-" description:"DEPRECATED -- use appdata instead"`
@ -236,14 +265,17 @@ 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{},
DBTimeout: wallet.DefaultDBTimeout,
Passphrase: defaultPassphrase,
}
// Pre-parse the command line options to see if an alternative config
@ -336,8 +368,52 @@ func loadConfig() (*config, []string, error) {
activeNet = &netparams.RegTestParams
numNets++
}
if cfg.SimNet {
activeNet = &netparams.SimNetParams
numNets++
}
if cfg.SigNet {
activeNet = &netparams.SigNetParams
numNets++
// Let the user overwrite the default signet parameters. The
// challenge defines the actual signet network to join and the
// seed nodes are needed for network discovery.
sigNetChallenge := chaincfg.DefaultSignetChallenge
sigNetSeeds := chaincfg.DefaultSignetDNSSeeds
if cfg.SigNetChallenge != "" {
challenge, err := hex.DecodeString(cfg.SigNetChallenge)
if err != nil {
str := "%s: Invalid signet challenge, hex " +
"decode failed: %v"
err := fmt.Errorf(str, funcName, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
sigNetChallenge = challenge
}
if len(cfg.SigNetSeedNode) > 0 {
sigNetSeeds = make(
[]chaincfg.DNSSeed, len(cfg.SigNetSeedNode),
)
for idx, seed := range cfg.SigNetSeedNode {
sigNetSeeds[idx] = chaincfg.DNSSeed{
Host: seed,
HasFiltering: false,
}
}
}
chainParams := chaincfg.CustomSignetParams(
sigNetChallenge, sigNetSeeds,
)
activeNet.Params = &chainParams
}
if numNets > 1 {
str := "%s: more than one networks has been specified"
str := "%s: The testnet, signet and simnet params can't be " +
"used together -- choose one"
err := fmt.Errorf(str, "loadConfig")
fmt.Fprintln(os.Stderr, err)
parser.WriteHelp(os.Stderr)
@ -378,9 +454,9 @@ func loadConfig() (*config, []string, error) {
}
// 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"
// simnet, regtest or testnet3.
if !(cfg.Regtest || cfg.SimNet || cfg.TestNet3) {
errMsg += "for network other than simnet, regtest, or testnet3"
fmt.Fprintln(os.Stderr, errMsg)
os.Exit(0)
}
@ -503,7 +579,12 @@ func loadConfig() (*config, []string, error) {
}
}
if len(cfg.LegacyRPCListeners) == 0 {
// 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 {
addrs, err := net.LookupHost("localhost")
if err != nil {
return nil, nil, err
@ -524,9 +605,36 @@ 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
}
}
}
if cfg.DisableServerTLS {
for _, addr := range cfg.LegacyRPCListeners {
allListeners := append(cfg.LegacyRPCListeners,
cfg.ExperimentalRPCListeners...)
for _, addr := range allListeners {
_, _, err := net.SplitHostPort(addr)
if err != nil {
str := "%s: RPC listen interface '%s' is " +
@ -544,6 +652,17 @@ func loadConfig() (*config, []string, error) {
cfg.RPCCert.Value = cleanAndExpandPath(cfg.RPCCert.Value)
cfg.RPCKey.Value = cleanAndExpandPath(cfg.RPCKey.Value)
// If the lbcd username or password are unset, use the same auth as for
// the client. The two settings were previously shared for lbcd and
// client auth, so this avoids breaking backwards compatibility while
// allowing users to use different auth settings for lbcd and wallet.
if cfg.LbcdUsername == "" {
cfg.LbcdUsername = cfg.Username
}
if cfg.LbcdPassword == "" {
cfg.LbcdPassword = 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
deps.txt Normal file
View file

@ -0,0 +1,28 @@
Dependency Commits
==================
lbcwallet 0.7.0 Alpha
----------------
bolt 1139dd23c5f9d1a28096b511959044b29364a3fe
cea5d3c1cc16eb07a1686c557db23004655ae11b
btclog 5005b7240f310ae8f01c7664a3954d280241eb2b
btcrpcclient b81555beeac8eda71e8150cc9d63631aaa756965
btcutil ff82dacded1c76d101bce55c394c03c0bbff69e8
fastsha256 302ad4db268b46f9ebda3078f6f7397f96047735
go-flags 6c288d648c1cc1befcb90cb5511dcacf64ae8e61
go-socks cfe8b59e565c1a5bd4e2005d77cd9aa8b2e14524
golangcrypto 53f62d9b43e87a6c56975cf862af7edf33a8d0df
seelog 313961b101eb55f65ae0f03ddd4e322731763b6c
websocket 31079b6807923eb23992c421b114992b95131b55
lbcwallet 0.1.0 Alpha
----------------
3108b944017b14a3c5863ed1401f1a2471907d84
btcec a97fd5fe2c670030f8d77dc13b9fa8401ef9f349
btcjson d20f958c92e1444d83215c3cf98d6eef41898dcb
btcscript f4a6449ad3b90d0c830bf2895b83ced8d5fb91e9
btcutil aa811871654079f5036d3692dcf6c66928d19447
btcwire dd41f7e91a682b7c1ceed633e12ece6ba7b6bc72
btcws 497f1770445677372557d70621782d921a5318e3
go-flags fa177a84d3b73bf7e4b79125b2a963bc134eff77
seelog 6b91ad56123bb473755caa213db2bde5422177bf

3
docs/README.md Normal file
View file

@ -0,0 +1,3 @@
### Guides
[Rebuilding all transaction history with forced rescans](https://github.com/lbryio/lbcwallet/tree/master/docs/force_rescans.md)

80
docs/force_rescans.md Normal file
View file

@ -0,0 +1,80 @@
# 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.
lbcwallet 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/lbryio/lbcwallet/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/.lbcwallet/mainnet/wallet.db
Drop all lbcwallet 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 ~/.lbcwallet/testnet/wallet.db
Database path: /home/username/.lbcwallet/testnet/wallet.db
Drop all lbcwallet transaction history? [y/N] y
Dropping wtxmgr namespace
```
After dropping transaction history, lbcwallet may be restarted and a full rescan
will be triggered to sync the wallet:
```
$ lbcwallet
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)
```

2
go.mod
View file

@ -6,7 +6,7 @@ require (
github.com/davecgh/go-spew v1.1.1
github.com/jessevdk/go-flags v1.5.0
github.com/jrick/logrotate v1.0.0
github.com/lbryio/lbcd v0.22.118
github.com/lbryio/lbcd v0.22.115-0.20220926180819-987a53342314
github.com/lbryio/lbcutil v1.0.202
github.com/lightningnetwork/lnd/clock v1.1.0
github.com/stretchr/testify v1.7.1

4
go.sum
View file

@ -187,8 +187,8 @@ 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/lbcd v0.22.115-0.20220926180819-987a53342314 h1:O9BBH3J3AcQc396xIzU8rRx9pPmEDug1/ORAi19fPDc=
github.com/lbryio/lbcd v0.22.115-0.20220926180819-987a53342314/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=

View file

@ -21,7 +21,14 @@ import (
"golang.org/x/crypto/ssh/terminal"
)
func promptSeed(reader *bufio.Reader) ([]byte, error) {
// ProvideSeed is used to prompt for the wallet seed which maybe required during
// upgrades.
func ProvideSeed() func() ([]byte, error) {
return func() ([]byte, error) {
return provideSeed(bufio.NewReader(os.Stdin))
}
}
func provideSeed(reader *bufio.Reader) ([]byte, error) {
for {
fmt.Print("Enter existing wallet seed: ")
seedStr, err := reader.ReadString('\n')
@ -45,6 +52,26 @@ func promptSeed(reader *bufio.Reader) ([]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.
@ -120,15 +147,10 @@ func promptUnixTimestamp(reader *bufio.Reader, prefix string,
}
}
// 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
}
// 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(_ *bufio.Reader, prefix string, confirm bool) ([]byte, error) {
// Prompt the user until they enter a passphrase.
prompt := fmt.Sprintf("%s: ", prefix)
for {
@ -169,11 +191,56 @@ func birthday(reader *bufio.Reader) (time.Time, error) {
return promptUnixTimestamp(reader, prompt, "0")
}
// 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)
// PrivatePass prompts the user for a private passphrase. 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) ([]byte, error) {
return promptPass(reader, "Enter the private "+
"passphrase for your new wallet", true)
}
// 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
}
}
pubPass, err = provideSeed(reader)
if err != nil {
return nil, err
}
fmt.Println("NOTE: Use the --walletpass option to configure your " +
"public passphrase.")
return pubPass, nil
}
// Seed prompts the user whether they want to use an existing wallet generation
@ -217,7 +284,7 @@ func Seed(reader *bufio.Reader) ([]byte, time.Time, error) {
return seed, bday, nil
}
seed, err := promptSeed(reader)
seed, err := provideSeed(reader)
if err != nil {
return nil, bday, err
}

View file

@ -0,0 +1,30 @@
// Copyright (c) 2015-2021 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package prompt
import (
"bufio"
"fmt"
)
func ProvideSeed() ([]byte, error) {
return nil, fmt.Errorf("prompt not supported in WebAssembly")
}
func ProvidePrivPassphrase() ([]byte, error) {
return nil, fmt.Errorf("prompt not supported in WebAssembly")
}
func PrivatePass(_ *bufio.Reader) ([]byte, error) {
return nil, fmt.Errorf("prompt not supported in WebAssembly")
}
func PublicPass(_ *bufio.Reader, _, _, _ []byte) ([]byte, error) {
return nil, fmt.Errorf("prompt not supported in WebAssembly")
}
func Seed(_ *bufio.Reader) ([]byte, error) {
return nil, fmt.Errorf("prompt not supported in WebAssembly")
}

View file

@ -348,15 +348,6 @@ var helpDescsEnUS = map[string]string{
"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": "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.",

View file

@ -70,7 +70,6 @@ var Methods = []struct {
{"listaddresstransactions", returnsLTRArray},
{"listalltransactions", returnsLTRArray},
{"renameaccount", nil},
{"rescanblockchain", []interface{}{(*btcjson.RescanBlockchainResult)(nil)}},
{"walletislocked", returnsBool},
}

View file

@ -81,21 +81,24 @@ func walletMain() error {
return err
}
go rpcClientConnectLoop(legacyRPCServer, loader)
// 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)
}
loader.RunAfterLoad(func(w *wallet.Wallet) {
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)
}
})
_, err = loader.OpenExistingWallet()
if err != nil {
log.Error(err)
return 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
}
}
// Add interrupt handlers to shutdown the various process components
@ -132,7 +135,10 @@ func walletMain() error {
// associated with the server for RPC passthrough and to enable additional
// methods.
func rpcClientConnectLoop(legacyRPCServer *legacyrpc.Server, loader *wallet.Loader) {
certs := readCAFile()
var certs []byte
if !cfg.UseSPV {
certs = readCAFile()
}
for {
var (
@ -219,7 +225,7 @@ func readCAFile() []byte {
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.RPCUser, cfg.RPCPass, certs, cfg.DisableClientTLS,
cfg.LbcdUsername, cfg.LbcdPassword, certs, cfg.DisableClientTLS,
cfg.SkipVerify, 0)
if err != nil {
return nil, err

View file

@ -6,6 +6,7 @@ package netparams
import (
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcd/wire"
)
// Params is used to group parameters for various networks such as the main
@ -41,3 +42,31 @@ var RegTestParams = Params{
RPCClientPort: "29245",
RPCServerPort: "29244",
}
// SimNetParams contains parameters specific to the simulation test network
// (wire.SimNet).
var SimNetParams = Params{
Params: &chaincfg.SimNetParams,
RPCClientPort: "39245",
RPCServerPort: "39244",
}
// SigNetParams contains parameters specific to the signet test network
// (wire.SigNet).
var SigNetParams = Params{
Params: &chaincfg.SigNetParams,
RPCClientPort: "49245",
RPCServerPort: "49244",
}
// SigNetWire is a helper function that either returns the given chain
// parameter's net value if the parameter represents a signet network or 0 if
// it's not. This is necessary because there can be custom signet networks that
// have a different net value.
func SigNetWire(params *chaincfg.Params) wire.BitcoinNet {
if params.Name == chaincfg.SigNetParams.Name {
return params.Net
}
return 0
}

View file

@ -102,7 +102,6 @@ var rpcHandlers = map[string]struct {
"listunspent": {handler: listUnspent},
"lockunspent": {handler: lockUnspent},
"sendfrom": {handlerWithChain: sendFrom},
"rescanblockchain": {handlerWithChain: rescanBlockchain},
"sendmany": {handler: sendMany},
"sendtoaddress": {handler: sendToAddress},
"settxfee": {handler: setTxFee},
@ -1586,49 +1585,6 @@ func makeOutputs(pairs map[string]btcutil.Amount, chainParams *chaincfg.Params)
return outputs, nil
}
// rescanBlockchain handles a rescanblockhain RPC request.
func rescanBlockchain(icmd interface{}, w *wallet.Wallet,
chainClient *chain.RPCClient) (interface{}, error) {
cmd := icmd.(*btcjson.RescanBlockchainCmd)
_, bestHeight, err := chainClient.GetBestBlock()
if err != nil {
return nil, err
}
startHeight := *cmd.StartHeight
if startHeight < 0 || startHeight > bestHeight {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "Invalid start height",
}
}
// Scan to the best block if no stopHeight is specified.
stopHeight := bestHeight
if cmd.StopHeight != nil {
stopHeight = *cmd.StopHeight
}
if stopHeight < 0 || stopHeight > bestHeight {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "Invalid stop height",
}
}
startHeight, stopHeight, err = w.RescanBlockchain(chainClient,
startHeight, stopHeight)
if err != nil {
return nil, fmt.Errorf("rescanblockchain: %w", err)
}
ret := btcjson.RescanBlockchainResult{
StartHeight: startHeight,
StoptHeight: stopHeight,
}
return ret, nil
}
// sendPairs creates and sends payment transactions.
// It returns the transaction hash in string format upon success
// All errors are returned in btcjson.RPCError format
@ -2198,7 +2154,7 @@ func walletPassphrase(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
func walletPassphraseChange(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
cmd := icmd.(*btcjson.WalletPassphraseChangeCmd)
err := w.ChangePassphrase([]byte(cmd.OldPassphrase),
err := w.ChangePrivatePassphrase([]byte(cmd.OldPassphrase),
[]byte(cmd.NewPassphrase))
if waddrmgr.IsError(err, waddrmgr.ErrWrongPassphrase) {
return nil, &btcjson.RPCError{

View file

@ -48,7 +48,6 @@ func helpDescsEnUS() map[string]string {
"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",
}
}
@ -57,4 +56,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=\"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"
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\"\nwalletislocked"

View file

@ -126,8 +126,8 @@ func startRPCServers(walletLoader *wallet.Loader) (*legacyrpc.Server, error) {
}
if cfg.RPCUser == "" || cfg.RPCPass == "" {
log.Info("RPC server disabled (requires rpcuser and rpcpass)")
if cfg.Username == "" || cfg.Password == "" {
log.Info("Legacy RPC server disabled (requires username and password)")
} else if len(cfg.LegacyRPCListeners) != 0 {
listeners := makeListeners(cfg.LegacyRPCListeners, legacyListen)
if len(listeners) == 0 {
@ -135,8 +135,8 @@ func startRPCServers(walletLoader *wallet.Loader) (*legacyrpc.Server, error) {
return nil, err
}
opts := legacyrpc.Options{
Username: cfg.RPCUser,
Password: cfg.RPCPass,
Username: cfg.Username,
Password: cfg.Password,
MaxPOSTClients: cfg.LegacyRPCMaxClients,
MaxWebsocketClients: cfg.LegacyRPCMaxWebsockets,
}

View file

@ -4,9 +4,12 @@
; Bitcoin wallet settings
; ------------------------------------------------------------------------------
; Use testnet
; Use testnet (cannot be used with simnet=1).
; 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.
@ -85,8 +88,15 @@
; Username and password to authenticate to lbcd a RPC server and authenticate
; new client connections
; rpcuser=
; rpcpass=
; username=
; password=
; Alternative username and password for lbcd. If set, these will be used
; instead of the username and password set above for authentication to a
; lbcd RPC server.
; lbcdusername=
; lbcdpassword=
; ------------------------------------------------------------------------------
; Debug

View file

@ -29,7 +29,9 @@ var (
rootKey, _ = hdkeychain.NewMaster(seed, &chaincfg.MainNetParams)
passphrase = []byte("81lUHXnOMZ@?XXd7O9xyDIWIbXX-lj")
pubPassphrase = []byte("_DJr{fL4H0O}*-0\n:V1izc)(6BomK")
privPassphrase = []byte("81lUHXnOMZ@?XXd7O9xyDIWIbXX-lj")
pubPassphrase2 = []byte("-0NV4P~VSJBWbunw}%<Z]fuGpbN[ZI")
privPassphrase2 = []byte("~{<]08%6!-?2s<$(8$8:f(5[4/!/{Y")
// fastScrypt are parameters used throughout the tests to speed up the
@ -285,13 +287,13 @@ func setupManager(t *testing.T) (tearDownFunc func(), db walletdb.DB, mgr *Manag
return err
}
err = Create(
ns, rootKey, passphrase, &chaincfg.MainNetParams,
fastScrypt, time.Time{},
ns, rootKey, pubPassphrase, privPassphrase,
&chaincfg.MainNetParams, fastScrypt, time.Time{},
)
if err != nil {
return err
}
mgr, err = Open(ns, &chaincfg.MainNetParams)
mgr, err = Open(ns, pubPassphrase, &chaincfg.MainNetParams)
return err
})
if err != nil {

17
waddrmgr/cov_report.sh Normal file
View file

@ -0,0 +1,17 @@
#!/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

View file

@ -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 passphrase.
// wallet seed and private passphrase.
type ObtainUserInputFunc func() ([]byte, error)
// maybeConvertDbError converts the passed error to a ManagerError with an

View file

@ -81,7 +81,7 @@ const (
InternalBranch uint32 = 1
// saltSize is the number of bytes of the salt used when hashing
// passphrases.
// private passphrases.
saltSize = 32
)
@ -113,11 +113,11 @@ type OpenCallbacks struct {
// from the user (or any other mechanism the caller deems fit).
ObtainSeed ObtainUserInputFunc
// ObtainPassphrase is a callback function that is potentially invoked
// ObtainPrivatePass is a callback function that is potentially invoked
// during upgrades. It is intended to be used to request the wallet
// passphrase from the user (or any other mechanism the caller deems
// fit).
ObtainPassphrase ObtainUserInputFunc
// private passphrase from the user (or any other mechanism the caller
// deems fit).
ObtainPrivatePass ObtainUserInputFunc
}
// DefaultScryptOptions is the default options used with scrypt.
@ -373,11 +373,11 @@ type Manager struct {
cryptoKeyScriptEncrypted []byte
cryptoKeyScript EncryptorDecryptor
// pssphraseSalt and hashedPassphrase allow for the secure detection
// of a correct passphrase on manager unlock when the manager is already
// unlocked. The hash is zeroed each lock.
passphraseSalt [saltSize]byte
hashedPassphrase [sha512.Size]byte
// privPassphraseSalt and hashedPrivPassphrase allow for the secure
// detection of a correct passphrase on manager unlock when the
// manager is already unlocked. The hash is zeroed each lock.
privPassphraseSalt [saltSize]byte
hashedPrivPassphrase [sha512.Size]byte
}
// lock performs a best try effort to remove and zero all secret keys associated
@ -413,7 +413,7 @@ func (m *Manager) lock() {
m.masterKeyPriv.Zero()
// Zero the hashed passphrase.
zero.Bytea64(&m.hashedPassphrase)
zero.Bytea64(&m.hashedPrivPassphrase)
// NOTE: m.cryptoKeyPub is intentionally not cleared here as the address
// manager needs to be able to continue to read and decrypt public data
@ -825,12 +825,13 @@ func (m *Manager) ChainParams() *chaincfg.Params {
return m.chainParams
}
// ChangePassphrase changes passphrase to the provided value. The new
// passphrase keys are derived using the scrypt parameters in the options, so
// changing the passphrase may be used to bump the computational difficulty
// needed to brute force the passphrase.
// ChangePassphrase changes either the public or private passphrase to the
// provided value depending on the private flag. The new passphrase keys are
// derived using the scrypt parameters in the options, so changing the
// passphrase may be used to bump the computational difficulty needed to brute
// force the passphrase.
func (m *Manager) ChangePassphrase(ns walletdb.ReadWriteBucket, oldPassphrase,
newPassphrase []byte, config *ScryptOptions) error {
newPassphrase []byte, private bool, config *ScryptOptions) error {
m.mtx.Lock()
defer m.mtx.Unlock()
@ -841,9 +842,13 @@ func (m *Manager) ChangePassphrase(ns walletdb.ReadWriteBucket, oldPassphrase,
// cleared when done to avoid leaving a copy in memory.
var keyName string
secretKey := snacl.SecretKey{Key: &snacl.CryptoKey{}}
keyName = "private"
secretKey.Parameters = m.masterKeyPriv.Parameters
if private {
keyName = "private"
secretKey.Parameters = m.masterKeyPriv.Parameters
} else {
keyName = "public"
secretKey.Parameters = m.masterKeyPub.Parameters
}
if err := secretKey.DeriveKey(&oldPassphrase); err != nil {
if err == snacl.ErrInvalidPassword {
str := fmt.Sprintf("invalid passphrase for %s master "+
@ -865,84 +870,111 @@ func (m *Manager) ChangePassphrase(ns walletdb.ReadWriteBucket, oldPassphrase,
}
newKeyParams := newMasterKey.Marshal()
// Technically, the locked state could be checked here to only
// do the decrypts when the address manager is locked as the
// clear text keys are already available in memory when it is
// unlocked, but this is not a hot path, decryption is quite
// fast, and it's less cyclomatic complexity to simply decrypt
// in either case.
if private {
// Technically, the locked state could be checked here to only
// do the decrypts when the address manager is locked as the
// clear text keys are already available in memory when it is
// unlocked, but this is not a hot path, decryption is quite
// fast, and it's less cyclomatic complexity to simply decrypt
// in either case.
// Create a new salt that will be used for hashing the new
// passphrase each unlock.
var passphraseSalt [saltSize]byte
_, err = rand.Read(passphraseSalt[:])
if err != nil {
str := "failed to read random source for passhprase salt"
return managerError(ErrCrypto, str, err)
}
// Create a new salt that will be used for hashing the new
// passphrase each unlock.
var passphraseSalt [saltSize]byte
_, err := rand.Read(passphraseSalt[:])
if err != nil {
str := "failed to read random source for passhprase salt"
return managerError(ErrCrypto, str, err)
}
// Re-encrypt the crypto private key using the new master
// private key.
decPriv, err := secretKey.Decrypt(m.cryptoKeyPrivEncrypted)
if err != nil {
str := "failed to decrypt crypto private key"
return managerError(ErrCrypto, str, err)
}
encPriv, err := newMasterKey.Encrypt(decPriv)
zero.Bytes(decPriv)
if err != nil {
str := "failed to encrypt crypto private key"
return managerError(ErrCrypto, str, err)
}
// Re-encrypt the crypto private key using the new master
// private key.
decPriv, err := secretKey.Decrypt(m.cryptoKeyPrivEncrypted)
if err != nil {
str := "failed to decrypt crypto private key"
return managerError(ErrCrypto, str, err)
}
encPriv, err := newMasterKey.Encrypt(decPriv)
zero.Bytes(decPriv)
if err != nil {
str := "failed to encrypt crypto private key"
return managerError(ErrCrypto, str, err)
}
// Re-encrypt the crypto script key using the new master
// private key.
decScript, err := secretKey.Decrypt(m.cryptoKeyScriptEncrypted)
if err != nil {
str := "failed to decrypt crypto script key"
return managerError(ErrCrypto, str, err)
}
encScript, err := newMasterKey.Encrypt(decScript)
zero.Bytes(decScript)
if err != nil {
str := "failed to encrypt crypto script key"
return managerError(ErrCrypto, str, err)
}
// Re-encrypt the crypto script key using the new master
// private key.
decScript, err := secretKey.Decrypt(m.cryptoKeyScriptEncrypted)
if err != nil {
str := "failed to decrypt crypto script key"
return managerError(ErrCrypto, str, err)
}
encScript, err := newMasterKey.Encrypt(decScript)
zero.Bytes(decScript)
if err != nil {
str := "failed to encrypt crypto script key"
return managerError(ErrCrypto, str, err)
}
// When the manager is locked, ensure the new clear text master
// key is cleared from memory now that it is no longer needed.
// If unlocked, create the new passphrase hash with the new
// passphrase and salt.
var hashedPassphrase [sha512.Size]byte
if m.locked {
newMasterKey.Zero()
// When the manager is locked, ensure the new clear text master
// key is cleared from memory now that it is no longer needed.
// If unlocked, create the new passphrase hash with the new
// passphrase and salt.
var hashedPassphrase [sha512.Size]byte
if m.locked {
newMasterKey.Zero()
} else {
saltedPassphrase := append(passphraseSalt[:],
newPassphrase...)
hashedPassphrase = sha512.Sum512(saltedPassphrase)
zero.Bytes(saltedPassphrase)
}
// Save the new keys and params to the db in a single
// transaction.
err = putCryptoKeys(ns, nil, encPriv, encScript)
if err != nil {
return maybeConvertDbError(err)
}
err = putMasterKeyParams(ns, nil, newKeyParams)
if err != nil {
return maybeConvertDbError(err)
}
// Now that the db has been successfully updated, clear the old
// key and set the new one.
copy(m.cryptoKeyPrivEncrypted, encPriv)
copy(m.cryptoKeyScriptEncrypted, encScript)
m.masterKeyPriv.Zero() // Clear the old key.
m.masterKeyPriv = newMasterKey
m.privPassphraseSalt = passphraseSalt
m.hashedPrivPassphrase = hashedPassphrase
} else {
saltedPassphrase := append(passphraseSalt[:],
newPassphrase...)
hashedPassphrase = sha512.Sum512(saltedPassphrase)
zero.Bytes(saltedPassphrase)
}
// Re-encrypt the crypto public key using the new master public
// key.
encryptedPub, err := newMasterKey.Encrypt(m.cryptoKeyPub.Bytes())
if err != nil {
str := "failed to encrypt crypto public key"
return managerError(ErrCrypto, str, err)
}
// Save the new keys and params to the db in a single
// transaction.
err = putCryptoKeys(ns, nil, encPriv, encScript)
if err != nil {
return maybeConvertDbError(err)
}
// Save the new keys and params to the the db in a single
// transaction.
err = putCryptoKeys(ns, encryptedPub, nil, nil)
if err != nil {
return maybeConvertDbError(err)
}
err = putMasterKeyParams(ns, nil, newKeyParams)
if err != nil {
return maybeConvertDbError(err)
}
err = putMasterKeyParams(ns, newKeyParams, nil)
if err != nil {
return maybeConvertDbError(err)
}
// Now that the db has been successfully updated, clear the old
// key and set the new one.
copy(m.cryptoKeyPrivEncrypted, encPriv)
copy(m.cryptoKeyScriptEncrypted, encScript)
m.masterKeyPriv.Zero() // Clear the old key.
m.masterKeyPriv = newMasterKey
m.passphraseSalt = passphraseSalt
m.hashedPassphrase = hashedPassphrase
// Now that the db has been successfully updated, clear the old
// key and set the new one.
m.masterKeyPub.Zero()
m.masterKeyPub = newMasterKey
}
return nil
}
@ -995,10 +1027,11 @@ func (m *Manager) Unlock(ns walletdb.ReadBucket, passphrase []byte) error {
// Avoid actually unlocking if the manager is already unlocked
// and the passphrases match.
if !m.locked {
saltedPassphrase := append(m.passphraseSalt[:], passphrase...)
saltedPassphrase := append(m.privPassphraseSalt[:],
passphrase...)
hashedPassphrase := sha512.Sum512(saltedPassphrase)
zero.Bytes(saltedPassphrase)
if hashedPassphrase != m.hashedPassphrase {
if hashedPassphrase != m.hashedPrivPassphrase {
m.lock()
str := "invalid passphrase for master private key"
return managerError(ErrWrongPassphrase, str, nil)
@ -1093,8 +1126,8 @@ func (m *Manager) Unlock(ns walletdb.ReadBucket, passphrase []byte) error {
}
m.locked = false
saltedPassphrase := append(m.passphraseSalt[:], passphrase...)
m.hashedPassphrase = sha512.Sum512(saltedPassphrase)
saltedPassphrase := append(m.privPassphraseSalt[:], passphrase...)
m.hashedPrivPassphrase = sha512.Sum512(saltedPassphrase)
zero.Bytes(saltedPassphrase)
return nil
}
@ -1202,7 +1235,7 @@ func (m *Manager) Decrypt(keyType CryptoKeyType, in []byte) ([]byte, error) {
func newManager(chainParams *chaincfg.Params, masterKeyPub *snacl.SecretKey,
masterKeyPriv *snacl.SecretKey, cryptoKeyPub EncryptorDecryptor,
cryptoKeyPrivEncrypted, cryptoKeyScriptEncrypted []byte, syncInfo *syncState,
birthday time.Time, passphraseSalt [saltSize]byte,
birthday time.Time, privPassphraseSalt [saltSize]byte,
scopedManagers map[KeyScope]*ScopedKeyManager) *Manager {
m := &Manager{
@ -1217,7 +1250,7 @@ func newManager(chainParams *chaincfg.Params, masterKeyPub *snacl.SecretKey,
cryptoKeyPriv: &cryptoKey{},
cryptoKeyScriptEncrypted: cryptoKeyScriptEncrypted,
cryptoKeyScript: &cryptoKey{},
passphraseSalt: passphraseSalt,
privPassphraseSalt: privPassphraseSalt,
scopedManagers: scopedManagers,
externalAddrSchemas: make(map[AddressType][]KeyScope),
internalAddrSchemas: make(map[AddressType][]KeyScope),
@ -1328,9 +1361,10 @@ func checkBranchKeys(acctKey *hdkeychain.ExtendedKey) error {
}
// loadManager returns a new address manager that results from loading it from
// the passed opened database.
func loadManager(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (
*Manager, error) {
// the passed opened database. The public passphrase is required to decrypt
// the public keys.
func loadManager(ns walletdb.ReadBucket, pubPassphrase []byte,
chainParams *chaincfg.Params) (*Manager, error) {
// Verify the version is neither too old or too new.
version, err := fetchManagerVersion(ns)
@ -1347,7 +1381,7 @@ func loadManager(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (
}
// Load the master key params from the db.
masterKeyPubParams, masterKeyparams, err := fetchMasterKeyParams(ns)
masterKeyPubParams, masterKeyPrivParams, err := fetchMasterKeyParams(ns)
if err != nil {
return nil, maybeConvertDbError(err)
}
@ -1376,7 +1410,7 @@ func loadManager(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (
// Set the master private key params, but don't derive it now since the
// manager starts off locked.
var masterKeyPriv snacl.SecretKey
err = masterKeyPriv.Unmarshal(masterKeyparams)
err = masterKeyPriv.Unmarshal(masterKeyPrivParams)
if err != nil {
str := "failed to unmarshal master private key"
return nil, managerError(ErrCrypto, str, err)
@ -1389,8 +1423,6 @@ func loadManager(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (
str := "failed to unmarshal master public key"
return nil, managerError(ErrCrypto, str, err)
}
pubPassphrase := []byte("public") // Hardcoded salt.
if err := masterKeyPub.DeriveKey(&pubPassphrase); err != nil {
str := "invalid passphrase for master public key"
return nil, managerError(ErrWrongPassphrase, str, nil)
@ -1409,9 +1441,9 @@ func loadManager(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (
// Create the sync state struct.
syncInfo := newSyncState(startBlock, syncedTo)
// Generate passphrase salt.
var passphraseSalt [saltSize]byte
_, err = rand.Read(passphraseSalt[:])
// Generate private passphrase salt.
var privPassphraseSalt [saltSize]byte
_, err = rand.Read(privPassphraseSalt[:])
if err != nil {
str := "failed to read random source for passphrase salt"
return nil, managerError(ErrCrypto, str, err)
@ -1448,7 +1480,7 @@ func loadManager(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (
mgr := newManager(
chainParams, &masterKeyPub, &masterKeyPriv,
cryptoKeyPub, cryptoKeyPrivEnc, cryptoKeyScriptEnc, syncInfo,
birthday, passphraseSalt, scopedManagers)
birthday, privPassphraseSalt, scopedManagers)
for _, scopedManager := range scopedManagers {
scopedManager.rootManager = mgr
@ -1457,15 +1489,18 @@ func loadManager(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (
return mgr, nil
}
// Open loads an existing address manager from the given namespace.
// Open loads an existing address manager from the given namespace. The public
// passphrase is required to decrypt the public keys used to protect the public
// information such as addresses. This is important since access to BIP0032
// extended keys means it is possible to generate all future addresses.
//
// If a config structure is passed to the function, that configuration will
// override the defaults.
//
// A ManagerError with an error code of ErrNoExist will be returned if the
// passed manager does not exist in the specified namespace.
func Open(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (
*Manager, error) {
func Open(ns walletdb.ReadBucket, pubPassphrase []byte,
chainParams *chaincfg.Params) (*Manager, error) {
// Return an error if the manager has NOT already been created in the
// given database namespace.
@ -1475,7 +1510,7 @@ func Open(ns walletdb.ReadBucket, chainParams *chaincfg.Params) (
return nil, managerError(ErrNoExist, str, nil)
}
return loadManager(ns, chainParams)
return loadManager(ns, pubPassphrase, chainParams)
}
// createManagerKeyScope creates a new key scoped for a target manager's scope.
@ -1587,10 +1622,12 @@ func createManagerKeyScope(ns walletdb.ReadWriteBucket,
// derived. This allows all chained addresses in the address manager
// to be recovered by using the same seed.
//
// All private keys and information are protected by secret keys derived
// from the provided passphrase.
// The passphrase is required to unlock the address manager in order to gain
// access to any private keys and information.
// All private and public keys and information are protected by secret
// keys derived from the provided private and public passphrases. The
// public passphrase is required on subsequent opens of the address
// manager, and the private passphrase is required to unlock the
// address manager in order to gain access to any private keys and
// information.
//
// If a config structure is passed to the function, that configuration
// will override the defaults.
@ -1599,8 +1636,9 @@ func createManagerKeyScope(ns walletdb.ReadWriteBucket,
// returned the address manager already exists in the specified
// namespace.
func Create(ns walletdb.ReadWriteBucket, rootKey *hdkeychain.ExtendedKey,
passphrase []byte, chainParams *chaincfg.Params,
config *ScryptOptions, birthday time.Time) error {
pubPassphrase, privPassphrase []byte,
chainParams *chaincfg.Params, config *ScryptOptions,
birthday time.Time) error {
// Return an error if the manager has already been created in
// the given database namespace.
@ -1609,9 +1647,9 @@ func Create(ns walletdb.ReadWriteBucket, rootKey *hdkeychain.ExtendedKey,
return managerError(ErrAlreadyExists, errAlreadyExists, nil)
}
// Ensure the passphrase is not empty.
if len(passphrase) == 0 {
str := "passphrase may not be empty"
// Ensure the private passphrase is not empty.
if len(privPassphrase) == 0 {
str := "private passphrase may not be empty"
return managerError(ErrEmptyPassphrase, str, nil)
}
@ -1626,7 +1664,6 @@ func Create(ns walletdb.ReadWriteBucket, rootKey *hdkeychain.ExtendedKey,
// Generate new master keys. These master keys are used to protect the
// crypto keys that will be generated next.
pubPassphrase := []byte("public") // Hardcoded salt.
masterKeyPub, err := newSecretKey(&pubPassphrase, config)
if err != nil {
str := "failed to master public key"
@ -1662,22 +1699,22 @@ func Create(ns walletdb.ReadWriteBucket, rootKey *hdkeychain.ExtendedKey,
pubParams := masterKeyPub.Marshal()
var params []byte
var privParams []byte
var masterKeyPriv *snacl.SecretKey
var cryptoKeyPrivEnc []byte
var cryptoKeyScriptEnc []byte
masterKeyPriv, err = newSecretKey(&passphrase, config)
masterKeyPriv, err = newSecretKey(&privPassphrase, config)
if err != nil {
str := "failed to master private key"
return managerError(ErrCrypto, str, err)
}
defer masterKeyPriv.Zero()
// Generate the passphrase salt. This is used when hashing passwords
// to detect whether an unlock can be avoided when the manager is
// already unlocked.
var passphraseSalt [saltSize]byte
_, err = rand.Read(passphraseSalt[:])
// Generate the private passphrase salt. This is used when
// hashing passwords to detect whether an unlock can be
// avoided when the manager is already unlocked.
var privPassphraseSalt [saltSize]byte
_, err = rand.Read(privPassphraseSalt[:])
if err != nil {
str := "failed to read random source for passphrase salt"
return managerError(ErrCrypto, str, err)
@ -1749,10 +1786,10 @@ func Create(ns walletdb.ReadWriteBucket, rootKey *hdkeychain.ExtendedKey,
return maybeConvertDbError(err)
}
params = masterKeyPriv.Marshal()
privParams = masterKeyPriv.Marshal()
// Save the master key params to the database.
err = putMasterKeyParams(ns, pubParams, params)
err = putMasterKeyParams(ns, pubParams, privParams)
if err != nil {
return maybeConvertDbError(err)
}

View file

@ -431,7 +431,7 @@ func testExternalAddresses(tc *testContext) bool {
// private information is valid as well.
err := walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, passphrase)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
@ -463,7 +463,7 @@ func testInternalAddresses(tc *testContext) bool {
// private information is valid as well.
err := walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, passphrase)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
@ -603,7 +603,7 @@ func testLocking(tc *testContext) bool {
// unexpected errors and the manager properly reports it is unlocked.
err = walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, passphrase)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
@ -617,7 +617,7 @@ func testLocking(tc *testContext) bool {
// Unlocking the manager again is allowed.
err = walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, passphrase)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
@ -696,7 +696,7 @@ func testImportPrivateKey(tc *testContext) bool {
// The manager must be unlocked to import a private key.
err := walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, passphrase)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
@ -913,7 +913,7 @@ func testImportScript(tc *testContext) bool {
// testing private data.
err := walletdb.View(tc.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return tc.rootManager.Unlock(ns, passphrase)
return tc.rootManager.Unlock(ns, privPassphrase)
})
if err != nil {
tc.t.Errorf("Unlock: unexpected error: %v", err)
@ -1122,11 +1122,74 @@ func testMarkUsed(tc *testContext, doScript bool) bool {
func testChangePassphrase(tc *testContext) bool {
pfx := fmt.Sprintf("(%s) ", tc.caseName)
testName := pfx + "ChangePassphrase with invalid old passphrase"
// Force an error when changing the passphrase due to failure to
// generate a new secret key by replacing the generation function one
// that intentionally errors.
testName := pfx + "ChangePassphrase (public) with invalid new secret key"
oldKeyGen := SetSecretKeyGen(failingSecretKeyGen)
err := walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
return tc.rootManager.ChangePassphrase(
ns, []byte("bogus"), privPassphrase2, fastScrypt,
ns, pubPassphrase, pubPassphrase2, false, fastScrypt,
)
})
if !checkManagerError(tc.t, testName, err, ErrCrypto) {
return false
}
// Attempt to change public passphrase with invalid old passphrase.
testName = pfx + "ChangePassphrase (public) with invalid old passphrase"
SetSecretKeyGen(oldKeyGen)
err = walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
return tc.rootManager.ChangePassphrase(
ns, []byte("bogus"), pubPassphrase2, false, fastScrypt,
)
})
if !checkManagerError(tc.t, testName, err, ErrWrongPassphrase) {
return false
}
// Change the public passphrase.
testName = pfx + "ChangePassphrase (public)"
err = walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
return tc.rootManager.ChangePassphrase(
ns, pubPassphrase, pubPassphrase2, false, fastScrypt,
)
})
if err != nil {
tc.t.Errorf("%s: unexpected error: %v", testName, err)
return false
}
// Ensure the public passphrase was successfully changed. We do this by
// being able to re-derive the public key with the new passphrase.
secretKey := snacl.SecretKey{Key: &snacl.CryptoKey{}}
secretKey.Parameters = tc.rootManager.masterKeyPub.Parameters
if err := secretKey.DeriveKey(&pubPassphrase2); err != nil {
tc.t.Errorf("%s: passphrase does not match", testName)
return false
}
// Change the private passphrase back to what it was.
err = walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
return tc.rootManager.ChangePassphrase(
ns, pubPassphrase2, pubPassphrase, false, fastScrypt,
)
})
if err != nil {
tc.t.Errorf("%s: unexpected error: %v", testName, err)
return false
}
testName = pfx + "ChangePassphrase (private) with invalid old passphrase"
err = walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
return tc.rootManager.ChangePassphrase(
ns, []byte("bogus"), privPassphrase2, true, fastScrypt,
)
})
wantErrCode := ErrWrongPassphrase
@ -1134,11 +1197,12 @@ func testChangePassphrase(tc *testContext) bool {
return false
}
testName = pfx + "ChangePassphrase"
// Change the private passphrase.
testName = pfx + "ChangePassphrase (private)"
err = walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
return tc.rootManager.ChangePassphrase(
ns, passphrase, privPassphrase2, fastScrypt,
ns, privPassphrase, privPassphrase2, true, fastScrypt,
)
})
if err != nil {
@ -1153,8 +1217,8 @@ func testChangePassphrase(tc *testContext) bool {
return tc.rootManager.Unlock(ns, privPassphrase2)
})
if err != nil {
tc.t.Errorf("%s: failed to unlock with new passphrase: %v",
testName, err)
tc.t.Errorf("%s: failed to unlock with new private "+
"passphrase: %v", testName, err)
return false
}
tc.unlocked = true
@ -1164,7 +1228,7 @@ func testChangePassphrase(tc *testContext) bool {
err = walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
return tc.rootManager.ChangePassphrase(
ns, privPassphrase2, passphrase, fastScrypt,
ns, privPassphrase2, privPassphrase, true, fastScrypt,
)
})
if err != nil {
@ -1205,7 +1269,7 @@ func testNewAccount(tc *testContext) bool {
// to derive account keys
err = walletdb.Update(tc.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
err := tc.rootManager.Unlock(ns, passphrase)
err := tc.rootManager.Unlock(ns, privPassphrase)
return err
})
if err != nil {
@ -1604,7 +1668,7 @@ func _TestManager(t *testing.T) {
{
name: "created with seed",
rootKey: rootKey,
privPassphrase: passphrase,
privPassphrase: privPassphrase,
},
}
@ -1624,7 +1688,7 @@ func testManagerCase(t *testing.T, caseName string,
// returned.
err := walletdb.View(db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
_, err := Open(ns, &chaincfg.MainNetParams)
_, err := Open(ns, pubPassphrase, &chaincfg.MainNetParams)
return err
})
if !checkManagerError(t, "Open non-existent", err, ErrNoExist) {
@ -1639,13 +1703,13 @@ func testManagerCase(t *testing.T, caseName string,
return err
}
err = Create(
ns, caseKey, casePrivPassphrase,
ns, caseKey, pubPassphrase, casePrivPassphrase,
&chaincfg.MainNetParams, fastScrypt, time.Time{},
)
if err != nil {
return err
}
mgr, err = Open(ns, &chaincfg.MainNetParams)
mgr, err = Open(ns, pubPassphrase, &chaincfg.MainNetParams)
if err != nil {
return err
}
@ -1665,7 +1729,7 @@ func testManagerCase(t *testing.T, caseName string,
err = walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
return Create(
ns, caseKey, casePrivPassphrase,
ns, caseKey, pubPassphrase, casePrivPassphrase,
&chaincfg.MainNetParams, fastScrypt, time.Time{},
)
})
@ -1698,7 +1762,7 @@ func testManagerCase(t *testing.T, caseName string,
err = walletdb.View(db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
mgr, err = Open(ns, &chaincfg.MainNetParams)
mgr, err = Open(ns, pubPassphrase, &chaincfg.MainNetParams)
return err
})
if err != nil {
@ -1781,7 +1845,7 @@ func TestManagerHigherVersion(t *testing.T) {
// should expect to see the error ErrUpgrade.
err = walletdb.View(db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
_, err := Open(ns, &chaincfg.MainNetParams)
_, err := Open(ns, pubPassphrase, &chaincfg.MainNetParams)
return err
})
if !checkManagerError(t, "Upgrade needed", err, ErrUpgrade) {
@ -1805,7 +1869,7 @@ func TestManagerHigherVersion(t *testing.T) {
// ErrUpgrade.
err = walletdb.View(db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
_, err := Open(ns, &chaincfg.MainNetParams)
_, err := Open(ns, pubPassphrase, &chaincfg.MainNetParams)
return err
})
if !checkManagerError(t, "Upgrade needed", err, ErrUpgrade) {
@ -1849,7 +1913,7 @@ func TestEncryptDecryptErrors(t *testing.T) {
// Unlock the manager for these tests
err = walletdb.View(db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return mgr.Unlock(ns, passphrase)
return mgr.Unlock(ns, privPassphrase)
})
if err != nil {
t.Fatal("Attempted to unlock the manager, but failed:", err)
@ -1881,7 +1945,7 @@ func TestEncryptDecrypt(t *testing.T) {
// Make sure address manager is unlocked
err := walletdb.View(db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
return mgr.Unlock(ns, passphrase)
return mgr.Unlock(ns, privPassphrase)
})
if err != nil {
t.Fatal("Attempted to unlock the manager, but failed:", err)
@ -1929,19 +1993,19 @@ func TestScopedKeyManagerManagement(t *testing.T) {
return err
}
err = Create(
ns, rootKey, passphrase,
ns, rootKey, pubPassphrase, privPassphrase,
&chaincfg.MainNetParams, fastScrypt, time.Time{},
)
if err != nil {
return err
}
mgr, err = Open(ns, &chaincfg.MainNetParams)
mgr, err = Open(ns, pubPassphrase, &chaincfg.MainNetParams)
if err != nil {
return err
}
return mgr.Unlock(ns, passphrase)
return mgr.Unlock(ns, privPassphrase)
})
if err != nil {
t.Fatalf("create/open: unexpected error: %v", err)
@ -2088,12 +2152,12 @@ func TestScopedKeyManagerManagement(t *testing.T) {
err = walletdb.View(db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(waddrmgrNamespaceKey)
var err error
mgr, err = Open(ns, &chaincfg.MainNetParams)
mgr, err = Open(ns, pubPassphrase, &chaincfg.MainNetParams)
if err != nil {
return err
}
return mgr.Unlock(ns, passphrase)
return mgr.Unlock(ns, privPassphrase)
})
if err != nil {
t.Fatalf("open: unexpected error: %v", err)
@ -2179,19 +2243,19 @@ func TestRootHDKeyNeutering(t *testing.T) {
return err
}
err = Create(
ns, rootKey, passphrase,
ns, rootKey, pubPassphrase, privPassphrase,
&chaincfg.MainNetParams, fastScrypt, time.Time{},
)
if err != nil {
return err
}
mgr, err = Open(ns, &chaincfg.MainNetParams)
mgr, err = Open(ns, pubPassphrase, &chaincfg.MainNetParams)
if err != nil {
return err
}
return mgr.Unlock(ns, passphrase)
return mgr.Unlock(ns, privPassphrase)
})
if err != nil {
t.Fatalf("create/open: unexpected error: %v", err)
@ -2272,19 +2336,19 @@ func TestNewRawAccount(t *testing.T) {
return err
}
err = Create(
ns, rootKey, passphrase,
ns, rootKey, pubPassphrase, privPassphrase,
&chaincfg.MainNetParams, fastScrypt, time.Time{},
)
if err != nil {
return err
}
mgr, err = Open(ns, &chaincfg.MainNetParams)
mgr, err = Open(ns, pubPassphrase, &chaincfg.MainNetParams)
if err != nil {
return err
}
return mgr.Unlock(ns, passphrase)
return mgr.Unlock(ns, privPassphrase)
})
if err != nil {
t.Fatalf("create/open: unexpected error: %v", err)
@ -2385,18 +2449,18 @@ func TestDeriveFromKeyPathCache(t *testing.T) {
return err
}
err = Create(
ns, rootKey, passphrase,
ns, rootKey, pubPassphrase, privPassphrase,
&chaincfg.MainNetParams, fastScrypt, time.Time{},
)
if err != nil {
return err
}
mgr, err = Open(ns, &chaincfg.MainNetParams)
mgr, err = Open(ns, pubPassphrase, &chaincfg.MainNetParams)
if err != nil {
return err
}
return mgr.Unlock(ns, passphrase)
return mgr.Unlock(ns, privPassphrase)
})
require.NoError(t, err, "create/open: unexpected error: %v", err)

View file

@ -318,6 +318,14 @@ func populateBirthdayBlock(ns walletdb.ReadWriteBucket) error {
genesisTimestamp =
chaincfg.RegressionNetParams.GenesisBlock.Header.Timestamp
case *chaincfg.SimNetParams.GenesisHash:
genesisTimestamp =
chaincfg.SimNetParams.GenesisBlock.Header.Timestamp
case *chaincfg.SigNetParams.GenesisHash:
genesisTimestamp =
chaincfg.SigNetParams.GenesisBlock.Header.Timestamp
default:
return fmt.Errorf("unknown genesis hash %v", genesisHash)
}

View file

@ -14,6 +14,7 @@ import (
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcutil/hdkeychain"
"github.com/lbryio/lbcwallet/internal/zero"
"github.com/lbryio/lbcwallet/netparams"
"github.com/lbryio/lbcwallet/walletdb"
)
@ -45,6 +46,11 @@ const (
// HDVersionTestNetBIP0084 is the HDVersion for BIP-0084 on the test
// network.
HDVersionTestNetBIP0084 HDVersion = 0x045f1cf6 // vpub
// HDVersionSimNetBIP0044 is the HDVersion for BIP-0044 on the
// simulation test network. There aren't any other versions defined for
// the simulation test network.
HDVersionSimNetBIP0044 HDVersion = 0x0420bd3a // spub
)
const (
@ -2163,7 +2169,9 @@ func (s *ScopedKeyManager) cloneKeyWithVersion(key *hdkeychain.ExtendedKey) (
return nil, fmt.Errorf("unsupported scope %v", s.scope)
}
case wire.TestNet, wire.TestNet3:
case wire.TestNet, wire.TestNet3,
netparams.SigNetWire(s.rootManager.ChainParams()):
switch s.scope {
case KeyScopeBIP0044:
version = HDVersionTestNetBIP0044
@ -2175,6 +2183,21 @@ func (s *ScopedKeyManager) cloneKeyWithVersion(key *hdkeychain.ExtendedKey) (
return nil, fmt.Errorf("unsupported scope %v", s.scope)
}
case wire.SimNet:
switch s.scope {
case KeyScopeBIP0044:
version = HDVersionSimNetBIP0044
// We use the mainnet versions for simnet keys when the keys
// belong to a key scope which simnet doesn't have a defined
// version for.
case KeyScopeBIP0049:
version = HDVersionMainNetBIP0049
case KeyScopeBIP0084:
version = HDVersionMainNetBIP0084
default:
return nil, fmt.Errorf("unsupported scope %v", s.scope)
}
default:
return nil, fmt.Errorf("unsupported net %v", net)
}

126
waddrmgr/test_coverage.txt Normal file
View file

@ -0,0 +1,126 @@
github.com/lbryio/lbcwallet/waddrmgr/db.go serializeBIP0044AccountRow 100.00% (19/19)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.lock 100.00% (12/12)
github.com/lbryio/lbcwallet/waddrmgr/db.go serializeScriptAddress 100.00% (10/10)
github.com/lbryio/lbcwallet/waddrmgr/db.go serializeImportedAddress 100.00% (10/10)
github.com/lbryio/lbcwallet/waddrmgr/db.go serializeAddressRow 100.00% (9/9)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.Address 100.00% (8/8)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.Lock 100.00% (8/8)
github.com/lbryio/lbcwallet/waddrmgr/address.go scriptAddress.Script 100.00% (7/7)
github.com/lbryio/lbcwallet/waddrmgr/db.go serializeAccountRow 100.00% (6/6)
github.com/lbryio/lbcwallet/waddrmgr/sync.go BlockIterator.Prev 100.00% (6/6)
github.com/lbryio/lbcwallet/waddrmgr/address.go zeroBigInt 100.00% (5/5)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.zeroSensitivePublicData 100.00% (5/5)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.lock 100.00% (4/4)
github.com/lbryio/lbcwallet/waddrmgr/address.go scriptAddress.lock 100.00% (4/4)
github.com/lbryio/lbcwallet/waddrmgr/db.go serializeChainedAddress 100.00% (4/4)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.ExportPrivKey 100.00% (4/4)
github.com/lbryio/lbcwallet/waddrmgr/manager.go fileExists 100.00% (4/4)
github.com/lbryio/lbcwallet/waddrmgr/error.go ManagerError.Error 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/error.go ErrorCode.String 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.pubKeyBytes 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/sync.go Manager.NewIterateRecentBlocks 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/sync.go BlockIterator.BlockStamp 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/db.go accountKey 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/sync.go Manager.SyncedTo 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutAccountInfo 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.IsLocked 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutImportedAddress 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.ExistsAddress 100.00% (3/3)
github.com/lbryio/lbcwallet/waddrmgr/address.go zero 100.00% (2/2)
github.com/lbryio/lbcwallet/waddrmgr/address.go scriptAddress.Account 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go scriptAddress.Compressed 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/sync.go newSyncState 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go scriptAddress.Internal 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/manager.go cryptoKey.CopyBytes 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/manager.go newManager 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.AddrHash 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/manager.go defaultNewSecretKey 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go scriptAddress.Imported 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go scriptAddress.AddrHash 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go scriptAddress.Address 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.Account 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.Internal 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.Net 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.ExportPubKey 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/error.go managerError 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.PubKey 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/manager.go cryptoKey.Bytes 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.Compressed 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.Address 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.Imported 100.00% (1/1)
github.com/lbryio/lbcwallet/waddrmgr/sync.go Manager.SetSyncedTo 93.94% (31/33)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.PrivKey 91.67% (11/12)
github.com/lbryio/lbcwallet/waddrmgr/db.go deserializeBIP0044AccountRow 90.48% (19/21)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.keyToManaged 90.00% (9/10)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchCryptoKeys 88.89% (16/18)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.Close 88.89% (8/9)
github.com/lbryio/lbcwallet/waddrmgr/address.go newManagedAddressWithoutPrivKey 87.50% (7/8)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutRecentBlocks 85.71% (12/14)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Open 85.71% (6/7)
github.com/lbryio/lbcwallet/waddrmgr/db.go deserializeScriptAddress 84.62% (11/13)
github.com/lbryio/lbcwallet/waddrmgr/db.go deserializeImportedAddress 84.62% (11/13)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchRecentBlocks 84.62% (11/13)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchMasterKeyParams 84.62% (11/13)
github.com/lbryio/lbcwallet/waddrmgr/db.go deserializeAddressRow 83.33% (10/12)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.loadAndCacheAddress 83.33% (10/12)
github.com/lbryio/lbcwallet/waddrmgr/address.go managedAddress.unlock 81.82% (9/11)
github.com/lbryio/lbcwallet/waddrmgr/address.go scriptAddress.unlock 81.82% (9/11)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.nextAddresses 80.00% (52/65)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutScriptAddress 80.00% (4/5)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.ChangePassphrase 79.10% (53/67)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutChainedAddress 78.26% (18/23)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchSyncedTo 77.78% (7/9)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutStartBlock 77.78% (7/9)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchStartBlock 77.78% (7/9)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutSyncedTo 77.78% (7/9)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.existsAddress 77.78% (7/9)
github.com/lbryio/lbcwallet/waddrmgr/db.go deserializeAccountRow 77.78% (7/9)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.ExportWatchingOnly 75.00% (12/16)
github.com/lbryio/lbcwallet/waddrmgr/address.go newManagedAddressFromExtKey 75.00% (12/16)
github.com/lbryio/lbcwallet/waddrmgr/address.go newManagedAddress 75.00% (9/12)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutWatchingOnly 75.00% (6/8)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutNumAccounts 75.00% (6/8)
github.com/lbryio/lbcwallet/waddrmgr/address.go newScriptAddress 75.00% (3/4)
github.com/lbryio/lbcwallet/waddrmgr/manager.go defaultNewCryptoKey 75.00% (3/4)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.chainAddressRowToManaged 75.00% (3/4)
github.com/lbryio/lbcwallet/waddrmgr/manager.go checkBranchKeys 75.00% (3/4)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.deriveKeyFromPath 75.00% (3/4)
github.com/lbryio/lbcwallet/waddrmgr/manager.go loadManager 72.55% (37/51)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.putAddress 71.43% (5/7)
github.com/lbryio/lbcwallet/waddrmgr/db.go deserializeChainedAddress 71.43% (5/7)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.deriveKey 69.23% (9/13)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.ImportScript 67.44% (29/43)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.Unlock 67.35% (33/49)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchAddress 66.67% (10/15)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.importedAddressRowToManaged 66.67% (10/15)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutMasterKeyParams 66.67% (8/12)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.LastInternalAddress 66.67% (6/9)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.LastExternalAddress 66.67% (6/9)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.putAccountRow 66.67% (4/6)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.rowInterfaceToManaged 66.67% (4/6)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.NextExternalAddresses 66.67% (4/6)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.NextInternalAddresses 66.67% (4/6)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchWatchingOnly 66.67% (4/6)
github.com/lbryio/lbcwallet/waddrmgr/sync.go syncState.iter 66.67% (2/3)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.DeletePrivateKeys 66.04% (35/53)
github.com/lbryio/lbcwallet/waddrmgr/db.go openOrCreateDB 66.04% (35/53)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.ImportPrivateKey 64.71% (33/51)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.PutCryptoKeys 64.71% (11/17)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.loadAccountInfo 62.96% (34/54)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchAccountInfo 61.54% (8/13)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.scriptAddressRowToManaged 60.00% (3/5)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Create 58.59% (58/99)
github.com/lbryio/lbcwallet/waddrmgr/manager.go deriveAccountKey 53.85% (7/13)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerDB.Update 50.00% (4/8)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerDB.View 50.00% (4/8)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerDB.Close 50.00% (2/4)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerDB.CopyDB 45.45% (5/11)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchAllAddresses 0.00% (0/20)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.AllActiveAddresses 0.00% (0/16)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerDB.WriteTo 0.00% (0/11)
github.com/lbryio/lbcwallet/waddrmgr/sync.go BlockIterator.Next 0.00% (0/6)
github.com/lbryio/lbcwallet/waddrmgr/db.go managerTx.FetchNumAccounts 0.00% (0/6)
github.com/lbryio/lbcwallet/waddrmgr/manager.go Manager.Export 0.00% (0/3)
github.com/lbryio/lbcwallet/waddrmgr ----------------------------------- 72.59% (1030/1419)

View file

@ -33,18 +33,19 @@ func testWallet(t *testing.T) (*Wallet, func()) {
t.Fatalf("unable to create seed: %v", err)
}
passphrase := []byte("hello world")
pubPass := []byte("hello")
privPass := []byte("world")
loader := NewLoader(
&chaincfg.TestNet3Params, dir, true, defaultDBTimeout, 250,
)
w, err := loader.CreateNewWallet(passphrase, seed, time.Now())
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(passphrase, time.After(10*time.Minute)); err != nil {
if err := w.Unlock(privPass, time.After(10*time.Minute)); err != nil {
t.Fatalf("unable to unlock wallet: %v", err)
}

View file

@ -9,6 +9,7 @@ import (
"github.com/lbryio/lbcd/wire"
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcutil/hdkeychain"
"github.com/lbryio/lbcwallet/netparams"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/walletdb"
)
@ -37,7 +38,8 @@ func keyScopeFromPubKey(pubKey *hdkeychain.ExtendedKey,
// 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:
case waddrmgr.HDVersionMainNetBIP0044, waddrmgr.HDVersionTestNetBIP0044,
waddrmgr.HDVersionSimNetBIP0044:
if addrType == nil {
return waddrmgr.KeyScope{}, nil, errors.New("address " +
@ -107,10 +109,20 @@ func (w *Wallet) isPubKeyForNet(pubKey *hdkeychain.ExtendedKey) bool {
version == waddrmgr.HDVersionMainNetBIP0049 ||
version == waddrmgr.HDVersionMainNetBIP0084
case wire.TestNet, wire.TestNet3:
case wire.TestNet, wire.TestNet3, netparams.SigNetWire(w.chainParams):
return version == waddrmgr.HDVersionTestNetBIP0044 ||
version == waddrmgr.HDVersionTestNetBIP0049 ||
version == waddrmgr.HDVersionTestNetBIP0084
// For simnet, we'll also allow the mainnet versions since simnet
// doesn't have defined versions for some of our key scopes, and the
// mainnet versions are usually used as the default regardless of the
// network/key scope.
case wire.SimNet:
return version == waddrmgr.HDVersionSimNetBIP0044 ||
version == waddrmgr.HDVersionMainNetBIP0049 ||
version == waddrmgr.HDVersionMainNetBIP0084
default:
return false
}

View file

@ -14,6 +14,8 @@ import (
"github.com/lbryio/lbcd/chaincfg"
"github.com/lbryio/lbcutil/hdkeychain"
"github.com/lbryio/lbcwallet/internal/prompt"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/walletdb"
)
@ -138,10 +140,10 @@ func (l *Loader) OnWalletCreated(fn func(walletdb.ReadWriteTx) error) {
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,
// 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,
bday time.Time) (*Wallet, error) {
var (
@ -166,20 +168,20 @@ func (l *Loader) CreateNewWallet(passphrase, seed []byte,
}
}
return l.createNewWallet(passphrase, rootKey, bday)
return l.createNewWallet(pubPassphrase, privPassphrase, 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
// key using the provided public and private passphrases. 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,
func (l *Loader) CreateNewWalletExtendedKey(pubPassphrase, privPassphrase []byte,
rootKey *hdkeychain.ExtendedKey, bday time.Time) (*Wallet, error) {
return l.createNewWallet(passphrase, rootKey, bday)
return l.createNewWallet(pubPassphrase, privPassphrase, rootKey, bday)
}
func (l *Loader) createNewWallet(passphrase []byte,
func (l *Loader) createNewWallet(pubPassphrase, privPassphrase []byte,
rootKey *hdkeychain.ExtendedKey, bday time.Time) (*Wallet, error) {
defer l.mu.Unlock()
@ -214,15 +216,16 @@ func (l *Loader) createNewWallet(passphrase []byte,
}
// Initialize the newly created database for the wallet before opening.
err = CreateWithCallback(l.db, passphrase, rootKey, l.chainParams,
bday, l.walletCreated,
err = CreateWithCallback(
l.db, pubPassphrase, privPassphrase, rootKey,
l.chainParams, bday, l.walletCreated,
)
if err != nil {
return nil, err
}
// Open the newly-created wallet.
w, err := Open(l.db, l.chainParams, l.recoveryWindow)
w, err := Open(l.db, pubPassphrase, nil, l.chainParams, l.recoveryWindow)
if err != nil {
return nil, err
}
@ -234,10 +237,15 @@ func (l *Loader) createNewWallet(passphrase []byte,
var errNoConsole = errors.New("db upgrade requires console access for additional input")
// 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) {
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) {
defer l.mu.Unlock()
l.mu.Lock()
@ -263,7 +271,19 @@ func (l *Loader) OpenExistingWallet() (*Wallet, error) {
}
}
w, err := Open(l.db, l.chainParams, l.recoveryWindow)
var cbs *waddrmgr.OpenCallbacks
if canConsolePrompt {
cbs = &waddrmgr.OpenCallbacks{
ObtainSeed: prompt.ProvideSeed(),
ObtainPrivatePass: prompt.ProvidePrivPassphrase,
}
} else {
cbs = &waddrmgr.OpenCallbacks{
ObtainSeed: noConsole,
ObtainPrivatePass: noConsole,
}
}
w, err := Open(l.db, pubPassphrase, cbs, 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

View file

@ -26,6 +26,7 @@ import (
btcutil "github.com/lbryio/lbcutil"
"github.com/lbryio/lbcutil/hdkeychain"
"github.com/lbryio/lbcwallet/chain"
"github.com/lbryio/lbcwallet/internal/prompt"
"github.com/lbryio/lbcwallet/waddrmgr"
"github.com/lbryio/lbcwallet/wallet/txauthor"
"github.com/lbryio/lbcwallet/wallet/txrules"
@ -35,6 +36,16 @@ import (
)
const (
// InsecurePubPassphrase is the default outer encryption passphrase used
// for public data (everything but private keys). Using a non-default
// public passphrase can prevent an attacker without the public
// passphrase from discovering all past and future wallet addresses if
// they gain access to the wallet database.
//
// NOTE: at time of writing, public encryption only applies to public
// data in the waddrmgr namespace. Transactions are not yet encrypted.
InsecurePubPassphrase = "public"
// recoveryBatchSize is the default number of blocks that will be
// scanned successively by the recovery manager, in the event that the
// wallet is started in recovery mode.
@ -88,6 +99,8 @@ const (
// complete wallet. It contains the Armory-style key store
// addresses and keys),
type Wallet struct {
publicPassphrase []byte
// Data stores
db walletdb.DB
Manager *waddrmgr.Manager
@ -121,6 +134,7 @@ type Wallet struct {
holdUnlockRequests chan chan heldUnlock
lockState chan bool
changePassphrase chan changePassphraseRequest
changePassphrases chan changePassphrasesRequest
NtfnServer *NotificationServer
@ -406,7 +420,7 @@ func (w *Wallet) syncWithChain(birthdayStamp *waddrmgr.BlockStamp) error {
// If the wallet requested an on-chain recovery of its funds, we'll do
// so now.
if w.recoveryWindow > 0 {
if err := w.Recovery(chainClient); err != nil {
if err := w.recovery(chainClient, birthdayStamp); err != nil {
return fmt.Errorf("unable to perform wallet recovery: "+
"%v", err)
}
@ -528,10 +542,11 @@ func (w *Wallet) syncWithChain(birthdayStamp *waddrmgr.BlockStamp) error {
}
// isDevEnv determines whether the wallet is currently under a local developer
// environment, e.g. regtest.
// environment, e.g. simnet or regtest.
func (w *Wallet) isDevEnv() bool {
switch uint32(w.ChainParams().Net) {
case uint32(chaincfg.RegressionNetParams.Net):
case uint32(chaincfg.SimNetParams.Net):
default:
return false
}
@ -637,12 +652,13 @@ func locateBirthdayBlock(chainClient chainConn,
return birthdayBlock, nil
}
// Recovery attempts to recover any unspent outputs that pay to any of our
// recovery attempts to recover any unspent outputs that pay to any of our
// addresses starting from our birthday, or the wallet's tip (if higher), which
// would indicate resuming a recovery after a restart.
func (w *Wallet) Recovery(chainClient chain.Interface) error {
func (w *Wallet) recovery(chainClient chain.Interface,
birthdayBlock *waddrmgr.BlockStamp) error {
log.Infof("Recovery for used addresses "+
log.Infof("RECOVERY MODE ENABLED -- rescanning for used addresses "+
"with recovery_window=%d", w.recoveryWindow)
// We'll initialize the recovery manager with a default batch size of
@ -670,36 +686,44 @@ func (w *Wallet) Recovery(chainClient chain.Interface) error {
return err
}
return nil
}
func (w *Wallet) RescanBlockchain(chainClient chain.Interface,
startHeight int32, stopHeight int32) (int32, int32, error) {
log.Infof("Rescanning blockchain from block %d to %d "+
"with recovery_window=%d", startHeight, stopHeight,
w.recoveryWindow)
defer log.Infof("Rescan blockchain done")
recoveryMgr := NewRecoveryManager(
w.recoveryWindow, recoveryBatchSize, w.chainParams,
)
scopedMgrs := make(map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager)
for _, scopedMgr := range w.Manager.ActiveScopedKeyManagers() {
scopedMgrs[scopedMgr.Scope()] = scopedMgr
// Fetch the best height from the backend to determine when we should
// stop.
_, bestHeight, err := chainClient.GetBestBlock()
if err != nil {
return err
}
// Now we can begin scanning the chain from the wallet's current tip to
// ensure we properly handle restarts. Since the recovery process itself
// acts as rescan, we'll also update our wallet's synced state along the
// way to reflect the blocks we process and prevent rescanning them
// later on.
//
// NOTE: We purposefully don't update our best height since we assume
// that a wallet rescan will be performed from the wallet's tip, which
// will be of bestHeight after completing the recovery process.
pass, err := prompt.ProvidePrivPassphrase()
if err != nil {
return err
}
err = w.Unlock(pass, nil)
if err != nil {
return err
}
defer w.Lock()
var blocks []*waddrmgr.BlockStamp
for height := startHeight; height <= stopHeight; height++ {
startHeight := w.Manager.SyncedTo().Height + 1
for height := startHeight; height <= bestHeight; height++ {
hash, err := chainClient.GetBlockHash(int64(height))
if err != nil {
return startHeight, stopHeight, err
return err
}
header, err := chainClient.GetBlockHeader(hash)
if err != nil {
return startHeight, stopHeight, err
return err
}
blocks = append(blocks, &waddrmgr.BlockStamp{
Hash: *hash,
@ -710,7 +734,7 @@ func (w *Wallet) RescanBlockchain(chainClient chain.Interface,
// It's possible for us to run into blocks before our birthday
// if our birthday is after our reorg safe height, so we'll make
// sure to not add those to the batch.
if height >= startHeight {
if height >= birthdayBlock.Height {
recoveryMgr.AddToBlockBatch(
hash, height, header.Timestamp,
)
@ -721,12 +745,18 @@ func (w *Wallet) RescanBlockchain(chainClient chain.Interface,
// the recovery batch size, so we can proceed to commit our
// state to disk.
recoveryBatch := recoveryMgr.BlockBatch()
if len(recoveryBatch) != recoveryBatchSize && height != stopHeight {
if len(recoveryBatch) != recoveryBatchSize && height != bestHeight {
continue
}
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)
for _, block := range blocks {
err = w.Manager.SetSyncedTo(ns, block)
if err != nil {
return err
}
}
for scope, scopedMgr := range scopedMgrs {
scopeState := recoveryMgr.State().StateForScope(scope)
err = expandScopeHorizons(ns, scopedMgr, scopeState)
@ -739,7 +769,7 @@ func (w *Wallet) RescanBlockchain(chainClient chain.Interface,
)
})
if err != nil {
return startHeight, stopHeight, err
return err
}
if len(recoveryBatch) > 0 {
@ -753,7 +783,8 @@ func (w *Wallet) RescanBlockchain(chainClient chain.Interface,
blocks = blocks[:0]
recoveryMgr.ResetBlockBatch()
}
return startHeight, stopHeight, nil
return nil
}
// recoverScopedAddresses scans a range of blocks in attempts to recover any
@ -1157,9 +1188,16 @@ type (
changePassphraseRequest struct {
old, new []byte
private bool
err chan error
}
changePassphrasesRequest struct {
publicOld, publicNew []byte
privateOld, privateNew []byte
err chan error
}
// heldUnlock is a tool to prevent the wallet from automatically
// locking after some timeout before an operation which needed
// the unlocked wallet has finished. Any acquired heldUnlock
@ -1198,13 +1236,32 @@ out:
err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
return w.Manager.ChangePassphrase(
addrmgrNs, req.old, req.new,
addrmgrNs, req.old, req.new, req.private,
&waddrmgr.DefaultScryptOptions,
)
})
req.err <- err
continue
case req := <-w.changePassphrases:
err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
err := w.Manager.ChangePassphrase(
addrmgrNs, req.publicOld, req.publicNew,
false, &waddrmgr.DefaultScryptOptions,
)
if err != nil {
return err
}
return w.Manager.ChangePassphrase(
addrmgrNs, req.privateOld, req.privateNew,
true, &waddrmgr.DefaultScryptOptions,
)
})
req.err <- err
continue
case req := <-w.holdUnlockRequests:
if w.Manager.IsLocked() {
close(req)
@ -1305,16 +1362,45 @@ func (c heldUnlock) release() {
c <- struct{}{}
}
// ChangePassphrase attempts to change the passphrase for a wallet from
// ChangePrivatePassphrase attempts to change the passphrase for a wallet from
// old to new. Changing the passphrase is synchronized with all other address
// manager locking and unlocking. The lock state will be the same as it was
// before the password change.
func (w *Wallet) ChangePassphrase(old, new []byte) error {
func (w *Wallet) ChangePrivatePassphrase(old, new []byte) error {
err := make(chan error, 1)
w.changePassphrase <- changePassphraseRequest{
old: old,
new: new,
err: err,
old: old,
new: new,
private: true,
err: err,
}
return <-err
}
// ChangePublicPassphrase modifies the public passphrase of the wallet.
func (w *Wallet) ChangePublicPassphrase(old, new []byte) error {
err := make(chan error, 1)
w.changePassphrase <- changePassphraseRequest{
old: old,
new: new,
private: false,
err: err,
}
return <-err
}
// ChangePassphrases modifies the public and private passphrase of the wallet
// atomically.
func (w *Wallet) ChangePassphrases(publicOld, publicNew, privateOld,
privateNew []byte) error {
err := make(chan error, 1)
w.changePassphrases <- changePassphrasesRequest{
publicOld: publicOld,
publicNew: publicNew,
privateOld: privateOld,
privateNew: privateNew,
err: err,
}
return <-err
}
@ -3573,23 +3659,29 @@ func (w *Wallet) Database() walletdb.DB {
// CreateWithCallback is the same as Create with an added callback that will be
// called in the same transaction the wallet structure is initialized.
func CreateWithCallback(db walletdb.DB, privPass []byte,
func CreateWithCallback(db walletdb.DB, pubPass, privPass []byte,
rootKey *hdkeychain.ExtendedKey, params *chaincfg.Params,
birthday time.Time, cb func(walletdb.ReadWriteTx) error) error {
return create(db, privPass, rootKey, params, birthday, cb)
return create(
db, pubPass, privPass, rootKey, params, birthday, cb,
)
}
// Create creates an new wallet, writing it to an empty database. If the passed
// root key is non-nil, it is used. Otherwise, a secure random seed of the
// recommended length is generated.
func Create(db walletdb.DB, privPass []byte, rootKey *hdkeychain.ExtendedKey,
params *chaincfg.Params, birthday time.Time) error {
func Create(db walletdb.DB, pubPass, privPass []byte,
rootKey *hdkeychain.ExtendedKey, params *chaincfg.Params,
birthday time.Time) error {
return create(db, privPass, rootKey, params, birthday, nil)
return create(
db, pubPass, privPass, rootKey, params, birthday, nil,
)
}
func create(db walletdb.DB, privPass []byte, rootKey *hdkeychain.ExtendedKey,
params *chaincfg.Params, birthday time.Time,
func create(db walletdb.DB, pubPass, privPass []byte,
rootKey *hdkeychain.ExtendedKey, params *chaincfg.Params,
birthday time.Time,
cb func(walletdb.ReadWriteTx) error) error {
// If no root key was provided, we create one now from a random seed.
@ -3626,7 +3718,7 @@ func create(db walletdb.DB, privPass []byte, rootKey *hdkeychain.ExtendedKey,
}
err = waddrmgr.Create(
addrmgrNs, rootKey, privPass, params, nil,
addrmgrNs, rootKey, pubPass, privPass, params, nil,
birthday,
)
if err != nil {
@ -3647,8 +3739,8 @@ func create(db walletdb.DB, privPass []byte, rootKey *hdkeychain.ExtendedKey,
}
// Open loads an already-created wallet from the passed database and namespaces.
func Open(db walletdb.DB, params *chaincfg.Params, recoveryWindow uint32) (
*Wallet, error) {
func Open(db walletdb.DB, pubPass []byte, cbs *waddrmgr.OpenCallbacks,
params *chaincfg.Params, recoveryWindow uint32) (*Wallet, error) {
var (
addrMgr *waddrmgr.Manager
@ -3676,7 +3768,7 @@ func Open(db walletdb.DB, params *chaincfg.Params, recoveryWindow uint32) (
return err
}
addrMgr, err = waddrmgr.Open(addrMgrBucket, params)
addrMgr, err = waddrmgr.Open(addrMgrBucket, pubPass, params)
if err != nil {
return err
}
@ -3694,6 +3786,7 @@ func Open(db walletdb.DB, params *chaincfg.Params, recoveryWindow uint32) (
log.Infof("Opened wallet") // TODO: log balance? last sync height?
w := &Wallet{
publicPassphrase: pubPass,
db: db,
Manager: addrMgr,
TxStore: txMgr,
@ -3710,6 +3803,7 @@ func Open(db walletdb.DB, params *chaincfg.Params, recoveryWindow uint32) (
holdUnlockRequests: make(chan chan heldUnlock),
lockState: make(chan bool),
changePassphrase: make(chan changePassphraseRequest),
changePassphrases: make(chan changePassphrasesRequest),
chainParams: params,
quit: make(chan struct{}),
}

7
walletdb/cov_report.sh Normal file
View file

@ -0,0 +1,7 @@
#!/bin/sh
# This script uses go tool cover to generate a test coverage report.
go test -coverprofile=cov.out && go tool cover -func=cov.out && rm -f cov.out
echo "============================================================"
(cd bdb && go test -coverprofile=cov.out && go tool cover -func=cov.out && \
rm -f cov.out)

View file

@ -0,0 +1,39 @@
PASS
coverage: 100.0% of statements
ok github.com/lbryio/lbcwallet/walletdb 0.130s
github.com\lbryio\lbcwallet\walletdb\interface.go:190: RegisterDriver 100.0%
github.com\lbryio\lbcwallet\walletdb\interface.go:201: SupportedDrivers 100.0%
github.com\lbryio\lbcwallet\walletdb\interface.go:214: Create 100.0%
github.com\lbryio\lbcwallet\walletdb\interface.go:228: Open 100.0%
total: (statements) 100.0%
============================================================
PASS
coverage: 91.7% of statements
ok github.com/lbryio/lbcwallet/walletdb/bdb 0.149s
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:28: convertErr 76.9%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:74: Bucket 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:90: CreateBucket 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:103: CreateBucketIfNotExists 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:116: DeleteBucket 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:129: ForEach 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:136: Writable 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:145: Put 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:157: Get 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:166: Delete 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:185: RootBucket 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:193: Commit 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:201: Rollback 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:227: Begin 85.7%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:249: View 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:270: Update 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:294: Namespace 93.3%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:329: DeleteNamespace 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:339: WriteTo 0.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:348: Close 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:353: fileExists 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\db.go:364: openDB 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\driver.go:34: parseArgs 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\driver.go:50: openDBDriver 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\driver.go:60: createDBDriver 100.0%
github.com\lbryio\lbcwallet\walletdb\bdb\driver.go:69: init 66.7%
total: (statements) 91.7%

View file

@ -45,10 +45,22 @@ func createWallet(cfg *config) error {
activeNet.Params, dbDir, true, cfg.DBTimeout, 250,
)
// Start by prompting for the passphrase.
passphrase := []byte(cfg.Passphrase)
// Start by prompting for the private passphrase.
reader := bufio.NewReader(os.Stdin)
privPass, err := prompt.PrivatePass(reader)
if err != nil {
return err
}
// Ascertain the public passphrase. This will either be a value
// specified by the user or the default hard-coded public passphrase if
// the user does not want the additional public data encryption.
pubPass, err := prompt.PublicPass(reader, privPass,
[]byte(wallet.InsecurePubPassphrase), []byte(cfg.WalletPass))
if err != nil {
return err
}
// Ascertain the wallet generation seed. This will either be an
// automatically generated value the user has already confirmed or a
// value the user has entered which has already been validated.
@ -58,7 +70,7 @@ func createWallet(cfg *config) error {
}
fmt.Println("Creating the wallet...")
w, err := loader.CreateNewWallet(passphrase, seed, bday)
w, err := loader.CreateNewWallet(pubPass, privPass, seed, bday)
if err != nil {
return err
}
@ -76,6 +88,9 @@ func createSimulationWallet(cfg *config) error {
// Simulation wallet password is 'password'.
privPass := []byte("password")
// Public passphrase is the default.
pubPass := []byte(wallet.InsecurePubPassphrase)
netDir := networkDir(cfg.AppDataDir.Value, activeNet.Params)
// Create the wallet.
@ -90,7 +105,7 @@ func createSimulationWallet(cfg *config) error {
defer db.Close()
// Create the wallet.
err = wallet.Create(db, privPass, nil, activeNet.Params, time.Now())
err = wallet.Create(db, pubPass, privPass, nil, activeNet.Params, time.Now())
if err != nil {
return err
}