org.bitcoinj.core.Transaction Java Examples

The following examples show how to use org.bitcoinj.core.Transaction. 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: GATx.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public static Coin addUtxo(final GaService service, final Transaction tx,
                           final List<JSONMap> utxos, final List<JSONMap> used,
                           final List<Long> inValues, final List<byte[]> inAssetIds,
                           final List<byte[]> inAbfs, final List<byte[]> inVbfs) {
    final JSONMap utxo = utxos.get(0);
    utxos.remove(0);
    if (utxo.getBool("confidential")) {
        inAssetIds.add(utxo.getBytes("assetId"));
        inAbfs.add(utxo.getBytes("abf"));
        inVbfs.add(utxo.getBytes("vbf"));
    }
    used.add(utxo);
    addInput(service, tx, utxo);
    if (inValues != null)
        inValues.add(utxo.getLong("value"));
    return utxo.getCoin("value");
}
 
Example #2
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void bounce() throws Exception {
    // This test covers bug 64 (False double spends). Check that if we create a spend and it's immediately sent
    // back to us, this isn't considered as a double spend.
    Coin coin1 = COIN;
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, coin1);
    // Send half to some other guy. Sending only half then waiting for a confirm is important to ensure the tx is
    // in the unspent pool, not pending or spent.
    Coin coinHalf = valueOf(0, 50);
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    assertEquals(1, wallet.getTransactions(true).size());
    Transaction outbound1 = wallet.createSend(OTHER_ADDRESS, coinHalf);
    wallet.commitTx(outbound1);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, outbound1);
    assertTrue(outbound1.getWalletOutputs(wallet).size() <= 1); //the change address at most
    // That other guy gives us the coins right back.
    Transaction inbound2 = new Transaction(PARAMS);
    inbound2.addOutput(new TransactionOutput(PARAMS, inbound2, coinHalf, myAddress));
    assertTrue(outbound1.getWalletOutputs(wallet).size() >= 1);
    inbound2.addInput(outbound1.getOutputs().get(0));
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, inbound2);
    assertEquals(coin1, wallet.getBalance());
}
 
Example #3
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void lowerThanDefaultFee() throws InsufficientMoneyException {
    int feeFactor = 50;
    Coin fee = Transaction.DEFAULT_TX_FEE.divide(feeFactor);
    receiveATransactionAmount(wallet, myAddress, Coin.COIN);
    SendRequest req = SendRequest.to(myAddress, Coin.CENT);
    req.feePerKb = fee;
    wallet.completeTx(req);
    assertEquals(Coin.valueOf(22700).divide(feeFactor), req.tx.getFee());
    wallet.commitTx(req.tx);
    SendRequest emptyReq = SendRequest.emptyWallet(myAddress);
    emptyReq.feePerKb = fee;
    emptyReq.ensureMinRequiredFee = true;
    emptyReq.emptyWallet = true;
    emptyReq.coinSelector = AllowUnconfirmedCoinSelector.get();
    wallet.completeTx(emptyReq);
    assertEquals(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE, emptyReq.tx.getFee());
    wallet.commitTx(emptyReq.tx);
}
 
Example #4
Source File: VoteRevealService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private void publishTx(Transaction voteRevealTx) {
    walletsManager.publishAndCommitBsqTx(voteRevealTx, TxType.VOTE_REVEAL, new TxBroadcaster.Callback() {
        @Override
        public void onSuccess(Transaction transaction) {
            log.info("voteRevealTx successfully broadcast.");
            voteRevealTxPublishedListeners.forEach(l -> l.onVoteRevealTxPublished(transaction.getHashAsString()));
        }

        @Override
        public void onFailure(TxBroadcastException exception) {
            log.error(exception.toString());
            voteRevealExceptions.add(new VoteRevealException("Publishing of voteRevealTx failed.",
                    exception, voteRevealTx));
        }
    });
}
 
