org.bitcoinj.core.TransactionOutPoint Java Examples

The following examples show how to use org.bitcoinj.core.TransactionOutPoint. 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: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void removeScriptsBloomFilter() throws Exception {
    List<Address> addressesForRemoval = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
        addressesForRemoval.add(watchedAddress);
        wallet.addWatchedAddress(watchedAddress);
    }

    wallet.removeWatchedAddresses(addressesForRemoval);

    for (Address addr : addressesForRemoval) {
        Transaction t1 = createFakeTx(UNITTEST, CENT, addr);
        TransactionOutPoint outPoint = new TransactionOutPoint(UNITTEST, 0, t1);

        // Note that this has a 1e-12 chance of failing this unit test due to a false positive
        assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));

        sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
        assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));
    }
}
 
Example #2
Source File: MemPooler.java    From jelectrum with MIT License 6 votes vote down vote up
public boolean areSomeInputsPending(Transaction tx)
{
  MemPoolInfo info = latest_info;
  if (info == null) return false; //Hard to say

  for(TransactionInput tx_in : tx.getInputs())
  {
    if (!tx_in.isCoinBase())
    {
      TransactionOutPoint tx_out = tx_in.getOutpoint();
      Sha256Hash parent_hash = tx_out.getHash();
      if (info.tx_set.contains(parent_hash)) return true;
    }
  }
  return false;
}
 
Example #3
Source File: Importer.java    From jelectrum with MIT License 6 votes vote down vote up
public void putTxOutSpents(Transaction tx)
{
  LinkedList<String> tx_outs = new LinkedList<String>();

    for(TransactionInput in : tx.getInputs())
    {
        if (!in.isCoinBase())
        {
            TransactionOutPoint out = in.getOutpoint();
            String key = out.getHash().toString() + ":" + out.getIndex();
            //file_db.addTxOutSpentByMap(key, tx.getHash());
            tx_outs.add(key);

        }
    }
}
 
Example #4
Source File: SimpleUtxoMgr.java    From jelectrum with MIT License 6 votes vote down vote up
@Override
public synchronized Collection<TransactionOutPoint> getUnspentForScriptHash(ByteString prefix)
{ 
  Collection<ByteString> txinfo = db_map.getSet(prefix, 10000);

  LinkedList<TransactionOutPoint> outs = new LinkedList<TransactionOutPoint>();

    for(ByteString key : txinfo)
    {
      
      ByteString tx_data = key.substring(0,32);
      ByteBuffer bb = ByteBuffer.wrap(key.substring(32).toByteArray());
      bb.order(java.nio.ByteOrder.LITTLE_ENDIAN);
      int idx=bb.getInt();

      Sha256Hash tx_id = Sha256Hash.wrap(tx_data.toByteArray());
      TransactionOutPoint o = new TransactionOutPoint(jelly.getNetworkParameters(), idx, tx_id);
      outs.add(o);
     
    }

  return outs;
}
 
Example #5
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void removeScriptsBloomFilter() throws Exception {
    List<Address> addressesForRemoval = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        Address watchedAddress = new ECKey().toAddress(PARAMS);
        addressesForRemoval.add(watchedAddress);
        wallet.addWatchedAddress(watchedAddress);
    }

    wallet.removeWatchedAddresses(addressesForRemoval);

    for (Address addr : addressesForRemoval) {
        Transaction t1 = createFakeTx(PARAMS, CENT, addr);
        TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1);

        // Note that this has a 1e-12 chance of failing this unit test due to a false positive
        assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));

        sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
        assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));
    }
}
 
Example #6
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void watchingScriptsBloomFilter() throws Exception {
    assertFalse(wallet.isRequiringUpdateAllBloomFilter());

    Address watchedAddress = new ECKey().toAddress(PARAMS);
    Transaction t1 = createFakeTx(PARAMS, CENT, watchedAddress);
    TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1);
    wallet.addWatchedAddress(watchedAddress);

    assertTrue(wallet.isRequiringUpdateAllBloomFilter());
    // Note that this has a 1e-12 chance of failing this unit test due to a false positive
    assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));

    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
    assertTrue(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));
}
 
