Search in sources :

Example 1 with TxOutput

use of bisq.core.dao.blockchain.vo.TxOutput in project bisq-core by bisq-network.

the class JsonBlockChainExporter method maybeExport.

public void maybeExport() {
    if (dumpBlockchainData) {
        ListenableFuture<Void> future = executor.submit(() -> {
            final BsqBlockChain bsqBlockChainClone = readableBsqBlockChain.getClone();
            for (Tx tx : bsqBlockChainClone.getTxMap().values()) {
                String txId = tx.getId();
                JsonTxType txType = tx.getTxType() != TxType.UNDEFINED_TX_TYPE ? JsonTxType.valueOf(tx.getTxType().name()) : null;
                List<JsonTxOutput> outputs = new ArrayList<>();
                tx.getOutputs().stream().forEach(txOutput -> {
                    final JsonTxOutput outputForJson = new JsonTxOutput(txId, txOutput.getIndex(), txOutput.isVerified() ? txOutput.getValue() : 0, !txOutput.isVerified() ? txOutput.getValue() : 0, txOutput.getBlockHeight(), txOutput.isVerified(), tx.getBurntFee(), txOutput.getAddress(), new JsonScriptPubKey(txOutput.getPubKeyScript()), txOutput.getSpentInfo() != null ? new JsonSpentInfo(txOutput.getSpentInfo()) : null, tx.getTime(), txType, txType != null ? txType.getDisplayString() : "", txOutput.getOpReturnData() != null ? Utils.HEX.encode(txOutput.getOpReturnData()) : null);
                    outputs.add(outputForJson);
                    txOutputFileManager.writeToDisc(Utilities.objectToJson(outputForJson), outputForJson.getId());
                });
                List<JsonTxInput> inputs = tx.getInputs().stream().map(txInput -> {
                    final TxOutput connectedTxOutput = txInput.getConnectedTxOutput();
                    return new JsonTxInput(txInput.getConnectedTxOutputIndex(), txInput.getConnectedTxOutputTxId(), connectedTxOutput != null ? connectedTxOutput.getValue() : 0, connectedTxOutput != null && connectedTxOutput.isVerified(), connectedTxOutput != null ? connectedTxOutput.getAddress() : null, tx.getTime());
                }).collect(Collectors.toList());
                final JsonTx jsonTx = new JsonTx(txId, tx.getBlockHeight(), tx.getBlockHash(), tx.getTime(), inputs, outputs, txType, txType != null ? txType.getDisplayString() : "", tx.getBurntFee());
                txFileManager.writeToDisc(Utilities.objectToJson(jsonTx), txId);
            }
            bsqBlockChainFileManager.writeToDisc(Utilities.objectToJson(bsqBlockChainClone), "BsqBlockChain");
            return null;
        });
        Futures.addCallback(future, new FutureCallback<Void>() {

            public void onSuccess(Void ignore) {
                log.trace("onSuccess");
            }

            public void onFailure(@NotNull Throwable throwable) {
                log.error(throwable.toString());
                throwable.printStackTrace();
            }
        });
    }
}
Also used : ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Utilities(bisq.common.util.Utilities) ReadableBsqBlockChain(bisq.core.dao.blockchain.ReadableBsqBlockChain) Inject(com.google.inject.Inject) DaoOptionKeys(bisq.core.dao.DaoOptionKeys) ArrayList(java.util.ArrayList) JsonFileManager(bisq.common.storage.JsonFileManager) Named(javax.inject.Named) BsqBlockChain(bisq.core.dao.blockchain.BsqBlockChain) Tx(bisq.core.dao.blockchain.vo.Tx) Utils(org.bitcoinj.core.Utils) IOException(java.io.IOException) TxOutput(bisq.core.dao.blockchain.vo.TxOutput) TxType(bisq.core.dao.blockchain.vo.TxType) Collectors(java.util.stream.Collectors) FutureCallback(com.google.common.util.concurrent.FutureCallback) File(java.io.File) FileUtil(bisq.common.storage.FileUtil) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Paths(java.nio.file.Paths) Storage(bisq.common.storage.Storage) NotNull(org.jetbrains.annotations.NotNull) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) TxOutput(bisq.core.dao.blockchain.vo.TxOutput) Tx(bisq.core.dao.blockchain.vo.Tx) ArrayList(java.util.ArrayList) ReadableBsqBlockChain(bisq.core.dao.blockchain.ReadableBsqBlockChain) BsqBlockChain(bisq.core.dao.blockchain.BsqBlockChain)

