Search in sources :

Example 61 with Transaction

use of org.bitcoinj.core.Transaction in project catena-java by alinush.

the class CatenaUtils method getPrevCatenaTx.

public static Transaction getPrevCatenaTx(Wallet wallet, Sha256Hash currHash) {
    Transaction currTxn = wallet.getTransaction(currHash);
    TransactionOutput spentOutput = currTxn.getInput(0).getConnectedOutput();
    if (spentOutput != null && spentOutput.getParentTransaction() != null) {
        return spentOutput.getParentTransaction();
    } else {
        return null;
    }
}
Also used : TransactionOutput(org.bitcoinj.core.TransactionOutput) Transaction(org.bitcoinj.core.Transaction)

Example 62 with Transaction

use of org.bitcoinj.core.Transaction in project catena-java by alinush.

the class WriteChainTest method testFees.

// @Test
public void testFees() throws InsufficientMoneyException, IOException, InterruptedException {
    log.info("Test: Correct TXN fee");
    String[] s1 = TestUtils.generateStatements(1, 0);
    String[] s2 = TestUtils.generateStatements(1, 1);
    // Issue a TXN with the default fee
    Coin defaultFeePerKb = Context.get().getFeePerKb();
    log.debug("Default fee per KB: " + defaultFeePerKb.toFriendlyString());
    issueStatements(s1);
    // Set the fee per KB
    Coin customFeePerKb = Coin.SATOSHI.multiply(100000);
    log.debug("Custom fee per KB: " + customFeePerKb.toFriendlyString());
    catenaServer.setFeePerKb(customFeePerKb);
    // Issue a TXN with a different fee
    issueStatements(s2);
    // Check the TXNs fee
    Iterator<CatenaStatement> it = catenaServer.getCatenaWallet().statementIterator(true);
    CatenaStatement stmt1 = it.next();
    CatenaStatement stmt2 = it.next();
    Transaction tx1 = catenaServer.getCatenaWallet().getTransaction(stmt1.getTxHash());
    Transaction tx2 = catenaServer.getCatenaWallet().getTransaction(stmt2.getTxHash());
    log.debug("Default fee TXN #1: " + tx1);
    log.debug("Custom fee TXN #1: " + tx2);
    // FIXME: This fails because bitcoinj pays the wrong fee in calculateFee (check later)
    // assertCorrectFee(defaultFeePerKb, tx1);
    // assertCorrectFee(customFeePerKb, tx2);
    // There should be no extra statements after
    assertFalse(it.hasNext());
}
Also used : CatenaStatement(org.catena.common.CatenaStatement) Coin(org.bitcoinj.core.Coin) Transaction(org.bitcoinj.core.Transaction)

Example 63 with Transaction

use of org.bitcoinj.core.Transaction in project catena-java by alinush.

the class WriteChainTest method testTxnSize.

@Test
public void testTxnSize() throws InsufficientMoneyException, IOException, InterruptedException {
    log.info("Test: Average TXN size");
    int numStmts = 10;
    byte[][] s = new byte[numStmts][Sha256Hash.LENGTH];
    for (int i = 0; i < numStmts; i++) {
        byte[] hash = Sha256Hash.of(new String("" + i).getBytes()).getBytes();
        assertEquals(Sha256Hash.LENGTH, hash.length);
        System.arraycopy(hash, 0, s[i], 0, hash.length);
        issueStatement(s[i]);
    }
    Iterator<CatenaStatement> it = catenaServer.getCatenaWallet().statementIterator(true);
    int i = 0;
    int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
    double avg = 0.0;
    while (it.hasNext()) {
        i++;
        CatenaStatement stmt = it.next();
        Transaction tx = catenaServer.getCatenaWallet().getTransaction(stmt.getTxHash());
        int size = tx.unsafeBitcoinSerialize().length;
        // 1000 bytes = 1 kB
        // log.debug("TXN #{} size in kB: {}", i, ((double)size)/1000.0);
        log.debug("TXN #{} size in bytes: {} (OP_RETURN data: {} bytes): {}", i, size, CatenaUtils.getCatenaTxData(tx).length, tx);
        min = min > size ? size : min;
        max = max < size ? size : max;
        avg += size;
    }
    avg = avg / numStmts;
    log.info("Min: {}, Max: {}, Avg: {}", min, max, avg);
}
Also used : CatenaStatement(org.catena.common.CatenaStatement) Transaction(org.bitcoinj.core.Transaction) Test(org.junit.Test) ClientServerTest(org.catena.common.ClientServerTest)

Example 64 with Transaction

use of org.bitcoinj.core.Transaction in project catena-java by alinush.

the class SemaphoredStatementListener method onStatementAppended.

