Search in sources :

Example 6 with BtcBlockStore

use of co.rsk.bitcoinj.store.BtcBlockStore in project rskj by rsksmart.

the class BridgeSupport method registerBtcTransaction.

/**
 * In case of a lock tx: Transfers some SBTCs to the sender of the btc tx and keeps track of the new UTXOs available for spending.
 * In case of a release tx: Keeps track of the change UTXOs, now available for spending.
 * @param btcTx The bitcoin transaction
 * @param height The height of the bitcoin block that contains the tx
 * @param pmt Partial Merklee Tree that proves the tx is included in the btc block
 * @throws BlockStoreException
 * @throws IOException
 */
public void registerBtcTransaction(Transaction rskTx, BtcTransaction btcTx, int height, PartialMerkleTree pmt) throws BlockStoreException, IOException {
    Context.propagate(btcContext);
    Federation federation = getActiveFederation();
    // Check the tx was not already processed
    if (provider.getBtcTxHashesAlreadyProcessed().keySet().contains(btcTx.getHash())) {
        logger.warn("Supplied tx was already processed");
        return;
    }
    // Check the tx is in the partial merkle tree
    List<Sha256Hash> hashesInPmt = new ArrayList<>();
    Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashesInPmt);
    if (!hashesInPmt.contains(btcTx.getHash())) {
        logger.warn("Supplied tx is not in the supplied partial merkle tree");
        panicProcessor.panic("btclock", "Supplied tx is not in the supplied partial merkle tree");
        return;
    }
    if (height < 0) {
        logger.warn("Height is " + height + " but should be greater than 0");
        panicProcessor.panic("btclock", "Height is " + height + " but should be greater than 0");
        return;
    }
    // Check there are at least N blocks on top of the supplied height
    int headHeight = btcBlockChain.getBestChainHeight();
    if ((headHeight - height + 1) < bridgeConstants.getBtc2RskMinimumAcceptableConfirmations()) {
        logger.warn("At least " + bridgeConstants.getBtc2RskMinimumAcceptableConfirmations() + " confirmations are required, but there are only " + (headHeight - height) + " confirmations");
        return;
    }
    // Check the the merkle root equals merkle root of btc block at specified height in the btc best chain
    BtcBlock blockHeader = BridgeUtils.getStoredBlockAtHeight(btcBlockStore, height).getHeader();
    if (!blockHeader.getMerkleRoot().equals(merkleRoot)) {
        logger.warn("Supplied merkle root " + merkleRoot + "does not match block's merkle root " + blockHeader.getMerkleRoot());
        panicProcessor.panic("btclock", "Supplied merkle root " + merkleRoot + "does not match block's merkle root " + blockHeader.getMerkleRoot());
        return;
    }
    // Checks the transaction contents for sanity
    btcTx.verify();
    if (btcTx.getInputs().isEmpty()) {
        logger.warn("Tx has no inputs " + btcTx);
        panicProcessor.panic("btclock", "Tx has no inputs " + btcTx);
        return;
    }
    boolean locked = true;
    // Specific code for lock/release/none txs
    if (BridgeUtils.isLockTx(btcTx, getLiveFederations(), btcContext, bridgeConstants)) {
        logger.debug("This is a lock tx {}", btcTx);
        Script scriptSig = btcTx.getInput(0).getScriptSig();
        if (scriptSig.getChunks().size() != 2) {
            logger.warn("First input does not spend a Pay-to-PubkeyHash " + btcTx.getInput(0));
            panicProcessor.panic("btclock", "First input does not spend a Pay-to-PubkeyHash " + btcTx.getInput(0));
            return;
        }
        // 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());
        Coin amountToRetiring = Coin.ZERO;
        Wallet retiringFederationWallet = getRetiringFederationWallet();
        if (retiringFederationWallet != null) {
            amountToRetiring = btcTx.getValueSentToMe(retiringFederationWallet);
        }
        Coin totalAmount = amountToActive.add(amountToRetiring);
        // Get the sender public key
        byte[] data = scriptSig.getChunks().get(1).data;
        // Tx is a lock tx, check whether the sender is whitelisted
        BtcECKey senderBtcKey = BtcECKey.fromPublicOnly(data);
        Address senderBtcAddress = new Address(btcContext.getParams(), senderBtcKey.getPubKeyHash());
        // If the address is not whitelisted, then return the funds
        // using the exact same utxos sent to us.
        // That is, build a release transaction and get it in the release transaction set.
        // Otherwise, transfer SBTC to the sender of the BTC
        // The RSK account to update is the one that matches the pubkey "spent" on the first bitcoin tx input
        LockWhitelist lockWhitelist = provider.getLockWhitelist();
        if (!lockWhitelist.isWhitelistedFor(senderBtcAddress, totalAmount, height)) {
            locked = false;
            // Build the list of UTXOs in the BTC transaction sent to either the active
            // or retiring federation
            List<UTXO> utxosToUs = btcTx.getWalletOutputs(getNoSpendWalletForLiveFederations()).stream().map(output -> new UTXO(btcTx.getHash(), output.getIndex(), output.getValue(), 0, btcTx.isCoinBase(), output.getScriptPubKey())).collect(Collectors.toList());
            // Use the list of UTXOs to build a transaction builder
            // for the return btc transaction generation
            ReleaseTransactionBuilder txBuilder = new ReleaseTransactionBuilder(btcContext.getParams(), getUTXOBasedWalletForLiveFederations(utxosToUs), senderBtcAddress, getFeePerKb());
            Optional<ReleaseTransactionBuilder.BuildResult> buildReturnResult = txBuilder.buildEmptyWalletTo(senderBtcAddress);
            if (buildReturnResult.isPresent()) {
                provider.getReleaseTransactionSet().add(buildReturnResult.get().getBtcTx(), rskExecutionBlock.getNumber());
                logger.info("whitelist money return tx build successful to {}. Tx {}. Value {}.", senderBtcAddress, rskTx, totalAmount);
            } else {
                logger.warn("whitelist money return tx build for btc tx {} error. Return was to {}. Tx {}. Value {}", btcTx.getHash(), senderBtcAddress, rskTx, totalAmount);
                panicProcessor.panic("whitelist-return-funds", String.format("whitelist money return tx build for btc tx {} error. Return was to {}. Tx {}. Value {}", btcTx.getHash(), senderBtcAddress, rskTx, totalAmount));
            }
        } else {
            org.ethereum.crypto.ECKey key = org.ethereum.crypto.ECKey.fromPublicOnly(data);
            RskAddress sender = new RskAddress(key.getAddress());
            rskRepository.transfer(PrecompiledContracts.BRIDGE_ADDR, sender, co.rsk.core.Coin.fromBitcoin(totalAmount));
            lockWhitelist.remove(senderBtcAddress);
        }
    } else if (BridgeUtils.isReleaseTx(btcTx, federation, bridgeConstants)) {
        logger.debug("This is a release tx {}", btcTx);
    // do-nothing
    // We could call removeUsedUTXOs(btcTx) here, but we decided to not do that.
    // Used utxos should had been removed when we created the release tx.
    // Invoking removeUsedUTXOs() here would make "some" sense in theses scenarios:
    // a) In testnet, devnet or local: we restart the RSK blockchain whithout changing the federation address. We don't want to have utxos that were already spent.
    // Open problem: TxA spends TxB. registerBtcTransaction() for TxB is called, it spends a utxo the bridge is not yet aware of,
    // so nothing is removed. Then registerBtcTransaction() for TxA and the "already spent" utxo is added as it was not spent.
    // When is not guaranteed to be called in the chronological order, so a Federator can inform
    // b) In prod: Federator created a tx manually or the federation was compromised and some utxos were spent. Better not try to spend them.
    // Open problem: For performance removeUsedUTXOs() just removes 1 utxo
    } else if (BridgeUtils.isMigrationTx(btcTx, getActiveFederation(), getRetiringFederation(), btcContext, bridgeConstants)) {
        logger.debug("This is a migration tx {}", btcTx);
    } else {
        logger.warn("This is not a lock, a release nor a migration tx {}", btcTx);
        panicProcessor.panic("btclock", "This is not a lock, a release nor a migration tx " + btcTx);
        return;
    }
    Sha256Hash btcTxHash = btcTx.getHash();
    // Mark tx as processed on this block
    provider.getBtcTxHashesAlreadyProcessed().put(btcTxHash, rskExecutionBlock.getNumber());
    // locked the funds.
    if (locked) {
        saveNewUTXOs(btcTx);
    }
    logger.info("BTC Tx {} processed in RSK", btcTxHash);
}
Also used : java.util(java.util) Hex(org.spongycastle.util.encoders.Hex) LoggerFactory(org.slf4j.LoggerFactory) RskAddress(co.rsk.core.RskAddress) Keccak256(co.rsk.crypto.Keccak256) Block(org.ethereum.core.Block) TransactionSignature(co.rsk.bitcoinj.crypto.TransactionSignature) Pair(org.apache.commons.lang3.tuple.Pair) BridgeConstants(co.rsk.config.BridgeConstants) co.rsk.bitcoinj.core(co.rsk.bitcoinj.core) PrecompiledContracts(org.ethereum.vm.PrecompiledContracts) BigInteger(java.math.BigInteger) Nullable(javax.annotation.Nullable) Wallet(co.rsk.bitcoinj.wallet.Wallet) BtcBlockStore(co.rsk.bitcoinj.store.BtcBlockStore) PanicProcessor(co.rsk.panic.PanicProcessor) ScriptChunk(co.rsk.bitcoinj.script.ScriptChunk) Logger(org.slf4j.Logger) IOException(java.io.IOException) Instant(java.time.Instant) Repository(org.ethereum.core.Repository) Collectors(java.util.stream.Collectors) SendRequest(co.rsk.bitcoinj.wallet.SendRequest) Program(org.ethereum.vm.program.Program) ScriptBuilder(co.rsk.bitcoinj.script.ScriptBuilder) Script(co.rsk.bitcoinj.script.Script) BlockStoreException(co.rsk.bitcoinj.store.BlockStoreException) VisibleForTesting(com.google.common.annotations.VisibleForTesting) RskSystemProperties(co.rsk.config.RskSystemProperties) BridgeEventLogger(co.rsk.peg.utils.BridgeEventLogger) Transaction(org.ethereum.core.Transaction) InputStream(java.io.InputStream) Script(co.rsk.bitcoinj.script.Script) RskAddress(co.rsk.core.RskAddress) Wallet(co.rsk.bitcoinj.wallet.Wallet) RskAddress(co.rsk.core.RskAddress)