Example 2 with TxOutput

use of bisq.core.dao.blockchain.vo.TxOutput in project bisq-core by bisq-network.

the class BsqTxController method getTxTypeForOpReturn.

@NotNull
private TxType getTxTypeForOpReturn(Tx tx, OpReturnType opReturnType) {
    TxType txType;
    switch(opReturnType) {
        case COMPENSATION_REQUEST:
            checkArgument(tx.getOutputs().size() >= 3, "Compensation request tx need to have at least 3 outputs");
            final TxOutput issuanceTxOutput = tx.getOutputs().get(1);
            checkArgument(issuanceTxOutput.getTxOutputType() == TxOutputType.ISSUANCE_CANDIDATE_OUTPUT, "Compensation request txOutput type need to be COMPENSATION_REQUEST_ISSUANCE_CANDIDATE_OUTPUT");
            // second output is issuance candidate
            if (issuanceTxOutput.isVerified()) {
                // TODO can that even happen as the voting will be applied later then the parsing of the tx
                // If he have the issuance candidate already accepted by voting it gets the verified flag set
                txType = TxType.ISSUANCE;
            } else {
                // Otherwise we have an open or rejected compensation request
                txType = TxType.COMPENSATION_REQUEST;
            }
            break;
        case PROPOSAL:
            txType = TxType.PROPOSAL;
            break;
        case BLIND_VOTE:
            txType = TxType.BLIND_VOTE;
            break;
        case VOTE_REVEAL:
            txType = TxType.VOTE_REVEAL;
            break;
        case LOCK_UP:
            // TODO
            txType = TxType.LOCK_UP;
            break;
        case UNLOCK:
            // TODO
            txType = TxType.UN_LOCK;
            break;
        default:
            log.warn("We got a BSQ tx with fee and unknown OP_RETURN. tx={}", tx);
            txType = TxType.INVALID;
    }
    return txType;
}
Also used : TxOutput(bisq.core.dao.blockchain.vo.TxOutput) TxType(bisq.core.dao.blockchain.vo.TxType) NotNull(org.jetbrains.annotations.NotNull)

Example 3 with TxOutput

use of bisq.core.dao.blockchain.vo.TxOutput in project bisq-core by bisq-network.

the class RpcService method requestTx.

