检查钱包的余额(bitcoinj)

时间:2015-05-25 19:04:56

标签: java bitcoinj

我正在尝试使用bitcoinj为比特币创建一个p2p android钱包。 我创建了一个地址并将其添加为钱包中的wachedAddress。 当我从http://tpfaucet.appspot.com/添加一些硬币时,我的听众向我显示我的地址已经添加了0.02个硬币,但是当我试图看到我的应用程序中的余额显示0 BTC时。我错过了什么?

以下是我的听众的代码:

public class WalletListener extends AbstractWalletEventListener {
    public static final String TAG = "WalletListener";
    private WalletState walletState;
    private Wallet wallet;

    @Override
    public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
        Log.d(TAG, "-----> coins resceived: " + tx.getHashAsString());
        Log.d(TAG, "received: " + tx.getValue(wallet));
        walletState = WalletState.getInstantce();
        wallet = walletState.getReadyWallet();
        Log.d(TAG, "The balance is: " + wallet.getBalance().toFriendlyString());
    }
}

这是我的WalletState类的代码

package com.tools;

import android.os.AsyncTask;
import android.util.Log;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.mybitcoinwallet.WalletActivity;
import com.mybitcoinwallet.adapter.MyPagerAdapter;
import com.mybitcoinwallet.fragment.WalletFragment;
import com.mybitcoinwallet.listeners.WalletListener;

import org.bitcoinj.core.Address;
import org.bitcoinj.core.BlockChain;
import org.bitcoinj.core.CheckpointManager;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.InsufficientMoneyException;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.PeerGroup;
import org.bitcoinj.core.ScriptException;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.Wallet;
import org.bitcoinj.crypto.KeyCrypterException;
import org.bitcoinj.net.discovery.DnsDiscovery;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.SPVBlockStore;
import org.bitcoinj.store.UnreadableWalletException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

    /**
     * Created by Mihail on 5/23/15.
     */
    public class WalletState {
        public static final String TAG = "WalletState";
        private NetworkParameters network = TestNet3Params.get();
        private Wallet wallet;
        private Address address;
        private MyPagerAdapter pagerAdapter;
        private static WalletState walletState;
        private PeerGroup peerGroup;
        private BlockStore blockStore;
        private File walletFile;

        private WalletState() {
        }

        public void initiate() {
            new BackgroundTask().execute();
        }

        public static WalletState getInstantce() {
            if (walletState == null) {
                walletState = new WalletState();
            }
            return walletState;
        }

        public static Wallet getWallet(NetworkParameters netParams) {
            File walletFile = new File(WalletActivity.getMainActivity().getFilesDir().getPath().toString()
                    + "my_wallet_file");
            Log.i(TAG, WalletActivity.getMainActivity().getFilesDir().getPath().toString()
                    + "my_wallet_file");
            Wallet wallet;
            try {
                wallet = Wallet.loadFromFile(walletFile);
            } catch (UnreadableWalletException e) {
                wallet = new Wallet(netParams);
                ECKey key = new ECKey();
                wallet.addKey(key);
                try {
                    wallet.saveToFile(walletFile);
                } catch (IOException a) {
                    Log.e(TAG, "Caught IOException: ", a);
                }
            }
            return wallet;
        }

        public class BackgroundTask extends AsyncTask {
            public static final String TAG = "BackgroundTask";

            @Override
            protected Object doInBackground(Object[] params) {

                try {
                    Log.d(TAG, "Started");
                    wallet = getWallet(network);
                    wallet.addEventListener(new WalletListener());
                    ECKey key = wallet.getImportedKeys().iterator().next();

                    File file = new File(WalletActivity.getMainActivity().getFilesDir().getPath()
                            + "my_wallet_file" + ".spvchain");
                    boolean chainExistedAlready = file.exists();
                    blockStore = new SPVBlockStore(network, file);
                    if (!chainExistedAlready) {
                        File checkpointsFile = new File("checkpoints");
                        if (checkpointsFile.exists()) {
                            FileInputStream stream = new FileInputStream(checkpointsFile);
                            CheckpointManager.checkpoint(network, stream, blockStore, key.getCreationTimeSeconds());
                        }
                    }

                    BlockChain chain = new BlockChain(network, wallet, blockStore);
                    // Connect to the localhost node. One minute timeout since we won't try any other peers
                    Log.i(TAG, "Connecting ...");
                    peerGroup = new PeerGroup(network, chain);
                    peerGroup.setUserAgent("PingService", "1.0");
                    peerGroup.addPeerDiscovery(new DnsDiscovery(network));
                    peerGroup.addWallet(wallet);
                    peerGroup.startAsync();
                    peerGroup.awaitRunning();
                    Log.i(TAG, "Peers are fully synchronized! ");

                    address = wallet.currentReceiveAddress();
                    Log.i(TAG, "currentReceiveAddress: " + address);
                    wallet.addWatchedAddress(address);
                    ECKey ecKey = wallet.currentReceiveKey();

                    // Making sure that everything is shut down cleanly!
                    Runtime.getRuntime().addShutdownHook(new Thread() {
                        @Override
                        public void run() {
                            try {
                                System.out.print("Shutting down ... ");
                                peerGroup.stopAsync();
                                peerGroup.awaitTerminated();
                                wallet.saveToFile(walletFile);
                                blockStore.close();
                                System.out.print("done ");
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });

                } catch (Exception e) {
                    Log.e(TAG, "AAAAAA Exception!!!!!!", e);
                }
                return null;
            }

            @Override
            protected void onPostExecute(Object o) {
                Log.i(TAG, "onPostExecute! finally and the Key is: " + address.toString());
                pagerAdapter = WalletActivity.getMainActivity().getPagerAdapter();
                WalletFragment fragment = pagerAdapter.getFragment();
                fragment.setmTextView(address.toString());
                Coin balance = wallet.getBalance();
                fragment.setBalanceText(balance.toFriendlyString());
                Log.i(TAG, "The balance is " + balance.toFriendlyString());
                fragment.setWallet_progressBar_visibility();

            }

        }

        public void sendCoins(final Wallet wallet, Transaction tx) {
            // It's impossible to pick one specific identity that you receive coins from in Bitcoin as there
            // could be inputs from many addresses. So instead we just pick the first and assume they were all
            // owned by the same person.
            try {
                Coin value = tx.getValueSentToMe(wallet);
                TransactionInput input = tx.getInputs().get(0);
                Address from = input.getFromAddress();
                final Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, from, value);
                System.out.println("Sending ...");
                Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() {
                    public void onSuccess(Transaction transaction) {
                        System.out.println("Sent coins back! Transaction hash is " + sendResult.tx.getHashAsString());
                        // The wallet has changed now, it'll get auto saved shortly or when the app shuts down.
                    }

                    public void onFailure(Throwable throwable) {
                        System.err.println("Failed to send coins :(");
                        throwable.printStackTrace();
                    }
                });
            } catch (ScriptException e) {
                // If we didn't understand the scriptSig, just crash.
                throw new RuntimeException(e);
            } catch (KeyCrypterException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (InsufficientMoneyException e) {
                e.printStackTrace();
            }


        }

        public Wallet getReadyWallet() {
            if (wallet != null) {
                Log.i(TAG, "The ready wallet was returned");
                return wallet;
            }
            return getWallet(network);
        }
    }

0 个答案:

没有答案