Example 7 with BtcBlockStore

use of co.rsk.bitcoinj.store.BtcBlockStore in project rskj by rsksmart.

the class BridgeSupportTest method registerBtcTransactionTxNotLockNorReleaseTx.

@Test
public void registerBtcTransactionTxNotLockNorReleaseTx() throws BlockStoreException, AddressFormatException, IOException {
    Repository repository = new RepositoryImpl(config);
    Repository track = repository.startTracking();
    BridgeConstants bridgeConstants = config.getBlockchainConfig().getCommonConstants().getBridgeConstants();
    BtcTransaction tx = new BtcTransaction(this.btcParams);
    Address address = ScriptBuilder.createP2SHOutputScript(2, Lists.newArrayList(new BtcECKey(), new BtcECKey(), new BtcECKey())).getToAddress(bridgeConstants.getBtcParams());
    tx.addOutput(Coin.COIN, address);
    tx.addInput(PegTestUtils.createHash(), 0, ScriptBuilder.createInputScript(null, new BtcECKey()));
    Context btcContext = new Context(bridgeConstants.getBtcParams());
    BtcBlockStore btcBlockStore = new RepositoryBlockStore(config, track, PrecompiledContracts.BRIDGE_ADDR);
    BtcBlockChain btcBlockChain = new SimpleBlockChain(btcContext, btcBlockStore);
    BridgeStorageProvider provider = new BridgeStorageProvider(track, contractAddress, config.getBlockchainConfig().getCommonConstants().getBridgeConstants());
    BridgeSupport bridgeSupport = new BridgeSupport(config, track, null, config.getBlockchainConfig().getCommonConstants().getBridgeConstants(), provider, btcBlockStore, btcBlockChain);
    byte[] bits = new byte[1];
    bits[0] = 0x01;
    List<Sha256Hash> hashes = new ArrayList<>();
    hashes.add(tx.getHash());
    PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1);
    List<Sha256Hash> hashlist = new ArrayList<>();
    Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist);
    co.rsk.bitcoinj.core.BtcBlock block = new co.rsk.bitcoinj.core.BtcBlock(btcParams, 1, PegTestUtils.createHash(), merkleRoot, 1, 1, 1, new ArrayList<BtcTransaction>());
    btcBlockChain.add(block);
    bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx, 1, pmt);
    bridgeSupport.save();
    track.commit();
    BridgeStorageProvider provider2 = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, config.getBlockchainConfig().getCommonConstants().getBridgeConstants());
    Assert.assertEquals(0, provider2.getNewFederationBtcUTXOs().size());
    Assert.assertEquals(0, provider2.getReleaseRequestQueue().getEntries().size());
    Assert.assertEquals(0, provider2.getReleaseTransactionSet().getEntries().size());
    Assert.assertTrue(provider2.getRskTxsWaitingForSignatures().isEmpty());
    Assert.assertTrue(provider2.getBtcTxHashesAlreadyProcessed().isEmpty());
}
Also used : RskAddress(co.rsk.core.RskAddress) SimpleBlockChain(co.rsk.peg.simples.SimpleBlockChain) BridgeConstants(co.rsk.config.BridgeConstants) BtcBlockStore(co.rsk.bitcoinj.store.BtcBlockStore) co.rsk.bitcoinj.core(co.rsk.bitcoinj.core) org.ethereum.core(org.ethereum.core) SimpleRskTransaction(co.rsk.peg.simples.SimpleRskTransaction) RepositoryImpl(co.rsk.db.RepositoryImpl) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 8 with BtcBlockStore