public Tx requestTx(String txId, int blockHeight) throws BsqBlockchainException {
    try {
        RawTransaction rawTransaction = requestRawTransaction(txId);
        // rawTransaction.getTime() is in seconds but we keep it in ms internally
        final long time = rawTransaction.getTime() * 1000;
        final List<TxInput> txInputs = rawTransaction.getVIn().stream().filter(rawInput -> rawInput != null && rawInput.getVOut() != null && rawInput.getTxId() != null).map(rawInput -> new TxInput(rawInput.getTxId(), rawInput.getVOut())).collect(Collectors.toList());
        final List<TxOutput> txOutputs = rawTransaction.getVOut().stream().filter(e -> e != null && e.getN() != null && e.getValue() != null && e.getScriptPubKey() != null).map(rawOutput -> {
            byte[] opReturnData = null;
            final com.neemre.btcdcli4j.core.domain.PubKeyScript scriptPubKey = rawOutput.getScriptPubKey();
            if (scriptPubKey.getType().equals(ScriptTypes.NULL_DATA)) {
                String[] chunks = scriptPubKey.getAsm().split(" ");
                // We get on testnet a lot of "OP_RETURN 0" data, so we filter those away
                if (chunks.length == 2 && chunks[0].equals("OP_RETURN") && !"0".equals(chunks[1])) {
                    try {
                        opReturnData = Utils.HEX.decode(chunks[1]);
                    } catch (Throwable t) {
                        // We get sometimes exceptions, seems BitcoinJ
                        // cannot handle all existing OP_RETURN data, but we ignore them
                        // anyway as our OP_RETURN data is valid in BitcoinJ
                        log.warn("Error at Utils.HEX.decode(chunks[1]): " + t.toString() + " / chunks[1]=" + chunks[1]);
                    }
                }
            }
            // We don't support raw MS which are the only case where scriptPubKey.getAddresses()>1
            String address = scriptPubKey.getAddresses() != null && scriptPubKey.getAddresses().size() == 1 ? scriptPubKey.getAddresses().get(0) : null;
            final PubKeyScript pubKeyScript = dumpBlockchainData ? new PubKeyScript(scriptPubKey) : null;
            return new TxOutput(rawOutput.getN(), rawOutput.getValue().movePointRight(8).longValue(), rawTransaction.getTxId(), pubKeyScript, address, opReturnData, blockHeight);
        }).collect(Collectors.toList());
        return new Tx(txId, blockHeight, rawTransaction.getBlockHash(), time, ImmutableList.copyOf(txInputs), ImmutableList.copyOf(txOutputs));
    } catch (BitcoindException | CommunicationException e) {
        log.error("error at requestTx with txId={}, blockHeight={}", txId, blockHeight);
        throw new BsqBlockchainException(e.getMessage(), e);
    }
}
Also used : BtcdClientImpl(com.neemre.btcdcli4j.core.client.BtcdClientImpl) Coin(org.bitcoinj.core.Coin) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) DaoOptionKeys(bisq.core.dao.DaoOptionKeys) RawTransaction(com.neemre.btcdcli4j.core.domain.RawTransaction) BtcdDaemonImpl(com.neemre.btcdcli4j.daemon.BtcdDaemonImpl) BigDecimal(java.math.BigDecimal) ImmutableList(com.google.common.collect.ImmutableList) Transaction(com.neemre.btcdcli4j.core.domain.Transaction) Map(java.util.Map) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) PubKeyScript(bisq.core.dao.blockchain.btcd.PubKeyScript) BitcoindException(com.neemre.btcdcli4j.core.BitcoindException) Named(javax.inject.Named) TxInput(bisq.core.dao.blockchain.vo.TxInput) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Properties(java.util.Properties) Logger(org.slf4j.Logger) Tx(bisq.core.dao.blockchain.vo.Tx) Utils(org.bitcoinj.core.Utils) CommunicationException(com.neemre.btcdcli4j.core.CommunicationException) ScriptTypes(com.neemre.btcdcli4j.core.domain.enums.ScriptTypes) BtcdClient(com.neemre.btcdcli4j.core.client.BtcdClient) TxOutput(bisq.core.dao.blockchain.vo.TxOutput) Collectors(java.util.stream.Collectors) BlockListener(com.neemre.btcdcli4j.daemon.event.BlockListener) Consumer(java.util.function.Consumer) Block(com.neemre.btcdcli4j.core.domain.Block) List(java.util.List) BsqBlockchainException(bisq.core.dao.blockchain.exceptions.BsqBlockchainException) BtcdDaemon(com.neemre.btcdcli4j.daemon.BtcdDaemon) HttpClients(org.apache.http.impl.client.HttpClients) TxOutput(bisq.core.dao.blockchain.vo.TxOutput) Tx(bisq.core.dao.blockchain.vo.Tx) CommunicationException(com.neemre.btcdcli4j.core.CommunicationException) PubKeyScript(bisq.core.dao.blockchain.btcd.PubKeyScript) TxInput(bisq.core.dao.blockchain.vo.TxInput) BsqBlockchainException(bisq.core.dao.blockchain.exceptions.BsqBlockchainException) RawTransaction(com.neemre.btcdcli4j.core.domain.RawTransaction) BitcoindException(com.neemre.btcdcli4j.core.BitcoindException)

Example 4 with TxOutput

use of bisq.core.dao.blockchain.vo.TxOutput in project bisq-core by bisq-network.