Example #7
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void removeScriptsBloomFilter() throws Exception {
    List<Address> addressesForRemoval = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        Address watchedAddress = new ECKey().toAddress(PARAMS);
        addressesForRemoval.add(watchedAddress);
        wallet.addWatchedAddress(watchedAddress);
    }

    wallet.removeWatchedAddresses(addressesForRemoval);

    for (Address addr : addressesForRemoval) {
        Transaction t1 = createFakeTx(PARAMS, CENT, addr);
        TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1);

        // Note that this has a 1e-12 chance of failing this unit test due to a false positive
        assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));

        sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
        assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));
    }
}
 
Example #8
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void watchingScriptsBloomFilter() throws Exception {
    assertFalse(wallet.isRequiringUpdateAllBloomFilter());

    Address watchedAddress = new ECKey().toAddress(PARAMS);
    Transaction t1 = createFakeTx(PARAMS, CENT, watchedAddress);
    TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1);
    wallet.addWatchedAddress(watchedAddress);

    assertTrue(wallet.isRequiringUpdateAllBloomFilter());
    // Note that this has a 1e-12 chance of failing this unit test due to a false positive
    assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));

    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
    assertTrue(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));
}
 
Example #9
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void watchingScriptsBloomFilter() throws Exception {
    assertFalse(wallet.isRequiringUpdateAllBloomFilter());

    Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    Transaction t1 = createFakeTx(UNITTEST, CENT, watchedAddress);
    TransactionOutPoint outPoint = new TransactionOutPoint(UNITTEST, 0, t1);
    wallet.addWatchedAddress(watchedAddress);

    assertTrue(wallet.isRequiringUpdateAllBloomFilter());
    // Note that this has a 1e-12 chance of failing this unit test due to a false positive
    assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));

    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
    assertTrue(wallet.getBloomFilter(1e-12).contains(outPoint.unsafeBitcoinSerialize()));
}
 
Example #10
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a fake coinbase transaction.
 */
public static Transaction createFakeCoinbaseTx(final NetworkParameters params) {
    TransactionOutPoint outpoint = new TransactionOutPoint(params, -1, Sha256Hash.ZERO_HASH);
    TransactionInput input = new TransactionInput(params, null, new byte[0], outpoint);
    Transaction tx = new Transaction(params);
    tx.addInput(input);
    TransactionOutput outputToMe = new TransactionOutput(params, tx, Coin.FIFTY_COINS,
            LegacyAddress.fromKey(params, new ECKey()));
    tx.addOutput(outputToMe);

    checkState(tx.isCoinBase());
    return tx;
}
 
Example #11
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void marriedKeychainBloomFilter() throws Exception {
    createMarriedWallet(2, 2);
    Address address = wallet.currentReceiveAddress();

    assertTrue(wallet.getBloomFilter(0.001).contains(address.getHash()));

    Transaction t1 = createFakeTx(UNITTEST, CENT, address);
    TransactionOutPoint outPoint = new TransactionOutPoint(UNITTEST, 0, t1);

    assertFalse(wallet.getBloomFilter(0.001).contains(outPoint.unsafeBitcoinSerialize()));

    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
    assertTrue(wallet.getBloomFilter(0.001).contains(outPoint.unsafeBitcoinSerialize()));
}
 
Example #12
Source File: UtxoTrieMgr.java    From jelectrum with MIT License 5 votes vote down vote up
public synchronized Collection<TransactionOutPoint> getUnspentForAddress(Address a)
{ 
  String prefix = getPrefixForAddress(a);

  Collection<String> keys = getByKey("").getKeysByPrefix(prefix, this);

  LinkedList<TransactionOutPoint> outs = new LinkedList<TransactionOutPoint>();

  try
  {
    for(String key : keys)
    {
      byte[] key_data=Hex.decodeHex(key.toCharArray());
      ByteBuffer bb = ByteBuffer.wrap(key_data);
      bb.order(java.nio.ByteOrder.LITTLE_ENDIAN);
      bb.position(20);
      byte[] tx_data = new byte[32];
      bb.get(tx_data);
      int idx=bb.getInt();
      Sha256Hash tx_id = new Sha256Hash(tx_data);
      TransactionOutPoint o = new TransactionOutPoint(jelly.getNetworkParameters(), idx, tx_id);
      outs.add(o);
     
    }
  }
  catch(org.apache.commons.codec.DecoderException e)
  { 
    throw new RuntimeException(e);
  }



  return outs;
}
 
Example #13
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private TransactionInput getTransactionInput(Transaction depositTx,
                                             byte[] scriptProgram,
                                             RawTransactionInput rawTransactionInput) {
    return new TransactionInput(params, depositTx, scriptProgram, new TransactionOutPoint(params,
            rawTransactionInput.index, new Transaction(params, rawTransactionInput.parentTransaction)),
            Coin.valueOf(rawTransactionInput.value));
}
 