use of co.rsk.bitcoinj.store.BtcBlockStore in project rskj by rsksmart.

the class BridgeSupportTest method registerBtcTransactionMigrationTx.

@Test
public void registerBtcTransactionMigrationTx() throws BlockStoreException, AddressFormatException, IOException {
    BridgeConstants bridgeConstants = BridgeRegTestConstants.getInstance();
    NetworkParameters parameters = bridgeConstants.getBtcParams();
    List<BtcECKey> activeFederationKeys = Stream.of(BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02"))).sorted(BtcECKey.PUBKEY_COMPARATOR).collect(Collectors.toList());
    Federation activeFederation = new Federation(activeFederationKeys, Instant.ofEpochMilli(2000L), 2L, parameters);
    List<BtcECKey> retiringFederationKeys = Stream.of(BtcECKey.fromPrivate(Hex.decode("fb01")), BtcECKey.fromPrivate(Hex.decode("fb02"))).sorted(BtcECKey.PUBKEY_COMPARATOR).collect(Collectors.toList());
    Federation retiringFederation = new Federation(retiringFederationKeys, Instant.ofEpochMilli(1000L), 1L, parameters);
    Repository repository = new RepositoryImpl(config);
    repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE);
    Block executionBlock = Mockito.mock(Block.class);
    Mockito.when(executionBlock.getNumber()).thenReturn(15L);
    Repository track = repository.startTracking();
    BtcTransaction tx = new BtcTransaction(parameters);
    Address activeFederationAddress = activeFederation.getAddress();
    tx.addOutput(Coin.COIN, activeFederationAddress);
    // Create previous tx
    BtcTransaction prevTx = new BtcTransaction(btcParams);
    TransactionOutput prevOut = new TransactionOutput(btcParams, prevTx, Coin.FIFTY_COINS, retiringFederation.getAddress());
    prevTx.addOutput(prevOut);
    // Create tx input
    tx.addInput(prevOut);
    // Create tx input base script sig
    Script scriptSig = PegTestUtils.createBaseInputScriptThatSpendsFromTheFederation(retiringFederation);
    // Create sighash
    Script redeemScript = ScriptBuilder.createRedeemScript(retiringFederation.getNumberOfSignaturesRequired(), retiringFederation.getPublicKeys());
    Sha256Hash sighash = tx.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false);
    // Sign by federator 0
    BtcECKey.ECDSASignature sig0 = retiringFederationKeys.get(0).sign(sighash);
    TransactionSignature txSig0 = new TransactionSignature(sig0, BtcTransaction.SigHash.ALL, false);
    int sigIndex0 = scriptSig.getSigInsertionIndex(sighash, retiringFederation.getPublicKeys().get(0));
    scriptSig = ScriptBuilder.updateScriptWithSignature(scriptSig, txSig0.encodeToBitcoin(), sigIndex0, 1, 1);
    // Sign by federator 1
    BtcECKey.ECDSASignature sig1 = retiringFederationKeys.get(1).sign(sighash);
    TransactionSignature txSig1 = new TransactionSignature(sig1, BtcTransaction.SigHash.ALL, false);
    int sigIndex1 = scriptSig.getSigInsertionIndex(sighash, retiringFederation.getPublicKeys().get(1));
    scriptSig = ScriptBuilder.updateScriptWithSignature(scriptSig, txSig1.encodeToBitcoin(), sigIndex1, 1, 1);
    // Set scipt sign to tx input
    tx.getInput(0).setScriptSig(scriptSig);
    Context btcContext = new Context(bridgeConstants.getBtcParams());
    BtcBlockStore btcBlockStore = new RepositoryBlockStore(config, track, PrecompiledContracts.BRIDGE_ADDR);
    BtcBlockChain btcBlockChain = new SimpleBlockChain(btcContext, btcBlockStore);
    BridgeStorageProvider provider = new BridgeStorageProvider(track, contractAddress, config.getBlockchainConfig().getCommonConstants().getBridgeConstants());
    provider.setNewFederation(activeFederation);
    provider.setOldFederation(retiringFederation);
    BridgeSupport bridgeSupport = new BridgeSupport(config, track, null, config.getBlockchainConfig().getCommonConstants().getBridgeConstants(), provider, btcBlockStore, btcBlockChain);
    Whitebox.setInternalState(bridgeSupport, "rskExecutionBlock", executionBlock);
    byte[] bits = new byte[1];
    bits[0] = 0x3f;
    List<Sha256Hash> hashes = new ArrayList<>();
    hashes.add(tx.getHash());
    PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 1);
    List<Sha256Hash> hashlist = new ArrayList<>();
    Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist);
    co.rsk.bitcoinj.core.BtcBlock block = new co.rsk.bitcoinj.core.BtcBlock(btcParams, 1, PegTestUtils.createHash(), merkleRoot, 1, 1, 1, new ArrayList<BtcTransaction>());
    btcBlockChain.add(block);
    ((SimpleBlockChain) btcBlockChain).useHighBlock();
    bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx, 1, pmt);
    bridgeSupport.save();
    ((SimpleBlockChain) btcBlockChain).useBlock();
    track.commit();
    List<UTXO> activeFederationBtcUTXOs = provider.getNewFederationBtcUTXOs();
    List<Coin> activeFederationBtcCoins = activeFederationBtcUTXOs.stream().map(UTXO::getValue).collect(Collectors.toList());
    assertThat(activeFederationBtcUTXOs, hasSize(1));
    assertThat(activeFederationBtcCoins, hasItem(Coin.COIN));
}
Also used : RskAddress(co.rsk.core.RskAddress) TransactionSignature(co.rsk.bitcoinj.crypto.TransactionSignature) SimpleBlockChain(co.rsk.peg.simples.SimpleBlockChain) BridgeConstants(co.rsk.config.BridgeConstants) Script(co.rsk.bitcoinj.script.Script) BtcBlockStore(co.rsk.bitcoinj.store.BtcBlockStore) co.rsk.bitcoinj.core(co.rsk.bitcoinj.core) org.ethereum.core(org.ethereum.core) SimpleRskTransaction(co.rsk.peg.simples.SimpleRskTransaction) RepositoryImpl(co.rsk.db.RepositoryImpl) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 9 with BtcBlockStore