Example #5
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void watchingScriptsSentFrom() throws Exception {
    int baseElements = wallet.getBloomFilterElementCount();

    Address watchedAddress = LegacyAddress.fromKey(UNITTEST, new ECKey());
    wallet.addWatchedAddress(watchedAddress);
    assertEquals(baseElements + 1, wallet.getBloomFilterElementCount());

    Transaction t1 = createFakeTx(UNITTEST, CENT, watchedAddress);
    Transaction t2 = createFakeTx(UNITTEST, COIN, OTHER_ADDRESS);
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
    assertEquals(baseElements + 2, wallet.getBloomFilterElementCount());
    Transaction st2 = new Transaction(UNITTEST);
    st2.addOutput(CENT, OTHER_ADDRESS);
    st2.addOutput(COIN, OTHER_ADDRESS);
    st2.addInput(t1.getOutput(0));
    st2.addInput(t2.getOutput(0));
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, st2);
    assertEquals(baseElements + 2, wallet.getBloomFilterElementCount());
    assertEquals(CENT, st2.getValueSentFromMe(wallet));
}
 
Example #6
Source File: DefaultRiskAnalysis.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private Result analyzeIsStandard() {
    // The IsStandard rules don't apply on testnet, because they're just a safety mechanism and we don't want to
    // crush innovation with valueless test coins.
    if (wallet != null && !wallet.getNetworkParameters().getId().equals(NetworkParameters.ID_MAINNET))
        return Result.OK;

    RuleViolation ruleViolation = isStandard(tx);
    if (ruleViolation != RuleViolation.NONE) {
        nonStandard = tx;
        return Result.NON_STANDARD;
    }

    for (Transaction dep : dependencies) {
        ruleViolation = isStandard(dep);
        if (ruleViolation != RuleViolation.NONE) {
            nonStandard = dep;
            return Result.NON_STANDARD;
        }
    }

    return Result.OK;
}
 
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 isConsistent_duplicates() throws Exception {
    // This test ensures that isConsistent catches duplicate transactions, eg, because we submitted the same block
    // twice (this is not allowed).
    Transaction tx = createFakeTx(PARAMS, COIN, myAddress);
    TransactionOutput output = new TransactionOutput(PARAMS, tx, valueOf(0, 5), OTHER_ADDRESS);
    tx.addOutput(output);
    wallet.receiveFromBlock(tx, null, BlockChain.NewBlockType.BEST_CHAIN, 0);

    assertTrue(wallet.isConsistent());

    Transaction txClone = PARAMS.getDefaultSerializer().makeTransaction(tx.bitcoinSerialize());
    try {
        wallet.receiveFromBlock(txClone, null, BlockChain.NewBlockType.BEST_CHAIN, 0);
        fail("Illegal argument not thrown when it should have been.");
    } catch (IllegalStateException ex) {
        // expected
    }
}
 
Example #8
Source File: AssetService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction payFee(StatefulAsset statefulAsset, long listingFee) throws InsufficientMoneyException, TxException {
    checkArgument(!statefulAsset.wasRemovedByVoting(), "Asset must not have been removed");
    checkArgument(listingFee >= getFeePerDay().value, "Fee must not be less then listing fee for 1 day.");
    checkArgument(listingFee % 100 == 0, "Fee must be a multiple of 1 BSQ (100 satoshi).");
    try {
        // We create a prepared Bsq Tx for the listing fee.
        Transaction preparedBurnFeeTx = bsqWalletService.getPreparedBurnFeeTxForAssetListing(Coin.valueOf(listingFee));
        byte[] hash = AssetConsensus.getHash(statefulAsset);
        byte[] opReturnData = AssetConsensus.getOpReturnData(hash);
        // We add the BTC inputs for the miner fee.
        Transaction txWithBtcFee = btcWalletService.completePreparedBurnBsqTx(preparedBurnFeeTx, opReturnData);
        // We sign the BSQ inputs of the final tx.
        Transaction transaction = bsqWalletService.signTx(txWithBtcFee);
        log.info("Asset listing fee tx: " + transaction);
        return transaction;
    } catch (WalletException | TransactionVerificationException e) {
        throw new TxException(e);
    }
}
 
