Minor refactorings and fixes in VersionMessage.

* Fixed toString() bug.
* Updated comments to match present Bitcoin Core behavior with respect to User-Agent.
* Removed constructor accepting a boolean. This changes public API but neither multibit
  nor bitcoin-wallet nor mycelium nor hive-android uses this version of constructor.
  The rationale is to avoid passing a boolean to a method as this makes code hard to read.
  Client classes updated to preserve original semantic. All tests pass.

Wallet: rename setLookaheadThreshold() to setKeychainLookaheadThreshold()

for consistency

Add a method to deserialize a DeterministicKey from a byte-array rather than from the base-58 encoding thereof.

Tests for new `DeterministicKey.deserialize()` method.

Fixed indentation in `DeterministicKey.java`.

Fixed a mis-indented line.

Replaced tab characters with spaces.

Changed tabs to spaces -- for customary consistency with existing code

Remove undocumented and unused Transaction constructor. I found it misleading because it allows you to pass in a hash, but the hash can be changed without notice.

Fix Wallet.isTransactionRelevant() JavaDoc. There is no "includeDoubleSpending".

Fix Wallet.checkForDoubleSpendAgainstPending() JavaDoc. It returns a boolean.

Fix link in Wallet.notifyTransactionIsInBlock() JavaDoc.

Copy @throws from the JavaDoc of Wallet.completeTx() to all calling methods.

Remove unused CouldNotAdjustDownwards. Move JavaDoc to the real one.

Allow zero repetitions for CoinFormat.repeatOptionalDecimals(). Also add tests.

Fixed bitcoinj DoS. It could have been crashed by a malicious message.

Bitcoinj can be crashed with OutOfMemory by sending a message with
a large claimed var_str length or bytes array length.

The actual message size does not matter, it's the claimed length that matters.

This affects all bitcoinj-based apps that receive messages including Multibit, Android Bitcoin Wallet, Mycelium and Hive.

The fix limits accepted length to max message size (32 MB).

Signed-off-by: Mike Hearn <mike@plan99.net>

HD wallet: currentKey is now stable after serialization roundtrip

At the moment currentKeys map of KeyChainGroup is not restored after
deserialization and subsequent call to currentKey produces different
key then expected.
Proposed solution reconstructs currentKey map on deserialization using
stored numbers of issues keys. It is
not future-proof as it assumes only RECEIVE and CHANGE keys are being
used.

Add a method to deserialize a DeterministicKey from a byte-array rather than from the base-58 encoding thereof.

Update AUTHORS file with recent contributors

Add a missing lock on BasicKeyChain.getBloomFilter

Fix failing deserialization of wallet with an empty HD chain

Error occurred when deserializing wallet if either internal or external
zero account key chain of this wallet has no keys issued

Fix failing WalletProtobufSerializerTest

Make Transaction comparators compatible with equals

Add Alexykot's test net DNS seed. Tested using Bitcoin Wallet, works fine.

Fix redundant expression in MnemonicCode.

HD Wallets: implement auto upgrade behaviour and refresh the design doc.

Fix a bug because the SendRequest.fee field is written to 0 when SendRequest.emptyWallet is used. Missing tests for this case are added.

Use SendRequest.tx.getFee() to get the fee, rather than reading SendRequest.fee.

Add SendRequest.signInputs flag to allow skipping the signing. It takes a long time and is not needed for when you only want to determine the fee.

Harmonize how BTC values are printed to the log by Wallet.completeTx(). Also, print the value that is emptied.

Add SendRequest.toString().

HD Wallets: do auto upgrade when possible on all inbound codepaths, and make DeterministicUpgradeRequiresPassword extend RuntimeException.

Full mode test generator: use OP_NOP in inputs instead of OP_TRUE to avoid unclean stacks after execution. Additionally, reduce the verbosity of the code somewhat. There's still plenty that could be done to make the code cleaner but .... not today.

Remove undefined arithmetics method.

Fixed VarInt serialization bug for the 0xffffffff number. Fixed VarInt sizeOf bug for the 0xffffffff number and added tests for VarInt edge cases.

The 4294967295 number (0xffffffff) was incorrectly serialized because the UnsignedInteger.MAX_VALUE.longValue() helper returned 4294967295 instead of expected 4294967296.

The VarInt.sizeOf() incorrectly returned 9 instead of 5 for the 4294967295 (0xffffffff) number.

See https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer

Extension of java.text.Format for locale-sensitive Bitcoin value formatting & parsing.

Fix key derivation

