bitcoinj.github.io - Working with the wallet









Search Preview

Working with the wallet

bitcoinj.github.io
Introduction Getting started Documentation Community Working with the wallet Introduction Setup Getting add
.io > bitcoinj.github.io

SEO audit: Content analysis

Language Error! No language localisation is found.
Title Working with the wallet
Text / HTML ratio 62 %
Frame Excellent! The website does not use iFrame solutions.
Flash Excellent! The website does not have any flash contents.
Keywords cloud wallet transaction keys transactions key = default block Wallet chain wallets object method network spend balance create fee SendRequest private
Keywords consistency
Keyword Content Title Description Headings
wallet 96
transaction 47
keys 44
transactions 43
key 33
= 29
Headings
H1 H2 H3 H4 H5 H6
1 17 0 0 0 0
Images We found 1 images on this web page.

SEO Keywords (Single)

Keyword Occurrence Density
wallet 96 4.80 %
transaction 47 2.35 %
keys 44 2.20 %
transactions 43 2.15 %
key 33 1.65 %
= 29 1.45 %
default 19 0.95 %
block 19 0.95 %
Wallet 18 0.90 %
chain 16 0.80 %
wallets 15 0.75 %
object 15 0.75 %
method 15 0.75 %
network 15 0.75 %
spend 14 0.70 %
balance 13 0.65 %
create 13 0.65 %
fee 13 0.65 %
SendRequest 13 0.65 %
private 13 0.65 %

SEO Keywords (Two Word)

Keyword Occurrence Density
the wallet 55 2.75 %
of the 20 1.00 %
the transaction 19 0.95 %
You can 18 0.90 %
can be 16 0.80 %
to be 13 0.65 %
if you 13 0.65 %
in the 12 0.60 %
to a 12 0.60 %
and then 11 0.55 %
to the 11 0.55 %
you can 10 0.50 %
private keys 10 0.50 %
how to 9 0.45 %
and the 9 0.45 %
= new 9 0.45 %
will be 9 0.45 %
the network 9 0.45 %
a transaction 9 0.45 %
use the 8 0.40 %

SEO Keywords (Three Word)

Keyword Occurrence Density Possible Spam
the wallet to 6 0.30 % No
the private keys 6 0.30 % No
the block chain 6 0.30 % No
a list of 6 0.30 % No
You can also 5 0.25 % No
to commit a 4 0.20 % No
if you don’t 4 0.20 % No
a wallet that 4 0.20 % No
commit a transaction 4 0.20 % No
= new Addressparams 4 0.20 % No
across the network 4 0.20 % No
in the wallet 3 0.15 % No
in this case 3 0.15 % No
at the right 3 0.15 % No
in order to 3 0.15 % No
the wallet is 3 0.15 % No
the transaction to 3 0.15 % No
transactions in it 3 0.15 % No
no way to 3 0.15 % No
one of the 3 0.15 % No

SEO Keywords (Four Word)

Keyword Occurrence Density Possible Spam
how to use the 3 0.15 % No
= new Addressparams 1RbxbA1yP2Lebauuef3cBiBho853f7jxs 3 0.15 % No
to commit a transaction 3 0.15 % No
wallets and pluggable signers 2 0.10 % No
wallet to a UTXO 2 0.10 % No
the wallet to a 2 0.10 % No
Connecting the wallet to 2 0.10 % No
appear in a block 2 0.10 % No
make the transaction valid 2 0.10 % No
to the remote service 2 0.10 % No
Marriedmultisignature wallets and pluggable 2 0.10 % No
the wallet is loaded 2 0.10 % No
talk to the remote 2 0.10 % No
lower than what you 2 0.10 % No
Encrypting the private keys 2 0.10 % No
the wallet using the 2 0.10 % No
multisends and other contracts 2 0.10 % No
Creating multisends and other 2 0.10 % No
to a UTXO store 2 0.10 % No
the next block The 2 0.10 % No

Internal links in - bitcoinj.github.io

