Search in sources :

Example 26 with Wallet

use of co.rsk.bitcoinj.wallet.Wallet in project rskj by rsksmart.

the class BridgeSupport method computeTotalAmountSent.

private Coin computeTotalAmountSent(BtcTransaction btcTx) throws IOException {
    // Compute the total amount sent. Value could have been sent both to the
    // currently active federation as well as to the currently retiring federation.
    // Add both amounts up in that case.
    Coin amountToActive = btcTx.getValueSentToMe(getActiveFederationWallet(false));
    Coin amountToRetiring = Coin.ZERO;
    Wallet retiringFederationWallet = getRetiringFederationWallet(false);
    if (retiringFederationWallet != null) {
        amountToRetiring = btcTx.getValueSentToMe(retiringFederationWallet);
    }
    return amountToActive.add(amountToRetiring);
}
Also used : Coin(co.rsk.bitcoinj.core.Coin) Wallet(co.rsk.bitcoinj.wallet.Wallet)

Example 27 with Wallet

use of co.rsk.bitcoinj.wallet.Wallet in project rskj by rsksmart.

the class BridgeSupport method processFundsMigration.

private void processFundsMigration(Transaction rskTx) throws IOException {
    Wallet retiringFederationWallet = getRetiringFederationWallet(true);
    List<UTXO> availableUTXOs = getRetiringFederationBtcUTXOs();
    ReleaseTransactionSet releaseTransactionSet = provider.getReleaseTransactionSet();
    Federation activeFederation = getActiveFederation();
    if (federationIsInMigrationAge(activeFederation) && hasMinimumFundsToMigrate(retiringFederationWallet)) {
        logger.info("Active federation (age={}) is in migration age and retiring federation has funds to migrate: {}.", rskExecutionBlock.getNumber() - activeFederation.getCreationBlockNumber(), retiringFederationWallet.getBalance().toFriendlyString());
        Pair<BtcTransaction, List<UTXO>> createResult = createMigrationTransaction(retiringFederationWallet, activeFederation.getAddress());
        BtcTransaction btcTx = createResult.getLeft();
        List<UTXO> selectedUTXOs = createResult.getRight();
        // Add the TX to the release set
        if (activations.isActive(ConsensusRule.RSKIP146)) {
            Coin amountMigrated = selectedUTXOs.stream().map(UTXO::getValue).reduce(Coin.ZERO, Coin::add);
            releaseTransactionSet.add(btcTx, rskExecutionBlock.getNumber(), rskTx.getHash());
            // Log the Release request
            eventLogger.logReleaseBtcRequested(rskTx.getHash().getBytes(), btcTx, amountMigrated);
        } else {
            releaseTransactionSet.add(btcTx, rskExecutionBlock.getNumber());
        }
        // Mark UTXOs as spent
        availableUTXOs.removeIf(utxo -> selectedUTXOs.stream().anyMatch(selectedUtxo -> utxo.getHash().equals(selectedUtxo.getHash()) && utxo.getIndex() == selectedUtxo.getIndex()));
    }
    if (retiringFederationWallet != null && federationIsPastMigrationAge(activeFederation)) {
        if (retiringFederationWallet.getBalance().isGreaterThan(Coin.ZERO)) {
            logger.info("Federation is past migration age and will try to migrate remaining balance: {}.", retiringFederationWallet.getBalance().toFriendlyString());
            try {
                Pair<BtcTransaction, List<UTXO>> createResult = createMigrationTransaction(retiringFederationWallet, activeFederation.getAddress());
                BtcTransaction btcTx = createResult.getLeft();
                List<UTXO> selectedUTXOs = createResult.getRight();
                // Add the TX to the release set
                if (activations.isActive(ConsensusRule.RSKIP146)) {
                    Coin amountMigrated = selectedUTXOs.stream().map(UTXO::getValue).reduce(Coin.ZERO, Coin::add);
                    releaseTransactionSet.add(btcTx, rskExecutionBlock.getNumber(), rskTx.getHash());
                    // Log the Release request
                    eventLogger.logReleaseBtcRequested(rskTx.getHash().getBytes(), btcTx, amountMigrated);
                } else {
                    releaseTransactionSet.add(btcTx, rskExecutionBlock.getNumber());
                }
                // Mark UTXOs as spent
                availableUTXOs.removeIf(utxo -> selectedUTXOs.stream().anyMatch(selectedUtxo -> utxo.getHash().equals(selectedUtxo.getHash()) && utxo.getIndex() == selectedUtxo.getIndex()));
            } catch (Exception e) {
                logger.error("Unable to complete retiring federation migration. Balance left: {} in {}", retiringFederationWallet.getBalance().toFriendlyString(), getRetiringFederationAddress());
                panicProcessor.panic("updateCollection", "Unable to complete retiring federation migration.");
            }
        }
        logger.info("Retiring federation migration finished. Available UTXOs left: {}.", availableUTXOs.size());
        provider.setOldFederation(null);
    }
}
Also used : OneOffWhiteListEntry(co.rsk.peg.whitelist.OneOffWhiteListEntry) Arrays(java.util.Arrays) VMException(org.ethereum.vm.exception.VMException) BtcLockSenderProvider(co.rsk.peg.btcLockSender.BtcLockSenderProvider) Address(co.rsk.bitcoinj.core.Address) LoggerFactory(org.slf4j.LoggerFactory) RskAddress(co.rsk.core.RskAddress) UTXOProviderException(co.rsk.bitcoinj.core.UTXOProviderException) TxSenderAddressType(co.rsk.peg.btcLockSender.BtcLockSender.TxSenderAddressType) Keccak256(co.rsk.crypto.Keccak256) RSKIP219(org.ethereum.config.blockchain.upgrades.ConsensusRule.RSKIP219) Sha256Hash(co.rsk.bitcoinj.core.Sha256Hash) ActivationConfig(org.ethereum.config.blockchain.upgrades.ActivationConfig) TransactionSignature(co.rsk.bitcoinj.crypto.TransactionSignature) Context(co.rsk.bitcoinj.core.Context) Pair(org.apache.commons.lang3.tuple.Pair) BtcBlockChain(co.rsk.bitcoinj.core.BtcBlockChain) Map(java.util.Map) BigInteger(java.math.BigInteger) PrecompiledContracts(org.ethereum.vm.PrecompiledContracts) RSKIP186(org.ethereum.config.blockchain.upgrades.ConsensusRule.RSKIP186) MerkleBranch(co.rsk.peg.bitcoin.MerkleBranch) Wallet(co.rsk.bitcoinj.wallet.Wallet) Coin(co.rsk.bitcoinj.core.Coin) TransactionOutput(co.rsk.bitcoinj.core.TransactionOutput) FastBridgeRedeemScriptParser(co.rsk.bitcoinj.script.FastBridgeRedeemScriptParser) Set(java.util.Set) CallType(co.rsk.rpc.modules.trace.CallType) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Repository(org.ethereum.core.Repository) TransactionInput(co.rsk.bitcoinj.core.TransactionInput) Objects(java.util.Objects) ScriptBuilder(co.rsk.bitcoinj.script.ScriptBuilder) Script(co.rsk.bitcoinj.script.Script) List(java.util.List) VerificationException(co.rsk.bitcoinj.core.VerificationException) Optional(java.util.Optional) UTXO(co.rsk.bitcoinj.core.UTXO) BtcBlock(co.rsk.bitcoinj.core.BtcBlock) LockWhitelistEntry(co.rsk.peg.whitelist.LockWhitelistEntry) CheckpointManager(co.rsk.bitcoinj.core.CheckpointManager) NetworkParameters(co.rsk.bitcoinj.core.NetworkParameters) co.rsk.peg.utils(co.rsk.peg.utils) ProgramSubtrace(co.rsk.rpc.modules.trace.ProgramSubtrace) PeginInstructionsProvider(co.rsk.peg.pegininstructions.PeginInstructionsProvider) ArrayList(java.util.ArrayList) Hex(org.bouncycastle.util.encoders.Hex) Block(org.ethereum.core.Block) BridgeUtils.getRegularPegoutTxSize(co.rsk.peg.BridgeUtils.getRegularPegoutTxSize) InsufficientMoneyException(co.rsk.bitcoinj.core.InsufficientMoneyException) BridgeConstants(co.rsk.config.BridgeConstants) Nullable(javax.annotation.Nullable) AddressFormatException(co.rsk.bitcoinj.core.AddressFormatException) BtcECKey(co.rsk.bitcoinj.core.BtcECKey) PanicProcessor(co.rsk.panic.PanicProcessor) FastBridgeFederationInformation(co.rsk.peg.fastbridge.FastBridgeFederationInformation) ScriptChunk(co.rsk.bitcoinj.script.ScriptChunk) Logger(org.slf4j.Logger) CoinbaseInformation(co.rsk.peg.bitcoin.CoinbaseInformation) HashUtil(org.ethereum.crypto.HashUtil) DataWord(org.ethereum.vm.DataWord) IOException(java.io.IOException) LockWhitelist(co.rsk.peg.whitelist.LockWhitelist) SendRequest(co.rsk.bitcoinj.wallet.SendRequest) BtcTransaction(co.rsk.bitcoinj.core.BtcTransaction) Program(org.ethereum.vm.program.Program) UnlimitedWhiteListEntry(co.rsk.peg.whitelist.UnlimitedWhiteListEntry) BlockStoreException(co.rsk.bitcoinj.store.BlockStoreException) PartialMerkleTree(co.rsk.bitcoinj.core.PartialMerkleTree) ByteUtil(org.ethereum.util.ByteUtil) InternalTransaction(org.ethereum.vm.program.InternalTransaction) PeginInstructionsException(co.rsk.peg.pegininstructions.PeginInstructionsException) RskAllowUnconfirmedCoinSelector(co.rsk.peg.bitcoin.RskAllowUnconfirmedCoinSelector) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ProgramResult(org.ethereum.vm.program.ProgramResult) StoredBlock(co.rsk.bitcoinj.core.StoredBlock) Transaction(org.ethereum.core.Transaction) Collections(java.util.Collections) ConsensusRule(org.ethereum.config.blockchain.upgrades.ConsensusRule) TransferInvoke(org.ethereum.vm.program.invoke.TransferInvoke) InputStream(java.io.InputStream) ECKey(org.ethereum.crypto.ECKey) UTXO(co.rsk.bitcoinj.core.UTXO) Coin(co.rsk.bitcoinj.core.Coin) Wallet(co.rsk.bitcoinj.wallet.Wallet) BtcTransaction(co.rsk.bitcoinj.core.BtcTransaction) List(java.util.List) ArrayList(java.util.ArrayList) VMException(org.ethereum.vm.exception.VMException) UTXOProviderException(co.rsk.bitcoinj.core.UTXOProviderException) VerificationException(co.rsk.bitcoinj.core.VerificationException) InsufficientMoneyException(co.rsk.bitcoinj.core.InsufficientMoneyException) AddressFormatException(co.rsk.bitcoinj.core.AddressFormatException) IOException(java.io.IOException) BlockStoreException(co.rsk.bitcoinj.store.BlockStoreException) PeginInstructionsException(co.rsk.peg.pegininstructions.PeginInstructionsException)

