Search in sources :

Example 21 with NetworkParameters

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

the class BridgeTest method registerFastBridgeBtcTransaction_after_RSKIP176_activation_p2sh_refund_address_before_RSKIP284_activation_fails.

@Test
public void registerFastBridgeBtcTransaction_after_RSKIP176_activation_p2sh_refund_address_before_RSKIP284_activation_fails() throws VMException, IOException, BlockStoreException {
    NetworkParameters networkParameters = constants.getBridgeConstants().getBtcParams();
    doReturn(true).when(activationConfig).isActive(eq(RSKIP176), anyLong());
    doReturn(false).when(activationConfig).isActive(eq(RSKIP284), anyLong());
    BridgeSupport bridgeSupportMock = mock(BridgeSupport.class);
    Bridge bridge = getBridgeInstance(bridgeSupportMock);
    when(bridgeSupportMock.registerFastBridgeBtcTransaction(any(Transaction.class), any(byte[].class), anyInt(), any(byte[].class), any(Keccak256.class), any(Address.class), any(RskAddress.class), any(Address.class), anyBoolean())).thenReturn(BigInteger.valueOf(2));
    byte[] value = Sha256Hash.ZERO_HASH.getBytes();
    Address refundBtcAddress = Address.fromBase58(networkParameters, "2MyEXHyt2fXqdFm3r4xXEkTdbwdZm7qFiDP");
    byte[] refundBtcAddressBytes = BridgeUtils.serializeBtcAddressWithVersion(activationConfig.forBlock(anyLong()), refundBtcAddress);
    BtcECKey btcECKeyLp = new BtcECKey();
    Address lpBtcAddress = btcECKeyLp.toAddress(networkParameters);
    byte[] lpBtcAddressBytes = BridgeUtils.serializeBtcAddressWithVersion(activationConfig.forBlock(anyLong()), lpBtcAddress);
    ECKey ecKey = new ECKey();
    RskAddress rskAddress = new RskAddress(ecKey.getAddress());
    byte[] data = Bridge.REGISTER_FAST_BRIDGE_BTC_TRANSACTION.encode(value, 1, value, value, refundBtcAddressBytes, rskAddress.toHexString(), lpBtcAddressBytes, true);
    byte[] result = bridge.execute(data);
    // Assert
    assertEquals(BigInteger.valueOf(-900), Bridge.REGISTER_FAST_BRIDGE_BTC_TRANSACTION.decodeResult(result)[0]);
    verify(bridgeSupportMock, times(0)).registerFastBridgeBtcTransaction(any(Transaction.class), eq(value), eq(1), eq(value), eq(new Keccak256(value)), eq(refundBtcAddress), eq(rskAddress), eq(lpBtcAddress), eq(true));
}
Also used : CallTransaction(org.ethereum.core.CallTransaction) Transaction(org.ethereum.core.Transaction) Address(co.rsk.bitcoinj.core.Address) RskAddress(co.rsk.core.RskAddress) NetworkParameters(co.rsk.bitcoinj.core.NetworkParameters) RskAddress(co.rsk.core.RskAddress) BtcECKey(co.rsk.bitcoinj.core.BtcECKey) ECKey(org.ethereum.crypto.ECKey) Keccak256(co.rsk.crypto.Keccak256) BtcECKey(co.rsk.bitcoinj.core.BtcECKey) Test(org.junit.Test) ActivationConfigsForTest(org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest)

Example 22 with NetworkParameters

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

the class BridgeTest method receiveHeader_bridgeSupport_Exception.

