org.bitcoinj.wallet.Wallet Java Examples

The following examples show how to use org.bitcoinj.wallet.Wallet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PeerGroup.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private List<Message> handleGetData(GetDataMessage m) {
    // Scans the wallets and memory pool for transactions in the getdata message and returns them.
    // Runs on peer threads.
    lock.lock();
    try {
        LinkedList<Message> transactions = new LinkedList<>();
        LinkedList<InventoryItem> items = new LinkedList<>(m.getItems());
        Iterator<InventoryItem> it = items.iterator();
        while (it.hasNext()) {
            InventoryItem item = it.next();
            // Check the wallets.
            for (Wallet w : wallets) {
                Transaction tx = w.getTransaction(item.hash);
                if (tx == null) continue;
                transactions.add(tx);
                it.remove();
                break;
            }
        }
        return transactions;
    } finally {
        lock.unlock();
    }
}
 
Example #2
Source File: TransactionInputTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: WalletTool.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private static Protos.Wallet attemptHexConversion(Protos.Wallet proto) {
    // Try to convert any raw hashes and such to textual equivalents for easier debugging. This makes it a bit
    // less "raw" but we will just abort on any errors.
    try {
        Protos.Wallet.Builder builder = proto.toBuilder();
        for (Protos.Transaction.Builder tx : builder.getTransactionBuilderList()) {
            tx.setHash(bytesToHex(tx.getHash()));
            for (int i = 0; i < tx.getBlockHashCount(); i++)
                tx.setBlockHash(i, bytesToHex(tx.getBlockHash(i)));
            for (Protos.TransactionInput.Builder input : tx.getTransactionInputBuilderList())
                input.setTransactionOutPointHash(bytesToHex(input.getTransactionOutPointHash()));
            for (Protos.TransactionOutput.Builder output : tx.getTransactionOutputBuilderList()) {
                if (output.hasSpentByTransactionHash())
                    output.setSpentByTransactionHash(bytesToHex(output.getSpentByTransactionHash()));
            }
            // TODO: keys, ip addresses etc.
        }
        return builder.build();
    } catch (Throwable throwable) {
        log.error("Failed to do hex conversion on wallet proto", throwable);
        return proto;
    }
}
 
Example #4
Source File: WalletProtobufSerializerTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void extensions() throws Exception {
    myWallet.addExtension(new FooWalletExtension("com.whatever.required", true));
    Protos.Wallet proto = new WalletProtobufSerializer().walletToProto(myWallet);
    // Initial extension is mandatory: try to read it back into a wallet that doesn't know about it.
    try {
        new WalletProtobufSerializer().readWallet(PARAMS, null, proto);
        fail();
    } catch (UnreadableWalletException e) {
        assertTrue(e.getMessage().contains("mandatory"));
    }
    Wallet wallet = new WalletProtobufSerializer().readWallet(PARAMS,
            new WalletExtension[]{ new FooWalletExtension("com.whatever.required", true) },
            proto);
    assertTrue(wallet.getExtensions().containsKey("com.whatever.required"));

    // Non-mandatory extensions are ignored if the wallet doesn't know how to read them.
    Wallet wallet2 = new Wallet(PARAMS);
    wallet2.addExtension(new FooWalletExtension("com.whatever.optional", false));
    Protos.Wallet proto2 = new WalletProtobufSerializer().walletToProto(wallet2);
    Wallet wallet5 = new WalletProtobufSerializer().readWallet(PARAMS, null, proto2);
    assertEquals(0, wallet5.getExtensions().size());
}
 
Example #5
Source File: PeerGroupTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWalletCatchupTime() throws Exception {
    // Check the fast catchup time was initialized to something around the current runtime minus a week.
    // The wallet was already added to the peer in setup.
    final int WEEK = 86400 * 7;
    final long now = Utils.currentTimeSeconds();
    peerGroup.start();
    assertTrue(peerGroup.getFastCatchupTimeSecs() > now - WEEK - 10000);
    Wallet w2 = new Wallet(PARAMS);
    ECKey key1 = new ECKey();
    key1.setCreationTimeSeconds(now - 86400);  // One day ago.
    w2.importKey(key1);
    peerGroup.addWallet(w2);
    peerGroup.waitForJobQueue();
    assertEquals(peerGroup.getFastCatchupTimeSecs(), now - 86400 - WEEK);
    // Adding a key to the wallet should update the fast catchup time, but asynchronously and in the background
    // due to the need to avoid complicated lock inversions.
    ECKey key2 = new ECKey();
    key2.setCreationTimeSeconds(now - 100000);
    w2.importKey(key2);
    peerGroup.waitForJobQueue();
    assertEquals(peerGroup.getFastCatchupTimeSecs(), now - WEEK - 100000);
}
 