Example 28 with Wallet

use of co.rsk.bitcoinj.wallet.Wallet in project rskj by rsksmart.

the class BridgeSupport method getFastBridgeWallet.

protected Wallet getFastBridgeWallet(Context btcContext, List<UTXO> utxos, FastBridgeFederationInformation fb) {
    Wallet wallet = new FastBridgeCompatibleBtcWalletWithSingleScript(btcContext, getLiveFederations(), fb);
    RskUTXOProvider utxoProvider = new RskUTXOProvider(btcContext.getParams(), utxos);
    wallet.setUTXOProvider(utxoProvider);
    wallet.setCoinSelector(new RskAllowUnconfirmedCoinSelector());
    return wallet;
}
Also used : Wallet(co.rsk.bitcoinj.wallet.Wallet) RskAllowUnconfirmedCoinSelector(co.rsk.peg.bitcoin.RskAllowUnconfirmedCoinSelector)

Example 29 with Wallet

use of co.rsk.bitcoinj.wallet.Wallet in project rskj by rsksmart.

the class BridgeSupport method createMigrationTransaction.

private Pair<BtcTransaction, List<UTXO>> createMigrationTransaction(Wallet originWallet, Address destinationAddress) {
    Coin expectedMigrationValue = originWallet.getBalance();
    logger.debug("[createMigrationTransaction] Balance to migrate: {}", expectedMigrationValue);
    for (; ; ) {
        BtcTransaction migrationBtcTx = new BtcTransaction(originWallet.getParams());
        migrationBtcTx.addOutput(expectedMigrationValue, destinationAddress);
        SendRequest sr = SendRequest.forTx(migrationBtcTx);
        sr.changeAddress = destinationAddress;
        sr.feePerKb = getFeePerKb();
        sr.missingSigsMode = Wallet.MissingSigsMode.USE_OP_ZERO;
        sr.recipientsPayFees = true;
        try {
            originWallet.completeTx(sr);
            for (TransactionInput transactionInput : migrationBtcTx.getInputs()) {
                transactionInput.disconnect();
            }
            List<UTXO> selectedUTXOs = originWallet.getUTXOProvider().getOpenTransactionOutputs(originWallet.getWatchedAddresses()).stream().filter(utxo -> migrationBtcTx.getInputs().stream().anyMatch(input -> input.getOutpoint().getHash().equals(utxo.getHash()) && input.getOutpoint().getIndex() == utxo.getIndex())).collect(Collectors.toList());
            return Pair.of(migrationBtcTx, selectedUTXOs);
        } catch (InsufficientMoneyException | Wallet.ExceededMaxTransactionSize | Wallet.CouldNotAdjustDownwards e) {
            expectedMigrationValue = expectedMigrationValue.divide(2);
        } catch (Wallet.DustySendRequested e) {
            throw new IllegalStateException("Retiring federation wallet cannot be emptied", e);
        } catch (UTXOProviderException e) {
            throw new RuntimeException("Unexpected UTXO provider error", e);
        }
    }
}
Also used : OneOffWhiteListEntry(co.rsk.peg.whitelist.OneOffWhiteListEntry) Arrays(java.util.Arrays) VMException(org.ethereum.vm.exception.VMException) BtcLockSenderProvider(co.rsk.peg.btcLockSender.BtcLockSenderProvider) Address(co.rsk.bitcoinj.core.Address) LoggerFactory(org.slf4j.LoggerFactory) RskAddress(co.rsk.core.RskAddress) UTXOProviderException(co.rsk.bitcoinj.core.UTXOProviderException) TxSenderAddressType(co.rsk.peg.btcLockSender.BtcLockSender.TxSenderAddressType) Keccak256(co.rsk.crypto.Keccak256) RSKIP219(org.ethereum.config.blockchain.upgrades.ConsensusRule.RSKIP219) Sha256Hash(co.rsk.bitcoinj.core.Sha256Hash) ActivationConfig(org.ethereum.config.blockchain.upgrades.ActivationConfig) TransactionSignature(co.rsk.bitcoinj.crypto.TransactionSignature) Context(co.rsk.bitcoinj.core.Context) Pair(org.apache.commons.lang3.tuple.Pair) BtcBlockChain(co.rsk.bitcoinj.core.BtcBlockChain) Map(java.util.Map) BigInteger(java.math.BigInteger) PrecompiledContracts(org.ethereum.vm.PrecompiledContracts) RSKIP186(org.ethereum.config.blockchain.upgrades.ConsensusRule.RSKIP186) MerkleBranch(co.rsk.peg.bitcoin.MerkleBranch) Wallet(co.rsk.bitcoinj.wallet.Wallet) Coin(co.rsk.bitcoinj.core.Coin) TransactionOutput(co.rsk.bitcoinj.core.TransactionOutput) FastBridgeRedeemScriptParser(co.rsk.bitcoinj.script.FastBridgeRedeemScriptParser) Set(java.util.Set) CallType(co.rsk.rpc.modules.trace.CallType) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Repository(org.ethereum.core.Repository) TransactionInput(co.rsk.bitcoinj.core.TransactionInput) Objects(java.util.Objects) ScriptBuilder(co.rsk.bitcoinj.script.ScriptBuilder) Script(co.rsk.bitcoinj.script.Script) List(java.util.List) VerificationException(co.rsk.bitcoinj.core.VerificationException) Optional(java.util.Optional) UTXO(co.rsk.bitcoinj.core.UTXO) BtcBlock(co.rsk.bitcoinj.core.BtcBlock) LockWhitelistEntry(co.rsk.peg.whitelist.LockWhitelistEntry) CheckpointManager(co.rsk.bitcoinj.core.CheckpointManager) NetworkParameters(co.rsk.bitcoinj.core.NetworkParameters) co.rsk.peg.utils(co.rsk.peg.utils) ProgramSubtrace(co.rsk.rpc.modules.trace.ProgramSubtrace) PeginInstructionsProvider(co.rsk.peg.pegininstructions.PeginInstructionsProvider) ArrayList(java.util.ArrayList) Hex(org.bouncycastle.util.encoders.Hex) Block(org.ethereum.core.Block) BridgeUtils.getRegularPegoutTxSize(co.rsk.peg.BridgeUtils.getRegularPegoutTxSize) InsufficientMoneyException(co.rsk.bitcoinj.core.InsufficientMoneyException) BridgeConstants(co.rsk.config.BridgeConstants) Nullable(javax.annotation.Nullable) AddressFormatException(co.rsk.bitcoinj.core.AddressFormatException) BtcECKey(co.rsk.bitcoinj.core.BtcECKey) PanicProcessor(co.rsk.panic.PanicProcessor) FastBridgeFederationInformation(co.rsk.peg.fastbridge.FastBridgeFederationInformation) ScriptChunk(co.rsk.bitcoinj.script.ScriptChunk) Logger(org.slf4j.Logger) CoinbaseInformation(co.rsk.peg.bitcoin.CoinbaseInformation) HashUtil(org.ethereum.crypto.HashUtil) DataWord(org.ethereum.vm.DataWord) IOException(java.io.IOException) LockWhitelist(co.rsk.peg.whitelist.LockWhitelist) SendRequest(co.rsk.bitcoinj.wallet.SendRequest) BtcTransaction(co.rsk.bitcoinj.core.BtcTransaction) Program(org.ethereum.vm.program.Program) UnlimitedWhiteListEntry(co.rsk.peg.whitelist.UnlimitedWhiteListEntry) BlockStoreException(co.rsk.bitcoinj.store.BlockStoreException) PartialMerkleTree(co.rsk.bitcoinj.core.PartialMerkleTree) ByteUtil(org.ethereum.util.ByteUtil) InternalTransaction(org.ethereum.vm.program.InternalTransaction) PeginInstructionsException(co.rsk.peg.pegininstructions.PeginInstructionsException) RskAllowUnconfirmedCoinSelector(co.rsk.peg.bitcoin.RskAllowUnconfirmedCoinSelector) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ProgramResult(org.ethereum.vm.program.ProgramResult) StoredBlock(co.rsk.bitcoinj.core.StoredBlock) Transaction(org.ethereum.core.Transaction) Collections(java.util.Collections) ConsensusRule(org.ethereum.config.blockchain.upgrades.ConsensusRule) TransferInvoke(org.ethereum.vm.program.invoke.TransferInvoke) InputStream(java.io.InputStream) ECKey(org.ethereum.crypto.ECKey) SendRequest(co.rsk.bitcoinj.wallet.SendRequest) Wallet(co.rsk.bitcoinj.wallet.Wallet) BtcTransaction(co.rsk.bitcoinj.core.BtcTransaction) InsufficientMoneyException(co.rsk.bitcoinj.core.InsufficientMoneyException) TransactionInput(co.rsk.bitcoinj.core.TransactionInput) Coin(co.rsk.bitcoinj.core.Coin) UTXO(co.rsk.bitcoinj.core.UTXO) UTXOProviderException(co.rsk.bitcoinj.core.UTXOProviderException)

