@Override public Wallet create(NetworkParameters params, KeyChainGroup keyChainGroup) { return new Wallet(params, keyChainGroup); } });
/** * Adds an event listener object. Methods on this object are called when something interesting happens, * like receiving money. Runs the listener methods in the user thread. */ public void addEventListener(WalletEventListener listener) { addChangeEventListener(Threading.USER_THREAD, listener); addCoinsReceivedEventListener(Threading.USER_THREAD, listener); addCoinsSentEventListener(Threading.USER_THREAD, listener); addKeyChainEventListener(Threading.USER_THREAD, listener); addReorganizeEventListener(Threading.USER_THREAD, listener); addScriptChangeEventListener(Threading.USER_THREAD, listener); addTransactionConfidenceEventListener(Threading.USER_THREAD, listener); }
/** * Returns the AVAILABLE balance of this wallet. See {@link BalanceType#AVAILABLE} for details on what this * means. */ public Coin getBalance() { return getBalance(BalanceType.AVAILABLE); }
private void addWalletListeners() { wallet.addChangeEventListener(mWalletListener); wallet.addCoinsReceivedEventListener(mWalletListener); wallet.addCoinsSentEventListener(mWalletListener); wallet.addReorganizeEventListener(mWalletListener); }
private Wallet createWallet(File walletFile) throws IOException { Wallet wallet = new Wallet(Constants.NETWORK_PARAMETERS); WalletFiles walletFiles = wallet.autosaveToFile(walletFile, 3 * 1000, TimeUnit.MILLISECONDS, null); walletFiles.saveNow(); return wallet; }
try { StringBuilder builder = new StringBuilder(); Coin estimatedBalance = getBalance(BalanceType.ESTIMATED); Coin availableBalance = getBalance(BalanceType.AVAILABLE_SPENDABLE); builder.append("Wallet containing ").append(estimatedBalance.toFriendlyString()).append(" (spendable: ") .append(availableBalance.toFriendlyString()).append(") in:\n"); builder.append(" ").append(spent.size()).append(" spent transactions\n"); builder.append(" ").append(dead.size()).append(" dead transactions\n"); final Date lastBlockSeenTime = getLastBlockSeenTime(); builder.append("Last seen best block: ").append(getLastBlockSeenHeight()).append(" (") .append(lastBlockSeenTime == null ? "time unknown" : Utils.dateTimeFormat(lastBlockSeenTime)) .append("): ").append(getLastBlockSeenHash()).append('\n'); final KeyCrypter crypter = keyChainGroup.getKeyCrypter(); if (crypter != null) builder.append("Encryption: ").append(crypter).append('\n'); if (isWatching()) builder.append("Wallet is watching.\n"); builder.append("Earliest creation time: ").append(Utils.dateTimeFormat(getEarliestKeyCreationTime() * 1000)) .append('\n'); final Date keyRotationTime = getKeyRotationTime(); if (keyRotationTime != null) builder.append("Key rotation time: ").append(Utils.dateTimeFormat(keyRotationTime)).append('\n'); toStringHelper(builder, pending, chain, Transaction.SORT_TX_BY_UPDATE_TIME); toStringHelper(builder, unspent, chain, Transaction.SORT_TX_BY_HEIGHT);
selector.excludeOutputsSpentBy(other); CoinSelection toMove = selector.select(Coin.ZERO, calculateAllSpendCandidates()); if (toMove.valueGathered.equals(Coin.ZERO)) return null; // Nothing to do. maybeUpgradeToHD(aesKey); Transaction rekeyTx = new Transaction(params); for (TransactionOutput output : toMove.gathered) { rekeyTx.addOutput(toMove.valueGathered, sign ? freshReceiveAddress() : currentReceiveAddress()); if (!adjustOutputDownwardsForFee(rekeyTx, toMove, Transaction.DEFAULT_TX_FEE, true)) { log.error("Failed to adjust rekey tx for fees."); return null; req.aesKey = aesKey; if (sign) signTransaction(req);
public BitcoinTestPaymentService(BlockChain bitcoinBlockchain, Context bitcoinContext, NetworkParameters bitcoinNetworkParameters, PeerGroup peerGroup, String walletPassword, String walletPath) throws IOException, CipherException, UnreadableWalletException { this.bitcoinBlockchain = bitcoinBlockchain; this.bitcoinContext = bitcoinContext; this.bitcoinNetworkParameters = bitcoinNetworkParameters; this.peerGroup = peerGroup; File walletFile = new File(walletPath); if (walletFile.exists()) { LOG.info("Wallet exists... trying to load from: {}", walletPath); this.bitcoinWallet = Wallet.loadFromFile(new File(walletPath)); } else { LOG.info("Wallet does NOT exist... creating one.", walletPath); this.bitcoinWallet = new Wallet(this.bitcoinContext); this.bitcoinWallet.saveToFile(walletFile); } LOG.info("Wallet loaded: address={}", this.bitcoinWallet.currentReceiveAddress()); this.bitcoinWallet.autosaveToFile(walletFile, 500, TimeUnit.MILLISECONDS, null); this.bitcoinBlockchain.addWallet(this.bitcoinWallet); peerGroup.addWallet(this.bitcoinWallet); }
@Test(expected = KeyCrypterException.class) public void addEncryptedKeyToUnencryptedWallet() throws Exception { Wallet encryptedWallet = new Wallet(PARAMS); encryptedWallet.encrypt(PASSWORD1); KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter(); ECKey key1 = new ECKey(); key1 = key1.encrypt(keyCrypter, keyCrypter.deriveKey("PASSWORD!")); wallet.importKey(key1); }
@Test public void testStandardWalletDisconnect() throws Exception { NetworkParameters params = UnitTestParams.get(); Wallet w = new Wallet(new Context(params)); w.setCoinSelector(new AllowUnconfirmedCoinSelector()); Address a = w.currentReceiveAddress(); Transaction tx1 = FakeTxBuilder.createFakeTxWithoutChangeAddress(params, Coin.COIN, a); w.receivePending(tx1, null); Transaction tx2 = new Transaction(params); tx2.addOutput(Coin.valueOf(99000000), new ECKey()); w.completeTx(SendRequest.forTx(tx2)); TransactionInput txInToDisconnect = tx2.getInput(0); assertEquals(tx1, txInToDisconnect.getOutpoint().fromTx); assertNull(txInToDisconnect.getOutpoint().connectedOutput); txInToDisconnect.disconnect(); assertNull(txInToDisconnect.getOutpoint().fromTx); assertNull(txInToDisconnect.getOutpoint().connectedOutput); }
private static void go(Coin feeToTest, int numOutputs) throws InterruptedException, java.util.concurrent.ExecutionException, InsufficientMoneyException { kit.peerGroup().setMaxConnections(25); if (kit.wallet().getBalance().compareTo(feeToTest) < 0) { System.out.println("Send some money to " + kit.wallet().currentReceiveAddress()); System.out.println("... and wait for it to confirm"); kit.wallet().getBalanceFuture(feeToTest, Wallet.BalanceType.AVAILABLE).get(); System.out.println("Height at start is " + heightAtStart); Coin value = kit.wallet().getBalance().subtract(feeToTest); Coin outputValue = value.divide(numOutputs); Transaction transaction = new Transaction(PARAMS); for (int i = 0; i < numOutputs - 1; i++) { transaction.addOutput(outputValue, kit.wallet().freshReceiveAddress()); value = value.subtract(outputValue); transaction.addOutput(value, kit.wallet().freshReceiveAddress()); SendRequest request = SendRequest.forTx(transaction); request.feePerKb = feeToTest; request.ensureMinRequiredFee = false; kit.wallet().completeTx(request); System.out.println("Size in bytes is " + request.tx.unsafeBitcoinSerialize().length); System.out.println("TX is " + request.tx);
@Test public void testSequenceNumber() throws Exception { Wallet wallet = new Wallet(PARAMS); Transaction tx1 = createFakeTx(PARAMS, Coin.COIN, wallet.currentReceiveAddress()); tx1.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE); wallet.receivePending(tx1, null); Transaction tx2 = createFakeTx(PARAMS, Coin.COIN, wallet.currentReceiveAddress()); tx2.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 1); wallet.receivePending(tx2, null); Wallet walletCopy = roundTrip(wallet); Transaction tx1copy = checkNotNull(walletCopy.getTransaction(tx1.getHash())); assertEquals(TransactionInput.NO_SEQUENCE, tx1copy.getInput(0).getSequenceNumber()); Transaction tx2copy = checkNotNull(walletCopy.getTransaction(tx2.getHash())); assertEquals(TransactionInput.NO_SEQUENCE - 1, tx2copy.getInput(0).getSequenceNumber()); }
@Test public void scriptCreationTime() throws Exception { Utils.setMockClock(); long now = Utils.currentTimeSeconds(); wallet = new Wallet(PARAMS); assertEquals(now, wallet.getEarliestKeyCreationTime()); Utils.rollMockClock(-120); wallet.addWatchedAddress(OTHER_ADDRESS); wallet.freshReceiveKey(); assertEquals(now - 120, wallet.getEarliestKeyCreationTime()); }
private void setupWalletListeners(Wallet wallet) { wallet.addCoinsReceivedEventListener((wallet1, tx, prevBalance, newBalance) -> { view.displayMyBalance(wallet.getBalance().toFriendlyString()); if(tx.getPurpose() == Transaction.Purpose.UNKNOWN) view.showToastMessage("Receive " + newBalance.minus(prevBalance).toFriendlyString()); }); wallet.addCoinsSentEventListener((wallet12, tx, prevBalance, newBalance) -> { view.displayMyBalance(wallet.getBalance().toFriendlyString()); view.clearAmount(); view.displayRecipientAddress(null); view.showToastMessage("Sent " + prevBalance.minus(newBalance).minus(tx.getFee()).toFriendlyString()); }); } }
@Before public void setUp() throws Exception { BriefLogFormatter.initVerbose(); Context ctx = new Context(PARAMS); myWatchedKey = new ECKey(); myWallet = new Wallet(PARAMS); myKey = new ECKey(); myKey.setCreationTimeSeconds(123456789L); myWallet.importKey(myKey); myAddress = myKey.toAddress(PARAMS); myWallet = new Wallet(PARAMS); myWallet.importKey(myKey); mScriptCreationTime = new Date().getTime() / 1000 - 1234; myWallet.addWatchedAddress(myWatchedKey.toAddress(PARAMS), mScriptCreationTime); myWallet.setDescription(WALLET_DESCRIPTION); }
@Override protected void onSetupCompleted() { if (wallet().getImportedKeys().size() < 1) wallet().importKey(new ECKey()); wallet().allowSpendingUnconfirmedTransactions(); view.displayWalletPath(vWalletFile.getAbsolutePath()); setupWalletListeners(wallet()); Log.d("myLogs", "My address = " + wallet().freshReceiveAddress()); } };
assertNotNull(miningKey); Context context = new Context(PARAMS); Wallet wallet = new Wallet(context); wallet.importKey(miningKey); assertEquals(Coin.ZERO, wallet.getBalance()); wallet.receiveFromBlock(transactions.get(0), storedBlock, NewBlockType.BEST_CHAIN, 0); assertEquals(BALANCE_AFTER_BLOCK, wallet.getBalance(BalanceType.ESTIMATED)); assertEquals(Coin.ZERO, wallet.getBalance(BalanceType.AVAILABLE));
@Test public void keyCreationTime() throws Exception { Utils.setMockClock(); long now = Utils.currentTimeSeconds(); wallet = new Wallet(PARAMS); assertEquals(now, wallet.getEarliestKeyCreationTime()); Utils.rollMockClock(60); wallet.freshReceiveKey(); assertEquals(now, wallet.getEarliestKeyCreationTime()); }
@Test public void testUTXOWalletDisconnect() throws Exception { final NetworkParameters params = UnitTestParams.get(); Wallet w = new Wallet(new Context(params)); Address a = w.currentReceiveAddress(); final UTXO utxo = new UTXO(Sha256Hash.of(new byte[] { 1, 2, 3 }), 1, Coin.COIN, 0, false, ScriptBuilder.createOutputScript(a)); w.setUTXOProvider(new UTXOProvider() { @Override public NetworkParameters getParams() { w.completeTx(SendRequest.forTx(tx2));