the class VoteService method revealVote.

private void revealVote(MyVote myVote) {
    byte[] hashOfBlindVoteList = VoteConsensus.getHashOfBlindVoteList(blindVoteSortedList);
    log.info("Sha256Ripemd160 hash of hashOfBlindVoteList " + Utilities.bytesAsHexString(hashOfBlindVoteList));
    byte[] opReturnData = VoteConsensus.getOpReturnDataForVoteReveal(hashOfBlindVoteList, myVote.getSecretKey());
    final Set<TxOutput> lockedForVoteTxOutputs = readableBsqBlockChain.getLockedForVoteTxOutputs();
    Optional<TxOutput> optionalStakeTxOutput = lockedForVoteTxOutputs.stream().filter(txOutput -> txOutput.getTxId().equals(myVote.getTxId())).findAny();
    if (optionalStakeTxOutput.isPresent()) {
        try {
            final TxOutput stakeTxOutput = optionalStakeTxOutput.get();
            VoteConsensus.unlockStakeTxOutputType(stakeTxOutput);
            Transaction voteRevealTx = getVoteRevealTx(stakeTxOutput, opReturnData);
            myVote.setRevealTxId(voteRevealTx.getHashAsString());
            myVoteListStorage.queueUpForSave();
            publishRevealTx(voteRevealTx, new FutureCallback<Transaction>() {

                @Override
                public void onSuccess(@Nullable Transaction result) {
                }

                @Override
                public void onFailure(@NotNull Throwable t) {
                }
            });
        } catch (InsufficientMoneyException e) {
            e.printStackTrace();
        } catch (WalletException e) {
            e.printStackTrace();
        } catch (TransactionVerificationException e) {
            e.printStackTrace();
        }
    } else {
    // log.warn("optionalStakeTxOutput is not present. myVote={}", myVote);
    }
}
Also used : Transaction(org.bitcoinj.core.Transaction) ChangeBelowDustException(bisq.core.btc.wallet.ChangeBelowDustException) Utilities(bisq.common.util.Utilities) Coin(org.bitcoinj.core.Coin) ReadableBsqBlockChain(bisq.core.dao.blockchain.ReadableBsqBlockChain) Proposal(bisq.core.dao.proposal.Proposal) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) BsqBlockChain(bisq.core.dao.blockchain.BsqBlockChain) SortedList(javafx.collections.transformation.SortedList) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) WalletException(bisq.core.btc.exceptions.WalletException) P2PService(bisq.network.p2p.P2PService) PersistedDataHost(bisq.common.proto.persistable.PersistedDataHost) Utils(org.bitcoinj.core.Utils) FilteredList(javafx.collections.transformation.FilteredList) Set(java.util.Set) TxOutput(bisq.core.dao.blockchain.vo.TxOutput) BsqWalletService(bisq.core.btc.wallet.BsqWalletService) Encryption(bisq.common.crypto.Encryption) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) DevEnv(bisq.common.app.DevEnv) VoteConsensus(bisq.core.dao.vote.consensus.VoteConsensus) ProtectedStorageEntry(bisq.network.p2p.storage.payload.ProtectedStorageEntry) UserThread(bisq.common.UserThread) Optional(java.util.Optional) ProtectedStoragePayload(bisq.network.p2p.storage.payload.ProtectedStoragePayload) ObservableList(javafx.collections.ObservableList) SecretKey(javax.crypto.SecretKey) NotNull(org.jetbrains.annotations.NotNull) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) CryptoException(bisq.common.crypto.CryptoException) Getter(lombok.Getter) FXCollections(javafx.collections.FXCollections) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) TransactionVerificationException(bisq.core.btc.exceptions.TransactionVerificationException) Nullable(javax.annotation.Nullable) DaoPeriodService(bisq.core.dao.DaoPeriodService) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) PublicKey(java.security.PublicKey) BisqEnvironment(bisq.core.app.BisqEnvironment) InsufficientMoneyException(org.bitcoinj.core.InsufficientMoneyException) FutureCallback(com.google.common.util.concurrent.FutureCallback) HashMapChangedListener(bisq.network.p2p.storage.HashMapChangedListener) Storage(bisq.common.storage.Storage) ProposalList(bisq.core.dao.proposal.ProposalList) KeyRing(bisq.common.crypto.KeyRing) ChangeListener(javafx.beans.value.ChangeListener) ProposalCollectionsService(bisq.core.dao.proposal.ProposalCollectionsService) WalletException(bisq.core.btc.exceptions.WalletException) TxOutput(bisq.core.dao.blockchain.vo.TxOutput) Transaction(org.bitcoinj.core.Transaction) TransactionVerificationException(bisq.core.btc.exceptions.TransactionVerificationException) InsufficientMoneyException(org.bitcoinj.core.InsufficientMoneyException)

