forked from bitcoinj/bitcoinj
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Wallet.java
5512 lines (5082 loc) · 257 KB
/
Wallet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2013 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bitcoinj.wallet;
import com.google.common.annotations.*;
import com.google.common.base.*;
import com.google.common.collect.*;
import com.google.common.primitives.*;
import com.google.common.util.concurrent.*;
import com.google.protobuf.*;
import net.jcip.annotations.*;
import org.bitcoinj.core.listeners.*;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Base58;
import org.bitcoinj.core.AbstractBlockChain;
import org.bitcoinj.core.BlockChain;
import org.bitcoinj.core.BloomFilter;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Context;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.FilteredBlock;
import org.bitcoinj.core.InsufficientMoneyException;
import org.bitcoinj.core.LegacyAddress;
import org.bitcoinj.core.Message;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Peer;
import org.bitcoinj.core.PeerFilterProvider;
import org.bitcoinj.core.PeerGroup;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.StoredBlock;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionBag;
import org.bitcoinj.core.TransactionBroadcast;
import org.bitcoinj.core.TransactionBroadcaster;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.core.UTXO;
import org.bitcoinj.core.UTXOProvider;
import org.bitcoinj.core.UTXOProviderException;
import org.bitcoinj.core.Utils;
import org.bitcoinj.core.VerificationException;
import org.bitcoinj.core.TransactionConfidence.*;
import org.bitcoinj.crypto.*;
import org.bitcoinj.script.*;
import org.bitcoinj.script.Script.ScriptType;
import org.bitcoinj.signers.*;
import org.bitcoinj.utils.*;
import org.bitcoinj.wallet.Protos.Wallet.*;
import org.bitcoinj.wallet.WalletTransaction.*;
import org.bitcoinj.wallet.listeners.KeyChainEventListener;
import org.bitcoinj.wallet.listeners.ScriptsChangeEventListener;
import org.bitcoinj.wallet.listeners.WalletChangeEventListener;
import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener;
import org.bitcoinj.wallet.listeners.WalletCoinsSentEventListener;
import org.bitcoinj.wallet.listeners.WalletReorganizeEventListener;
import org.slf4j.*;
import org.bouncycastle.crypto.params.*;
import javax.annotation.*;
import java.io.*;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import static com.google.common.base.Preconditions.*;
// To do list:
//
// - Take all wallet-relevant data out of Transaction and put it into WalletTransaction. Make Transaction immutable.
// - Only store relevant transaction outputs, don't bother storing the rest of the data. Big RAM saving.
// - Split block chain and tx output tracking into a superclass that doesn't have any key or spending related code.
// - Simplify how transactions are tracked and stored: in particular, have the wallet maintain positioning information
// for transactions independent of the transactions themselves, so the timeline can be walked without having to
// process and sort every single transaction.
// - Split data persistence out into a backend class and make the wallet transactional, so we can store a wallet
// in a database not just in RAM.
// - Make clearing of transactions able to only rewind the wallet a certain distance instead of all blocks.
// - Make it scale:
// - eliminate all the algorithms with quadratic complexity (or worse)
// - don't require everything to be held in RAM at once
// - consider allowing eviction of no longer re-orgable transactions or keys that were used up
//
// Finally, find more ways to break the class up and decompose it. Currently every time we move code out, other code
// fills up the lines saved!
/**
* <p>A Wallet stores keys and a record of transactions that send and receive value from those keys. Using these,
* it is able to create new transactions that spend the recorded transactions, and this is the fundamental operation
* of the Bitcoin protocol.</p>
*
* <p>To learn more about this class, read <b><a href="https://bitcoinj.github.io/working-with-the-wallet">
* working with the wallet.</a></b></p>
*
* <p>To fill up a Wallet with transactions, you need to use it in combination with a {@link BlockChain} and various
* other objects, see the <a href="https://bitcoinj.github.io/getting-started">Getting started</a> tutorial
* on the website to learn more about how to set everything up.</p>
*
* <p>Wallets can be serialized using protocol buffers. You need to save the wallet whenever it changes, there is an
* auto-save feature that simplifies this for you although you're still responsible for manually triggering a save when
* your app is about to quit because the auto-save feature waits a moment before actually committing to disk to avoid IO
* thrashing when the wallet is changing very fast (eg due to a block chain sync). See
* {@link Wallet#autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)}
* for more information about this.</p>
*/
public class Wallet extends BaseTaggableObject
implements NewBestBlockListener, TransactionReceivedInBlockListener, PeerFilterProvider, KeyBag, TransactionBag, ReorganizeListener {
private static final Logger log = LoggerFactory.getLogger(Wallet.class);
private static final int MINIMUM_BLOOM_DATA_LENGTH = 8;
// Ordering: lock > keyChainGroupLock. KeyChainGroup is protected separately to allow fast querying of current receive address
// even if the wallet itself is busy e.g. saving or processing a big reorg. Useful for reducing UI latency.
protected final ReentrantLock lock = Threading.lock("wallet");
protected final ReentrantLock keyChainGroupLock = Threading.lock("wallet-keychaingroup");
// The various pools below give quick access to wallet-relevant transactions by the state they're in:
//
// Pending: Transactions that didn't make it into the best chain yet. Pending transactions can be killed if a
// double spend against them appears in the best chain, in which case they move to the dead pool.
// If a double spend appears in the pending state as well, we update the confidence type
// of all txns in conflict to IN_CONFLICT and wait for the miners to resolve the race.
// Unspent: Transactions that appeared in the best chain and have outputs we can spend. Note that we store the
// entire transaction in memory even though for spending purposes we only really need the outputs, the
// reason being that this simplifies handling of re-orgs. It would be worth fixing this in future.
// Spent: Transactions that appeared in the best chain but don't have any spendable outputs. They're stored here
// for history browsing/auditing reasons only and in future will probably be flushed out to some other
// kind of cold storage or just removed.
// Dead: Transactions that we believe will never confirm get moved here, out of pending. Note that Bitcoin
// Core has no notion of dead-ness: the assumption is that double spends won't happen so there's no
// need to notify the user about them. We take a more pessimistic approach and try to track the fact that
// transactions have been double spent so applications can do something intelligent (cancel orders, show
// to the user in the UI, etc). A transaction can leave dead and move into spent/unspent if there is a
// re-org to a chain that doesn't include the double spend.
private final Map<Sha256Hash, Transaction> pending;
private final Map<Sha256Hash, Transaction> unspent;
private final Map<Sha256Hash, Transaction> spent;
private final Map<Sha256Hash, Transaction> dead;
// All transactions together.
protected final Map<Sha256Hash, Transaction> transactions;
// All the TransactionOutput objects that we could spend (ignoring whether we have the private key or not).
// Used to speed up various calculations.
protected final HashSet<TransactionOutput> myUnspents = Sets.newHashSet();
// Transactions that were dropped by the risk analysis system. These are not in any pools and not serialized
// to disk. We have to keep them around because if we ignore a tx because we think it will never confirm, but
// then it actually does confirm and does so within the same network session, remote peers will not resend us
// the tx data along with the Bloom filtered block, as they know we already received it once before
// (so it would be wasteful to repeat). Thus we keep them around here for a while. If we drop our network
// connections then the remote peers will forget that we were sent the tx data previously and send it again
// when relaying a filtered merkleblock.
private final LinkedHashMap<Sha256Hash, Transaction> riskDropped = new LinkedHashMap<Sha256Hash, Transaction>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Sha256Hash, Transaction> eldest) {
return size() > 1000;
}
};
// The key chain group is not thread safe, and generally the whole hierarchy of objects should not be mutated
// outside the wallet lock. So don't expose this object directly via any accessors!
@GuardedBy("keyChainGroupLock") private KeyChainGroup keyChainGroup;
// A list of scripts watched by this wallet.
@GuardedBy("keyChainGroupLock") private Set<Script> watchedScripts;
protected final Context context;
protected final NetworkParameters params;
@Nullable private Sha256Hash lastBlockSeenHash;
private int lastBlockSeenHeight;
private long lastBlockSeenTimeSecs;
private final CopyOnWriteArrayList<ListenerRegistration<WalletChangeEventListener>> changeListeners
= new CopyOnWriteArrayList<>();
private final CopyOnWriteArrayList<ListenerRegistration<WalletCoinsReceivedEventListener>> coinsReceivedListeners
= new CopyOnWriteArrayList<>();
private final CopyOnWriteArrayList<ListenerRegistration<WalletCoinsSentEventListener>> coinsSentListeners
= new CopyOnWriteArrayList<>();
private final CopyOnWriteArrayList<ListenerRegistration<WalletReorganizeEventListener>> reorganizeListeners
= new CopyOnWriteArrayList<>();
private final CopyOnWriteArrayList<ListenerRegistration<ScriptsChangeEventListener>> scriptChangeListeners
= new CopyOnWriteArrayList<>();
private final CopyOnWriteArrayList<ListenerRegistration<TransactionConfidenceEventListener>> transactionConfidenceListeners
= new CopyOnWriteArrayList<>();
// A listener that relays confidence changes from the transaction confidence object to the wallet event listener,
// as a convenience to API users so they don't have to register on every transaction themselves.
private TransactionConfidence.Listener txConfidenceListener;
// If a TX hash appears in this set then notifyNewBestBlock will ignore it, as its confidence was already set up
// in receive() via Transaction.setBlockAppearance(). As the BlockChain always calls notifyNewBestBlock even if
// it sent transactions to the wallet, without this we'd double count.
private HashSet<Sha256Hash> ignoreNextNewBlock;
// Whether or not to ignore pending transactions that are considered risky by the configured risk analyzer.
private boolean acceptRiskyTransactions;
// Object that performs risk analysis of pending transactions. We might reject transactions that seem like
// a high risk of being a double spending attack.
private RiskAnalysis.Analyzer riskAnalyzer = DefaultRiskAnalysis.FACTORY;
// Stuff for notifying transaction objects that we changed their confidences. The purpose of this is to avoid
// spuriously sending lots of repeated notifications to listeners that API users aren't really interested in as a
// side effect of how the code is written (e.g. during re-orgs confidence data gets adjusted multiple times).
private int onWalletChangedSuppressions;
private boolean insideReorg;
private Map<Transaction, TransactionConfidence.Listener.ChangeReason> confidenceChanged;
protected volatile WalletFiles vFileManager;
// Object that is used to send transactions asynchronously when the wallet requires it.
protected volatile TransactionBroadcaster vTransactionBroadcaster;
// UNIX time in seconds. Money controlled by keys created before this time will be automatically respent to a key
// that was created after it. Useful when you believe some keys have been compromised.
private volatile long vKeyRotationTimestamp;
protected CoinSelector coinSelector = new DefaultCoinSelector();
// The wallet version. This is an int that can be used to track breaking changes in the wallet format.
// You can also use it to detect wallets that come from the future (ie they contain features you
// do not know how to deal with).
private int version;
// User-provided description that may help people keep track of what a wallet is for.
private String description;
// Stores objects that know how to serialize/unserialize themselves to byte streams and whether they're mandatory
// or not. The string key comes from the extension itself.
private final HashMap<String, WalletExtension> extensions;
// Objects that perform transaction signing. Applied subsequently one after another
@GuardedBy("lock") private volatile List<TransactionSigner> signers;
// If this is set then the wallet selects spendable candidate outputs from a UTXO provider.
@Nullable private volatile UTXOProvider vUTXOProvider;
/**
* Creates a new, empty wallet with a randomly chosen seed and no transactions. Make sure to provide for sufficient
* backup! Any keys will be derived from the seed. If you want to restore a wallet from disk instead, see
* {@link #loadFromFile}.
* @param params network parameters
* @param outputScriptType type of addresses (aka output scripts) to generate for receiving
*/
public static Wallet createDeterministic(NetworkParameters params, Script.ScriptType outputScriptType) {
return createDeterministic(Context.getOrCreate(params), outputScriptType);
}
/**
* Creates a new, empty wallet with a randomly chosen seed and no transactions. Make sure to provide for sufficient
* backup! Any keys will be derived from the seed. If you want to restore a wallet from disk instead, see
* {@link #loadFromFile}.
* @param params network parameters
* @deprecated Use {@link #createDeterministic(NetworkParameters, ScriptType)}
*/
@Deprecated
public Wallet(NetworkParameters params) {
this(params, KeyChainGroup.builder(params).fromRandom(Script.ScriptType.P2PKH).build());
}
/**
* Creates a new, empty wallet with a randomly chosen seed and no transactions. Make sure to provide for sufficient
* backup! Any keys will be derived from the seed. If you want to restore a wallet from disk instead, see
* {@link #loadFromFile}.
* @param outputScriptType type of addresses (aka output scripts) to generate for receiving
*/
public static Wallet createDeterministic(Context context, Script.ScriptType outputScriptType) {
return new Wallet(context, KeyChainGroup.builder(context.getParams()).fromRandom(outputScriptType).build());
}
/**
* Creates a new, empty wallet with a randomly chosen seed and no transactions. Make sure to provide for sufficient
* backup! Any keys will be derived from the seed. If you want to restore a wallet from disk instead, see
* {@link #loadFromFile}.
* @deprecated Use {@link #createDeterministic(Context, ScriptType)}
*/
@Deprecated
public Wallet(Context context) {
this(context, KeyChainGroup.builder(context.getParams()).fromRandom(Script.ScriptType.P2PKH).build());
}
/**
* Creates a new, empty wallet with just a basic keychain and no transactions. No deterministic chains will be created
* automatically. This is meant for when you just want to import a few keys and operate on them.
* @param params network parameters
*/
public static Wallet createBasic(NetworkParameters params) {
return new Wallet(params, KeyChainGroup.createBasic(params));
}
/**
* @param params network parameters
* @param seed deterministic seed
* @param outputScriptType type of addresses (aka output scripts) to generate for receiving
* @return a wallet from a deterministic seed with a default account path
*/
public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed,
Script.ScriptType outputScriptType) {
return fromSeed(params, seed, outputScriptType, KeyChainGroupStructure.DEFAULT);
}
/**
* @param params network parameters
* @param seed deterministic seed
* @param outputScriptType type of addresses (aka output scripts) to generate for receiving
* @param structure structure for your wallet
* @return a wallet from a deterministic seed with a default account path
*/
public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, Script.ScriptType outputScriptType,
KeyChainGroupStructure structure) {
return new Wallet(params, KeyChainGroup.builder(params, structure).fromSeed(seed, outputScriptType).build());
}
/**
* @param params network parameters
* @param seed deterministic seed
* @return a wallet from a deterministic seed with a
* {@link DeterministicKeyChain#ACCOUNT_ZERO_PATH 0 hardened path}
* @deprecated Use {@link #fromSeed(NetworkParameters, DeterministicSeed, ScriptType, KeyChainGroupStructure)}
*/
@Deprecated
public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed) {
return fromSeed(params, seed, Script.ScriptType.P2PKH);
}
/**
* @param params network parameters
* @param seed deterministic seed
* @param outputScriptType type of addresses (aka output scripts) to generate for receiving
* @param accountPath account path to generate receiving addresses on
* @return an instance of a wallet from a deterministic seed.
*/
public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, Script.ScriptType outputScriptType,
ImmutableList<ChildNumber> accountPath) {
DeterministicKeyChain chain = DeterministicKeyChain.builder().seed(seed).outputScriptType(outputScriptType)
.accountPath(accountPath).build();
return new Wallet(params, KeyChainGroup.builder(params).addChain(chain).build());
}
/**
* @param params network parameters
* @param seed deterministic seed
* @param accountPath account path
* @return an instance of a wallet from a deterministic seed.
* @deprecated Use {@link #fromSeed(NetworkParameters, DeterministicSeed, ScriptType, ImmutableList)}
*/
@Deprecated
public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, ImmutableList<ChildNumber> accountPath) {
return fromSeed(params, seed, Script.ScriptType.P2PKH, accountPath);
}
/**
* Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key. This HAS
* to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}.
*/
public static Wallet fromWatchingKey(NetworkParameters params, DeterministicKey watchKey,
Script.ScriptType outputScriptType) {
DeterministicKeyChain chain = DeterministicKeyChain.builder().watch(watchKey).outputScriptType(outputScriptType)
.build();
return new Wallet(params, KeyChainGroup.builder(params).addChain(chain).build());
}
/**
* Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key. This HAS
* to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}.
* @deprecated Use {@link #fromWatchingKey(NetworkParameters, DeterministicKey, ScriptType)}
*/
@Deprecated
public static Wallet fromWatchingKey(NetworkParameters params, DeterministicKey watchKey) {
return fromWatchingKey(params, watchKey, Script.ScriptType.P2PKH);
}
/**
* Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key. The
* account path is specified. The key is specified in base58 notation and the creation time of the key. If you don't
* know the creation time, you can pass {@link DeterministicHierarchy#BIP32_STANDARDISATION_TIME_SECS}.
*/
public static Wallet fromWatchingKeyB58(NetworkParameters params, String watchKeyB58, long creationTimeSeconds) {
final DeterministicKey watchKey = DeterministicKey.deserializeB58(null, watchKeyB58, params);
watchKey.setCreationTimeSeconds(creationTimeSeconds);
return fromWatchingKey(params, watchKey, outputScriptTypeFromB58(params, watchKeyB58));
}
/**
* Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key. This HAS
* to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}. This wallet can also spend.
*/
public static Wallet fromSpendingKey(NetworkParameters params, DeterministicKey spendKey,
Script.ScriptType outputScriptType) {
DeterministicKeyChain chain = DeterministicKeyChain.builder().spend(spendKey).outputScriptType(outputScriptType)
.build();
return new Wallet(params, KeyChainGroup.builder(params).addChain(chain).build());
}
/**
* Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key. This HAS
* to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}. This wallet can also spend.
* @deprecated Use {@link #fromSpendingKey(NetworkParameters, DeterministicKey, ScriptType)}
*/
@Deprecated
public static Wallet fromSpendingKey(NetworkParameters params, DeterministicKey spendKey) {
return fromSpendingKey(params, spendKey, Script.ScriptType.P2PKH);
}
/**
* Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key.
* The key is specified in base58 notation and the creation time of the key. If you don't know the creation time,
* you can pass {@link DeterministicHierarchy#BIP32_STANDARDISATION_TIME_SECS}.
*/
public static Wallet fromSpendingKeyB58(NetworkParameters params, String spendingKeyB58, long creationTimeSeconds) {
final DeterministicKey spendKey = DeterministicKey.deserializeB58(null, spendingKeyB58, params);
spendKey.setCreationTimeSeconds(creationTimeSeconds);
return fromSpendingKey(params, spendKey, outputScriptTypeFromB58(params, spendingKeyB58));
}
/**
* Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key. This HAS
* to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}.
*/
public static Wallet fromMasterKey(NetworkParameters params, DeterministicKey masterKey,
Script.ScriptType outputScriptType, ChildNumber accountNumber) {
DeterministicKey accountKey = HDKeyDerivation.deriveChildKey(masterKey, accountNumber);
accountKey = accountKey.dropParent();
accountKey.setCreationTimeSeconds(masterKey.getCreationTimeSeconds());
DeterministicKeyChain chain = DeterministicKeyChain.builder().spend(accountKey)
.outputScriptType(outputScriptType).build();
return new Wallet(params, KeyChainGroup.builder(params).addChain(chain).build());
}
/**
* @deprecated Use {@link #createBasic(NetworkParameters)}, then {@link #importKeys(List)}.
*/
@Deprecated
public static Wallet fromKeys(NetworkParameters params, List<ECKey> keys) {
for (ECKey key : keys)
checkArgument(!(key instanceof DeterministicKey));
KeyChainGroup group = KeyChainGroup.builder(params).build();
group.importKeys(keys);
return new Wallet(params, group);
}
private static Script.ScriptType outputScriptTypeFromB58(NetworkParameters params, String base58) {
int header = ByteBuffer.wrap(Base58.decodeChecked(base58)).getInt();
if (header == params.getBip32HeaderP2PKHpub() || header == params.getBip32HeaderP2PKHpriv())
return Script.ScriptType.P2PKH;
else if (header == params.getBip32HeaderP2WPKHpub() || header == params.getBip32HeaderP2WPKHpriv())
return Script.ScriptType.P2WPKH;
else
throw new IllegalArgumentException(base58.substring(0, 4));
}
public Wallet(NetworkParameters params, KeyChainGroup keyChainGroup) {
this(Context.getOrCreate(params), keyChainGroup);
}
private Wallet(Context context, KeyChainGroup keyChainGroup) {
this.context = checkNotNull(context);
this.params = checkNotNull(context.getParams());
this.keyChainGroup = checkNotNull(keyChainGroup);
watchedScripts = Sets.newHashSet();
unspent = new HashMap<>();
spent = new HashMap<>();
pending = new HashMap<>();
dead = new HashMap<>();
transactions = new HashMap<>();
extensions = new HashMap<>();
// Use a linked hash map to ensure ordering of event listeners is correct.
confidenceChanged = new LinkedHashMap<>();
signers = new ArrayList<>();
addTransactionSigner(new LocalTransactionSigner());
createTransientState();
}
private void createTransientState() {
ignoreNextNewBlock = new HashSet<>();
txConfidenceListener = new TransactionConfidence.Listener() {
@Override
public void onConfidenceChanged(TransactionConfidence confidence, TransactionConfidence.Listener.ChangeReason reason) {
// This will run on the user code thread so we shouldn't do anything too complicated here.
// We only want to queue a wallet changed event and auto-save if the number of peers announcing
// the transaction has changed, as that confidence change is made by the networking code which
// doesn't necessarily know at that point which wallets contain which transactions, so it's up
// to us to listen for that. Other types of confidence changes (type, etc) are triggered by us,
// so we'll queue up a wallet change event in other parts of the code.
if (reason == ChangeReason.SEEN_PEERS) {
lock.lock();
try {
checkBalanceFuturesLocked(null);
Transaction tx = getTransaction(confidence.getTransactionHash());
queueOnTransactionConfidenceChanged(tx);
maybeQueueOnWalletChanged();
} finally {
lock.unlock();
}
}
}
};
acceptRiskyTransactions = false;
}
public NetworkParameters getNetworkParameters() {
return params;
}
/**
* Gets the active keychains via {@link KeyChainGroup#getActiveKeyChains(long)}.
*/
public List<DeterministicKeyChain> getActiveKeyChains() {
keyChainGroupLock.lock();
try {
long keyRotationTimeSecs = vKeyRotationTimestamp;
return keyChainGroup.getActiveKeyChains(keyRotationTimeSecs);
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Gets the default active keychain via {@link KeyChainGroup#getActiveKeyChain()}.
*/
public DeterministicKeyChain getActiveKeyChain() {
keyChainGroupLock.lock();
try {
return keyChainGroup.getActiveKeyChain();
} finally {
keyChainGroupLock.unlock();
}
}
/**
* <p>Adds given transaction signer to the list of signers. It will be added to the end of the signers list, so if
* this wallet already has some signers added, given signer will be executed after all of them.</p>
* <p>Transaction signer should be fully initialized before adding to the wallet, otherwise {@link IllegalStateException}
* will be thrown</p>
*/
public final void addTransactionSigner(TransactionSigner signer) {
lock.lock();
try {
if (signer.isReady())
signers.add(signer);
else
throw new IllegalStateException("Signer instance is not ready to be added into Wallet: " + signer.getClass());
} finally {
lock.unlock();
}
}
public List<TransactionSigner> getTransactionSigners() {
lock.lock();
try {
return ImmutableList.copyOf(signers);
} finally {
lock.unlock();
}
}
// ***************************************************************************************************************
//region Key Management
/**
* Returns a key that hasn't been seen in a transaction yet, and which is suitable for displaying in a wallet
* user interface as "a convenient key to receive funds on" when the purpose parameter is
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS}. The returned key is stable until
* it's actually seen in a pending or confirmed transaction, at which point this method will start returning
* a different key (for each purpose independently).
*/
public DeterministicKey currentKey(KeyChain.KeyPurpose purpose) {
keyChainGroupLock.lock();
try {
return keyChainGroup.currentKey(purpose);
} finally {
keyChainGroupLock.unlock();
}
}
/**
* An alias for calling {@link #currentKey(KeyChain.KeyPurpose)} with
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} as the parameter.
*/
public DeterministicKey currentReceiveKey() {
return currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
}
/**
* Returns address for a {@link #currentKey(KeyChain.KeyPurpose)}
*/
public Address currentAddress(KeyChain.KeyPurpose purpose) {
keyChainGroupLock.lock();
try {
return keyChainGroup.currentAddress(purpose);
} finally {
keyChainGroupLock.unlock();
}
}
/**
* An alias for calling {@link #currentAddress(KeyChain.KeyPurpose)} with
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} as the parameter.
*/
public Address currentReceiveAddress() {
return currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
}
/**
* Returns a key that has not been returned by this method before (fresh). You can think of this as being
* a newly created key, although the notion of "create" is not really valid for a
* {@link DeterministicKeyChain}. When the parameter is
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} the returned key is suitable for being put
* into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key out
* to someone who wishes to send money.
*/
public DeterministicKey freshKey(KeyChain.KeyPurpose purpose) {
return freshKeys(purpose, 1).get(0);
}
/**
* Returns a key/s that has not been returned by this method before (fresh). You can think of this as being
* a newly created key/s, although the notion of "create" is not really valid for a
* {@link DeterministicKeyChain}. When the parameter is
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} the returned key is suitable for being put
* into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key/s out
* to someone who wishes to send money.
*/
public List<DeterministicKey> freshKeys(KeyChain.KeyPurpose purpose, int numberOfKeys) {
List<DeterministicKey> keys;
keyChainGroupLock.lock();
try {
keys = keyChainGroup.freshKeys(purpose, numberOfKeys);
} finally {
keyChainGroupLock.unlock();
}
// Do we really need an immediate hard save? Arguably all this is doing is saving the 'current' key
// and that's not quite so important, so we could coalesce for more performance.
saveNow();
return keys;
}
/**
* An alias for calling {@link #freshKey(KeyChain.KeyPurpose)} with
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} as the parameter.
*/
public DeterministicKey freshReceiveKey() {
return freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
}
/**
* Returns address for a {@link #freshKey(KeyChain.KeyPurpose)}
*/
public Address freshAddress(KeyChain.KeyPurpose purpose) {
Address address;
keyChainGroupLock.lock();
try {
address = keyChainGroup.freshAddress(purpose);
} finally {
keyChainGroupLock.unlock();
}
saveNow();
return address;
}
/**
* An alias for calling {@link #freshAddress(KeyChain.KeyPurpose)} with
* {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} as the parameter.
*/
public Address freshReceiveAddress() {
return freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
}
/**
* <p>Returns a fresh receive address for a given {@link Script.ScriptType}.</p>
* <p>This method is meant for when you really need a fallback address. Normally, you should be
* using {@link #freshAddress(KeyChain.KeyPurpose)} or
* {@link #currentAddress(KeyChain.KeyPurpose)}.</p>
*/
public Address freshReceiveAddress(Script.ScriptType scriptType) {
Address address;
keyChainGroupLock.lock();
try {
long keyRotationTimeSecs = vKeyRotationTimestamp;
address = keyChainGroup.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS, scriptType, keyRotationTimeSecs);
} finally {
keyChainGroupLock.unlock();
}
saveNow();
return address;
}
/**
* Returns only the keys that have been issued by {@link #freshReceiveKey()}, {@link #freshReceiveAddress()},
* {@link #currentReceiveKey()} or {@link #currentReceiveAddress()}.
*/
public List<ECKey> getIssuedReceiveKeys() {
keyChainGroupLock.lock();
try {
List<ECKey> keys = new LinkedList<>();
long keyRotationTimeSecs = vKeyRotationTimestamp;
for (final DeterministicKeyChain chain : keyChainGroup.getActiveKeyChains(keyRotationTimeSecs))
keys.addAll(chain.getIssuedReceiveKeys());
return keys;
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Returns only the addresses that have been issued by {@link #freshReceiveKey()}, {@link #freshReceiveAddress()},
* {@link #currentReceiveKey()} or {@link #currentReceiveAddress()}.
*/
public List<Address> getIssuedReceiveAddresses() {
keyChainGroupLock.lock();
try {
List<Address> addresses = new ArrayList<>();
long keyRotationTimeSecs = vKeyRotationTimestamp;
for (final DeterministicKeyChain chain : keyChainGroup.getActiveKeyChains(keyRotationTimeSecs)) {
Script.ScriptType outputScriptType = chain.getOutputScriptType();
for (ECKey key : chain.getIssuedReceiveKeys())
addresses.add(Address.fromKey(getParams(), key, outputScriptType));
}
return addresses;
} finally {
keyChainGroupLock.unlock();
}
}
/** @deprecated Use {@link #upgradeToDeterministic(ScriptType, KeyParameter)} */
@Deprecated
public void upgradeToDeterministic(@Nullable KeyParameter aesKey) {
upgradeToDeterministic(Script.ScriptType.P2PKH, aesKey);
}
/**
* Upgrades the wallet to be deterministic (BIP32). You should call this, possibly providing the users encryption
* key, after loading a wallet produced by previous versions of bitcoinj. If the wallet is encrypted the key
* <b>must</b> be provided, due to the way the seed is derived deterministically from private key bytes: failing
* to do this will result in an exception being thrown. For non-encrypted wallets, the upgrade will be done for
* you automatically the first time a new key is requested (this happens when spending due to the change address).
*/
public void upgradeToDeterministic(Script.ScriptType outputScriptType, @Nullable KeyParameter aesKey)
throws DeterministicUpgradeRequiresPassword {
upgradeToDeterministic(outputScriptType, KeyChainGroupStructure.DEFAULT, aesKey);
}
/**
* Upgrades the wallet to be deterministic (BIP32). You should call this, possibly providing the users encryption
* key, after loading a wallet produced by previous versions of bitcoinj. If the wallet is encrypted the key
* <b>must</b> be provided, due to the way the seed is derived deterministically from private key bytes: failing
* to do this will result in an exception being thrown. For non-encrypted wallets, the upgrade will be done for
* you automatically the first time a new key is requested (this happens when spending due to the change address).
*/
public void upgradeToDeterministic(Script.ScriptType outputScriptType, KeyChainGroupStructure structure,
@Nullable KeyParameter aesKey) throws DeterministicUpgradeRequiresPassword {
keyChainGroupLock.lock();
try {
long keyRotationTimeSecs = vKeyRotationTimestamp;
keyChainGroup.upgradeToDeterministic(outputScriptType, structure, keyRotationTimeSecs, aesKey);
} finally {
keyChainGroupLock.unlock();
}
}
/** @deprecated Use {@link #isDeterministicUpgradeRequired(ScriptType)} */
@Deprecated
public boolean isDeterministicUpgradeRequired() {
return isDeterministicUpgradeRequired(Script.ScriptType.P2PKH);
}
/**
* Returns true if the wallet contains random keys and no HD chains, in which case you should call
* {@link #upgradeToDeterministic(ScriptType, KeyParameter)} before attempting to do anything
* that would require a new address or key.
*/
public boolean isDeterministicUpgradeRequired(Script.ScriptType outputScriptType) {
keyChainGroupLock.lock();
try {
long keyRotationTimeSecs = vKeyRotationTimestamp;
return keyChainGroup.isDeterministicUpgradeRequired(outputScriptType, keyRotationTimeSecs);
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Returns a snapshot of the watched scripts. This view is not live.
*/
public List<Script> getWatchedScripts() {
keyChainGroupLock.lock();
try {
return new ArrayList<>(watchedScripts);
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Removes the given key from the basicKeyChain. Be very careful with this - losing a private key <b>destroys the
* money associated with it</b>.
* @return Whether the key was removed or not.
*/
public boolean removeKey(ECKey key) {
keyChainGroupLock.lock();
try {
return keyChainGroup.removeImportedKey(key);
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Returns the number of keys in the key chain group, including lookahead keys.
*/
public int getKeyChainGroupSize() {
keyChainGroupLock.lock();
try {
return keyChainGroup.numKeys();
} finally {
keyChainGroupLock.unlock();
}
}
@VisibleForTesting
public int getKeyChainGroupCombinedKeyLookaheadEpochs() {
keyChainGroupLock.lock();
try {
return keyChainGroup.getCombinedKeyLookaheadEpochs();
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Returns a list of the non-deterministic keys that have been imported into the wallet, or the empty list if none.
*/
public List<ECKey> getImportedKeys() {
keyChainGroupLock.lock();
try {
return keyChainGroup.getImportedKeys();
} finally {
keyChainGroupLock.unlock();
}
}
/** Returns the address used for change outputs. Note: this will probably go away in future. */
public Address currentChangeAddress() {
return currentAddress(KeyChain.KeyPurpose.CHANGE);
}
/**
* <p>Imports the given ECKey to the wallet.</p>
*
* <p>If the wallet is configured to auto save to a file, triggers a save immediately. Runs the onKeysAdded event
* handler. If the key already exists in the wallet, does nothing and returns false.</p>
*/
public boolean importKey(ECKey key) {
return importKeys(Lists.newArrayList(key)) == 1;
}
/**
* Imports the given keys to the wallet.
* If {@link Wallet#autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)}
* has been called, triggers an auto save bypassing the normal coalescing delay and event handlers.
* Returns the number of keys added, after duplicates are ignored. The onKeyAdded event will be called for each key
* in the list that was not already present.
*/
public int importKeys(final List<ECKey> keys) {
// API usage check.
checkNoDeterministicKeys(keys);
int result;
keyChainGroupLock.lock();
try {
result = keyChainGroup.importKeys(keys);
} finally {
keyChainGroupLock.unlock();
}
saveNow();
return result;
}
private void checkNoDeterministicKeys(List<ECKey> keys) {
// Watch out for someone doing wallet.importKey(wallet.freshReceiveKey()); or equivalent: we never tested this.
for (ECKey key : keys)
if (key instanceof DeterministicKey)
throw new IllegalArgumentException("Cannot import HD keys back into the wallet");
}
/** Takes a list of keys and a password, then encrypts and imports them in one step using the current keycrypter. */
public int importKeysAndEncrypt(final List<ECKey> keys, CharSequence password) {
keyChainGroupLock.lock();
try {
checkNotNull(getKeyCrypter(), "Wallet is not encrypted");
return importKeysAndEncrypt(keys, getKeyCrypter().deriveKey(password));
} finally {
keyChainGroupLock.unlock();
}
}
/** Takes a list of keys and an AES key, then encrypts and imports them in one step using the current keycrypter. */
public int importKeysAndEncrypt(final List<ECKey> keys, KeyParameter aesKey) {
keyChainGroupLock.lock();
try {
checkNoDeterministicKeys(keys);
return keyChainGroup.importKeysAndEncrypt(keys, aesKey);
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Add a pre-configured keychain to the wallet. Useful for setting up a complex keychain,
* such as for a married wallet. For example:
* {@code
* MarriedKeyChain chain = MarriedKeyChain.builder()
* .random(new SecureRandom())
* .followingKeys(followingKeys)
* .threshold(2).build();
* wallet.addAndActivateHDChain(chain);
* }
*/
public void addAndActivateHDChain(DeterministicKeyChain chain) {
keyChainGroupLock.lock();
try {
keyChainGroup.addAndActivateHDChain(chain);
} finally {
keyChainGroupLock.unlock();
}
}
/** See {@link DeterministicKeyChain#setLookaheadSize(int)} for more info on this. */
public int getKeyChainGroupLookaheadSize() {
keyChainGroupLock.lock();
try {
return keyChainGroup.getLookaheadSize();
} finally {
keyChainGroupLock.unlock();
}
}
/** See {@link DeterministicKeyChain#setLookaheadThreshold(int)} for more info on this. */
public int getKeyChainGroupLookaheadThreshold() {
keyChainGroupLock.lock();
try {
return keyChainGroup.getLookaheadThreshold();
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Returns a public-only DeterministicKey that can be used to set up a watching wallet: that is, a wallet that
* can import transactions from the block chain just as the normal wallet can, but which cannot spend. Watching
* wallets are very useful for things like web servers that accept payments. This key corresponds to the account
* zero key in the recommended BIP32 hierarchy.
*/
public DeterministicKey getWatchingKey() {
keyChainGroupLock.lock();
try {
return keyChainGroup.getActiveKeyChain().getWatchingKey();
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Returns whether this wallet consists entirely of watching keys (unencrypted keys with no private part). Mixed
* wallets are forbidden.
*
* @throws IllegalStateException
* if there are no keys, or if there is a mix between watching and non-watching keys.
*/
public boolean isWatching() {
keyChainGroupLock.lock();
try {
return keyChainGroup.isWatching();
} finally {
keyChainGroupLock.unlock();
}
}
/**
* Return true if we are watching this address.
*/
public boolean isAddressWatched(Address address) {
Script script = ScriptBuilder.createOutputScript(address);
return isWatchedScript(script);