Hallo. I am using bitcoinj (I know very little this library) for check 
address balance, but I have problem with her. I don't understand how I can 
do it. 
I am using these 3 files for this exercise. I'm wrong something, but I 
can't figure out what!

Can anyone help with this problem?

-- 
You received this message because you are subscribed to the Google Groups 
"bitcoinj" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to bitcoinj+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
package org.my.balance;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

import org.bitcoinj.core.Address;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.wallet.CoinSelection;
import org.bitcoinj.wallet.CoinSelector;

/**
 * This class implements a {@link org.bitcoinj.wallet.CoinSelector} which attempts to select all outputs
 * from a designated address. Outputs are selected in order of highest priority.  Note that this means we may
 * end up "spending" more priority than would be required to get the transaction we are creating confirmed.
 */

public class AddressBalance implements CoinSelector {

    private Address addressToQuery;

    public AddressBalance(Address addressToQuery) {
        this.addressToQuery = addressToQuery;
    }

    @Override
    public CoinSelection select(Coin biTarget, List<TransactionOutput> candidates) {
        long target = biTarget.longValue();
        HashSet<TransactionOutput> selected = new HashSet<TransactionOutput>();
        // Sort the inputs by age*value so we get the highest "coindays" spent.
        // TODO: Consider changing the wallets internal format to track just outputs and keep them ordered.
        ArrayList<TransactionOutput> sortedOutputs = new ArrayList<TransactionOutput>(candidates);
        // When calculating the wallet balance, we may be asked to select all possible coins, if so, avoid sorting
        // them in order to improve performance.
        if (!biTarget.equals(NetworkParameters.MAX_MONEY)) {
            sortOutputs(sortedOutputs);
        }
        // Now iterate over the sorted outputs until we have got as close to the target as possible or a little
        // bit over (excessive value will be change).
        long totalOutputValue = 0;
        for (TransactionOutput output : sortedOutputs) {
            if (totalOutputValue >= target) break;
            // Only pick chain-included transactions, or transactions that are ours and pending.
            if (!shouldSelect(output)) continue;
            selected.add(output);
            totalOutputValue += output.getValue().longValue();
         }
        // Total may be lower than target here, if the given candidates were insufficient to create to requested
        // transaction.
        return new CoinSelection(Coin.valueOf(totalOutputValue), selected);
    }

    static void sortOutputs(ArrayList<TransactionOutput> outputs) {
        Collections.sort(outputs, new Comparator<TransactionOutput>() {
            public int compare(TransactionOutput a, TransactionOutput b) {
                int depth1 = 0;
                int depth2 = 0;
                TransactionConfidence conf1 = a.getParentTransaction().getConfidence();
                TransactionConfidence conf2 = b.getParentTransaction().getConfidence();
                if (conf1.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING)
                    depth1 = conf1.getDepthInBlocks();
                if (conf2.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING)
                    depth2 = conf2.getDepthInBlocks();
                Coin aValue = a.getValue();
                Coin bValue = b.getValue();
                BigInteger aCoinDepth = BigInteger.valueOf(aValue.value).multiply(BigInteger.valueOf(depth1));
                BigInteger bCoinDepth = BigInteger.valueOf(bValue.value).multiply(BigInteger.valueOf(depth2));
                int c1 = bCoinDepth.compareTo(aCoinDepth);
                if (c1 != 0) return c1;
                // The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size.
                int c2 = bValue.compareTo(aValue);
                if (c2 != 0) return c2;
                // They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering.
                BigInteger aHash = a.getParentTransaction().getHash().toBigInteger();
                BigInteger bHash = b.getParentTransaction().getHash().toBigInteger();
                return aHash.compareTo(bHash);
            }
        });
    }

    /** Sub-classes can override this to just customize whether transactions are usable, but keep age sorting. */
    protected boolean shouldSelect(TransactionOutput output) {
        Address outputToAddress = output.getScriptPubKey().getToAddress(addressToQuery.getParameters());
        try {
            // Check if output address matches addressToQuery and check if it can be spent.
            if(outputToAddress.equals(addressToQuery)) {
                if(output.isAvailableForSpending()) {
                    return isSelectable(output.getParentTransaction());
                }
            }
         } catch (Exception e) {
            e.printStackTrace();
         }

         return false;
    }

    public static boolean isSelectable(Transaction tx) {
        // Only pick chain-included transactions, or transactions that are ours and pending.
        TransactionConfidence confidence = tx.getConfidence();
        TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
        return type.equals(TransactionConfidence.ConfidenceType.BUILDING) || type.equals(TransactionConfidence.ConfidenceType.PENDING) && confidence.getSource().equals(TransactionConfidence.Source.SELF) && confidence.numBroadcastPeers() > 1;
    }
}
package org.my.balance;

import java.io.File;

import org.bitcoinj.core.Address;
import org.bitcoinj.core.BlockChain;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.PeerGroup;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.SPVBlockStore;
import org.bitcoinj.wallet.Wallet;