Example #6
Source File: AbstractBlockChain.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add a wallet to the BlockChain. Note that the wallet will be unaffected by any blocks received while it
 * was not part of this BlockChain. This method is useful if the wallet has just been created, and its keys
 * have never been in use, or if the wallet has been loaded along with the BlockChain. Note that adding multiple
 * wallets is not well tested!
 */
public final void addWallet(Wallet wallet) {
    addNewBestBlockListener(Threading.SAME_THREAD, wallet);
    addReorganizeListener(Threading.SAME_THREAD, wallet);
    addTransactionReceivedListener(Threading.SAME_THREAD, wallet);
    int walletHeight = wallet.getLastBlockSeenHeight();
    int chainHeight = getBestChainHeight();
    if (walletHeight != chainHeight) {
        log.warn("Wallet/chain height mismatch: {} vs {}", walletHeight, chainHeight);
        log.warn("Hashes: {} vs {}", wallet.getLastBlockSeenHash(), getChainHead().getHeader().getHash());

        // This special case happens when the VM crashes because of a transaction received. It causes the updated
        // block store to persist, but not the wallet. In order to fix the issue, we roll back the block store to
        // the wallet height to make it look like as if the block has never been received.
        if (walletHeight < chainHeight && walletHeight > 0) {
            try {
                rollbackBlockStore(walletHeight);
                log.info("Rolled back block store to height {}.", walletHeight);
            } catch (BlockStoreException x) {
                log.warn("Rollback of block store failed, continuing with mismatched heights. This can happen due to a replay.");
            }
        }
    }
}
 
Example #7
Source File: MainController.java    From cate with MIT License 6 votes vote down vote up
/**
 * Register a wallet to be tracked by this controller. This recalculates
 * wallet transactions, which is a long running task, and must be run on a
 * background thread.
 */
public void registerWallet(final Network network, final Wallet wallet) {
    // We rebuild the transactions on the current thread, rather than slowing
    // down the UI thread, and so keep a temporary copy to be pushed into the
    // main transaction list later.
    final List<WalletTransaction> tempTransactions = rebuildTransactions(network, wallet);

    Collections.reverse(tempTransactions);
    Platform.runLater(() -> {
        this.activeNetworks.add(network);
        if (this.activeNetworks.size() == 1) {
            // We've just added the first wallet, choose it
            receiveSelector.setValue(network);
            sendSelector.setValue(network);
            receiveSelector.setDisable(false);
            sendSelector.setDisable(false);
        }

        // TODO: Need to enforce order of transactions by time, not by
        // network and then time as this does
        transactions.addAll(tempTransactions);
    });
}
 
Example #8
Source File: PeerGroup.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private List<Message> handleGetData(GetDataMessage m) {
    // Scans the wallets and memory pool for transactions in the getdata message and returns them.
    // Runs on peer threads.
    lock.lock();
    try {
        LinkedList<Message> transactions = new LinkedList<>();
        LinkedList<InventoryItem> items = new LinkedList<>(m.getItems());
        Iterator<InventoryItem> it = items.iterator();
        while (it.hasNext()) {
            InventoryItem item = it.next();
            // Check the wallets.
            for (Wallet w : wallets) {
                Transaction tx = w.getTransaction(item.hash);
                if (tx == null)
                    continue;
                transactions.add(tx);
                it.remove();
                break;
            }
        }
        return transactions;
    } finally {
        lock.unlock();
    }
}
 