Example #9
Source File: LNPaymentLogicImpl.java    From thundernetwork with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction getServerTransaction () {
    Preconditions.checkNotNull(channel);

    Transaction transaction = new Transaction(Constants.getNetwork());
    transaction.addInput(channel.anchorTxHashServer, 0, Tools.getDummyScript());
    transaction.addInput(channel.anchorTxHashClient, 0, Tools.getDummyScript());
    transaction.addOutput(Coin.valueOf(0), ScriptTools.getChannelTxOutputRevocation(revocationHashServer,
            channel.keyServer, channel.keyClient, Constants.ESCAPE_REVOCATION_TIME));
    transaction.addOutput(Coin.valueOf(statusTemp.amountClient), ScriptTools.getChannelTxOutputPlain(channel.keyClient));
    transaction = addPayments(transaction, statusTemp, revocationHashServer, channel.keyServer, channel.keyClient);

    long amountEncumbered = statusTemp.amountServer - transaction.getMessageSize() * statusTemp.feePerByte;
    transaction.getOutput(0).setValue(Coin.valueOf(amountEncumbered));

    return transaction;
}
 
Example #10
Source File: SendRequest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * <p>Creates a new SendRequest to the given address for the given value.</p>
 *
 * <p>Be very careful when value is smaller than {@link Transaction#MIN_NONDUST_OUTPUT} as the transaction will
 * likely be rejected by the network in this case.</p>
 */
public static SendRequest to(Address destination, Coin value) {
    SendRequest req = new SendRequest();
    final NetworkParameters parameters = destination.getParameters();
    checkNotNull(parameters, "Address is for an unknown network");
    req.tx = new Transaction(parameters);
    req.tx.addOutput(value, destination);
    return req;
}
 
Example #11
Source File: MyceliumCoinSelector.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sub-classes can override this to just customize whether transactions are usable, but keep age sorting.
 */
protected boolean shouldSelect(Transaction tx) {
    if (tx != null) {
        return isSelectable(tx);
    }
    return true;
}
 
Example #12
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testIrrelevantDoubleSpend() throws Exception {
    Transaction tx0 = createFakeTx(UNITTEST);
    Transaction tx1 = createFakeTx(UNITTEST);

    Transaction tx2 = new Transaction(UNITTEST);
    tx2.addInput(tx0.getOutput(0));
    tx2.addOutput(COIN, myAddress);
    tx2.addOutput(COIN, OTHER_ADDRESS);

    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx2, tx1, tx0);

    // tx3 and tx4 double spend each other
    Transaction tx3 = new Transaction(UNITTEST);
    tx3.addInput(tx1.getOutput(0));
    tx3.addOutput(COIN, myAddress);
    tx3.addOutput(COIN, OTHER_ADDRESS);
    wallet.receivePending(tx3, null);

    // tx4 also spends irrelevant output from tx2
    Transaction tx4 = new Transaction(UNITTEST);
    tx4.addInput(tx1.getOutput(0)); // spends same output
    tx4.addInput(tx2.getOutput(1));
    tx4.addOutput(COIN, OTHER_ADDRESS);

    // tx4 does not actually get added to wallet here since it by itself is irrelevant
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx4);

    // since tx4 is not saved, tx2 output 1 will have bad spentBy
    wallet = roundTrip(wallet);

    assertTrue(wallet.isConsistent());
}
 
Example #13
Source File: WalletAppKitService.java    From consensusj with Apache License 2.0 5 votes vote down vote up
private static BlockInfo.Sha256HashList hashListFromTxList(List<Transaction> txList) {
    if (txList == null) {
        return null;
    } else {
        List<Sha256Hash> list = txList.stream()
                .map(Transaction::getTxId)
                .collect(Collectors.toList());
        return new BlockInfo.Sha256HashList(list);
    }
}
 
Example #14
Source File: TransactionSignature.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public Transaction.SigHash sigHashMode() {
    final int mode = sighashFlags & 0x1f;
    if (mode == Transaction.SigHash.NONE.value)
        return Transaction.SigHash.NONE;
    else if (mode == Transaction.SigHash.SINGLE.value)
        return Transaction.SigHash.SINGLE;
    else
        return Transaction.SigHash.ALL;
}
 