public class CheckBalance {

	private Coin addressBalance;
	private Wallet wallet;
	private Address address;
	private NetworkParameters params;
	private BlockChain blockChain;
	private PeerGroup peerGroup;
	private SPVBlockStore spvBlockStore;

	public Coin getAddressBalance() {
		return this.addressBalance;
	}

	private void setAddressBalance(Coin addressBalance) {
		this.addressBalance = addressBalance;
	}

	public Wallet getWallet() {
		return this.wallet;
	}

	private void setWallet(Wallet wallet) {
		this.wallet = wallet;
	}

	public Address getAddress() {
		return this.address;
	}

	private void setAddress(Address address) {
		this.address = address;
	}

	public NetworkParameters getParams() {
		return this.params;
	}

	private void setParams(NetworkParameters params) {
		this.params = params;
	}

	public BlockChain getBlockChain() {
		return this.blockChain;
	}

	private void setBlockChain(BlockChain blockChain) {
		this.blockChain = blockChain;
	}

	public PeerGroup getPeerGroup() {
		return this.peerGroup;
	}

	private void setPeerGroup(PeerGroup peerGroup) {
		this.peerGroup = peerGroup;
	}

	public SPVBlockStore getSpvBlockStore() {
		return this.spvBlockStore;
	}

	private void setSpvBlockStore(SPVBlockStore spvBlockStore) {
		this.spvBlockStore = spvBlockStore;
	}

	public CheckBalance(String address) throws BlockStoreException {
		super();
		this.setParams(MainNetParams.get());
		this.setWallet(new Wallet(this.getParams())); // TODO throw error
		this.setSpvBlockStore(new SPVBlockStore(this.getParams(),
				new File("/media/ivanof/_develop/bitcoin_blockchain/blocks/blk00000.dat")));
		this.setBlockChain(new BlockChain(this.getParams(), this.getWallet(), this.getSpvBlockStore()));
		this.setPeerGroup(new PeerGroup(this.getParams(), this.getBlockChain()));
		this.setAddress(Address.fromBase58(this.getParams(), address));

		this.checkBalance();
	}

	private void checkBalance() {

		this.getPeerGroup().addWallet(this.getWallet());
		this.getPeerGroup().startAsync();

		this.setAddressBalance(wallet.getBalance(new AddressBalance(this.getAddress())));
	}
}
package org.my.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import org.bitcoinj.core.Coin;
import org.bitcoinj.store.BlockStoreException;
import org.my.balance.CheckBalance;

public class ReadFile {

	private PrintWriter writer;
	private ListFilesUtil listFilesUtil;
	private File[] files;

	public PrintWriter getWriter() {
		return this.writer;
	}

	private void setWriter(PrintWriter writer) {
		this.writer = writer;
	}

	public ListFilesUtil getListFilesUtil() {
		return this.listFilesUtil;
	}

	private void setListFilesUtil(ListFilesUtil listFilesUtil) {
		this.listFilesUtil = listFilesUtil;
	}

	public File[] getFiles() {
		return this.files;
	}

	private void setFiles(File[] files) {
		this.files = files;
	}

	public static void main(String[] args) {
		// TODO add method for read and list directories and read file with all adresses
		ReadFile readFile = new ReadFile();

		final String directoryBitcoinLinux = "/media/ivanof/_develop/BitcoinAddress";

		try {
			readFile.readDir(directoryBitcoinLinux);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void readDir(String dirName) throws FileNotFoundException, IOException {
		this.setListFilesUtil(new ListFilesUtil());
		this.setFiles(this.getListFilesUtil().getAllFilesFromDir(dirName));
		this.readFiles();
	}

	private void readFiles() throws FileNotFoundException, IOException {

		String uniqueFileName = "beautifulAddresses" + UUID.randomUUID().toString() + ".txt";
		this.setWriter(new FileWrite(uniqueFileName).getWriter());

		if (this.getFiles().length > 0) {
			for (File file : this.getFiles()) {
				if (file.isFile()) {
					try (BufferedReader br = new BufferedReader(new FileReader(file))) {
						String line;

						while ((line = br.readLine()) != null) {
							String[] words = line.split(" ");
							if (words.length > 1) {
								String addressString = words[1].trim();
								String privateKey = words[4].trim();
								String privateKey2 = words[7].trim();

								CheckBalance checkBalance = new CheckBalance(addressString);
								Coin balance = checkBalance.getAddressBalance();
								System.out.println(balance.getValue());

								if (balance.getValue() > 0) {
									System.out.println(addressString);
									System.out.println(privateKey);
									System.out.println(privateKey2);
									System.out.println();

									// add to file if balance > 0
									// String str = String.format("Address: %s = PK: %s ---> PK2: %s Balance: %s%n",
									// addressString, privateKey, privateKey2, balance);
									// writer.print(str);
									// writer.flush();
								}
							}
						}
					} catch (BlockStoreException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

}

Reply via email to