Example 5 with TxOutput

use of bisq.core.dao.blockchain.vo.TxOutput in project bisq-desktop by bisq-network.

the class BsqTxView method getCompensationRequestTxListItems.

// We add manually a modified copy of the compensation request tx if it has become an issuance tx
// It is a bit weird to have one tx displayed 2 times but I think it is better to show both aspects
// separately. First the compensation request tx with the fee then after voting the issuance.
private List<BsqTxListItem> getCompensationRequestTxListItems(List<BsqTxListItem> items) {
    List<BsqTxListItem> issuanceTxList = new ArrayList<>();
    items.stream().filter(item -> item.getTxType() == TxType.COMPENSATION_REQUEST).peek(item -> {
        final Tx tx = readableBsqBlockChain.getTx(item.getTxId()).get();
        // We have mandatory BSQ change at output 0
        long changeValue = tx.getOutputs().get(0).getValue();
        long inputValue = tx.getInputs().stream().filter(input -> input.getConnectedTxOutput() != null).mapToLong(input -> input.getConnectedTxOutput().getValue()).sum();
        // We want to show fee as negative number
        long fee = changeValue - inputValue;
        item.setAmount(Coin.valueOf(fee));
    }).filter(item -> {
        final Optional<Tx> optionalTx = readableBsqBlockChain.getTx(item.getTxId());
        if (optionalTx.isPresent()) {
            final List<TxOutput> outputs = optionalTx.get().getOutputs();
            if (!outputs.isEmpty()) {
                return outputs.get(0).getTxOutputType() == TxOutputType.BSQ_OUTPUT;
            }
        }
        return false;
    }).forEach(item -> {
        final Tx tx = readableBsqBlockChain.getTx(item.getTxId()).get();
        final int blockHeight = tx.getBlockHeight();
        final int issuanceBlockHeight = daoPeriodService.getAbsoluteStartBlockOfPhase(blockHeight, DaoPeriodService.Phase.ISSUANCE);
        // We use the time of the block height of the start of the issuance period
        final long blockTimeInSec = readableBsqBlockChain.getBlockTime(issuanceBlockHeight);
        final BsqTxListItem issuanceItem = new BsqTxListItem(item.getTransaction(), bsqWalletService, btcWalletService, Optional.of(TxType.ISSUANCE), item.isBurnedBsqTx(), new Date(blockTimeInSec * 1000), bsqFormatter);
        // On output 1 we have the issuance candidate
        long issuanceValue = tx.getOutputs().get(1).getValue();
        issuanceItem.setAmount(Coin.valueOf(issuanceValue));
        issuanceTxList.add(issuanceItem);
    });
    return issuanceTxList;
}
Also used : Transaction(org.bitcoinj.core.Transaction) HyperlinkWithIcon(bisq.desktop.components.HyperlinkWithIcon) Coin(org.bitcoinj.core.Coin) Date(java.util.Date) ReadableBsqBlockChain(bisq.core.dao.blockchain.ReadableBsqBlockChain) VBox(javafx.scene.layout.VBox) BsqBalanceListener(bisq.core.btc.wallet.BsqBalanceListener) BsqNode(bisq.core.dao.node.BsqNode) ReadOnlyObjectWrapper(javafx.beans.property.ReadOnlyObjectWrapper) ListChangeListener(javafx.collections.ListChangeListener) Res(bisq.core.locale.Res) TableView(javafx.scene.control.TableView) Pane(javafx.scene.layout.Pane) SortedList(javafx.collections.transformation.SortedList) HBox(javafx.scene.layout.HBox) AutoTooltipTableColumn(bisq.desktop.components.AutoTooltipTableColumn) AutoTooltipLabel(bisq.desktop.components.AutoTooltipLabel) FormBuilder(bisq.desktop.util.FormBuilder) TxOutput(bisq.core.dao.blockchain.vo.TxOutput) Collectors(java.util.stream.Collectors) BsqWalletService(bisq.core.btc.wallet.BsqWalletService) BsqBalanceUtil(bisq.desktop.main.dao.wallet.BsqBalanceUtil) List(java.util.List) Preferences(bisq.core.user.Preferences) SimpleDoubleProperty(javafx.beans.property.SimpleDoubleProperty) Optional(java.util.Optional) ObservableList(javafx.collections.ObservableList) AwesomeIcon(de.jensd.fx.fontawesome.AwesomeIcon) GUIUtil(bisq.desktop.util.GUIUtil) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) ActivatableView(bisq.desktop.common.view.ActivatableView) FXCollections(javafx.collections.FXCollections) DoubleProperty(javafx.beans.property.DoubleProperty) BsqNodeProvider(bisq.core.dao.node.BsqNodeProvider) FxmlView(bisq.desktop.common.view.FxmlView) TableColumn(javafx.scene.control.TableColumn) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) TableCell(javafx.scene.control.TableCell) ProgressBar(javafx.scene.control.ProgressBar) Insets(javafx.geometry.Insets) AddressWithIconAndDirection(bisq.desktop.components.AddressWithIconAndDirection) Callback(javafx.util.Callback) Tooltip(javafx.scene.control.Tooltip) GridPane(javafx.scene.layout.GridPane) Label(javafx.scene.control.Label) DaoPeriodService(bisq.core.dao.DaoPeriodService) Tx(bisq.core.dao.blockchain.vo.Tx) AwesomeDude(de.jensd.fx.fontawesome.AwesomeDude) BisqEnvironment(bisq.core.app.BisqEnvironment) TxType(bisq.core.dao.blockchain.vo.TxType) BsqFormatter(bisq.desktop.util.BsqFormatter) TxOutputType(bisq.core.dao.blockchain.vo.TxOutputType) ChangeListener(javafx.beans.value.ChangeListener) Tx(bisq.core.dao.blockchain.vo.Tx) Optional(java.util.Optional) ArrayList(java.util.ArrayList) SortedList(javafx.collections.transformation.SortedList) List(java.util.List) ObservableList(javafx.collections.ObservableList) ArrayList(java.util.ArrayList) Date(java.util.Date)

Aggregations

TxOutput (bisq.core.dao.blockchain.vo.TxOutput)12 Tx (bisq.core.dao.blockchain.vo.Tx)9 Coin (org.bitcoinj.core.Coin)8 ReadableBsqBlockChain (bisq.core.dao.blockchain.ReadableBsqBlockChain)6 Slf4j (lombok.extern.slf4j.Slf4j)5 Transaction (org.bitcoinj.core.Transaction)5 List (java.util.List)4 Optional (java.util.Optional)4 BisqEnvironment (bisq.core.app.BisqEnvironment)3 BsqWalletService (bisq.core.btc.wallet.BsqWalletService)3 TxType (bisq.core.dao.blockchain.vo.TxType)3 ArrayList (java.util.ArrayList)3 Collectors (java.util.stream.Collectors)3 TransactionOutPoint (org.bitcoinj.core.TransactionOutPoint)3 TransactionOutput (org.bitcoinj.core.TransactionOutput)3 Utils (org.bitcoinj.core.Utils)3 NotNull (org.jetbrains.annotations.NotNull)3 Encryption (bisq.common.crypto.Encryption)2 Storage (bisq.common.storage.Storage)2 Utilities (bisq.common.util.Utilities)2