Example #15
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void opReturnOneOutputWithValueTest() throws Exception {
    // Tests basic send of transaction with one output that destroys coins and has an OP_RETURN.
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(PARAMS);
    Coin messagePrice = CENT;
    Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes());
    tx.addOutput(messagePrice, script);
    SendRequest request = SendRequest.forTx(tx);
    wallet.completeTx(request);
}
 
Example #16
Source File: MyBlindVoteListService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
public Tuple2<Coin, Integer> getMiningFeeAndTxSize(Coin stake)
        throws InsufficientMoneyException, WalletException, TransactionVerificationException {
    // We set dummy opReturn data
    Coin blindVoteFee = BlindVoteConsensus.getFee(bsqStateService, bsqStateService.getChainHeight());
    Transaction dummyTx = getBlindVoteTx(stake, blindVoteFee, new byte[22]);
    Coin miningFee = dummyTx.getFee();
    int txSize = dummyTx.bitcoinSerialize().length;
    return new Tuple2<>(miningFee, txSize);
}
 
Example #17
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void transactionsList() throws Exception {
    // Check the wallet can give us an ordered list of all received transactions.
    Utils.setMockClock();
    Transaction tx1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
    Utils.rollMockClock(60 * 10);
    Transaction tx2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(0, 5));
    // Check we got them back in order.
    List<Transaction> transactions = wallet.getTransactionsByTime();
    assertEquals(tx2, transactions.get(0));
    assertEquals(tx1, transactions.get(1));
    assertEquals(2, transactions.size());
    // Check we get only the last transaction if we request a subrage.
    transactions = wallet.getRecentTransactions(1, false);
    assertEquals(1, transactions.size());
    assertEquals(tx2,  transactions.get(0));

    // Create a spend five minutes later.
    Utils.rollMockClock(60 * 5);
    Transaction tx3 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 5));
    // Does not appear in list yet.
    assertEquals(2, wallet.getTransactionsByTime().size());
    wallet.commitTx(tx3);
    // Now it does.
    transactions = wallet.getTransactionsByTime();
    assertEquals(3, transactions.size());
    assertEquals(tx3, transactions.get(0));

    // Verify we can handle the case of older wallets in which the timestamp is null (guessed from the
    // block appearances list).
    tx1.setUpdateTime(null);
    tx3.setUpdateTime(null);
    // Check we got them back in order.
    transactions = wallet.getTransactionsByTime();
    assertEquals(tx2,  transactions.get(0));
    assertEquals(3, transactions.size());
}
 
Example #18
Source File: Trade.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("NullableProblems")
public void setDepositTx(Transaction tx) {
    log.debug("setDepositTx " + tx);
    this.depositTx = tx;
    depositTxId = depositTx.getHashAsString();
    setupConfidenceListener();
    persist();
}
 
Example #19
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void balance() throws Exception {
    // Receive 5 coins then half a coin.
    Coin v1 = valueOf(5, 0);
    Coin v2 = valueOf(0, 50);
    Coin expected = valueOf(5, 50);
    assertEquals(0, wallet.getTransactions(true).size());
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v1);
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v2);
    assertEquals(2, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    assertEquals(expected, wallet.getBalance());

    // Now spend one coin.
    Coin v3 = COIN;
    Transaction spend = wallet.createSend(OTHER_ADDRESS, v3);
    wallet.commitTx(spend);
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));

    // Available and estimated balances should not be the same. We don't check the exact available balance here
    // because it depends on the coin selection algorithm.
    assertEquals(valueOf(4, 50), wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    assertFalse(wallet.getBalance(Wallet.BalanceType.AVAILABLE).equals(
                wallet.getBalance(Wallet.BalanceType.ESTIMATED)));

    // Now confirm the transaction by including it into a block.
    sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, spend);

    // Change is confirmed. We started with 5.50 so we should have 4.50 left.
    Coin v4 = valueOf(4, 50);
    assertEquals(v4, wallet.getBalance(Wallet.BalanceType.AVAILABLE));
}
 
