Search in sources :

Example 1 with Tx

use of bisq.core.dao.state.blockchain.Tx in project bisq-core by bisq-network.

the class VoteResultConsensus method getBlindVoteTx.

public static Tx getBlindVoteTx(TxOutput blindVoteStakeOutput, BsqStateService bsqStateService, PeriodService periodService, int chainHeight) throws VoteResultException {
    try {
        String blindVoteTxId = blindVoteStakeOutput.getTxId();
        Optional<Tx> optionalBlindVoteTx = bsqStateService.getTx(blindVoteTxId);
        checkArgument(optionalBlindVoteTx.isPresent(), "blindVoteTx with txId " + blindVoteTxId + " not found.");
        Tx blindVoteTx = optionalBlindVoteTx.get();
        Optional<TxType> optionalTxType = bsqStateService.getOptionalTxType(blindVoteTx.getId());
        checkArgument(optionalTxType.isPresent(), "optionalTxType must be present");
        checkArgument(optionalTxType.get() == TxType.BLIND_VOTE, "blindVoteTx must have type BLIND_VOTE");
        checkArgument(periodService.isTxInCorrectCycle(blindVoteTx.getBlockHeight(), chainHeight), "blindVoteTx is not in correct cycle. blindVoteTx.getBlockHeight()=" + blindVoteTx.getBlockHeight());
        checkArgument(periodService.isInPhase(blindVoteTx.getBlockHeight(), DaoPhase.Phase.BLIND_VOTE), "blindVoteTx is not in BLIND_VOTE phase. blindVoteTx.getBlockHeight()=" + blindVoteTx.getBlockHeight());
        return blindVoteTx;
    } catch (Throwable t) {
        throw new VoteResultException(t);
    }
}
Also used : Tx(bisq.core.dao.state.blockchain.Tx) TxType(bisq.core.dao.state.blockchain.TxType)

Example 2 with Tx

use of bisq.core.dao.state.blockchain.Tx in project bisq-core by bisq-network.

the class VoteResultService method getDecryptedBallotsWithMeritsSet.