Example #14
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getPreparedUnlockTx(TxOutput lockupTxOutput) throws AddressFormatException {
    daoKillSwitch.assertDaoIsNotDisabled();
    Transaction tx = new Transaction(params);
    // Unlocking means spending the full value of the locked txOutput to another txOutput with the same value
    Coin amountToUnlock = Coin.valueOf(lockupTxOutput.getValue());
    checkArgument(Restrictions.isAboveDust(amountToUnlock), "The amount is too low (dust limit).");
    Transaction lockupTx = getTransaction(lockupTxOutput.getTxId());
    checkNotNull(lockupTx, "lockupTx must not be null");
    TransactionOutPoint outPoint = new TransactionOutPoint(params, lockupTxOutput.getIndex(), lockupTx);
    // Input is not signed yet so we use new byte[]{}
    tx.addInput(new TransactionInput(params, tx, new byte[]{}, outPoint, amountToUnlock));
    tx.addOutput(new TransactionOutput(params, tx, amountToUnlock, getUnusedAddress()));
    printTx("prepareUnlockTx", tx);
    return tx;
}
 
Example #15
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getPreparedVoteRevealTx(TxOutput stakeTxOutput) {
    daoKillSwitch.assertDaoIsNotDisabled();
    Transaction tx = new Transaction(params);
    final Coin stake = Coin.valueOf(stakeTxOutput.getValue());
    Transaction blindVoteTx = getTransaction(stakeTxOutput.getTxId());
    checkNotNull(blindVoteTx, "blindVoteTx must not be null");
    TransactionOutPoint outPoint = new TransactionOutPoint(params, stakeTxOutput.getIndex(), blindVoteTx);
    // Input is not signed yet so we use new byte[]{}
    tx.addInput(new TransactionInput(params, tx, new byte[]{}, outPoint, stake));
    tx.addOutput(new TransactionOutput(params, tx, stake, getUnusedAddress()));
    // printTx("getPreparedVoteRevealTx", tx);
    return tx;
}
 
Example #16
Source File: BitcoinExtendedClient.java    From consensusj with Apache License 2.0 5 votes vote down vote up
public List<TransactionOutPoint> listUnspentOutPoints(Address fromAddress) throws JsonRpcStatusException, IOException {
    List<Address> addresses = Collections.singletonList(fromAddress);
    List<UnspentOutput> unspentOutputsRPC = listUnspent(0, defaultMaxConf, addresses); // RPC UnspentOutput objects
    List<TransactionOutPoint> unspentOutPoints = new ArrayList<TransactionOutPoint>();
    for (UnspentOutput it : unspentOutputsRPC) {
        unspentOutPoints.add(new TransactionOutPoint(getNetParams(), it.getVout(), it.getTxid()));
    }
    return unspentOutPoints;
}
 
Example #17
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void marriedKeychainBloomFilter() throws Exception {
    createMarriedWallet(2, 2);
    Address address = wallet.currentReceiveAddress();

    assertTrue(wallet.getBloomFilter(0.001).contains(address.getHash160()));

    Transaction t1 = createFakeTx(PARAMS, CENT, address);
    TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1);

    assertFalse(wallet.getBloomFilter(0.001).contains(outPoint.unsafeBitcoinSerialize()));

    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
    assertTrue(wallet.getBloomFilter(0.001).contains(outPoint.unsafeBitcoinSerialize()));
}
 
Example #18
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
@NotNull
private TransactionInput getTransactionInput(Transaction depositTx, byte[] scriptProgram, RawTransactionInput rawTransactionInput) {
    return new TransactionInput(params,
            depositTx,
            scriptProgram,
            new TransactionOutPoint(params, rawTransactionInput.index, new Transaction(params, rawTransactionInput.parentTransaction)),
            Coin.valueOf(rawTransactionInput.value));
}
 