Example #20
Source File: LNPaymentMessageFactoryMock.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<TransactionSignature> getMockSig () {
    ECKey k = new ECKey();
    Transaction t = new Transaction(Constants.getNetwork());
    t.addInput(Sha256Hash.ZERO_HASH, 0, Tools.getDummyScript());
    t.addOutput(Coin.ZERO, Tools.getDummyScript());

    return Collections.singletonList(Tools.getSignature(t, 0, t.getOutput(0),k));
}
 
Example #21
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void opReturnMaxBytes() throws Exception {
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(PARAMS);
    Script script = ScriptBuilder.createOpReturnScript(new byte[80]);
    tx.addOutput(Coin.ZERO, script);
    SendRequest request = SendRequest.forTx(tx);
    request.ensureMinRequiredFee = true;
    wallet.completeTx(request);
}
 
Example #22
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void doubleSpendWeReceive() throws Exception {
    FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(PARAMS, myAddress);
    // doubleSpends.t1 spends to our wallet. doubleSpends.t2 double spends somewhere else.

    Transaction t1b = new Transaction(PARAMS);
    TransactionOutput t1bo = new TransactionOutput(PARAMS, t1b, valueOf(0, 50), OTHER_ADDRESS);
    t1b.addOutput(t1bo);
    t1b.addInput(doubleSpends.t1.getOutput(0));

    wallet.receivePending(doubleSpends.t1, null);
    wallet.receivePending(doubleSpends.t2, null);
    wallet.receivePending(t1b, null);
    assertInConflict(doubleSpends.t1);
    assertInConflict(doubleSpends.t1);
    assertInConflict(t1b);

    // Add a block to the block store. The rest of the blocks in this test will be on top of this one.
    FakeTxBuilder.BlockPair blockPair0 = createFakeBlock(blockStore, 1);

    // A block was mined including doubleSpends.t1
    FakeTxBuilder.BlockPair blockPair1 = createFakeBlock(blockStore, 2, doubleSpends.t1);
    wallet.receiveFromBlock(doubleSpends.t1, blockPair1.storedBlock, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
    wallet.notifyNewBestBlock(blockPair1.storedBlock);
    assertSpent(doubleSpends.t1);
    assertDead(doubleSpends.t2);
    assertPending(t1b);

    // A reorg: previous block "replaced" by new block containing doubleSpends.t2
    FakeTxBuilder.BlockPair blockPair2 = createFakeBlock(blockStore, blockPair0.storedBlock, 2, doubleSpends.t2);
    wallet.receiveFromBlock(doubleSpends.t2, blockPair2.storedBlock, AbstractBlockChain.NewBlockType.SIDE_CHAIN, 0);
    wallet.reorganize(blockPair0.storedBlock, Lists.newArrayList(blockPair1.storedBlock),
            Lists.newArrayList(blockPair2.storedBlock));
    assertDead(doubleSpends.t1);
    assertSpent(doubleSpends.t2);
    assertDead(t1b);
}
 
Example #23
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void balanceWithIdenticalOutputs() {
    assertEquals(Coin.ZERO, wallet.getBalance(BalanceType.ESTIMATED));
    Transaction tx = new Transaction(UNITTEST);
    tx.addOutput(Coin.COIN, myAddress);
    tx.addOutput(Coin.COIN, myAddress); // identical to the above
    wallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx));
    assertEquals(Coin.COIN.plus(Coin.COIN), wallet.getBalance(BalanceType.ESTIMATED));
}
 
Example #24
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void verifyTransaction(Transaction transaction) throws TransactionVerificationException {
    try {
        transaction.verify();
    } catch (Throwable t) {
        t.printStackTrace();
        log.error(t.getMessage());
        throw new TransactionVerificationException(t);
    }
}
 
Example #25
Source File: GATx.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static ChangeOutput addChangeOutput(final GaService service, final Transaction tx,
                                                               final int subaccount) {
    final JSONMap addrInfo = service.getNewAddress(subaccount);
    if (addrInfo == null)
        return null;
    return new ChangeOutput(tx.addOutput(Coin.ZERO, createChangeAddress(addrInfo, service.getNetworkParameters())),
                            addrInfo.getInt("pointer"),
                            addrInfo.getString("addr_type").equals("p2wsh"));
}
 