private Set<DecryptedBallotsWithMerits> getDecryptedBallotsWithMeritsSet(int chainHeight) {
    // We want all voteRevealTxOutputs which are in current cycle we are processing.
    return bsqStateService.getVoteRevealOpReturnTxOutputs().stream().filter(txOutput -> periodService.isTxInCorrectCycle(txOutput.getTxId(), chainHeight)).map(txOutput -> {
        // TODO make method
        byte[] opReturnData = txOutput.getOpReturnData();
        String voteRevealTxId = txOutput.getTxId();
        Optional<Tx> optionalVoteRevealTx = bsqStateService.getTx(voteRevealTxId);
        if (!optionalVoteRevealTx.isPresent()) {
            log.error("optionalVoteRevealTx is not present. voteRevealTxId={}", voteRevealTxId);
            // TODO throw exception
            return null;
        }
        Tx voteRevealTx = optionalVoteRevealTx.get();
        try {
            // TODO maybe verify version in opReturn
            byte[] hashOfBlindVoteList = VoteResultConsensus.getHashOfBlindVoteList(opReturnData);
            SecretKey secretKey = VoteResultConsensus.getSecretKey(opReturnData);
            TxOutput blindVoteStakeOutput = VoteResultConsensus.getConnectedBlindVoteStakeOutput(voteRevealTx, bsqStateService);
            long blindVoteStake = blindVoteStakeOutput.getValue();
            Tx blindVoteTx = VoteResultConsensus.getBlindVoteTx(blindVoteStakeOutput, bsqStateService, periodService, chainHeight);
            String blindVoteTxId = blindVoteTx.getId();
            // Here we deal with eventual consistency of the p2p network data!
            // TODO make more clear we are in p2p domain now
            List<BlindVote> blindVoteList = BlindVoteConsensus.getSortedBlindVoteListOfCycle(blindVoteListService);
            Optional<BlindVote> optionalBlindVote = blindVoteList.stream().filter(blindVote -> blindVote.getTxId().equals(blindVoteTxId)).findAny();
            if (optionalBlindVote.isPresent()) {
                BlindVote blindVote = optionalBlindVote.get();
                VoteWithProposalTxIdList voteWithProposalTxIdList = VoteResultConsensus.decryptVotes(blindVote.getEncryptedVotes(), secretKey);
                MeritList meritList = MeritConsensus.decryptMeritList(blindVote.getEncryptedMeritList(), secretKey);
                // We lookup for the proposals we have in our local list which match the txId from the
                // voteWithProposalTxIdList and create a ballot list with the proposal and the vote from
                // the voteWithProposalTxIdList
                BallotList ballotList = createBallotList(voteWithProposalTxIdList);
                return new DecryptedBallotsWithMerits(hashOfBlindVoteList, voteRevealTxId, blindVoteTxId, blindVoteStake, ballotList, meritList);
            } else {
                // TODO handle recovering
                log.warn("We have a blindVoteTx but we do not have the corresponding blindVote in our local list.\n" + "That can happen if the blindVote item was not properly broadcast. We will go on " + "and see if that blindVote was part of the majority data view. If so we should " + "recover the missing blind vote by a request to our peers. blindVoteTxId={}", blindVoteTxId);
                return null;
            }
        } catch (MissingBallotException e) {
            // TODO handle case that we are missing proposals
            log.error("We are missing proposals to create the vote result: " + e.toString());
            return null;
        } catch (Throwable e) {
            log.error("Could not create DecryptedBallotsWithMerits: " + e.toString());
            return null;
        }
    }).filter(Objects::nonNull).collect(Collectors.toSet());
}
Also used : VoteWithProposalTxId(bisq.core.dao.governance.blindvote.VoteWithProposalTxId) Arrays(java.util.Arrays) Utilities(bisq.common.util.Utilities) Vote(bisq.core.dao.governance.ballot.vote.Vote) P2PDataStorage(bisq.network.p2p.storage.P2PDataStorage) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) BlindVoteListService(bisq.core.dao.governance.blindvote.BlindVoteListService) Map(java.util.Map) VoteRevealConsensus(bisq.core.dao.governance.votereveal.VoteRevealConsensus) ChangeParamProposal(bisq.core.dao.governance.proposal.param.ChangeParamProposal) BlindVote(bisq.core.dao.governance.blindvote.BlindVote) CompensationProposal(bisq.core.dao.governance.proposal.compensation.CompensationProposal) VoteRevealService(bisq.core.dao.governance.votereveal.VoteRevealService) BondedRolesService(bisq.core.dao.governance.role.BondedRolesService) BallotListService(bisq.core.dao.governance.ballot.BallotListService) Proposal(bisq.core.dao.governance.proposal.Proposal) PeriodService(bisq.core.dao.state.period.PeriodService) Set(java.util.Set) ConfiscateBond(bisq.core.dao.state.governance.ConfiscateBond) Collectors(java.util.stream.Collectors) ProposalListPresentation(bisq.core.dao.governance.proposal.ProposalListPresentation) Objects(java.util.Objects) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) IssuanceService(bisq.core.dao.governance.voteresult.issuance.IssuanceService) Optional(java.util.Optional) BallotList(bisq.core.dao.governance.ballot.BallotList) ObservableList(javafx.collections.ObservableList) SecretKey(javax.crypto.SecretKey) Getter(lombok.Getter) BondedRoleProposal(bisq.core.dao.governance.proposal.role.BondedRoleProposal) TxOutput(bisq.core.dao.state.blockchain.TxOutput) MeritConsensus(bisq.core.dao.governance.merit.MeritConsensus) FXCollections(javafx.collections.FXCollections) HashMap(java.util.HashMap) Block(bisq.core.dao.state.blockchain.Block) ArrayList(java.util.ArrayList) Value(lombok.Value) Inject(javax.inject.Inject) HashSet(java.util.HashSet) ParamChange(bisq.core.dao.state.governance.ParamChange) BondedRole(bisq.core.dao.governance.role.BondedRole) Nullable(javax.annotation.Nullable) MeritList(bisq.core.dao.governance.merit.MeritList) ConfiscateBondProposal(bisq.core.dao.governance.proposal.confiscatebond.ConfiscateBondProposal) Ballot(bisq.core.dao.governance.ballot.Ballot) Tx(bisq.core.dao.state.blockchain.Tx) BsqStateService(bisq.core.dao.state.BsqStateService) DaoSetupService(bisq.core.dao.DaoSetupService) BlindVoteConsensus(bisq.core.dao.governance.blindvote.BlindVoteConsensus) VoteWithProposalTxIdList(bisq.core.dao.governance.blindvote.VoteWithProposalTxIdList) BsqStateListener(bisq.core.dao.state.BsqStateListener) Comparator(java.util.Comparator) DaoPhase(bisq.core.dao.state.period.DaoPhase) TxOutput(bisq.core.dao.state.blockchain.TxOutput) Tx(bisq.core.dao.state.blockchain.Tx) VoteWithProposalTxIdList(bisq.core.dao.governance.blindvote.VoteWithProposalTxIdList) MeritList(bisq.core.dao.governance.merit.MeritList) BlindVote(bisq.core.dao.governance.blindvote.BlindVote) BallotList(bisq.core.dao.governance.ballot.BallotList) SecretKey(javax.crypto.SecretKey)