Example #19
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getPreparedVoteRevealTx(TxOutput stakeTxOutput) {
    Transaction tx = new Transaction(params);
    final Coin stake = Coin.valueOf(stakeTxOutput.getValue());
    Transaction blindVoteTx = getTransaction(stakeTxOutput.getTxId());
    checkNotNull(blindVoteTx, "blindVoteTx must not be null");
    TransactionOutPoint outPoint = new TransactionOutPoint(params, stakeTxOutput.getIndex(), blindVoteTx);
    // Input is not signed yet so we use new byte[]{}
    tx.addInput(new TransactionInput(params, tx, new byte[]{}, outPoint, stake));
    tx.addOutput(new TransactionOutput(params, tx, stake, getUnusedAddress()));
    // printTx("getPreparedVoteRevealTx", tx);
    return tx;
}
 
Example #20
Source File: SPV.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private void updateBalance(final TransactionOutPoint txOutpoint, final int subAccount, final Coin addValue) {
    if (mCountedUtxoValues.containsKey(txOutpoint))
       return;
    mCountedUtxoValues.put(txOutpoint, addValue);
    final Coin verifiedBalance = getVerifiedBalance(subAccount);
    if (verifiedBalance == null)
        mVerifiedCoinBalances.put(subAccount, addValue);
    else
        mVerifiedCoinBalances.put(subAccount, verifiedBalance.add(addValue));
}
 
Example #21
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void marriedKeychainBloomFilter() throws Exception {
    createMarriedWallet(2, 2);
    Address address = wallet.currentReceiveAddress();

    assertTrue(wallet.getBloomFilter(0.001).contains(address.getHash160()));

    Transaction t1 = createFakeTx(PARAMS, CENT, address);
    TransactionOutPoint outPoint = new TransactionOutPoint(PARAMS, 0, t1);

    assertFalse(wallet.getBloomFilter(0.001).contains(outPoint.unsafeBitcoinSerialize()));

    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
    assertTrue(wallet.getBloomFilter(0.001).contains(outPoint.unsafeBitcoinSerialize()));
}
 
Example #22
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getPreparedUnlockTx(TxOutput lockedTxOutput) throws AddressFormatException {
    Transaction tx = new Transaction(params);
    // Unlocking means spending the full value of the locked txOutput to another txOutput with the same value
    Coin amountToUnlock = Coin.valueOf(lockedTxOutput.getValue());
    checkArgument(Restrictions.isAboveDust(amountToUnlock), "The amount is too low (dust limit).");
    Transaction lockupTx = getTransaction(lockedTxOutput.getTxId());
    checkNotNull(lockupTx, "lockupTx must not be null");
    TransactionOutPoint outPoint = new TransactionOutPoint(params, lockedTxOutput.getIndex(), lockupTx);
    // Input is not signed yet so we use new byte[]{}
    tx.addInput(new TransactionInput(params, tx, new byte[]{}, outPoint, amountToUnlock));
    tx.addOutput(new TransactionOutput(params, tx, amountToUnlock, getUnusedAddress()));
    printTx("prepareUnlockTx", tx);
    return tx;
}
 
Example #23
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public void emergencySignAndPublishPayoutTxFrom2of2MultiSig(String depositTxHex,
                                                            Coin buyerPayoutAmount,
                                                            Coin sellerPayoutAmount,
                                                            Coin txFee,
                                                            String buyerAddressString,
                                                            String sellerAddressString,
                                                            String buyerPrivateKeyAsHex,
                                                            String sellerPrivateKeyAsHex,
                                                            String buyerPubKeyAsHex,
                                                            String sellerPubKeyAsHex,
                                                            TxBroadcaster.Callback callback)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    byte[] buyerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(buyerPubKeyAsHex)).getPubKey();
    byte[] sellerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(sellerPubKeyAsHex)).getPubKey();

    Script p2SHMultiSigOutputScript = get2of2MultiSigOutputScript(buyerPubKey, sellerPubKey);

    Coin msOutput = buyerPayoutAmount.add(sellerPayoutAmount).add(txFee);
    TransactionOutput p2SHMultiSigOutput = new TransactionOutput(params, null, msOutput, p2SHMultiSigOutputScript.getProgram());
    Transaction depositTx = new Transaction(params);
    depositTx.addOutput(p2SHMultiSigOutput);

    Transaction payoutTx = new Transaction(params);
    Sha256Hash spendTxHash = Sha256Hash.wrap(depositTxHex);
    payoutTx.addInput(new TransactionInput(params, depositTx, p2SHMultiSigOutputScript.getProgram(), new TransactionOutPoint(params, 0, spendTxHash), msOutput));

    if (buyerPayoutAmount.isPositive()) {
        payoutTx.addOutput(buyerPayoutAmount, Address.fromBase58(params, buyerAddressString));
    }
    if (sellerPayoutAmount.isPositive()) {
        payoutTx.addOutput(sellerPayoutAmount, Address.fromBase58(params, sellerAddressString));
    }

    // take care of sorting!
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);

    ECKey buyerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(buyerPrivateKeyAsHex));
    checkNotNull(buyerPrivateKey, "key must not be null");
    ECKey.ECDSASignature buyerECDSASignature = buyerPrivateKey.sign(sigHash, aesKey).toCanonicalised();

    ECKey sellerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(sellerPrivateKeyAsHex));
    checkNotNull(sellerPrivateKey, "key must not be null");
    ECKey.ECDSASignature sellerECDSASignature = sellerPrivateKey.sign(sigHash, aesKey).toCanonicalised();

    TransactionSignature buyerTxSig = new TransactionSignature(buyerECDSASignature, Transaction.SigHash.ALL, false);
    TransactionSignature sellerTxSig = new TransactionSignature(sellerECDSASignature, Transaction.SigHash.ALL, false);
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig), redeemScript);

    TransactionInput input = payoutTx.getInput(0);
    input.setScriptSig(inputScript);
    WalletService.printTx("payoutTx", payoutTx);
    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);
    broadcastTx(payoutTx, callback, 20);
}
 