@Test(expected = VMException.class)
public void receiveHeader_bridgeSupport_Exception() throws VMException, IOException, BlockStoreException {
    ActivationConfig activations = spy(ActivationConfigsForTest.genesis());
    doReturn(true).when(activations).isActive(eq(RSKIP200), anyLong());
    BridgeSupport bridgeSupportMock = mock(BridgeSupport.class);
    doThrow(new IOException()).when(bridgeSupportMock).receiveHeader(any());
    Bridge bridge = getBridgeInstance(bridgeSupportMock, activations);
    NetworkParameters networkParameters = constants.bridgeConstants.getBtcParams();
    co.rsk.bitcoinj.core.BtcBlock block = new co.rsk.bitcoinj.core.BtcBlock(networkParameters, 1, PegTestUtils.createHash(1), PegTestUtils.createHash(1), 1, Utils.encodeCompactBits(networkParameters.getMaxTarget()), 1, new ArrayList<>()).cloneAsHeader();
    Object[] parameters = new Object[] { block.bitcoinSerialize() };
    byte[] data = Bridge.RECEIVE_HEADER.encode(parameters);
    bridge.execute(data);
}
Also used : co.rsk.bitcoinj.core(co.rsk.bitcoinj.core) NetworkParameters(co.rsk.bitcoinj.core.NetworkParameters) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ActivationConfig(org.ethereum.config.blockchain.upgrades.ActivationConfig) Test(org.junit.Test) ActivationConfigsForTest(org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest)

Example 23 with NetworkParameters

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

the class BridgeSupport method validationsForRegisterBtcTransaction.

@VisibleForTesting
protected boolean validationsForRegisterBtcTransaction(Sha256Hash btcTxHash, int height, byte[] pmtSerialized, byte[] btcTxSerialized) throws BlockStoreException, VerificationException.EmptyInputsOrOutputs, BridgeIllegalArgumentException {
    // Validates height and confirmations for tx
    try {
        int acceptableConfirmationsAmount = bridgeConstants.getBtc2RskMinimumAcceptableConfirmations();
        if (!BridgeUtils.validateHeightAndConfirmations(height, getBtcBlockchainBestChainHeight(), acceptableConfirmationsAmount, btcTxHash)) {
            return false;
        }
    } catch (Exception e) {
        String panicMessage = String.format("Btc Tx %s Supplied Height is %d but should be greater than 0", btcTxHash, height);
        logger.warn(panicMessage);
        panicProcessor.panic("btclock", panicMessage);
        return false;
    }
    // Validates pmt size
    if (!PartialMerkleTreeFormatUtils.hasExpectedSize(pmtSerialized)) {
        throw new BridgeIllegalArgumentException("PartialMerkleTree doesn't have expected size");
    }
    // Calculates merkleRoot
    Sha256Hash merkleRoot;
    try {
        NetworkParameters networkParameters = bridgeConstants.getBtcParams();
        merkleRoot = BridgeUtils.calculateMerkleRoot(networkParameters, pmtSerialized, btcTxHash);
        if (merkleRoot == null) {
            return false;
        }
    } catch (VerificationException e) {
        throw new BridgeIllegalArgumentException(e.getMessage(), e);
    }
    // Validates inputs count
    logger.info("Going to validate inputs for btc tx {}", btcTxHash);
    BridgeUtils.validateInputsCount(btcTxSerialized, activations.isActive(ConsensusRule.RSKIP143));
    // Check the the merkle root equals merkle root of btc block at specified height in the btc best chain
    // BTC blockstore is available since we've already queried the best chain height
    logger.trace("Getting btc block at height: {}", height);
    BtcBlock blockHeader = btcBlockStore.getStoredBlockAtMainChainHeight(height).getHeader();
    logger.trace("Validating block merkle root at height: {}", height);
    if (!isBlockMerkleRootValid(merkleRoot, blockHeader)) {
        String panicMessage = String.format("Btc Tx %s Supplied merkle root %s does not match block's merkle root %s", btcTxHash.toString(), merkleRoot, blockHeader.getMerkleRoot());
        logger.warn(panicMessage);
        panicProcessor.panic("btclock", panicMessage);
        return false;
    }
    return true;
}
Also used : NetworkParameters(co.rsk.bitcoinj.core.NetworkParameters) Sha256Hash(co.rsk.bitcoinj.core.Sha256Hash) VerificationException(co.rsk.bitcoinj.core.VerificationException) BtcBlock(co.rsk.bitcoinj.core.BtcBlock) 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) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 24 with NetworkParameters

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

the class ExtractPublicKeyFromExtendedPublicKey method execute.