Example 3 with Tx

use of bisq.core.dao.state.blockchain.Tx in project bisq-core by bisq-network.

the class BsqWalletService method updateBsqBalance.

// /////////////////////////////////////////////////////////////////////////////////////////
// Balance
// /////////////////////////////////////////////////////////////////////////////////////////
private void updateBsqBalance() {
    unverifiedBalance = Coin.valueOf(getTransactions(false).stream().filter(tx -> tx.getConfidence().getConfidenceType() == PENDING).mapToLong(tx -> {
        // Sum up outputs into BSQ wallet and subtract the inputs using lockup or unlocking
        // outputs since those inputs will be accounted for in lockupBondsBalance and
        // unlockingBondsBalance
        long outputs = tx.getOutputs().stream().filter(out -> out.isMine(wallet)).mapToLong(out -> out.getValue().value).sum();
        // Account for spending of locked connectedOutputs
        long lockedInputs = tx.getInputs().stream().filter(in -> {
            TransactionOutput connectedOutput = in.getConnectedOutput();
            if (connectedOutput != null) {
                Transaction parentTransaction = connectedOutput.getParentTransaction();
                // TODO SQ
                if (parentTransaction != null) /* &&
                                                    parentTransaction.getConfidence().getConfidenceType() == BUILDING*/
                {
                    TxOutputKey key = new TxOutputKey(parentTransaction.getHashAsString(), connectedOutput.getIndex());
                    return (connectedOutput.isMine(wallet) && (bsqStateService.isLockupOutput(key) || bsqStateService.isUnlockingOutput(key)));
                }
            }
            return false;
        }).mapToLong(in -> in != null ? in.getValue().value : 0).sum();
        return outputs - lockedInputs;
    }).sum());
    Set<String> confirmedTxIdSet = getTransactions(false).stream().filter(tx -> tx.getConfidence().getConfidenceType() == BUILDING).map(Transaction::getHashAsString).collect(Collectors.toSet());
    lockedForVotingBalance = Coin.valueOf(bsqStateService.getUnspentBlindVoteStakeTxOutputs().stream().filter(txOutput -> confirmedTxIdSet.contains(txOutput.getTxId())).mapToLong(TxOutput::getValue).sum());
    lockupBondsBalance = Coin.valueOf(bsqStateService.getLockupTxOutputs().stream().filter(txOutput -> bsqStateService.isUnspent(txOutput.getKey())).filter(txOutput -> confirmedTxIdSet.contains(txOutput.getTxId())).mapToLong(TxOutput::getValue).sum());
    unlockingBondsBalance = Coin.valueOf(bsqStateService.getUnspentUnlockingTxOutputsStream().filter(txOutput -> confirmedTxIdSet.contains(txOutput.getTxId())).mapToLong(TxOutput::getValue).sum());
    availableBalance = bsqCoinSelector.select(NetworkParameters.MAX_MONEY, wallet.calculateAllSpendCandidates()).valueGathered;
    if (availableBalance.isNegative())
        availableBalance = Coin.ZERO;
    availableNonBsqBalance = nonBsqCoinSelector.select(NetworkParameters.MAX_MONEY, wallet.calculateAllSpendCandidates()).valueGathered;
    bsqBalanceListeners.forEach(e -> e.onUpdateBalances(availableBalance, availableNonBsqBalance, unverifiedBalance, lockedForVotingBalance, lockupBondsBalance, unlockingBondsBalance));
}
Also used : Transaction(org.bitcoinj.core.Transaction) TransactionConfidence(org.bitcoinj.core.TransactionConfidence) Getter(lombok.Getter) Coin(org.bitcoinj.core.Coin) ScriptException(org.bitcoinj.core.ScriptException) CoinSelection(org.bitcoinj.wallet.CoinSelection) TxOutput(bisq.core.dao.state.blockchain.TxOutput) Wallet(org.bitcoinj.wallet.Wallet) FXCollections(javafx.collections.FXCollections) Block(bisq.core.dao.state.blockchain.Block) Function(java.util.function.Function) Inject(javax.inject.Inject) HashSet(java.util.HashSet) NetworkParameters(org.bitcoinj.core.NetworkParameters) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TransactionVerificationException(bisq.core.btc.exceptions.TransactionVerificationException) SendRequest(org.bitcoinj.wallet.SendRequest) Map(java.util.Map) AbstractWalletEventListener(org.bitcoinj.wallet.listeners.AbstractWalletEventListener) BUILDING(org.bitcoinj.core.TransactionConfidence.ConfidenceType.BUILDING) PENDING(org.bitcoinj.core.TransactionConfidence.ConfidenceType.PENDING) AddressFormatException(org.bitcoinj.core.AddressFormatException) WalletException(bisq.core.btc.exceptions.WalletException) TransactionOutPoint(org.bitcoinj.core.TransactionOutPoint) BlockChain(org.bitcoinj.core.BlockChain) Tx(bisq.core.dao.state.blockchain.Tx) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) BsqStateService(bisq.core.dao.state.BsqStateService) Set(java.util.Set) TxOutputKey(bisq.core.dao.state.blockchain.TxOutputKey) BisqEnvironment(bisq.core.app.BisqEnvironment) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) InsufficientMoneyException(org.bitcoinj.core.InsufficientMoneyException) Collectors(java.util.stream.Collectors) ECKey(org.bitcoinj.core.ECKey) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Script(org.bitcoinj.script.Script) TransactionInput(org.bitcoinj.core.TransactionInput) Preferences(bisq.core.user.Preferences) BsqStateListener(bisq.core.dao.state.BsqStateListener) TransactionOutput(org.bitcoinj.core.TransactionOutput) Optional(java.util.Optional) FeeService(bisq.core.provider.fee.FeeService) Address(org.bitcoinj.core.Address) ObservableList(javafx.collections.ObservableList) Restrictions(bisq.core.btc.Restrictions) TransactionOutput(org.bitcoinj.core.TransactionOutput) Transaction(org.bitcoinj.core.Transaction) TxOutputKey(bisq.core.dao.state.blockchain.TxOutputKey)