Example #24
Source File: SPV.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
private TransactionOutPoint createOutPoint(final Integer index, final Sha256Hash txHash,
                                           final NetworkParameters params) {
    return new TransactionOutPoint(params, index, txHash);
}
 
Example #25
Source File: SPV.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
void updateUnspentOutputs() {
    final NetworkData networkData = mService.getNetwork();
    final boolean currentlyEnabled = isEnabled();
    Log.d(TAG, "updateUnspentOutputs: " + Var("currentlyEnabled", currentlyEnabled));

    final List<TransactionData> utxos = new ArrayList<>();
    for (final SubaccountData subaccountData : mSubaccounts) {
        try {
            List<TransactionData> transactionDataList = getUtxos(subaccountData.getPointer());
            utxos.addAll(transactionDataList);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    final Set<TransactionOutPoint> newUtxos = new HashSet<>();
    boolean recalculateBloom = false;

    Log.d(TAG, Var("number of utxos", utxos.size()));
    for (final TransactionData utxo : utxos) {
        final Integer prevIndex = utxo.getPtIdx();
        final Integer subaccount = utxo.getSubaccount();
        final Integer pointer = utxo.getPointer();
        final Sha256Hash txHash = utxo.getTxhashAsSha256Hash();

        if (isVerified(txHash.toString())) {
            addToUtxo(txHash, prevIndex, subaccount, pointer);
            addUtxoToValues(txHash, false /* updateVerified */);
        } else {
            recalculateBloom = true;
            addToBloomFilter(utxo.getBlockHeight(), txHash, prevIndex, subaccount, pointer);
        }
        newUtxos.add(createOutPoint(prevIndex, txHash, networkData.getNetworkParameters()));
    }

    mPeerGroup.setFastCatchupTimeSecs(1393545600);  // GA inception

    final List<Integer> changedSubaccounts = new ArrayList<>();
    for (final TransactionOutPoint oldUtxo : new HashSet<>(mCountedUtxoValues.keySet())) {
        if (!newUtxos.contains(oldUtxo)) {
            recalculateBloom = true;

            final int subAccount = mUnspentDetails.get(oldUtxo).getSubAccount();
            final Coin verifiedBalance = getVerifiedBalance(subAccount);
            mVerifiedCoinBalances.put(subAccount,
                                      verifiedBalance.subtract(mCountedUtxoValues.get(oldUtxo)));
            changedSubaccounts.add(subAccount);
            mCountedUtxoValues.remove(oldUtxo);
            mUnspentDetails.remove(oldUtxo);
            mUnspentOutpoints.get(oldUtxo.getHash()).remove(((int) oldUtxo.getIndex()));
        }
    }

    if (recalculateBloom && mPeerGroup != null)
        mPeerGroup.recalculateFastCatchupAndFilter(PeerGroup.FilterRecalculateMode.SEND_IF_CHANGED);
}
 
Example #26
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testCompleteTxWithExistingInputs() throws Exception {
    // Tests calling completeTx with a SendRequest that already has a few inputs in it

    // Generate a few outputs to us
    StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
    Transaction tx1 = createFakeTx(UNITTEST, COIN, myAddress);
    wallet.receiveFromBlock(tx1, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
    Transaction tx2 = createFakeTx(UNITTEST, COIN, myAddress);
    assertNotEquals(tx1.getHash(), tx2.getHash());
    wallet.receiveFromBlock(tx2, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 1);
    Transaction tx3 = createFakeTx(UNITTEST, CENT, myAddress);
    wallet.receiveFromBlock(tx3, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 2);

    SendRequest request1 = SendRequest.to(OTHER_ADDRESS, CENT);
    // If we just complete as-is, we will use one of the COIN outputs to get higher priority,
    // resulting in a change output
    request1.shuffleOutputs = false;
    wallet.completeTx(request1);
    assertEquals(1, request1.tx.getInputs().size());
    assertEquals(2, request1.tx.getOutputs().size());
    assertEquals(CENT, request1.tx.getOutput(0).getValue());
    assertEquals(COIN.subtract(CENT), request1.tx.getOutput(1).getValue());

    // Now create an identical request2 and add an unsigned spend of the CENT output
    SendRequest request2 = SendRequest.to(OTHER_ADDRESS, CENT);
    request2.tx.addInput(tx3.getOutput(0));
    // Now completeTx will result in one input, one output
    wallet.completeTx(request2);
    assertEquals(1, request2.tx.getInputs().size());
    assertEquals(1, request2.tx.getOutputs().size());
    assertEquals(CENT, request2.tx.getOutput(0).getValue());
    // Make sure it was properly signed
    request2.tx.getInput(0).getScriptSig().correctlySpends(request2.tx, 0, tx3.getOutput(0).getScriptPubKey());

    // However, if there is no connected output, we will grab a COIN output anyway and add the CENT to fee
    SendRequest request3 = SendRequest.to(OTHER_ADDRESS, CENT);
    request3.tx.addInput(new TransactionInput(UNITTEST, request3.tx, new byte[]{}, new TransactionOutPoint(UNITTEST, 0, tx3.getHash())));
    // Now completeTx will result in two inputs, two outputs and a fee of a CENT
    // Note that it is simply assumed that the inputs are correctly signed, though in fact the first is not
    request3.shuffleOutputs = false;
    wallet.completeTx(request3);
    assertEquals(2, request3.tx.getInputs().size());
    assertEquals(2, request3.tx.getOutputs().size());
    assertEquals(CENT, request3.tx.getOutput(0).getValue());
    assertEquals(COIN.subtract(CENT), request3.tx.getOutput(1).getValue());

    SendRequest request4 = SendRequest.to(OTHER_ADDRESS, CENT);
    request4.tx.addInput(tx3.getOutput(0));
    // Now if we manually sign it, completeTx will not replace our signature
    wallet.signTransaction(request4);
    byte[] scriptSig = request4.tx.getInput(0).getScriptBytes();
    wallet.completeTx(request4);
    assertEquals(1, request4.tx.getInputs().size());
    assertEquals(1, request4.tx.getOutputs().size());
    assertEquals(CENT, request4.tx.getOutput(0).getValue());
    assertArrayEquals(scriptSig, request4.tx.getInput(0).getScriptBytes());
}
 
Example #27
Source File: ElectrumNotifier.java    From jelectrum with MIT License 4 votes vote down vote up
public void sendUnspent(StratumConnection conn, Object request_id, ByteString target)
  throws AddressFormatException
{
  try
  {
    Subscriber sub = new Subscriber(conn, request_id);
    JSONObject reply = sub.startReply();

    Collection<TransactionOutPoint> outs = jelly.getUtxoSource().getUnspentForScriptHash(target);

    
    JSONArray arr =new JSONArray();


    for(TransactionOutPoint out : outs)
    {
      JSONObject o = new JSONObject();
      o.put("tx_hash", out.getHash().toString());
      o.put("tx_pos", out.getIndex());

      SortedTransaction s_tx = new SortedTransaction(out.getHash(), false);

      Transaction tx = s_tx.tx; 
      long value = tx.getOutput((int)out.getIndex()).getValue().longValue();
      o.put("value",value);
      o.put("height", s_tx.getEffectiveHeight());
      
      arr.put(o);
    }


    reply.put("result", arr);



    sub.sendReply(reply);
  }
  catch(org.json.JSONException e)
  {   
    throw new RuntimeException(e);
  }
}
 
Example #28
Source File: UtxoTrieMgr.java    From jelectrum with MIT License 4 votes vote down vote up
public String getKeyForInput(TransactionInput in)
{
  if (in.isCoinBase()) return null;
  try
  {   
    byte[] public_key=null; 
    Address a = in.getFromAddress();
    public_key = a.getHash160();

    return getKey(public_key, in.getOutpoint().getHash(), (int)in.getOutpoint().getIndex());
  }
  catch(ScriptException e)
  {
    //Lets try this the other way
    try
    {   

      TransactionOutPoint out_p = in.getOutpoint();

      Transaction src_tx = tx_util.getTransaction(out_p.getHash());
      TransactionOutput out = src_tx.getOutput((int)out_p.getIndex());
      return getKeyForOutput(out, (int)out_p.getIndex());
    }
    catch(ScriptException e2)
    {   
      return null;
    }
  }

 
}
 
Example #29
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public Transaction emergencySignAndPublishPayoutTx(String depositTxHex,
                                                   Coin buyerPayoutAmount,
                                                   Coin sellerPayoutAmount,
                                                   Coin arbitratorPayoutAmount,
                                                   Coin txFee,
                                                   String buyerAddressString,
                                                   String sellerAddressString,
                                                   String arbitratorAddressString,
                                                   @Nullable String buyerPrivateKeyAsHex,
                                                   @Nullable String sellerPrivateKeyAsHex,
                                                   String arbitratorPrivateKeyAsHex,
                                                   String buyerPubKeyAsHex,
                                                   String sellerPubKeyAsHex,
                                                   String arbitratorPubKeyAsHex,
                                                   String P2SHMultiSigOutputScript,
                                                   TxBroadcaster.Callback callback)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    log.info("signAndPublishPayoutTx called");
    log.info("depositTxHex " + depositTxHex);
    log.info("buyerPayoutAmount " + buyerPayoutAmount.toFriendlyString());
    log.info("sellerPayoutAmount " + sellerPayoutAmount.toFriendlyString());
    log.info("arbitratorPayoutAmount " + arbitratorPayoutAmount.toFriendlyString());
    log.info("buyerAddressString " + buyerAddressString);
    log.info("sellerAddressString " + sellerAddressString);
    log.info("arbitratorAddressString " + arbitratorAddressString);
    log.info("buyerPrivateKeyAsHex (not displayed for security reasons)");
    log.info("sellerPrivateKeyAsHex (not displayed for security reasons)");
    log.info("arbitratorPrivateKeyAsHex (not displayed for security reasons)");
    log.info("buyerPubKeyAsHex " + buyerPubKeyAsHex);
    log.info("sellerPubKeyAsHex " + sellerPubKeyAsHex);
    log.info("arbitratorPubKeyAsHex " + arbitratorPubKeyAsHex);
    log.info("P2SHMultiSigOutputScript " + P2SHMultiSigOutputScript);

    checkNotNull((buyerPrivateKeyAsHex != null || sellerPrivateKeyAsHex != null), "either buyerPrivateKeyAsHex or sellerPrivateKeyAsHex must not be null");

    byte[] buyerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(buyerPubKeyAsHex)).getPubKey();
    byte[] sellerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(sellerPubKeyAsHex)).getPubKey();
    final byte[] arbitratorPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(arbitratorPubKeyAsHex)).getPubKey();

    Script p2SHMultiSigOutputScript = getP2SHMultiSigOutputScript(buyerPubKey, sellerPubKey, arbitratorPubKey);

    Coin msOutput = buyerPayoutAmount.add(sellerPayoutAmount).add(arbitratorPayoutAmount).add(txFee);
    TransactionOutput p2SHMultiSigOutput = new TransactionOutput(params, null, msOutput, p2SHMultiSigOutputScript.getProgram());
    Transaction depositTx = new Transaction(params);
    depositTx.addOutput(p2SHMultiSigOutput);

    Transaction payoutTx = new Transaction(params);
    Sha256Hash spendTxHash = Sha256Hash.wrap(depositTxHex);
    payoutTx.addInput(new TransactionInput(params, depositTx, p2SHMultiSigOutputScript.getProgram(), new TransactionOutPoint(params, 0, spendTxHash), msOutput));

    if (buyerPayoutAmount.isGreaterThan(Coin.ZERO))
        payoutTx.addOutput(buyerPayoutAmount, Address.fromBase58(params, buyerAddressString));
    if (sellerPayoutAmount.isGreaterThan(Coin.ZERO))
        payoutTx.addOutput(sellerPayoutAmount, Address.fromBase58(params, sellerAddressString));
    if (arbitratorPayoutAmount.isGreaterThan(Coin.ZERO))
        payoutTx.addOutput(arbitratorPayoutAmount, Address.fromBase58(params, arbitratorAddressString));

    // take care of sorting!
    Script redeemScript = getMultiSigRedeemScript(buyerPubKey, sellerPubKey, arbitratorPubKey);
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);

    ECKey.ECDSASignature tradersSignature;
    if (buyerPrivateKeyAsHex != null && !buyerPrivateKeyAsHex.isEmpty()) {
        final ECKey buyerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(buyerPrivateKeyAsHex));
        checkNotNull(buyerPrivateKey, "buyerPrivateKey must not be null");
        tradersSignature = buyerPrivateKey.sign(sigHash, aesKey).toCanonicalised();
    } else {
        checkNotNull(sellerPrivateKeyAsHex, "sellerPrivateKeyAsHex must not be null");
        final ECKey sellerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(sellerPrivateKeyAsHex));
        checkNotNull(sellerPrivateKey, "sellerPrivateKey must not be null");
        tradersSignature = sellerPrivateKey.sign(sigHash, aesKey).toCanonicalised();
    }
    final ECKey key = ECKey.fromPrivate(Utils.HEX.decode(arbitratorPrivateKeyAsHex));
    checkNotNull(key, "key must not be null");
    ECKey.ECDSASignature arbitratorSignature = key.sign(sigHash, aesKey).toCanonicalised();

    TransactionSignature tradersTxSig = new TransactionSignature(tradersSignature, Transaction.SigHash.ALL, false);
    TransactionSignature arbitratorTxSig = new TransactionSignature(arbitratorSignature, Transaction.SigHash.ALL, false);
    // Take care of order of signatures. See comment below at getMultiSigRedeemScript (sort order needed here: arbitrator, seller, buyer)
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(arbitratorTxSig, tradersTxSig), redeemScript);
    TransactionInput input = payoutTx.getInput(0);
    input.setScriptSig(inputScript);

    WalletService.printTx("payoutTx", payoutTx);

    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);

    broadcastTx(payoutTx, callback, 20);

    return payoutTx;
}
 