Watch or read a tutorial
Building a simple GUI wallet tutorial
Bitcoin standards
Which BIPs are supported by bitcoinj
use Maven
How to depend on bitcoinj with Maven using projects
use Gradle
How to depend on bitcoinj with Gradle using projects
Getting started
An introduction to using the library
0.14.7 API documentation
bitcoinj 0.14.7 API
Limitations and missing features
Limitations and missing features.
Understanding the bitcoinj security model
Understanding the bitcoinj security model
Working with bitcoinj
Working with bitcoinj
How the different components of your app fit together
How the different components of your app fit together
How to test your software
How to test applications
Working with transactions
Working with transactions
Working with the wallet
Working with the wallet
Working with monetary amounts
Working with monetary amounts
How to use the network API and info about Tor support
How to handle networking/peer APIs
API contexts
API Contexts
How to use the experimental fully verifying mode
Using the experimental full verification mode
Working with contracts
Working with contracts
Working with the BIP70 payment protocol
Working with the BIP70 payment protocol API
Working with micropayment channels
Working with micropayment channels
Using bitcoinj from other languages like C++, JavaScript, Ruby, Python, etc
How to access bitcoinj from other languages
Coding conventions in the library itself
Coding conventions in bitcoinj
release notes
Release notes

Bitcoinj.github.io Spined HTML