Example 4 with Tx

use of bisq.core.dao.state.blockchain.Tx in project bisq-core by bisq-network.

the class BsqWalletService method getValueSentFromMeForTransaction.

@Override
public Coin getValueSentFromMeForTransaction(Transaction transaction) throws ScriptException {
    Coin result = Coin.ZERO;
    // We check all our inputs and get the connected outputs.
    for (int i = 0; i < transaction.getInputs().size(); i++) {
        TransactionInput input = transaction.getInputs().get(i);
        // We grab the connected output for that input
        TransactionOutput connectedOutput = input.getConnectedOutput();
        if (connectedOutput != null) {
            // We grab the parent tx of the connected output
            final Transaction parentTransaction = connectedOutput.getParentTransaction();
            final boolean isConfirmed = parentTransaction != null && parentTransaction.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING;
            if (connectedOutput.isMineOrWatched(wallet)) {
                if (isConfirmed) {
                    // We lookup if we have a BSQ tx matching the parent tx
                    // We cannot make that findTx call outside of the loop as the parent tx can change at each iteration
                    Optional<Tx> txOptional = bsqStateService.getTx(parentTransaction.getHash().toString());
                    if (txOptional.isPresent()) {
                        TxOutput txOutput = txOptional.get().getTxOutputs().get(connectedOutput.getIndex());
                        if (bsqStateService.isBsqTxOutputType(txOutput)) {
                            // TODO check why values are not the same
                            if (txOutput.getValue() != connectedOutput.getValue().value)
                                log.warn("getValueSentToMeForTransaction: Value of BSQ output do not match BitcoinJ tx output. " + "txOutput.getValue()={}, output.getValue().value={}, txId={}", txOutput.getValue(), connectedOutput.getValue().value, txOptional.get().getId());
                            // If it is a valid BSQ output we add it
                            result = result.add(Coin.valueOf(txOutput.getValue()));
                        }
                    }
                }
            /*else {
                        // TODO atm we don't display amounts of unconfirmed txs but that might change so we leave that code
                        // if it will be required
                        // If the tx is not confirmed yet we add the value and assume it is a valid BSQ output.
                        result = result.add(connectedOutput.getValue());
                    }*/
            }
        }
    }
    return result;
}
Also used : Coin(org.bitcoinj.core.Coin) TxOutput(bisq.core.dao.state.blockchain.TxOutput) TransactionOutput(org.bitcoinj.core.TransactionOutput) Transaction(org.bitcoinj.core.Transaction) Tx(bisq.core.dao.state.blockchain.Tx) TransactionOutPoint(org.bitcoinj.core.TransactionOutPoint) TransactionInput(org.bitcoinj.core.TransactionInput)