Example #9
Source File: WalletTool.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private static Protos.Wallet attemptHexConversion(Protos.Wallet proto) {
    // Try to convert any raw hashes and such to textual equivalents for easier debugging. This makes it a bit
    // less "raw" but we will just abort on any errors.
    try {
        Protos.Wallet.Builder builder = proto.toBuilder();
        for (Protos.Transaction.Builder tx : builder.getTransactionBuilderList()) {
            tx.setHash(bytesToHex(tx.getHash()));
            for (int i = 0; i < tx.getBlockHashCount(); i++)
                tx.setBlockHash(i, bytesToHex(tx.getBlockHash(i)));
            for (Protos.TransactionInput.Builder input : tx.getTransactionInputBuilderList())
                input.setTransactionOutPointHash(bytesToHex(input.getTransactionOutPointHash()));
            for (Protos.TransactionOutput.Builder output : tx.getTransactionOutputBuilderList()) {
                if (output.hasSpentByTransactionHash())
                    output.setSpentByTransactionHash(bytesToHex(output.getSpentByTransactionHash()));
            }
            // TODO: keys, ip addresses etc.
        }
        return builder.build();
    } catch (Throwable throwable) {
        log.error("Failed to do hex conversion on wallet proto", throwable);
        return proto;
    }
}
 
Example #10
Source File: StoredPaymentChannelServerStates.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void deserializeWalletExtension(Wallet containingWallet, byte[] data) throws Exception {
    lock.lock();
    try {
        this.wallet = containingWallet;
        ServerState.StoredServerPaymentChannels states = ServerState.StoredServerPaymentChannels.parseFrom(data);
        NetworkParameters params = containingWallet.getParams();
        for (ServerState.StoredServerPaymentChannel storedState : states.getChannelsList()) {
            final int majorVersion = storedState.getMajorVersion();
            TransactionOutput clientOutput = null;
            ECKey clientKey = null;
            if (majorVersion == 1) {
                clientOutput = new TransactionOutput(params, null, storedState.getClientOutput().toByteArray(), 0);
            } else {
                clientKey = ECKey.fromPublicOnly(storedState.getClientKey().toByteArray());
            }
            StoredServerChannel channel = new StoredServerChannel(null,
                    majorVersion,
                    params.getDefaultSerializer().makeTransaction(storedState.getContractTransaction().toByteArray()),
                    clientOutput,
                    storedState.getRefundTransactionUnlockTimeSecs(),
                    ECKey.fromPrivate(storedState.getMyKey().toByteArray()),
                    clientKey,
                    Coin.valueOf(storedState.getBestValueToMe()),
                    storedState.hasBestValueSignature() ? storedState.getBestValueSignature().toByteArray() : null);
            putChannel(channel);
        }
    } finally {
        lock.unlock();
    }
}
 
Example #11
Source File: StoredPaymentChannelClientStates.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void deserializeWalletExtension(Wallet containingWallet, byte[] data) throws Exception {
    lock.lock();
    try {
        checkState(this.containingWallet == null || this.containingWallet == containingWallet);
        this.containingWallet = containingWallet;
        NetworkParameters params = containingWallet.getParams();
        ClientState.StoredClientPaymentChannels states = ClientState.StoredClientPaymentChannels.parseFrom(data);
        for (ClientState.StoredClientPaymentChannel storedState : states.getChannelsList()) {
            Transaction refundTransaction = params.getDefaultSerializer().makeTransaction(storedState.getRefundTransaction().toByteArray());
            refundTransaction.getConfidence().setSource(TransactionConfidence.Source.SELF);
            ECKey myKey = (storedState.getMyKey().isEmpty()) ?
                    containingWallet.findKeyFromPubKey(storedState.getMyPublicKey().toByteArray()) :
                    ECKey.fromPrivate(storedState.getMyKey().toByteArray());
            ECKey serverKey = storedState.hasServerKey() ? ECKey.fromPublicOnly(storedState.getServerKey().toByteArray()) : null;
            StoredClientChannel channel = new StoredClientChannel(storedState.getMajorVersion(),
                    Sha256Hash.wrap(storedState.getId().toByteArray()),
                    params.getDefaultSerializer().makeTransaction(storedState.getContractTransaction().toByteArray()),
                    refundTransaction,
                    myKey,
                    serverKey,
                    Coin.valueOf(storedState.getValueToMe()),
                    Coin.valueOf(storedState.getRefundFees()),
                    storedState.getExpiryTime(),
                    false);
            if (storedState.hasCloseTransactionHash()) {
                Sha256Hash closeTxHash = Sha256Hash.wrap(storedState.getCloseTransactionHash().toByteArray());
                channel.close = containingWallet.getTransaction(closeTxHash);
            }
            putChannel(channel, false);
        }
    } finally {
        lock.unlock();
    }
}
 