@Override
public void onStatementAppended(CatenaStatement s) {
    if (semAppended != null) {
        Transaction tx = wallet.getTransaction(s.getTxHash());
        log.info("New statement received: '{}', \n\ttxid={}, \n\tprev={}", s.getAsString(), s.getTxHash(), tx.getInput(0).getConnectedOutput().getOutPointFor().getHash());
        semAppended.release();
    }
}
Also used : Transaction(org.bitcoinj.core.Transaction)

Example 65 with Transaction

use of org.bitcoinj.core.Transaction in project bitcoin-wallet by bitcoin-wallet.

the class SweepWalletFragment method onCreate.

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.fragmentManager = getChildFragmentManager();
    setHasOptionsMenu(true);
    if (!Constants.ENABLE_SWEEP_WALLET)
        throw new IllegalStateException("ENABLE_SWEEP_WALLET is disabled");
    walletActivityViewModel = new ViewModelProvider(activity).get(AbstractWalletActivityViewModel.class);
    walletActivityViewModel.wallet.observe(this, wallet -> updateView());
    viewModel = new ViewModelProvider(this).get(SweepWalletViewModel.class);
    viewModel.getDynamicFees().observe(this, dynamicFees -> updateView());
    viewModel.progress.observe(this, new ProgressDialogFragment.Observer(fragmentManager));
    viewModel.privateKeyToSweep.observe(this, privateKeyToSweep -> updateView());
    viewModel.walletToSweep.observe(this, walletToSweep -> {
        if (walletToSweep != null) {
            balanceView.setVisibility(View.VISIBLE);
            final MonetaryFormat btcFormat = config.getFormat();
            final MonetarySpannable balanceSpannable = new MonetarySpannable(btcFormat, walletToSweep.getBalance(BalanceType.ESTIMATED));
            balanceSpannable.applyMarkup(null, null);
            final SpannableStringBuilder balance = new SpannableStringBuilder(balanceSpannable);
            balance.insert(0, ": ");
            balance.insert(0, getString(R.string.sweep_wallet_fragment_balance));
            balanceView.setText(balance);
        } else {
            balanceView.setVisibility(View.GONE);
        }
        updateView();
    });
    viewModel.sentTransaction.observe(this, transaction -> {
        if (viewModel.state == SweepWalletViewModel.State.SENDING) {
            final TransactionConfidence confidence = transaction.getConfidence();
            final ConfidenceType confidenceType = confidence.getConfidenceType();
            final int numBroadcastPeers = confidence.numBroadcastPeers();
            if (confidenceType == ConfidenceType.DEAD)
                setState(SweepWalletViewModel.State.FAILED);
            else if (numBroadcastPeers > 1 || confidenceType == ConfidenceType.BUILDING)
                setState(SweepWalletViewModel.State.SENT);
        }
        updateView();
    });
    viewModel.showDialog.observe(this, new DialogEvent.Observer(activity));
    viewModel.showDialogWithRetryRequestBalance.observe(this, new DialogEvent.Observer(activity) {

        @Override
        protected void onBuildButtons(final DialogBuilder dialog) {
            dialog.setPositiveButton(R.string.button_retry, (d, which) -> requestWalletBalance());
            dialog.setNegativeButton(R.string.button_dismiss, null);
        }
    });
    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());
    if (savedInstanceState == null) {
        final Intent intent = activity.getIntent();
        if (intent.hasExtra(SweepWalletActivity.INTENT_EXTRA_KEY)) {
            final PrefixedChecksummedBytes privateKeyToSweep = (PrefixedChecksummedBytes) intent.getSerializableExtra(SweepWalletActivity.INTENT_EXTRA_KEY);
            viewModel.privateKeyToSweep.setValue(privateKeyToSweep);
            // delay until fragment is resumed
            handler.post(maybeDecodeKeyRunnable);
        }
    }
}
Also used : MonetarySpannable(de.schildbach.wallet.util.MonetarySpannable) Bundle(android.os.Bundle) DumpedPrivateKey(org.bitcoinj.core.DumpedPrivateKey) Transaction(org.bitcoinj.core.Transaction) PackageManager(android.content.pm.PackageManager) Coin(org.bitcoinj.core.Coin) WalletTransaction(org.bitcoinj.wallet.WalletTransaction) LoggerFactory(org.slf4j.LoggerFactory) ScanActivity(de.schildbach.wallet.ui.scan.ScanActivity) AbstractWalletActivityViewModel(de.schildbach.wallet.ui.AbstractWalletActivityViewModel) Process(android.os.Process) NetworkParameters(org.bitcoinj.core.NetworkParameters) PrefixedChecksummedBytes(org.bitcoinj.core.PrefixedChecksummedBytes) SendRequest(org.bitcoinj.wallet.SendRequest) Handler(android.os.Handler) Map(java.util.Map) Fragment(androidx.fragment.app.Fragment) View(android.view.View) Button(android.widget.Button) R(de.schildbach.wallet.R) Configuration(de.schildbach.wallet.Configuration) Constants(de.schildbach.wallet.Constants) PaymentIntent(de.schildbach.wallet.data.PaymentIntent) BalanceType(org.bitcoinj.wallet.Wallet.BalanceType) ConfidenceType(org.bitcoinj.core.TransactionConfidence.ConfidenceType) Set(java.util.Set) ComparisonChain(com.google.common.collect.ComparisonChain) ViewGroup(android.view.ViewGroup) Preconditions.checkState(androidx.core.util.Preconditions.checkState) ECKey(org.bitcoinj.core.ECKey) TextView(android.widget.TextView) Nullable(androidx.annotation.Nullable) TransactionsAdapter(de.schildbach.wallet.ui.TransactionsAdapter) TransactionOutput(org.bitcoinj.core.TransactionOutput) UTXO(org.bitcoinj.core.UTXO) Context(android.content.Context) TransactionConfidence(org.bitcoinj.core.TransactionConfidence) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Wallet(org.bitcoinj.wallet.Wallet) Intent(android.content.Intent) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) MenuItem(android.view.MenuItem) AnimationUtils(android.view.animation.AnimationUtils) ProgressDialogFragment(de.schildbach.wallet.ui.ProgressDialogFragment) SpannableStringBuilder(android.text.SpannableStringBuilder) VerificationException(org.bitcoinj.core.VerificationException) MenuInflater(android.view.MenuInflater) Menu(android.view.Menu) DialogEvent(de.schildbach.wallet.ui.DialogEvent) Sha256Hash(org.bitcoinj.core.Sha256Hash) BIP38PrivateKey(org.bitcoinj.crypto.BIP38PrivateKey) FragmentManager(androidx.fragment.app.FragmentManager) TransactionOutPoint(org.bitcoinj.core.TransactionOutPoint) Logger(org.slf4j.Logger) ViewModelProvider(androidx.lifecycle.ViewModelProvider) LayoutInflater(android.view.LayoutInflater) MonetaryFormat(org.bitcoinj.utils.MonetaryFormat) Threading(org.bitcoinj.utils.Threading) AbstractWalletActivity(de.schildbach.wallet.ui.AbstractWalletActivity) DialogBuilder(de.schildbach.wallet.ui.DialogBuilder) HandlerThread(android.os.HandlerThread) TransactionInput(org.bitcoinj.core.TransactionInput) StringInputParser(de.schildbach.wallet.ui.InputParser.StringInputParser) WalletApplication(de.schildbach.wallet.WalletApplication) Comparator(java.util.Comparator) Activity(android.app.Activity) EditText(android.widget.EditText) MonetaryFormat(org.bitcoinj.utils.MonetaryFormat) PrefixedChecksummedBytes(org.bitcoinj.core.PrefixedChecksummedBytes) ProgressDialogFragment(de.schildbach.wallet.ui.ProgressDialogFragment) Handler(android.os.Handler) PaymentIntent(de.schildbach.wallet.data.PaymentIntent) Intent(android.content.Intent) MonetarySpannable(de.schildbach.wallet.util.MonetarySpannable) TransactionOutPoint(org.bitcoinj.core.TransactionOutPoint) ConfidenceType(org.bitcoinj.core.TransactionConfidence.ConfidenceType) DialogEvent(de.schildbach.wallet.ui.DialogEvent) HandlerThread(android.os.HandlerThread) AbstractWalletActivityViewModel(de.schildbach.wallet.ui.AbstractWalletActivityViewModel) DialogBuilder(de.schildbach.wallet.ui.DialogBuilder) TransactionConfidence(org.bitcoinj.core.TransactionConfidence) SpannableStringBuilder(android.text.SpannableStringBuilder) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Aggregations

Transaction (org.bitcoinj.core.Transaction)214 Coin (org.bitcoinj.core.Coin)71 TransactionInput (org.bitcoinj.core.TransactionInput)48 TransactionOutput (org.bitcoinj.core.TransactionOutput)42 TransactionOutPoint (org.bitcoinj.core.TransactionOutPoint)38 Address (org.bitcoinj.core.Address)35 ECKey (org.bitcoinj.core.ECKey)32 Script (org.bitcoinj.script.Script)32 ArrayList (java.util.ArrayList)31 HashMap (java.util.HashMap)29 SendRequest (org.bitcoinj.wallet.SendRequest)25 Wallet (org.bitcoinj.wallet.Wallet)25 IOException (java.io.IOException)24 List (java.util.List)24 InsufficientMoneyException (org.bitcoinj.core.InsufficientMoneyException)20 MyTransactionOutPoint (com.samourai.wallet.send.MyTransactionOutPoint)19 AddressFormatException (org.bitcoinj.core.AddressFormatException)19 Sha256Hash (org.bitcoinj.core.Sha256Hash)19 UTXO (com.samourai.wallet.send.UTXO)17 Nullable (javax.annotation.Nullable)17