Working with the wallet Introduction Getting started Documentation Community Working with the wallet Introduction Setup Getting addresses Seeds and mnemonic codes Replaying the uniting Creating spends When to commit a transaction Understanding balances and forge selection Using fees Learning well-nigh changes Saving the wallet at the right times Wallet maintenance and key rotation Creating multi-sends and other contracts Encrypting the private keys Watching wallets Married/multi-signature wallets and pluggable signers Connecting the wallet to a UTXO store Working with the wallet Learn how to use the wallet matriculation and craft custom transactions with it. Introduction The Wallet matriculation is one of the most important classes in bitcoinj. It stores keys and the transactions that assign value to/from those keys. It lets you create new transactions which spend the previously stored transactions outputs, and it notifies you when the contents of the wallet have changed. You’ll need to learn how to use the Wallet to build many kinds of apps. This vendible assumes you’ve read Satoshi’s white paper and the WorkingWithTransactions article. Setup For optimal operation the wallet needs to be unfluctuating to a BlockChain and a Peer or PeerGroup. The woodcut uniting can be passed a Wallet in its constructor. It will send the wallet blocks as they are received so the wallet can find and pericope relevant transactions, that is, transactions which send or receive coins to keys stored within it. The Peer/Group will send the wallet transactions which are unconcentrated wideness the network surpassing they towards in a block. A Wallet starts out its life with no transactions in it, and thus a wastefulness of zero, regardless of what the woodcut uniting contains. To use it you need to download the woodcut chain, which will load the wallet up with transactions that can be analyzed and spent. Wallet wallet = new Wallet(params); BlockChain uniting = new BlockChain(params, wallet, ...); PeerGroup peerGroup = new PeerGroup(params, chain); peerGroup.addWallet(wallet); peerGroup.startAndWait(); Getting addresses Of course, the snippet of lawmaking is fairly useless considering there’s no way to get money into it. You can obtain keys and addresses from the wallet with the pursuit API calls:Writea = wallet.currentReceiveAddress(); ECKey b = wallet.currentReceiveKey();Writec = wallet.freshReceiveAddress(); predicate b.toAddress(wallet.getParams()).equals(a); predicate !c.equals(a); These can then be handed out to receive payments on. The Wallet has a notion of a “current” address. This is intended for GUI wallets that wish to exhibit an write at all times. Once the current write is seen stuff used, it changes to a new one. The freshReceiveKey/Address methods on the other hand unchangingly return a newly derived address. Seeds and mnemonic codes The keys and addresses returned by these methods are derived deterministically from a seed, using the algorithms laid out in BIP 32 and BIP 39. The life of a key looks like this: A new Wallet object selects 128 shit of random entropy using SecureRandom. This randomness is transformed into a “mnemonic code”; a set of 12 words using a wordlist pre-defined by the BIP 39 standard. The string form of the 12 words is used as input to a key derivation algorithm (PBKDF2) and iterated numerous times to obtain the “seed”. Note that the seed is not simply the original random entropy represented using words as you might expect, rather, the seed is a derivative of the UTF-8 byte sequence of the words themselves. The newly calculated seed is then split into a master private key and a “chain code”. Together, these indulge for iteration of a key tree using the algorithms specified in BIP 32. This algorithm exploits properties of elliptic lines mathematics to indulge the public keys in a sequence to be iterated without having wangle to the equivalent private keys, which is very useful for vending addresses without needing the wallet to be decrypted if a password has been supplied. bitcoinj uses the default recommended tree structure from BIP 32. The wallet pre-calculates a set of lookahead keys. These are keys that were not issued by the Wallet yet via the current/freshReceiveKey APIs, but will be in future. Precalculation achieves several goals. One, it makes these APIs fast, which is useful for GUI apps that don’t want to wait for potentially slow EC math to be done. Two, it allows the wallet to notice transactions stuff made to/from keys that were not issued yet - this can happen if the wallet seed has been cloned to multiple devices, and if the woodcut uniting is stuff replayed. The seed and keys that were (pre) calculated are saved to disk in order to stave slow rederivation loops when the wallet is loaded. The “wallet words” are intended to be easier to work with and write lanugo than a raw private key: users can hands work with them using a pen and paper with less endangerment of unwittingly writing things lanugo wrong. So you’re encouraged to expose the words to users as a replacement mechanism (make sure they write lanugo the stage too, to speed up restore). You can work with seeds like this: DeterministicSeed seed = wallet.getKeyChainSeed(); println("Seed words are: " + Joiner.on(" ").join(seed.getMnemonicCode())); println("Seed birthday is: " + seed.getCreationTimeSeconds()); String seedCode = "yard impulse luxury momentum today throw sublet pepper survey wreck glass federal"; long creationtime = 1409478661L; DeterministicSeed seed = new DeterministicSeed(seedCode, null, "", creationtime); Wallet restoredWallet = Wallet.fromSeed(params, seed); // now sync the restored wallet as described below. The lookahead zone plays an important role when keeping wallets synchronised together. The default zone is 100 keys in size. This ways that if wallet A is cloned to wallet B, and wallet A issues 50 keys of which only the last one is unquestionably used to receive payment, wallet B will still notice that payment and move its lookahead zone such that B is tracking 150 keys in total. If wallet A handed out 120 keys and only the 110th received payment, wallet B would not notice anything had happened. For this reason when trying to alimony wallets in sync it’s important that you have some idea of how many outstanding addresses there may be pensile payment at any given time. The default of 100 is selected to be towardly for consumer wallets, but in a merchant scenario you may need a larger zone. Replaying the uniting If you import non-fresh keys to a wallet that once has transactions in it, to get the transactions for the widow keys you must remove transactions by resetting the wallet (using the reset method) and re-download the chain. Currently, there is no way to replay the uniting into a wallet that once has transactions in it and attempting to do so may untruthful the wallet. This is likely to transpiration in future. Alternatively, you could download the raw transaction data from some other source, like a woodcut explorer, and then insert the transactions directly into the wallet. However this is currently unsupported and untested. For most users, importing existing keys is a bad idea and reflects some deeper missing feature. Talk to us if you finger a urgent need to import keys into wallets regularly. The Wallet works with other classes in the system to speed up synchronisation with the woodcut chain, but only some optimisations are on by default. To understand what is washed-up and how to configure a Wallet/PeerGroup for optimal performance, please read SpeedingUpChainSync. Creating spendsWithouttransmissible up with the chain, you may have some coins misogynist for spending: System.out.println("You have " + Coin.FRIENDLY_FORMAT.format(wallet.getBalance())); Spending money consists of four steps: Create a send requestWell-constructedit Commit the transaction and then save the walletUnconcentratedthe generated transaction For convenience there are helper methods that do these steps for you. In the simplest case: // Get the write 1RbxbA1yP2Lebauuef3cBiBho853f7jxs in object form.WritetargetAddress = new Address(params, "1RbxbA1yP2Lebauuef3cBiBho853f7jxs"); // Do the send of 1 BTC in the background. This could throw InsufficientMoneyException. Wallet.SendResult result = wallet.sendCoins(peerGroup, targetAddress, Coin.COIN); // Save the wallet to disk, optional if using wheels saving (see below). wallet.saveToFile(....); // Wait for the transaction to propagate wideness the P2P network, indicating acceptance. result.broadcastComplete.get(); The sendCoins method returns both the transaction that was created, and a ListenableFuture that let’s you woodcut until the transaction has been wonted by the network (sent to one peer, heard when from the others). You can moreover register a callback on the returned future to learn when propagation was complete, or register your own TransactionConfidence.Listener on the transaction to watch the progress of propagation and mining yourself. At a lower level, we can do these steps ourselves: // Make sure this lawmaking is run in a single thread at once. SendRequest request = SendRequest.to(address, value); // The SendRequest object can be customized at this point to modify how the transaction will be created. wallet.completeTx(request); // Ensure these funds won't be spent again. wallet.commitTx(request.tx); wallet.saveToFile(...); // A proposed transaction is now sitting in request.tx - send it in the background. ListenableFuture<Transaction> future = peerGroup.broadcastTransaction(request.tx); // The future will well-constructed when we've seen the transaction ripple wideness the network to a sufficient degree. // Here, we just wait for it to finish, but we can moreover nail a listener that'll get run on a preliminaries // thread when finished. Or we could just seem the network accepts the transaction and siphon on. future.get(); To create a transaction we first build a SendRequest object using one of the static helper methods. A SendRequest consists of a partially well-constructed (invalid) Transaction object. It has other fields let you customize things that aren’t washed-up yet like the fee, transpiration write and maybe in future privacy features like how coins are selected. You can modify the partial transaction if you like, or simply construct your own from scratch. The static helper methods on SendRequest are simply variegated ways to construct the partial transaction. Then we well-constructed the request - that ways the transaction in the send request has inputs/outputs widow and signed to make the transaction valid. It’s now winning to the Bitcoin network. Note that between completeTx and commitTx no lock is stuff held. So it’s possible for this lawmaking to race and goof if the wallet changes out from underneath you - for example, if the keys in the wallet have been exported and used elsewhere, and a transaction that spends the selected outputs comes in between the two calls. When you use the simpler construction the wallet is locked whilst both operations are run, ensuring that you don’t end up trying to commit a double spend. When to commit a transaction To commit a transaction ways to update the spent flags of the wallets transactions so they won’t be re-used. It’s important to commit a transaction at the right time and there are variegated strategies for doing so. The default sendCoins() behaviour is to commit and then broadcast, which is a good nomination most of the time. It ways there’s no endangerment of unwittingly creating a double spend if there’s a network problem or if there are multiple threads trying to create and unconcentrated transactions simultaneously. On the other hand, it ways that if the network doesn’t winnow your transaction for some reason (eg, insufficient fees/non-standard form) the wallet thinks the money is spent when it wasn’t and you’ll have to fix things yourself. You can moreover just not undeniability wallet.commitTx and use peerGroup.broadcastTransaction instead. Once a transaction has been seen by a tuft of peers it will be given to the wallet which will then commit it for you. The main reason you may want to commit without successful unconcentrated is if you’re experimenting with new lawmaking and are creating transactions that won’t necessarily be accepted. It’s worrying to have to constantly roll when your wallet in this case. Once you know the network will unchangingly winnow your transactions you can create the send request, well-constructed it and commit the resulting transaction all under a single lock so multiple threads won’t create double spends by mistake. Understanding balances and forge selection The Wallet.getBalance() undeniability has by default behaviour that may surprise you. If you unconcentrated a transaction that sends money and then immediately succeeding trammels the balance, it may be lower than what you expect (or plane be zero). The reason is that bitcoinj has a somewhat ramified notion of balance. You need to understand this in order to write robust applications. The getBalance() method has two volitional forms. In one, you pass in a Wallet.BalanceType enum. It has four possible values, AVAILABLE, ESTIMATED, AVAILABLE_SPENDABLE and ESTIMATED_SPENDABLE. Often these will be the same, but sometimes they will vary. The other overload of getBalance() takes a CoinSelector object. The ESTIMATED wastefulness is perhaps what you may imagine as a “balance” - it’s simply all outputs in the wallet which are not yet spent. However, that doesn’t midpoint it’s really unscratched to spend them.ConsideringBitcoin is a global consensus system, deciding when you can really trust you received money and the transaction won’t be rolled when can be a subtle art. This concept of safety is therefore exposed via the AVAILABLE wastefulness type, and the CoinSelector abstraction. A forge selector is just an object that implements the CoinSelector interface. That interface has a single method, which given a list of all unspent outputs and a target value, returns a smaller list of outputs that adds up to at least the target (and possibly more).Forgeselection can be a ramified process that trades off safety, privacy, fee-efficiency and other factors, which is why it’s pluggable. The default forge selector bitcoinj provides (DefaultCoinSelector) implements a relatively unscratched policy: it requires at least one confirmation for any transaction to be considered for selection, except for transactions created by the wallet itself which are considered spendable as long as it was seen propagating wideness the network. This is the wastefulness you get when when you use getBalance(BalanceType.AVAILABLE) or the simplest form, getBalance() - it’s the value of money that the spend megacosm methods will consider for usage. The reason for this policy is as follows: You trust your own transactions implicitly, as you “know” you are trustworthy. However, it’s still possible for bugs and other things to rationalization you to create unconfirmable transactions - for instance if you don’t include sufficient fees. Therefore we don’t want to spend transpiration outputs unless we saw that network nodes relayed the transaction, giving a upper stratum of conviction that it will be mined upon. For other transactions, we wait until we saw at least one woodcut considering in SPV mode, you cannot trammels for yourself that a transaction is valid. If your internet connection was hacked, you might be talking to a fake Bitcoin network that feeds you a nonsense transaction which spends non-existent Bitcoins. Please read the SecurityModel vendible to learn increasingly well-nigh this. Waiting for the transaction to towards in a woodcut gives you conviction the transaction is real. The original Bitcoin vendee waits for 6 confirmations, but this value was picked at a time when mining hash rate was much lower and it was thus much easier to forge a small fake chain. We’ve not yet heard reports of merchants stuff defrauded using invalid blocks, so waiting for one woodcut is sufficient. The default forge selector moreover takes into worth the age of the outputs, in order to maximise the probability of your transaction getting confirmed in the next block. The default selector is somewhat customisable via subclassing. But normally the only customisation you’re interested in is stuff worldly-wise to spend unconfirmed transactions. If your using knows the money you’re receiving is valid via some other mechanism (e.g. you are unfluctuating to a trusted node), or you just don’t superintendency well-nigh fraud considering the value at stake is very low, then you can undeniability Wallet.allowSpendingUnconfirmedTransactions() to make the wallet use a variegated selector that drops the 1-block policy. You can moreover segregate the forge selector on a per-payment basis, using the SendRequest.coinSelector field. As a magnitude of all of the above, if you query the AVAILABLE wastefulness immediately without doing a PeerGroup.broadcastTransaction, you are likely to see a wastefulness lower than what you anticipate, as you’re racing the process of dissemination the transacation and seeing it propagate wideness the network. If you instead undeniability getBalance() without the returned ListenableFuture<Transaction> completes successfully, you will see the wastefulness you expect. The difference between AVAILABLE_SPENDABLE and AVAILABLE variants is whether the wallet considers outputs for which it does not have the keys. In a “watching wallet”, the wallet may be tracking the wastefulness of flipside wallet elsewhere by watching for the public keys. By default, watched addresses/scripts/keys are considered to be a part of the wastefulness plane though attempting to spend those outputs would fail. The only time these two notions of wastefulness differ is if you have a mix of private keys and public-only keys in your wallet: this can occur when writing wide contracts based applications but otherwise should never yield up. Using fees Transactions can have fees tying to them when they are completed by the wallet. To tenancy this, the SendRequest object has several fields that can be used. The simplest is SendRequest.fee which is an wool override. If set, that is the fee that will be attached. A increasingly useful field is SendRequest.feePerKb which allows you to scale the final fee with the size of the completed transaction. When woodcut space is limited, miners decide ranking by fee-per-1000-bytes so typically you do want to pay increasingly for larger transactions, otherwise you may fall unelevated miners fee thresholds. There are moreover some fee rules in place intended to stave unseemly flooding attacks. Most notably, any transaction that has an output of value less than 0.01 coins ($1) requires the min fee which is currently set to be 10,000 satoshis (0.0001 coins or at June 2013 mart rates well-nigh $0.01). By default nodes will refuse to relay transactions that don’t meet that rule, although mining them is of undertow allowed. You can disable it and thus create transactions that may be un-relayable by waffly SendRequest.ensureMinRequiredFee to false. bitcoinj will by default ensure you unchangingly nail a small fee per kilobyte to each transaction regardless of whether one is technically necessary or not. The value of fee used depends on the size of the transaction. You can find out what fee was tying by reading the fee field of SendRequest without completion. There are several reasons for why bitcoinj unchangingly sets a fee by default: Most apps were once setting a stock-still fee anyway. There is only 27kb in each woodcut for self-ruling “high priority” transactions. This is a quite small value of space which will often be used up already. SPV clients have no way to know whether that 27kb of free-high-priority space is once full in the next block. The default fee is quite low. It increasingly or less guarantees that the transaction will personize quickly. Over time, it’d be nice to get when to a state where most transactions are free. However it will require some changes on the C++ and mining side withal with shielding co-ordinated rollouts. Learning well-nigh changes The wallet provides the WalletEventListener interface for learning well-nigh changes to its contents. You can derive from AbstractWalletEventListener to get a default implementation of these methods. You get callbacks on: Receiving money. Money stuff sent from the wallet (regardless of whether the tx was created by it or not). Changes in transaction confidence. See WorkingWithTransactions for information well-nigh this. Saving the wallet at the right times By default the Wallet is just an in-memory object, it won’t save by itself. You can use saveToFile() or saveToOutputStream() when you want to persist the wallet. It’s weightier to use saveToFile() if possible considering this will write to a temporary file and then atomically rename it, giving you warranty that the wallet won’t be half-written or corrupted if something goes wrong half way through the saving process. It can be difficult to know exactly when to save the wallet, and if you do it too aggressively you can negatively stupefy the performance of your app. To help solve this, the wallet can auto-save itself to a named file. Use the autoSaveToFile() method to set this up. You can optionally provide a wait period, eg, of a few hundred milliseconds. This will create a preliminaries thread that saves the wallet every N milliseconds if it needs saving. Note that some important operations, like subtracting a key, unchangingly trigger an firsthand auto-save. Delaying writes of the wallet can help modernize performance in some cases, eg, if you’re transmissible up a wallet that is very rented (has lots of transactions moving in and out). You can register an auto-save listener to learn when the wallet saved itself. Wallet maintenance and key rotation The wallet has a notion of maintenance, which currently exists purely to support key rotation. Key rotation is useful when you believe some keys might be weak or compromised and want to stop using them. The wallet knows how to create a fresh HD key hierarchy and create spends that automatically move coins from rotating keys to the new keys. To start this process, you tell the wallet the time at which you believe the existing keys became weak, and then use the doMaintenance(KeyParameter, boolean) method to obtain transactions that move coins to the fresh keys. Note that you can’t mark individual keys as weak, only groups based on their megacosm time. Examples of when this can be useful: You learn that the random number generator used to create some keys was predictable You have a replacement somewhere that you can’t reliably delete, and worry that its keys may be vulnerable to theft. For example wallets written to flash/solid state disks can be nonflexible to reliably erase. The doMaintenance method takes the users password key if there is one, and a boolean executive whether the needed maintenance transactions will unquestionably be unconcentrated on the network. It returns a future that completes either immediately (if the bool treatise was false), or when all maintenance transactions have broadcast, and the future vends a list of the transactions that were created. The method might potentially throw an exception if it needs the users password key, plane if the bool treatise is false, so you should be ready to reservation that and ask the user to provide their password - probably with an subtitle of why. If no exception is thrown and the treatise is false, you can use get() on the returned future to obtain the list and then trammels if it’s empty. If it’s empty, no maintenance is required. If it’s not, you need to tell the user what’s going on and let it unconcentrated the transactions. The concept of maintenance is general. In future, the wallet might generate maintenance transactions for things like defragmenting the wallet or increasing user privacy. But currently, if you don’t use key rotation, this method will do nothing. Creating multi-sends and other contracts The default SendRequest static methods help you construct transactions of worldwide forms, but what if you want something increasingly advanced? You can customize or build your own transaction and put it into a SendRequest yourself. Here’s a simple example - sending to multiple addresses at once. A fresh Transaction object is first created with the outputs specifying where to send various quantities of coins. Then the incomplete, invalid transaction is completed, meaning the wallet adds inputs (and a transpiration output) as necessary to make the transaction valid.Writetarget1 = new Address(params, "17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL");Writetarget2 = new Address(params, "1RbxbA1yP2Lebauuef3cBiBho853f7jxs"); Transaction tx = new Transaction(params); tx.addOutput(Utils.toNanoCoins(1, 10), target1); tx.addOutput(Utils.toNanoCoins(2, 20), target2); SendRequest request = SendRequest.forTx(tx); if (!wallet.completeTx(request)) { // Cannot sire this! } else { wallet.commitTx(request.tx); peerGroup.broadcastTransaction(request.tx).get(); } You can add wrong-headed TransactionOutput objects and in this way, build transactions with exotic reuse conditions. For examples of what is achievable, see contracts. At this time SendRequest does not indulge you to request unusual forms of signing like SIGHASH_ANYONECANPAY. If you want to do that, you must use the lower level APIs. Fortunately it isn’t nonflexible - you can see examples of how to do that in the vendible WorkingWithContracts. Encrypting the private keys It’s a good idea to encrypt your private keys if you only spend money from your wallet rarely. The Wallet.encrypt("password") method will derive an AES key from an Scrypt hash of the given password string and use it to encrypt the private keys in the wallet, you can then provide the password when signing transactions or to fully decrypt the wallet. You can moreover provide your own AES keys if you don’t want to derive them from a password, and you can moreover customize the Scrypt hash parameters. Scrypt is a hash function designed to be harder to brute gravity at upper speed than volitional algorithms. By selecting difficult parameters, a password can be made to take multiple seconds to turn into a key. In the WalletTemplate using you can find lawmaking that shows how to measure the speed of the host computer and then select scrypt parameters to requite encryption/decryption time of a couple of seconds. Once encrypted, you will need to provide the AES key whenever you try and sign transactions. You do this via the SendRequest object:Writea = new Address(params, "1RbxbA1yP2Lebauuef3cBiBho853f7jxs"); SendRequest req = SendRequest.to(a, Coin.parseCoin("0.12")); req.aesKey = wallet.getKeyCrypter().deriveKey("password"); wallet.sendCoins(req); The wallet can be decrypted by using the wallet.decrypt method which takes either a textual password or a KeyParameter. Note that considering bitcoinj saves wallets by creating temp files and then renaming them, private key material may still exist on disk plane without encryption. Especially with modern SSD based systems deleting data on disk is rarely completely possible. Encryption should be seen as a reasonable way to raise the bar versus adversaries that are not extremely sophisticated. But if someone has once gained wangle to their wallet file, they could theoretically moreover just wait for the user to type in their password and obtain the private keys this way. Encryption is useful but should not be regarded as a silver bullet. Watching wallets A wallet can cloned such that the clone is worldly-wise to follow transactions from the P2P network but doesn’t have the private keys needed for spending. This wattle is very useful and makes a lot of sense for things like online web shops. The web server can observe all payments into the shops wallet, so knows when customers have paid, but cannot authorise withdrawals from that wallet itself thus significantly reducing the risk of hacking. To create a watching wallet from flipside HD BIP32/bitcoinj wallet: Wallet toWatch = ....; DeterministicKey watchingKey = toWatch.getWatchingKey(); // Get the standardised base58 encoded serialization System.out.println("Watching key data: " + watchingKey.serializePubB58()); System.out.println("Watching key birthday: " + watchingKey.getCreationTimeSeconds()); ////////////////////////////////////////////////////////////////////////////////////////// DeterministicKey key = DeterministicKey.deserializeB58(null, "key data goes here"); long keyBirthday = 12345678L; Wallet watchingWallet = Wallet.fromWatchingKey(params, key, keyBirthday); // now nail watchingWallet and replay the uniting as normal. The “watching key” in this specimen is the public form of the BIP32 worth zero key i.e. it’s the first key derived from the master.Consideringof how BIP32 works, the watching key cannot be the master public key itself. The internal (change) and external (for handing out) villenage are both unelevated this and thus all keys generated by each wallet will be in sync. In the web server case, the server can just undeniability wallet.freshReceiveAddress() as normal. The original wallet will be worldly-wise to see all the payments received to the watching wallet and moreover spend them, when synced. But it can be stored offline (a so tabbed “cold wallet”) for uneaten security. You can moreover create a wallet that watches wrong-headed addresses or scripts plane if you don’t have the HD watching key: wallet.addWatchedAddress(...); wallet.addWatchedScripts(List.of(script, script, script)); Obviously in this specimen you don’t get wheels synchronisation of new keys/addresses/scripts. Married/multi-signature wallets and pluggable signers Starting from bitcoinj 0.12 there is some support for wallets which require multiple signers to cooperate to sign transactions. This allows the usage of a remote “risk wringer service” which may only password transactions if some spare authorisation has been obtained or if the transaction seems to be low risk. A wallet that requires the cooperation of a third party in this way is tabbed a married wallet, considering it needs the permission of its spouse to spend money :-) To marry a wallet to flipside one, the spouse must moreover be an HD wallet using the default BIP 32 tree. You must obtain the watching key of that other wallet via some external protocol (it can be retrieved as outlined above) and then do: DeterministicKey spouseKey = ....; wallet.addFollowingAccountKeys(Lists.newArrayList(spouseKey), 2); // threshold of 2 keys, i.e. both are needed to spend.Writea = wallet.freshReceiveAddress(); predicate a.isP2SHAddress(); Once a wallet has a “following key” it becomes married and the API changes. You can no longer undeniability freshReceiveKey or currentReceiveKey considering those are specified to return single keys and a married wallet can only have money sent to it using pay-to-script-hash (P2SH) addresses, which start with the number 3 when written down. Instead you should use currentReceiveAddress and freshReceiveAddress exclusively. The pursuit key HD hierarchy must match the key hierarchy used by the wallet itself. That is, it’s not possible for the remote server to have a single HD key hierarchy that is shared between all users: each user must have their own key tree. The way you spend money moreover changes. Whilst the upper level API remains the same, the Wallet will throw an exception if you try to send coins without installing a pluggable transaction signer. The reason is, whilst it knows how to sign with its own private keys, it doesn’t know how to talk to the remote service and get the relevant signatures to finish things off. A pluggable transaction signer is an object that implements the TransactionSigner interface. It must have a no-args constructor and can provide data that will be serialized to the wallet when saved, such as hallmark credentials. During setup it should be created, configured with whatever info is required to let it talk to the remote service, demonstrate and obtain signatures. Once configured the isReady method should start returning true, and it can now be widow to the wallet using the Wallet.addTransactionSigner method. This only has to be washed-up once as deserialization will recreate the object using reflection and then use the TransactionSigner.deserialize(byte[]) method to reload it. The Wallet matriculation runs transaction signers in sequence. First comes the LocalTransactionSigner which knows how to use the private keys in the wallet’s KeyBag. Then comes yours. The TransactionSigner.signInputs(ProposedTransaction, KeyBag) method is tabbed and the transaction inside the ProposedTransaction object should have signatures fetched from the remote service and inserted as appropriate. The HD key paths to use can be retrieved from the ProposedTransaction object. Married wallets support is relatively new and experimental. If you do something with it, or encounter problems, let us know! Connecting the wallet to a UTXO store By default the wallet expects to find unspent outputs by scanning the woodcut uniting using Bloom filters, in the normal SPV manner. In some use cases you may once have this data from some other source, for example from a database built by one of the full pruned woodcut stores. You can configure the Wallet matriculation to use such a source instead of its own data and as such, stave the need to directly use the woodcut chain. This can be user-friendly when attempting to build something like a web wallet, where wallets need to be loaded and discarded very quickly. To configure the wallet in this manner, you need an implementation of the UTXOProvider interface. This interface is fairly simple and has two cadre methods, one to return the woodcut height known by the provider and the other to return a list of UTXO objects given a list ofWriteobjects: public interface UTXOProvider { List<UTXO> getOpenTransactionOutputs(List<Address> addresses) throws UTXOProviderException; .... } Note that this API will probably transpiration in future to take a list of scripts instead of/as well as a list of addresses, as not every output type can be expressed with an address. Conveniently the database backed FullPrunedBlockStore implementations that bitcoinj ships with (Postgres, MySQL, H2) implement this interface, so if you use them you can connect the wallet to the databases directly. Once you have a provider, just use Wallet.setUTXOProvider to plug it in. The provider will then be queried for spendable outputs whenever the wastefulness is calculated or a spend is completed. Note that the UTXO provider undertone is not serialized and must be reset every time the wallet is loaded. For typical web wallet scenarios however this isn’t a big deal as most likely, the wallet will be re-constructed from the random seed each time it is needed rather than stuff explicitly serialized.