Search in sources :

Example 16 with Coin

use of co.rsk.bitcoinj.core.Coin in project rskj by rsksmart.

the class BridgeSupport method adjustBalancesIfChangeOutputWasDust.

/**
 * If federation change output value had to be increased to be non-dust, the federation now has
 * more BTC than it should. So, we burn some sBTC to make balances match.
 *
 * @param btcTx      The btc tx that was just completed
 * @param sentByUser The number of sBTC originaly sent by the user
 */
private void adjustBalancesIfChangeOutputWasDust(BtcTransaction btcTx, Coin sentByUser) {
    if (btcTx.getOutputs().size() <= 1) {
        // If there is no change, do-nothing
        return;
    }
    Coin sumInputs = Coin.ZERO;
    for (TransactionInput transactionInput : btcTx.getInputs()) {
        sumInputs = sumInputs.add(transactionInput.getValue());
    }
    Coin change = btcTx.getOutput(1).getValue();
    Coin spentByFederation = sumInputs.subtract(change);
    if (spentByFederation.isLessThan(sentByUser)) {
        Coin coinsToBurn = sentByUser.subtract(spentByFederation);
        this.transferTo(BURN_ADDRESS, co.rsk.core.Coin.fromBitcoin(coinsToBurn));
    }
}
Also used : Coin(co.rsk.bitcoinj.core.Coin) TransactionInput(co.rsk.bitcoinj.core.TransactionInput)

Example 17 with Coin

use of co.rsk.bitcoinj.core.Coin 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)

Example 18 with Coin

use of co.rsk.bitcoinj.core.Coin in project rskj by rsksmart.

the class VoteFeePerKbChangeTest method voteFeePerKbChange_unauthorized.

@Test
public void voteFeePerKbChange_unauthorized() throws VMException {
    BridgeStorageProviderInitializer storageInitializer = Helper.buildNoopInitializer();
    Coin genesisFeePerKB = BridgeRegTestConstants.getInstance().getGenesisFeePerKb();
    ABIEncoder abiEncoder = (int executionIndex) -> Bridge.VOTE_FEE_PER_KB.encode(BigInteger.valueOf(Helper.randomCoin(Coin.MILLICOIN, 1, 100).getValue()));
    TxBuilder txBuilder = (int executionIndex) -> {
        String generator = "unauthorized";
        ECKey sender = ECKey.fromPrivate(HashUtil.keccak256(generator.getBytes(StandardCharsets.UTF_8)));
        return Helper.buildTx(sender);
    };
    ExecutionStats stats = new ExecutionStats("voteFeePerKbChange_unauthorized");
    executeAndAverage("voteFeePerKbChange_unauthorized", 1000, abiEncoder, storageInitializer, txBuilder, Helper.getRandomHeightProvider(10), stats, ((environment, callResult) -> {
        Assert.assertEquals(genesisFeePerKB.getValue(), ((Bridge) environment.getContract()).getFeePerKb(null));
    }));
    BridgePerformanceTest.addStats(stats);
}
Also used : Coin(co.rsk.bitcoinj.core.Coin) VMException(org.ethereum.vm.exception.VMException) Ignore(org.junit.Ignore) HashUtil(org.ethereum.crypto.HashUtil) Test(org.junit.Test) BigInteger(java.math.BigInteger) BridgeRegTestConstants(co.rsk.config.BridgeRegTestConstants) Assert(org.junit.Assert) AtomicReference(java.util.concurrent.atomic.AtomicReference) Bridge(co.rsk.peg.Bridge) StandardCharsets(java.nio.charset.StandardCharsets) ECKey(org.ethereum.crypto.ECKey) Coin(co.rsk.bitcoinj.core.Coin) ECKey(org.ethereum.crypto.ECKey) Bridge(co.rsk.peg.Bridge) Test(org.junit.Test)

Example 19 with Coin

use of co.rsk.bitcoinj.core.Coin in project rskj by rsksmart.

the class ReleaseBtcTest method releaseBtc.

@Test
public void releaseBtc() throws IOException {
    int minCentsBtc = 5;
    int maxCentsBtc = 100;
    final NetworkParameters parameters = NetworkParameters.fromID(NetworkParameters.ID_REGTEST);
    BridgeStorageProviderInitializer storageInitializer = (BridgeStorageProvider provider, Repository repository, int executionIndex) -> {
        ReleaseRequestQueue queue;
        try {
            queue = provider.getReleaseRequestQueue();
        } catch (Exception e) {
            throw new RuntimeException("Unable to gather release request queue");
        }
        for (int i = 0; i < Helper.randomInRange(10, 100); i++) {
            Coin value = Coin.CENT.multiply(Helper.randomInRange(minCentsBtc, maxCentsBtc));
            queue.add(new BtcECKey().toAddress(parameters), value);
        }
    };
    final byte[] releaseBtcEncoded = Bridge.RELEASE_BTC.encode();
    ABIEncoder abiEncoder = (int executionIndex) -> releaseBtcEncoded;
    TxBuilder txBuilder = (int executionIndex) -> {
        long satoshis = Coin.CENT.multiply(Helper.randomInRange(minCentsBtc, maxCentsBtc)).getValue();
        BigInteger weis = Denomination.satoshisToWeis(BigInteger.valueOf(satoshis));
        ECKey sender = new ECKey();
        return Helper.buildSendValueTx(sender, weis);
    };
    ExecutionStats stats = new ExecutionStats("releaseBtc");
    executeAndAverage("releaseBtc", 1000, abiEncoder, storageInitializer, txBuilder, Helper.getRandomHeightProvider(10), stats);
    BridgePerformanceTest.addStats(stats);
}
Also used : NetworkParameters(co.rsk.bitcoinj.core.NetworkParameters) BridgeStorageProvider(co.rsk.peg.BridgeStorageProvider) BtcECKey(co.rsk.bitcoinj.core.BtcECKey) ECKey(org.ethereum.crypto.ECKey) ReleaseRequestQueue(co.rsk.peg.ReleaseRequestQueue) BtcECKey(co.rsk.bitcoinj.core.BtcECKey) IOException(java.io.IOException) Coin(co.rsk.bitcoinj.core.Coin) Repository(org.ethereum.core.Repository) BigInteger(java.math.BigInteger) Test(org.junit.Test)

Aggregations

Coin (co.rsk.bitcoinj.core.Coin)19 BtcTransaction (co.rsk.bitcoinj.core.BtcTransaction)7 Address (co.rsk.bitcoinj.core.Address)6 Context (co.rsk.bitcoinj.core.Context)6 Script (co.rsk.bitcoinj.script.Script)6 RskAddress (co.rsk.core.RskAddress)6 Test (org.junit.Test)6 AddressFormatException (co.rsk.bitcoinj.core.AddressFormatException)4 NetworkParameters (co.rsk.bitcoinj.core.NetworkParameters)4 TransactionInput (co.rsk.bitcoinj.core.TransactionInput)4 Wallet (co.rsk.bitcoinj.wallet.Wallet)4 IOException (java.io.IOException)4 BigInteger (java.math.BigInteger)4 ActivationConfigsForTest (org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest)4 ECKey (org.ethereum.crypto.ECKey)4 VMException (org.ethereum.vm.exception.VMException)4 BtcECKey (co.rsk.bitcoinj.core.BtcECKey)3 InsufficientMoneyException (co.rsk.bitcoinj.core.InsufficientMoneyException)3 Sha256Hash (co.rsk.bitcoinj.core.Sha256Hash)3 UTXOProviderException (co.rsk.bitcoinj.core.UTXOProviderException)3