Example 5 with Tx

use of bisq.core.dao.state.blockchain.Tx in project bisq-core by bisq-network.

the class BsqWalletService method getValueSentToMeForTransaction.

@Override
public Coin getValueSentToMeForTransaction(Transaction transaction) throws ScriptException {
    Coin result = Coin.ZERO;
    final String txId = transaction.getHashAsString();
    // We check if we have a matching BSQ tx. We do that call here to avoid repeated calls in the loop.
    Optional<Tx> txOptional = bsqStateService.getTx(txId);
    // We check all the outputs of our tx
    for (int i = 0; i < transaction.getOutputs().size(); i++) {
        TransactionOutput output = transaction.getOutputs().get(i);
        final boolean isConfirmed = output.getParentTransaction() != null && output.getParentTransaction().getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING;
        if (output.isMineOrWatched(wallet)) {
            if (isConfirmed) {
                if (txOptional.isPresent()) {
                    // The index of the BSQ tx outputs are the same like the bitcoinj tx outputs
                    TxOutput txOutput = txOptional.get().getTxOutputs().get(i);
                    if (bsqStateService.isBsqTxOutputType(txOutput)) {
                        // TODO check why values are not the same
                        if (txOutput.getValue() != output.getValue().value) {
                            log.warn("getValueSentToMeForTransaction: Value of BSQ output do not match BitcoinJ tx output. " + "txOutput.getValue()={}, output.getValue().value={}, txId={}", txOutput.getValue(), output.getValue().value, txId);
                        }
                        // If it is a valid BSQ output we add it
                        result = result.add(Coin.valueOf(txOutput.getValue()));
                    }
                }
            }
        /*else {
                    // TODO atm we don't display amounts of unconfirmed txs but that might change so we leave that code
                    // if it will be required
                    // If the tx is not confirmed yet we add the value and assume it is a valid BSQ output.
                    result = result.add(output.getValue());
                }*/
        }
    }
    return result;
}
Also used : Coin(org.bitcoinj.core.Coin) TxOutput(bisq.core.dao.state.blockchain.TxOutput) TransactionOutput(org.bitcoinj.core.TransactionOutput) Tx(bisq.core.dao.state.blockchain.Tx) TransactionOutPoint(org.bitcoinj.core.TransactionOutPoint)

Aggregations

Tx (bisq.core.dao.state.blockchain.Tx)8 TxOutput (bisq.core.dao.state.blockchain.TxOutput)6 BsqStateService (bisq.core.dao.state.BsqStateService)4 Block (bisq.core.dao.state.blockchain.Block)3 Optional (java.util.Optional)3 Slf4j (lombok.extern.slf4j.Slf4j)3 Coin (org.bitcoinj.core.Coin)3 TransactionOutPoint (org.bitcoinj.core.TransactionOutPoint)3 TransactionOutput (org.bitcoinj.core.TransactionOutput)3 Utilities (bisq.common.util.Utilities)2 CompensationProposal (bisq.core.dao.governance.proposal.compensation.CompensationProposal)2 BsqStateListener (bisq.core.dao.state.BsqStateListener)2 TxType (bisq.core.dao.state.blockchain.TxType)2 DaoPhase (bisq.core.dao.state.period.DaoPhase)2 PeriodService (bisq.core.dao.state.period.PeriodService)2 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)2 List (java.util.List)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 Inject (javax.inject.Inject)2