use of co.rsk.bitcoinj.store.BtcBlockStore in project rskj by rsksmart.

the class BridgeSupportTest method registerBtcTransactionLockTxNotWhitelisted.

@Test
public void registerBtcTransactionLockTxNotWhitelisted() throws BlockStoreException, AddressFormatException, IOException {
    BridgeConstants bridgeConstants = config.getBlockchainConfig().getCommonConstants().getBridgeConstants();
    NetworkParameters parameters = bridgeConstants.getBtcParams();
    List<BtcECKey> federation1Keys = Arrays.asList(new BtcECKey[] { BtcECKey.fromPrivate(Hex.decode("fa01")), BtcECKey.fromPrivate(Hex.decode("fa02")) });
    federation1Keys.sort(BtcECKey.PUBKEY_COMPARATOR);
    Federation federation1 = new Federation(federation1Keys, Instant.ofEpochMilli(1000L), 0L, parameters);
    List<BtcECKey> federation2Keys = Arrays.asList(new BtcECKey[] { BtcECKey.fromPrivate(Hex.decode("fb01")), BtcECKey.fromPrivate(Hex.decode("fb02")), BtcECKey.fromPrivate(Hex.decode("fb03")) });
    federation2Keys.sort(BtcECKey.PUBKEY_COMPARATOR);
    Federation federation2 = new Federation(federation2Keys, Instant.ofEpochMilli(2000L), 0L, parameters);
    Repository repository = new RepositoryImpl(config);
    repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE);
    Block executionBlock = Mockito.mock(Block.class);
    Mockito.when(executionBlock.getNumber()).thenReturn(10L);
    Repository track = repository.startTracking();
    // First transaction goes only to the first federation
    BtcTransaction tx1 = new BtcTransaction(this.btcParams);
    tx1.addOutput(Coin.COIN.multiply(5), federation1.getAddress());
    BtcECKey srcKey1 = new BtcECKey();
    tx1.addInput(PegTestUtils.createHash(), 0, ScriptBuilder.createInputScript(null, srcKey1));
    // Second transaction goes only to the second federation
    BtcTransaction tx2 = new BtcTransaction(this.btcParams);
    tx2.addOutput(Coin.COIN.multiply(10), federation2.getAddress());
    BtcECKey srcKey2 = new BtcECKey();
    tx2.addInput(PegTestUtils.createHash(), 0, ScriptBuilder.createInputScript(null, srcKey2));
    // Third transaction has one output to each federation
    // Lock is expected to be done accordingly and utxos assigned accordingly as well
    BtcTransaction tx3 = new BtcTransaction(this.btcParams);
    tx3.addOutput(Coin.COIN.multiply(3), federation1.getAddress());
    tx3.addOutput(Coin.COIN.multiply(4), federation2.getAddress());
    BtcECKey srcKey3 = new BtcECKey();
    tx3.addInput(PegTestUtils.createHash(), 0, ScriptBuilder.createInputScript(null, srcKey3));
    Context btcContext = new Context(bridgeConstants.getBtcParams());
    BtcBlockStore btcBlockStore = new RepositoryBlockStore(config, track, PrecompiledContracts.BRIDGE_ADDR);
    BtcBlockChain btcBlockChain = new SimpleBlockChain(btcContext, btcBlockStore);
    BridgeStorageProvider provider = new BridgeStorageProvider(track, contractAddress, config.getBlockchainConfig().getCommonConstants().getBridgeConstants());
    provider.setNewFederation(federation1);
    provider.setOldFederation(federation2);
    BridgeSupport bridgeSupport = new BridgeSupport(config, track, null, config.getBlockchainConfig().getCommonConstants().getBridgeConstants(), provider, btcBlockStore, btcBlockChain);
    Whitebox.setInternalState(bridgeSupport, "rskExecutionBlock", executionBlock);
    byte[] bits = new byte[1];
    bits[0] = 0x3f;
    List<Sha256Hash> hashes = new ArrayList<>();
    hashes.add(tx1.getHash());
    hashes.add(tx2.getHash());
    hashes.add(tx3.getHash());
    PartialMerkleTree pmt = new PartialMerkleTree(btcParams, bits, hashes, 3);
    List<Sha256Hash> hashlist = new ArrayList<>();
    Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashlist);
    co.rsk.bitcoinj.core.BtcBlock block = new co.rsk.bitcoinj.core.BtcBlock(btcParams, 1, PegTestUtils.createHash(), merkleRoot, 1, 1, 1, new ArrayList<BtcTransaction>());
    btcBlockChain.add(block);
    Transaction rskTx1 = getMockedRskTxWithHash("aa");
    Transaction rskTx2 = getMockedRskTxWithHash("bb");
    Transaction rskTx3 = getMockedRskTxWithHash("cc");
    ((SimpleBlockChain) btcBlockChain).useHighBlock();
    bridgeSupport.registerBtcTransaction(rskTx1, tx1, 1, pmt);
    bridgeSupport.registerBtcTransaction(rskTx2, tx2, 1, pmt);
    bridgeSupport.registerBtcTransaction(rskTx3, tx3, 1, pmt);
    bridgeSupport.save();
    ((SimpleBlockChain) btcBlockChain).useBlock();
    track.commit();
    RskAddress srcKey1RskAddress = new RskAddress(org.ethereum.crypto.ECKey.fromPrivate(srcKey1.getPrivKey()).getAddress());
    RskAddress srcKey2RskAddress = new RskAddress(org.ethereum.crypto.ECKey.fromPrivate(srcKey2.getPrivKey()).getAddress());
    RskAddress srcKey3RskAddress = new RskAddress(org.ethereum.crypto.ECKey.fromPrivate(srcKey3.getPrivKey()).getAddress());
    Assert.assertEquals(0, repository.getBalance(srcKey1RskAddress).asBigInteger().intValue());
    Assert.assertEquals(0, repository.getBalance(srcKey2RskAddress).asBigInteger().intValue());
    Assert.assertEquals(0, repository.getBalance(srcKey3RskAddress).asBigInteger().intValue());
    Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR));
    BridgeStorageProvider provider2 = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, config.getBlockchainConfig().getCommonConstants().getBridgeConstants());
    Assert.assertEquals(0, provider2.getNewFederationBtcUTXOs().size());
    Assert.assertEquals(0, provider2.getOldFederationBtcUTXOs().size());
    Assert.assertEquals(0, provider2.getReleaseRequestQueue().getEntries().size());
    Assert.assertEquals(3, provider2.getReleaseTransactionSet().getEntries().size());
    List<BtcTransaction> releaseTxs = provider2.getReleaseTransactionSet().getEntries().stream().map(e -> e.getTransaction()).sorted(Comparator.comparing(BtcTransaction::getOutputSum)).collect(Collectors.toList());
    // First release tx should correspond to the 5 BTC lock tx
    BtcTransaction releaseTx = releaseTxs.get(0);
    Assert.assertEquals(1, releaseTx.getOutputs().size());
    Assert.assertThat(Coin.COIN.multiply(5).subtract(releaseTx.getOutput(0).getValue()), is(lessThanOrEqualTo(Coin.MILLICOIN)));
    Assert.assertEquals(srcKey1.toAddress(parameters), releaseTx.getOutput(0).getAddressFromP2PKHScript(parameters));
    Assert.assertEquals(1, releaseTx.getInputs().size());
    Assert.assertEquals(tx1.getHash(), releaseTx.getInput(0).getOutpoint().getHash());
    Assert.assertEquals(0, releaseTx.getInput(0).getOutpoint().getIndex());
    // Second release tx should correspond to the 7 (3+4) BTC lock tx
    releaseTx = releaseTxs.get(1);
    Assert.assertEquals(1, releaseTx.getOutputs().size());
    Assert.assertThat(Coin.COIN.multiply(7).subtract(releaseTx.getOutput(0).getValue()), is(lessThanOrEqualTo(Coin.MILLICOIN)));
    Assert.assertEquals(srcKey3.toAddress(parameters), releaseTx.getOutput(0).getAddressFromP2PKHScript(parameters));
    Assert.assertEquals(2, releaseTx.getInputs().size());
    List<TransactionOutPoint> releaseOutpoints = releaseTx.getInputs().stream().map(i -> i.getOutpoint()).sorted(Comparator.comparing(TransactionOutPoint::getIndex)).collect(Collectors.toList());
    Assert.assertEquals(tx3.getHash(), releaseOutpoints.get(0).getHash());
    Assert.assertEquals(tx3.getHash(), releaseOutpoints.get(1).getHash());
    Assert.assertEquals(0, releaseOutpoints.get(0).getIndex());
    Assert.assertEquals(1, releaseOutpoints.get(1).getIndex());
    // Third release tx should correspond to the 10 BTC lock tx
    releaseTx = releaseTxs.get(2);
    Assert.assertEquals(1, releaseTx.getOutputs().size());
    Assert.assertThat(Coin.COIN.multiply(10).subtract(releaseTx.getOutput(0).getValue()), is(lessThanOrEqualTo(Coin.MILLICOIN)));
    Assert.assertEquals(srcKey2.toAddress(parameters), releaseTx.getOutput(0).getAddressFromP2PKHScript(parameters));
    Assert.assertEquals(1, releaseTx.getInputs().size());
    Assert.assertEquals(tx2.getHash(), releaseTx.getInput(0).getOutpoint().getHash());
    Assert.assertEquals(0, releaseTx.getInput(0).getOutpoint().getIndex());
    Assert.assertTrue(provider2.getRskTxsWaitingForSignatures().isEmpty());
    Assert.assertEquals(3, provider2.getBtcTxHashesAlreadyProcessed().size());
}
Also used : SimpleBlockChain(co.rsk.peg.simples.SimpleBlockChain) RskAddress(co.rsk.core.RskAddress) BridgeConstants(co.rsk.config.BridgeConstants) BtcBlockStore(co.rsk.bitcoinj.store.BtcBlockStore) co.rsk.bitcoinj.core(co.rsk.bitcoinj.core) org.ethereum.core(org.ethereum.core) SimpleRskTransaction(co.rsk.peg.simples.SimpleRskTransaction) RepositoryImpl(co.rsk.db.RepositoryImpl) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 10 with BtcBlockStore