Aggregations

Wallet (co.rsk.bitcoinj.wallet.Wallet)29 Test (org.junit.Test)11 Script (co.rsk.bitcoinj.script.Script)8 RskAddress (co.rsk.core.RskAddress)7 RskAllowUnconfirmedCoinSelector (co.rsk.peg.bitcoin.RskAllowUnconfirmedCoinSelector)7 Keccak256 (co.rsk.crypto.Keccak256)6 Context (co.rsk.bitcoinj.core.Context)5 SendRequest (co.rsk.bitcoinj.wallet.SendRequest)5 BridgeConstants (co.rsk.config.BridgeConstants)5 IOException (java.io.IOException)5 Block (org.ethereum.core.Block)5 Repository (org.ethereum.core.Repository)5 Address (co.rsk.bitcoinj.core.Address)4 BtcTransaction (co.rsk.bitcoinj.core.BtcTransaction)4 Coin (co.rsk.bitcoinj.core.Coin)4 TransactionSignature (co.rsk.bitcoinj.crypto.TransactionSignature)4 ScriptBuilder (co.rsk.bitcoinj.script.ScriptBuilder)4 ScriptChunk (co.rsk.bitcoinj.script.ScriptChunk)4 BlockStoreException (co.rsk.bitcoinj.store.BlockStoreException)4 PanicProcessor (co.rsk.panic.PanicProcessor)4