Example #30
Source File: SPV.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
private void updateUnspentOutputs(final List<JSONMap> utxos) {
    final Set<TransactionOutPoint> newUtxos = new HashSet<>();
    boolean recalculateBloom = false;

    Log.d(TAG, Var("number of utxos", utxos.size()));
    for (final JSONMap utxo : utxos) {
        final Integer prevIndex = utxo.getInt("pt_idx");
        final Integer subaccount = utxo.getInt("subaccount");
        final Integer pointer = utxo.getInt("pointer");
        final Sha256Hash txHash = utxo.getHash("txhash");

        if (isVerified(txHash)) {
            addToUtxo(txHash, prevIndex, subaccount, pointer);
            addUtxoToValues(txHash, false /* updateVerified */);
        } else {
            recalculateBloom = true;
            addToBloomFilter(utxo.getInt("block_height"), txHash, prevIndex, subaccount, pointer);
        }
        newUtxos.add(createOutPoint(prevIndex, txHash, mService.getNetworkParameters()));
    }

    final List<Integer> changedSubaccounts = new ArrayList<>();
    for (final TransactionOutPoint oldUtxo : new HashSet<>(mCountedUtxoValues.keySet())) {
        if (!newUtxos.contains(oldUtxo)) {
            recalculateBloom = true;

            final int subAccount = mUnspentDetails.get(oldUtxo).getSubAccount();
            final Coin verifiedBalance = getVerifiedBalance(subAccount);
            mVerifiedCoinBalances.put(subAccount,
                                      verifiedBalance.subtract(mCountedUtxoValues.get(oldUtxo)));
            changedSubaccounts.add(subAccount);
            mCountedUtxoValues.remove(oldUtxo);
            mUnspentDetails.remove(oldUtxo);
            mUnspentOutpoints.get(oldUtxo.getHash()).remove(((int) oldUtxo.getIndex()));
        }
    }

    if (recalculateBloom && mPeerGroup != null)
        mPeerGroup.recalculateFastCatchupAndFilter(PeerGroup.FilterRecalculateMode.SEND_IF_CHANGED);

    fireBalanceChanged(changedSubaccounts);
}