use of co.rsk.bitcoinj.store.BtcBlockStore in project rskj by rsksmart.

the class BtcBlockchainTest method buildInitializer.

private BridgeStorageProviderInitializer buildInitializer() {
    final int minBtcBlocks = 1000;
    final int maxBtcBlocks = 2000;
    return (BridgeStorageProvider provider, Repository repository, int executionIndex) -> {
        BtcBlockStore btcBlockStore = new RepositoryBlockStore(new RskSystemProperties(), repository, PrecompiledContracts.BRIDGE_ADDR);
        Context btcContext = new Context(networkParameters);
        BtcBlockChain btcBlockChain;
        try {
            btcBlockChain = new BtcBlockChain(btcContext, btcBlockStore);
        } catch (BlockStoreException e) {
            throw new RuntimeException("Error initializing btc blockchain for tests");
        }
        int blocksToGenerate = Helper.randomInRange(minBtcBlocks, maxBtcBlocks);
        Helper.generateAndAddBlocks(btcBlockChain, blocksToGenerate);
    };
}
Also used : Context(co.rsk.bitcoinj.core.Context) Repository(org.ethereum.core.Repository) BlockStoreException(co.rsk.bitcoinj.store.BlockStoreException) BridgeStorageProvider(co.rsk.peg.BridgeStorageProvider) RepositoryBlockStore(co.rsk.peg.RepositoryBlockStore) BtcBlockStore(co.rsk.bitcoinj.store.BtcBlockStore) BtcBlockChain(co.rsk.bitcoinj.core.BtcBlockChain) RskSystemProperties(co.rsk.config.RskSystemProperties)