Changes to the `Coin` class: some convenience comparison operators;
`parseCoin()` now accepts negative values; the check for an excessive
value is moved to the constructor from `parseCoin()` and uses
`checkArgument()`; some `Coin`-type constants broken out into one
`long` one `Coin` in order to be usable in the constructor.
Corresponding tests included.  The `BitcoinURI` class constructor
throws exception on parsing a negative amount, which is needed now
that `Coin` class accepts negative amounts.

`TransactionOutput` class private `value` member changed to type `long` from `Coin`.

Married HD wallets: introduce shadow keychain notion

Pull request: #99
Based on design notes:
https://groups.google.com/d/msg/bitcoinj/Uxl-z40OLuQ/e2m4mEWR6gMJ

Improvement of getFollowingKeys

First of all, freshAddress was actually asking for a fresh key twice for non-married keychain. That was fixed by moving first call (needed only for married chain) inside the getFollowingKeys. As the latter now started to return all keys in a marriage and not only following ones, it was renamed to freshMarriedKeys.
Having all the keys in one block allows to do simple derivation path check to make sure keychains are in sync (as per @devrandom suggestion)

Prevent marriage of used keychain

 addFollowingAccounts method now has the check that active keychain has no keys in use. This would prevent divergence of derivation paths for followed and following keys. In future this behaviour should be replaced with some sort of key rotation.

Explain why a transaction output value is kept as a long rather than Coin.

Wallet: move setTag to the extensions section of the file.

Wallet: remove a few dead stores identified via static analysis.

Add a forgotten @Test annotation and fix the expected exception type.

Remove some superfluous new String() calls around HEX.encode, now it has a sane API.

Wallet tool launcher for Windows

Essentially it is just a port of wallet-tool bash script

Fix autosave in WalletTool on Windows

Wallet.saveToFile failed to remove original wallet file because WalletTool
left open input stream. This error happened on Windows-specific code path

Stacktrace:
```
Failed to save wallet! Old wallet should be left untouched.
java.io.IOException: Failed to delete canonical wallet file for
replacement with autosave
        at com.google.bitcoin.core.Wallet.saveToFile(Wallet.java:834)
	        at
		com.google.bitcoin.core.Wallet.saveToFile(Wallet.java:863)
		        at
			com.google.bitcoin.tools.WalletTool.saveWallet(WalletTool.java:851)
			        at
				com.google.bitcoin.tools.WalletTool.main(WalletTool.java:362)
```

Give regtest mode its own ID so wallets don't get mixed up between regtest and testnet.

Rename addFollowingAccounts -> addFollowingAccountKeys

Married HD wallets: Bloom filter adjustments

Pull request: #115
Based on design notes:
https://groups.google.com/forum/#!msg/bitcoinj/Uxl-z40OLuQ/e2m4mEWR6gMJ

Close connections in H2FullPrunedBlockStore

Add encrypt/decrypt command to the WalletTool help text.

HD Wallets: redo key rotation, it's no longer automatic and expects the wallet app to poll for maintenance transactions. Deterministic keys now inherit the creation time of their parent.

added a helper function to parse human readable deterministic paths

Married wallets: extending fee calculation

PeerGroup.startBlockChainDownload(): add the supplied listener to the
downloadingPeer

Updated AUTHORS file.

Peer.blockChainDownloadLocked() - fix getblocks message documentation

Update the documentation for Transaction.hashForSignature to note a quirk of P2SH outputs.

Update root POM for github switch and remove the old googlecode repo, which is blocked in China.

relax assumption that HD seeds are 128 bits

relax assumption that HD seeds are 128 bits

cleanup

Update HD wallets todo list.

Auto-upgrade to HD when fetching a change address.

Make DumpedPrivateKey serializable, so that it can be used to pass around keys between loosely coupled application components.

Fix a payment protocol unit test that had a forgotten @Test annotation and thus didn't actually work.

Fix ECKey.equals() and toString() to also include encryptedPrivateKey. Convert to Guava and consolidate at bottom of class.

Add ability to prefix or postfix currency codes when formatting coins. Defaults are BTC, mBTC and µBTC.

Coin.toFriendlyFormat() includes denomination (BTC). This saves a lot of string concatenation code.

Allow TestWithNetworkConnections subclasses to override the wallet with their own.

Fix java package of ExponentialBackoffTest.

Expose TransactionBroadcast.random

Add cobertura support

Fix BIP39 implementation

Remove support for mnemonic-less keychains

added test for HDUtils.formatPath and changed HDUtils.parsePath to handle paths that start with the letter M

Dead transaction does not contain confidence depth and should not fail when sorting.

Implement BIP38 password encrypted private keys, decryption only. Contains all the test vectors from the spec minus one that is incompatible to Java.