Example #26
Source File: WalletProtobufSerializerTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void coinbaseTxns() throws Exception {
    // Covers issue 420 where the outpoint index of a coinbase tx input was being mis-serialized.
    Block b = UNITTEST.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, myKey.getPubKey(), FIFTY_COINS, Block.BLOCK_HEIGHT_GENESIS);
    Transaction coinbase = b.getTransactions().get(0);
    assertTrue(coinbase.isCoinBase());
    BlockChain chain = new BlockChain(UNITTEST, myWallet, new MemoryBlockStore(UNITTEST));
    assertTrue(chain.add(b));
    // Wallet now has a coinbase tx in it.
    assertEquals(1, myWallet.getTransactions(true).size());
    assertTrue(myWallet.getTransaction(coinbase.getHash()).isCoinBase());
    Wallet wallet2 = roundTrip(myWallet);
    assertEquals(1, wallet2.getTransactions(true).size());
    assertTrue(wallet2.getTransaction(coinbase.getHash()).isCoinBase());
}
 
Example #27
Source File: RpcServerModule.java    From consensusj with Apache License 2.0 5 votes vote down vote up
public RpcServerModule(NetworkParameters netParams) {
    super("BitcoinJMappingServer", new Version(1, 0, 0, null, null, null));

    this.addDeserializer(Address.class, new AddressDeserializer(netParams))  // Null means use default list of netParams
            .addDeserializer(Coin.class, new CoinDeserializer())
            .addDeserializer(ECKey.class, new ECKeyDeserializer())
            .addDeserializer(Sha256Hash.class, new Sha256HashDeserializer())
            .addSerializer(Address.class, new AddressSerializer())
            .addSerializer(Coin.class, new CoinSerializer())
            .addSerializer(ECKey.class, new ECKeySerializer())
            .addSerializer(Peer.class, new PeerSerializer())
            .addSerializer(Sha256Hash.class, new Sha256HashSerializer())
            .addSerializer(Transaction.class, new TransactionSerializer());
}
 
Example #28
Source File: CompensationProposalFactory.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected Transaction completeTx(Transaction preparedBurnFeeTx, byte[] opReturnData, Proposal proposal)
        throws WalletException, InsufficientMoneyException, TransactionVerificationException {
    CompensationProposal compensationProposal = (CompensationProposal) proposal;
    return btcWalletService.completePreparedCompensationRequestTx(
            compensationProposal.getRequestedBsq(),
            compensationProposal.getAddress(),
            preparedBurnFeeTx,
            opReturnData);
}
 
Example #29
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public long calculateFee(String toAddress, long sumIntoSatoshi, long feeIntoSatoshi, UnspentOutputList unspentOutputList, long feePerKb) throws Exception {
    Coin AMOUNT = Coin.valueOf(sumIntoSatoshi);
    Coin FEE = Coin.valueOf(feeIntoSatoshi);
    Transaction tx = createTx(toAddress, AMOUNT.toPlainString(), FEE.toPlainString(), unspentOutputList);
    if (tx == null)
        return 0;
    int txSizeInB = (int) Math.ceil(tx.unsafeBitcoinSerialize().length);
    return (long)Math.ceil(feePerKb * txSizeInB / 1024.0);
}
 
Example #30
Source File: BuyerSetupPayoutTxListener.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
private void applyConfidence(TransactionConfidence confidence) {
    if (trade.getPayoutTx() == null) {
        Transaction walletTx = processModel.getTradeWalletService().getWalletTx(confidence.getTransactionHash());
        trade.setPayoutTx(walletTx);
        BtcWalletService.printTx("payoutTx received from network", walletTx);
        trade.setState(Trade.State.BUYER_SAW_PAYOUT_TX_IN_NETWORK);
    } else {
        log.info("We got the payout tx already set from BuyerProcessPayoutTxPublishedMessage. tradeId={}, state={}", trade.getId(), trade.getState());
    }

    swapMultiSigEntry();

    // need delay as it can be called inside the handler before the listener and tradeStateSubscription are actually set.
    UserThread.execute(this::unSubscribe);
}