Aggregations

BtcBlockStore (co.rsk.bitcoinj.store.BtcBlockStore)11 co.rsk.bitcoinj.core (co.rsk.bitcoinj.core)8 Test (org.junit.Test)8 BridgeConstants (co.rsk.config.BridgeConstants)7 RepositoryImpl (co.rsk.db.RepositoryImpl)7 org.ethereum.core (org.ethereum.core)7 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 RskAddress (co.rsk.core.RskAddress)6 SimpleBlockChain (co.rsk.peg.simples.SimpleBlockChain)6 SimpleRskTransaction (co.rsk.peg.simples.SimpleRskTransaction)5 BlockStoreException (co.rsk.bitcoinj.store.BlockStoreException)4 RskSystemProperties (co.rsk.config.RskSystemProperties)4 Repository (org.ethereum.core.Repository)4 TransactionSignature (co.rsk.bitcoinj.crypto.TransactionSignature)3 Script (co.rsk.bitcoinj.script.Script)3 BridgeStorageProvider (co.rsk.peg.BridgeStorageProvider)3 RepositoryBlockStore (co.rsk.peg.RepositoryBlockStore)3 BtcBlockChain (co.rsk.bitcoinj.core.BtcBlockChain)2 Context (co.rsk.bitcoinj.core.Context)2 BtcBlock (co.rsk.bitcoinj.core.BtcBlock)1