Fix a couple of static method via instance warnings.

Disable code that no longer compiles in WalletTool pending fix.

Generalise the crypto DRM workaround and use from the BIP38 codepath too.

Wallet Template: fix rendering of balance label after coin toFriendlyString change.

Less debug spam when sending bloom filters to keep FP rate low.

WalletAppKit/Template: Cleaner way to check if the app is already running. Backport from Lighthouse.

Clear an NPE in wallet printing that could occur when printing a wallet with private keys included.

WalletAppKit: support for restoring a wallet from a seed. The old wallet is moved out of the way.

Wallet template: add a UI to show the users seed words and demonstrate how to do a restore from seed with WalletAppKit.

Minor style cleanups in WalletSettingsController

Take out old WalletTool code that let you specify entropy as hex.

WalletTemplate: add support for encryption. Scrypt parameters are calculated by testing CPU speed. A pie chart shows smooth decryption progress.

WalletTemplate: introduce a simple wallet model and use the FX reactive bindings framework to clean up and fix some bugs. Empty wallet button now is disabled when the wallet is empty.

Add forgotten image file

Fix Java7'ism.

Remove superfluous AddressFormatException from BIP38PrivateKey.decrypt().

Turns out there was both a JFX way to do this, plus EasyBind which is even more concise.

Use released version of easybind

fixed MAX_STANDARD_TX_SIZE to match bitcoin core

in bitcoin core MAX_STANDARD_TX_SIZE is 100000, not 102400

https://github.com/bitcoin/bitcoin/blob/master/src/main.h#L43

HD Wallets: fix key lookahead and auto-advance so it works as intended.

Previously the codepath that was supposed to mark keys as used didn't work, and the lookahead calculation wasn't quite right. Now the current key advances correctly when an inbound tx is found that spends to it, including pending transactions. Additionally the lookahead zone now has the threshold zone after it, not inside it, meaning that if you request a lookahead size of 100 keys you'll actually always have at least 100 keys, never less.

Fix reason why BIP38 test vector is failing, Java strings can contain null characters just fine.

Fix some exception messages in BIP38PrivateKey.

Getter for addresses watched by wallet.

Made some methods public in BasicKeyChain. Fixes in deterministic key generation

Update wallet todo list.

Remove the HD wallets todo list - there's now sufficiently little left to do that it's no longer useful. Other stuff should be put into the bug tracker.

Re-organise the layout of the Wallet file and introduce IntelliJ compatible editor regions, so parts of the code can be folded by feature area. This also makes it easier to understand what exactly the wallet does and why it's so huge.

Update bip38 test3 ignore message again now the problem is better understood.

Adjust the behaviour of the current key mechanism to be more like what gui wallets really need.

Wallet Template: bugfix in ui logic for encryption

WalletTool: make raw-dump output a little more helpful.

Add ASSURANCE_CONTRACT_CLAIM/PLEDGE/STUB to the purpose field.

Add logging for output disconnection and reconnection.

Restore new tx purposes correctly.

Print full backtrace when a wallet extension fails to load.

BIP38: Fix test using supplementary characters in the passphrase.

use List interface instead of LinkedList implementation

Close connections in PostgresFullPrunedBlockStore. same as: b6f61e8850acabb38618baa05b4ca2edd9391a65

adds helper methods Transaction.getWalletOutputs, TransactionOutput.getAddressFromPubKey and TransactionOutput.getAddressFromScript.

Fix Script.getNumberOfBytesRequiredToSpend for P2SH

It is a size of redeem script that should be taken into account, not a
size of scriptPubKey

Upgrade to Bouncy/Spongy Castle 1.51

Switch to accelerated secp256k1: huge speed improvements.

Re-allow Android devs to override the mnemonic code instance.

Use a local Bitcoin node if one is detected instead of the p2p network. This allows any user of a bitcoinj based app to upgrade from SPV to full mode security by just installing and running Core on the same machine. Can be controlled with a new property on PeerGroup.

Improve javadocs, revert unnecessary unmodifiable list

Fix typo

close connection regardless of autocommit status and set conn to null

Add some javadocs for Wallet.fromWatchingKey

Fix Java 6 compatibility.

Fix race between connectionClosed() and ConnectionHandler()

Fix memory leak on timeout in NioClient

ConnectionHandler: Make comment a bit clearer.

Support for bundling an optional info Protobuf ByteString with an UpdatePayment message.

Payment channels:  ByteString.EMPTY -> null
`PaymentProtocol.createPaymentRequest()` was using milliseconds instead of seconds for the
`time` field of PaymentDetails as per BIP-70.