Example #12
Source File: WalletProtobufSerializerTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testKeys() throws Exception {
    for (int i = 0 ; i < 20 ; i++) {
        myKey = new ECKey();
        myAddress = myKey.toAddress(PARAMS);
        myWallet = new Wallet(PARAMS);
        myWallet.importKey(myKey);
        Wallet wallet1 = roundTrip(myWallet);
        assertArrayEquals(myKey.getPubKey(), wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getPubKey());
        assertArrayEquals(myKey.getPrivKeyBytes(), wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getPrivKeyBytes());
    }
}
 
Example #13
Source File: PaymentChannelServerTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() {
    broadcaster = createMock(TransactionBroadcaster.class);
    wallet = createMock(Wallet.class);
    connection = createMock(PaymentChannelServer.ServerConnection.class);
    serverVersionCapture = new Capture<TwoWayChannelMessage>();
    connection.sendToClient(capture(serverVersionCapture));
    Utils.setMockClock();
}
 
Example #14
Source File: PaymentChannelServerState.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
PaymentChannelServerState(StoredServerChannel storedServerChannel, Wallet wallet, TransactionBroadcaster broadcaster) throws VerificationException {
    synchronized (storedServerChannel) {
        this.stateMachine = new StateMachine<>(State.UNINITIALISED, getStateTransitions());
        this.wallet = checkNotNull(wallet);
        this.broadcaster = checkNotNull(broadcaster);
        this.contract = checkNotNull(storedServerChannel.contract);
        this.serverKey = checkNotNull(storedServerChannel.myKey);
        this.storedServerChannel = storedServerChannel;
        this.bestValueToMe = checkNotNull(storedServerChannel.bestValueToMe);
        this.minExpireTime = storedServerChannel.refundTransactionUnlockTimeSecs;
        this.bestValueSignature = storedServerChannel.bestValueSignature;
        checkArgument(bestValueToMe.equals(Coin.ZERO) || bestValueSignature != null);
        storedServerChannel.state = this;
    }
}
 
Example #15
Source File: TransactionInputTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@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() {
            return params;
        }

        @Override
        public List<UTXO> getOpenTransactionOutputs(List<Address> addresses) throws UTXOProviderException {
            return Lists.newArrayList(utxo);
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }
    });

    Transaction tx2 = new Transaction(params);
    tx2.addOutput(Coin.valueOf(99000000), new ECKey());
    w.completeTx(SendRequest.forTx(tx2));

    TransactionInput txInToDisconnect = tx2.getInput(0);

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertEquals(utxo.getHash(), txInToDisconnect.getOutpoint().connectedOutput.getParentTransactionHash());

    txInToDisconnect.disconnect();

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);
}
 