@Override
public Object execute(Object[] arguments) throws NativeContractIllegalArgumentException {
    if (arguments == null) {
        throw new NativeContractIllegalArgumentException(String.format(INVALID_EXTENDED_PUBLIC_KEY, null));
    }
    String xpub = (String) arguments[0];
    NetworkParameters params = helper.validateAndExtractNetworkFromExtendedPublicKey(xpub);
    DeterministicKey key;
    try {
        key = DeterministicKey.deserializeB58(xpub, params);
    } catch (IllegalArgumentException e) {
        throw new NativeContractIllegalArgumentException(String.format(INVALID_EXTENDED_PUBLIC_KEY, xpub), e);
    }
    return key.getPubKeyPoint().getEncoded(true);
}
Also used : NetworkParameters(co.rsk.bitcoinj.core.NetworkParameters) NativeContractIllegalArgumentException(co.rsk.pcc.exception.NativeContractIllegalArgumentException) DeterministicKey(co.rsk.bitcoinj.crypto.DeterministicKey) NativeContractIllegalArgumentException(co.rsk.pcc.exception.NativeContractIllegalArgumentException)

Example 25 with NetworkParameters

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

the class ExtractPublicKeyFromExtendedPublicKeyPerformanceTestCase method estimateExtractPublicKeyFromExtendedPublicKey.

private ExecutionStats estimateExtractPublicKeyFromExtendedPublicKey(int times, EnvironmentBuilder environmentBuilder) throws VMException {
    ExecutionStats stats = new ExecutionStats(function.name);
    Random rnd = new Random();
    byte[] chainCode = new byte[32];
    NetworkParameters networkParameters = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
    byte[] publicKey = new ECKey().getPubKey(true);
    String expectedHexPublicKey = ByteUtil.toHexString(publicKey);
    ABIEncoder abiEncoder = (int executionIndex) -> {
        rnd.nextBytes(chainCode);
        DeterministicKey key = HDKeyDerivation.createMasterPubKeyFromBytes(publicKey, chainCode);
        return function.encode(new Object[] { key.serializePubB58(networkParameters) });
    };
    executeAndAverage(function.name, times, environmentBuilder, abiEncoder, Helper.getZeroValueTxBuilder(new ECKey()), Helper.getRandomHeightProvider(10), stats, (EnvironmentBuilder.Environment environment, byte[] result) -> {
        Object[] decodedResult = function.decodeResult(result);
        Assert.assertEquals(byte[].class, decodedResult[0].getClass());
        String hexPublicKey = ByteUtil.toHexString((byte[]) decodedResult[0]);
        Assert.assertEquals(expectedHexPublicKey, hexPublicKey);
    });
    return stats;
}
Also used : Random(java.util.Random) NetworkParameters(co.rsk.bitcoinj.core.NetworkParameters) ECKey(org.ethereum.crypto.ECKey) DeterministicKey(co.rsk.bitcoinj.crypto.DeterministicKey) ExecutionStats(co.rsk.peg.performance.ExecutionStats)

Aggregations

NetworkParameters (co.rsk.bitcoinj.core.NetworkParameters)28 BtcBlock (co.rsk.bitcoinj.core.BtcBlock)11 Test (org.junit.Test)9 BtcTransaction (co.rsk.bitcoinj.core.BtcTransaction)8 Context (co.rsk.bitcoinj.core.Context)7 BigInteger (java.math.BigInteger)6 Address (co.rsk.bitcoinj.core.Address)5 ActivationConfigsForTest (org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest)5 ECKey (org.ethereum.crypto.ECKey)5 DeterministicKey (co.rsk.bitcoinj.crypto.DeterministicKey)4 co.rsk.bitcoinj.core (co.rsk.bitcoinj.core)3 BtcECKey (co.rsk.bitcoinj.core.BtcECKey)3 BlockGenerator (co.rsk.blockchain.utils.BlockGenerator)3 RskAddress (co.rsk.core.RskAddress)3 Keccak256 (co.rsk.crypto.Keccak256)3 SubmitBlockResult (co.rsk.mine.SubmitBlockResult)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 ActivationConfig (org.ethereum.config.blockchain.upgrades.ActivationConfig)3 CallTransaction (org.ethereum.core.CallTransaction)3