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);
}
}