Example #16
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock2(String mnemonicCode, Runnable callback) {
    if (mnemonicCode.charAt(mnemonicCode.length() - 1) == ' ') {
        mnemonicCode = mnemonicCode.substring(0, mnemonicCode.length() - 1);
    }

    DeterministicSeed seed = new DeterministicSeed(Splitter.on(' ').splitToList(mnemonicCode), null, "", 0);

    wallet = Wallet.fromSeed(params, seed);
    mnemonicKey = Joiner.on(" ").join(seed.getMnemonicCode());
    sharedManager.setLastSyncedBlock(Coders.encodeBase64(mnemonicKey));
    walletFriendlyAddress = wallet.currentReceiveAddress().toString();

    ChildNumber childNumber = new ChildNumber(ChildNumber.HARDENED_BIT);
    DeterministicKey de = wallet.getKeyByPath(ImmutableList.of(childNumber));
    xprvKey = de.serializePrivB58(params);

    wifKey = wallet.currentReceiveKey().getPrivateKeyAsWiF(params);

    callback.run();

    RequestorBtc.getUTXOListSbtcNew(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #17
Source File: WalletProtobufSerializerTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void extensionsWithError() throws Exception {
    WalletExtension extension = new WalletExtension() {
        @Override
        public String getWalletExtensionID() {
            return "test";
        }

        @Override
        public boolean isWalletExtensionMandatory() {
            return false;
        }

        @Override
        public byte[] serializeWalletExtension() {
            return new byte[0];
        }

        @Override
        public void deserializeWalletExtension(Wallet containingWallet, byte[] data) throws Exception {
            throw new NullPointerException();  // Something went wrong!
        }
    };
    myWallet.addExtension(extension);
    Protos.Wallet proto = new WalletProtobufSerializer().walletToProto(myWallet);
    Wallet wallet = new WalletProtobufSerializer().readWallet(UNITTEST, new WalletExtension[]{extension}, proto);
    assertEquals(0, wallet.getExtensions().size());
}
 
Example #18
Source File: ChannelConnectionTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private static Wallet roundTripClientWallet(Wallet wallet) throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    new WalletProtobufSerializer().writeWallet(wallet, bos);
    org.bitcoinj.wallet.Protos.Wallet proto = WalletProtobufSerializer.parseToProto(new ByteArrayInputStream(bos.toByteArray()));
    StoredPaymentChannelClientStates state = new StoredPaymentChannelClientStates(null, failBroadcaster);
    return new WalletProtobufSerializer().readWallet(wallet.getParams(), new WalletExtension[] { state }, proto);
}
 
Example #19
Source File: PeerGroupTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void receiveTxBroadcastOnAddedWallet() throws Exception {
    // Check that when we receive transactions on all our peers, we do the right thing.
    peerGroup.start();

    // Create a peer.
    InboundMessageQueuer p1 = connectPeer(1);
    
    Wallet wallet2 = new Wallet(PARAMS);
    ECKey key2 = wallet2.freshReceiveKey();
    Address address2 = key2.toAddress(PARAMS);
    
    peerGroup.addWallet(wallet2);
    blockChain.addWallet(wallet2);

    assertEquals(BloomFilter.class, waitForOutbound(p1).getClass());
    assertEquals(MemoryPoolMessage.class, waitForOutbound(p1).getClass());

    Coin value = COIN;
    Transaction t1 = FakeTxBuilder.createFakeTx(PARAMS, value, address2);
    InventoryMessage inv = new InventoryMessage(PARAMS);
    inv.addTransaction(t1);

    inbound(p1, inv);
    assertTrue(outbound(p1) instanceof GetDataMessage);
    inbound(p1, t1);
    // Asks for dependency.
    GetDataMessage getdata = (GetDataMessage) outbound(p1);
    assertNotNull(getdata);
    inbound(p1, new NotFoundMessage(PARAMS, getdata.getItems()));
    pingAndWait(p1);
    assertEquals(value, wallet2.getBalance(Wallet.BalanceType.ESTIMATED));
}
 
Example #20
Source File: PeerGroupTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void receiveTxBroadcast() throws Exception {
    // Check that when we receive transactions on all our peers, we do the right thing.
    peerGroup.start();

    // Create a couple of peers.
    InboundMessageQueuer p1 = connectPeer(1);
    InboundMessageQueuer p2 = connectPeer(2);

    // Check the peer accessors.
    assertEquals(2, peerGroup.numConnectedPeers());
    Set<Peer> tmp = new HashSet<>(peerGroup.getConnectedPeers());
    Set<Peer> expectedPeers = new HashSet<>();
    expectedPeers.add(peerOf(p1));
    expectedPeers.add(peerOf(p2));
    assertEquals(tmp, expectedPeers);

    Coin value = COIN;
    Transaction t1 = FakeTxBuilder.createFakeTx(UNITTEST, value, address);
    InventoryMessage inv = new InventoryMessage(UNITTEST);
    inv.addTransaction(t1);

    // Note: we start with p2 here to verify that transactions are downloaded from whichever peer announces first
    // which does not have to be the same as the download peer (which is really the "block download peer").
    inbound(p2, inv);
    assertTrue(outbound(p2) instanceof GetDataMessage);
    inbound(p1, inv);
    assertNull(outbound(p1));  // Only one peer is used to download.
    inbound(p2, t1);
    assertNull(outbound(p1));
    // Asks for dependency.
    GetDataMessage getdata = (GetDataMessage) outbound(p2);
    assertNotNull(getdata);
    inbound(p2, new NotFoundMessage(UNITTEST, getdata.getItems()));
    pingAndWait(p2);
    assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
}
 
Example #21
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock(String mnemonicCode, WalletCreationCallback callback) {
    mnemonicCode = mnemonicCode.trim();
    if (mnemonicCode.equals("")) {
        callback.onWalletCreated(null);
        return;
    }

    DeterministicSeed seed = new DeterministicSeed(Splitter.on(' ').splitToList(mnemonicCode), null, "", 0);

    wallet = Wallet.fromSeed(params, seed);
    mnemonicKey = Joiner.on(" ").join(seed.getMnemonicCode());
    //sharedManager.setLastSyncedBlock(Coders.encodeBase64(mnemonicKey));
    walletFriendlyAddress = wallet.currentReceiveAddress().toString();

    ChildNumber childNumber = new ChildNumber(ChildNumber.HARDENED_BIT);
    DeterministicKey de = wallet.getKeyByPath(ImmutableList.of(childNumber));
    xprvKey = de.serializePrivB58(params);

    wifKey = wallet.currentReceiveKey().getPrivateKeyAsWiF(params);

    callback.onWalletCreated(wallet);

    RequestorBtc.getUTXOListBtgNew(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #22
Source File: PeerGroup.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Unlinks the given wallet so it no longer receives broadcast transactions or has its transactions announced.
 */
public void removeWallet(Wallet wallet) {
    wallets.remove(checkNotNull(wallet));
    peerFilterProviders.remove(wallet);
    wallet.removeCoinsReceivedEventListener(walletCoinsReceivedEventListener);
    wallet.removeKeyChainEventListener(walletKeyEventListener);
    wallet.removeScriptChangeEventListener(walletScriptEventListener);
    wallet.setTransactionBroadcaster(null);
    for (Peer peer : peers) {
        peer.removeWallet(wallet);
    }        
}
 
Example #23
Source File: WalletProtobufSerializerTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void roundtripVersionTwoTransaction() throws Exception {
    Transaction tx = new Transaction(PARAMS, Utils.HEX.decode(
            "0200000001d7902864af9310420c6e606b814c8f89f7902d40c130594e85df2e757a7cc301070000006b483045022100ca1757afa1af85c2bb014382d9ce411e1628d2b3d478df9d5d3e9e93cb25dcdd02206c5d272b31a23baf64e82793ee5c816e2bbef251e733a638b630ff2331fc83ba0121026ac2316508287761befbd0f7495ea794b396dbc5b556bf276639f56c0bd08911feffffff0274730700000000001976a91456da2d038a098c42390c77ef163e1cc23aedf24088ac91062300000000001976a9148ebf3467b9a8d7ae7b290da719e61142793392c188ac22e00600"));
    assertEquals(tx.getVersion(), 2);
    assertEquals(tx.getHashAsString(), "0321b1413ed9048199815bd6bc2650cab1a9e8d543f109a42c769b1f18df4174");
    myWallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx));
    Wallet wallet1 = roundTrip(myWallet);
    Transaction tx2 = wallet1.getTransaction(tx.getHash());
    assertEquals(checkNotNull(tx2).getVersion(), 2);
}
 
Example #24
Source File: PeerGroupTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void receiveTxBroadcastOnAddedWallet() throws Exception {
    // Check that when we receive transactions on all our peers, we do the right thing.
    peerGroup.start();

    // Create a peer.
    InboundMessageQueuer p1 = connectPeer(1);

    Wallet wallet2 = new Wallet(UNITTEST);
    ECKey key2 = wallet2.freshReceiveKey();
    Address address2 = LegacyAddress.fromKey(UNITTEST, key2);

    peerGroup.addWallet(wallet2);
    blockChain.addWallet(wallet2);

    assertEquals(BloomFilter.class, waitForOutbound(p1).getClass());
    assertEquals(MemoryPoolMessage.class, waitForOutbound(p1).getClass());

    Coin value = COIN;
    Transaction t1 = FakeTxBuilder.createFakeTx(UNITTEST, value, address2);
    InventoryMessage inv = new InventoryMessage(UNITTEST);
    inv.addTransaction(t1);

    inbound(p1, inv);
    assertTrue(outbound(p1) instanceof GetDataMessage);
    inbound(p1, t1);
    // Asks for dependency.
    GetDataMessage getdata = (GetDataMessage) outbound(p1);
    assertNotNull(getdata);
    inbound(p1, new NotFoundMessage(UNITTEST, getdata.getItems()));
    pingAndWait(p1);
    assertEquals(value, wallet2.getBalance(Wallet.BalanceType.ESTIMATED));
}
 
Example #25
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV2(String xprv, Runnable callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(xprv));
        updateWalletFriendlyAddress();
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV2: " + iae.toString());
        callback.run();
        return;
    }

    callback.run();

    RequestorBtc.getUTXOListQtum(walletFriendlyAddress, new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #26
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock0(String mnemonicCode, Runnable callback) {
    if (mnemonicCode.charAt(mnemonicCode.length() - 1) == ' ') {
        mnemonicCode = mnemonicCode.substring(0, mnemonicCode.length() - 1);
    }

    DeterministicSeed seed = new DeterministicSeed(Splitter.on(' ').splitToList(mnemonicCode), null, "", 0);

    wallet = Wallet.fromSeed(params, seed);
    mnemonicKey = Joiner.on(" ").join(seed.getMnemonicCode());
    //sharedManager.setLastSyncedBlock(Coders.encodeBase64(mnemonicKey));

    walletFriendlyAddress = wallet.currentReceiveAddress().toString();

    callback.run();


    RequestorBtc.getUTXOList(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            UTXOListResponse utxoResponse = (UTXOListResponse) response;
            setUTXO(utxoResponse.getUTXOList());
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #27
Source File: BackupToMnemonicSeed.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {

        NetworkParameters params = TestNet3Params.get();
        Wallet wallet = new Wallet(params);

        DeterministicSeed seed = wallet.getKeyChainSeed();
        System.out.println("seed: " + seed.toString());

        System.out.println("creation time: " + seed.getCreationTimeSeconds());
        System.out.println("mnemonicCode: " + Utils.join(seed.getMnemonicCode()));
    }
 
Example #28
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock(String mnemonicCode, WalletCreationCallback callback) {
    mnemonicCode = mnemonicCode.trim();
    if (mnemonicCode.equals("")) {
        callback.onWalletCreated(null);
        return;
    }

    DeterministicSeed seed = new DeterministicSeed(Splitter.on(' ').splitToList(mnemonicCode), null, "", 0);

    wallet = Wallet.fromSeed(params, seed);
    mnemonicKey = Joiner.on(" ").join(seed.getMnemonicCode());
    //sharedManager.setLastSyncedBlock(Coders.encodeBase64(mnemonicKey));

    walletFriendlyAddress = wallet.currentReceiveAddress().toString();

    ChildNumber childNumber = new ChildNumber(ChildNumber.HARDENED_BIT);
    DeterministicKey de = wallet.getKeyByPath(ImmutableList.of(childNumber));
    xprvKey = de.serializePrivB58(params);

    wifKey = wallet.currentReceiveKey().getPrivateKeyAsWiF(params);

    callback.onWalletCreated(wallet);


    RequestorBtc.getUTXOList(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            UTXOListResponse utxoResponse = (UTXOListResponse) response;
            setUTXO(utxoResponse.getUTXOList());
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #29
Source File: FullPrunedBlockChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructs a block chain connected to the given list of wallets and a store.
 */
public FullPrunedBlockChain(Context context, List<Wallet> listeners, FullPrunedBlockStore blockStore) throws BlockStoreException {
    super(context, listeners, blockStore);
    this.blockStore = blockStore;
    // Ignore upgrading for now
    this.chainHead = blockStore.getVerifiedChainHead();
}
 
Example #30
Source File: Network.java    From cate with MIT License 5 votes vote down vote up
/**
 * @param context context this network manages.
 * @param controller the controller to push events back to.
 * @param directory the data directory to store the wallet and SPV chain in.
 * @param networkExecutor executor for tasks belonging to this network.
 * Must exist after the lifecycle of network (so that service status listeners
 * can be attached to it).
 */
public Network(final Context context, final MainController controller,
        final File directory, final Executor networkExecutor,
        final BiConsumer<Network, Wallet> registerWalletHook) {
    super(context, directory, "cate_" + context.getParams().getId());
    this.controller = controller;
    this.networkExecutor = networkExecutor;
    autoStop = false;
    blockingStartup = true;
    this.registerWalletHook = registerWalletHook;

    monetaryFormatter = context.getParams().getMonetaryFormat();
    addListener(new Service.Listener() {
        @Override
        public void running() {
            estimatedBalance.set(monetaryFormatter.format(wallet().getBalance(Wallet.BalanceType.ESTIMATED)).toString());
            try {
                blocks.set(store().getChainHead().getHeight());
            } catch (BlockStoreException ex) {
                logger.error("Error getting current chain head while starting wallet "
                        + params.getId(), ex);
            }
            encrypted.set(wallet().isEncrypted());
        }

        @Override
        public void failed(Service.State from, Throwable failure) {
            controller.onNetworkFailed(Network.this, from, failure);
        }
    }, networkExecutor);
}