use of co.rsk.peg.btcLockSender.BtcLockSenderProvider in project rskj by rsksmart.
the class BridgeSupportTestPowerMock method registerBtcTransactionReleaseTx.
@Test
public void registerBtcTransactionReleaseTx() throws BlockStoreException, AddressFormatException, IOException, BridgeIllegalArgumentException {
// Federation is the genesis federation ATM
Federation federation = bridgeConstants.getGenesisFederation();
Repository repository = createRepository();
repository.addBalance(PrecompiledContracts.BRIDGE_ADDR, LIMIT_MONETARY_BASE);
Repository track = repository.startTracking();
Block executionBlock = Mockito.mock(Block.class);
Mockito.when(executionBlock.getNumber()).thenReturn(10L);
ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class);
BtcTransaction tx = new BtcTransaction(this.btcParams);
Address address = ScriptBuilder.createP2SHOutputScript(2, Lists.newArrayList(new BtcECKey(), new BtcECKey(), new BtcECKey())).getToAddress(btcParams);
tx.addOutput(Coin.COIN, address);
Address address2 = federation.getAddress();
tx.addOutput(Coin.COIN, address2);
// Create previous tx
BtcTransaction prevTx = new BtcTransaction(btcParams);
TransactionOutput prevOut = new TransactionOutput(btcParams, prevTx, Coin.FIFTY_COINS, federation.getAddress());
prevTx.addOutput(prevOut);
// Create tx input
tx.addInput(prevOut);
// Create tx input base script sig
Script scriptSig = PegTestUtils.createBaseInputScriptThatSpendsFromTheFederation(federation);
// Create sighash
Script redeemScript = ScriptBuilder.createRedeemScript(federation.getNumberOfSignaturesRequired(), federation.getBtcPublicKeys());
Sha256Hash sighash = tx.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false);
// Sign by federator 0
BtcECKey.ECDSASignature sig0 = BridgeRegTestConstants.REGTEST_FEDERATION_PRIVATE_KEYS.get(0).sign(sighash);
TransactionSignature txSig0 = new TransactionSignature(sig0, BtcTransaction.SigHash.ALL, false);
int sigIndex0 = scriptSig.getSigInsertionIndex(sighash, federation.getBtcPublicKeys().get(0));
scriptSig = ScriptBuilder.updateScriptWithSignature(scriptSig, txSig0.encodeToBitcoin(), sigIndex0, 1, 1);
// Sign by federator 1
BtcECKey.ECDSASignature sig1 = BridgeRegTestConstants.REGTEST_FEDERATION_PRIVATE_KEYS.get(1).sign(sighash);
TransactionSignature txSig1 = new TransactionSignature(sig1, BtcTransaction.SigHash.ALL, false);
int sigIndex1 = scriptSig.getSigInsertionIndex(sighash, federation.getBtcPublicKeys().get(1));
scriptSig = ScriptBuilder.updateScriptWithSignature(scriptSig, txSig1.encodeToBitcoin(), sigIndex1, 1, 1);
// Set scipt sign to tx input
tx.getInput(0).setScriptSig(scriptSig);
BridgeStorageProvider provider = new BridgeStorageProvider(track, contractAddress, bridgeConstants, activationsBeforeForks);
BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class);
BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class);
when(mockFactory.newInstance(track, bridgeConstants, provider, activations)).thenReturn(btcBlockStore);
BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, provider, track, mock(BridgeEventLogger.class), new BtcLockSenderProvider(), executionBlock, mockFactory, activations);
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 registerHeader = new co.rsk.bitcoinj.core.BtcBlock(btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>());
int height = 30;
mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height);
bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx.bitcoinSerialize(), height, pmt.bitcoinSerialize());
bridgeSupport.save();
track.commit();
Assert.assertEquals(LIMIT_MONETARY_BASE, repository.getBalance(PrecompiledContracts.BRIDGE_ADDR));
BridgeStorageProvider provider2 = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activationsBeforeForks);
Assert.assertEquals(1, provider2.getNewFederationBtcUTXOs().size());
Assert.assertEquals(Coin.COIN, provider2.getNewFederationBtcUTXOs().get(0).getValue());
Assert.assertEquals(0, provider2.getReleaseRequestQueue().getEntries().size());
Assert.assertEquals(0, provider2.getReleaseTransactionSet().getEntries().size());
Assert.assertTrue(provider2.getRskTxsWaitingForSignatures().isEmpty());
Assert.assertTrue(provider2.getHeightIfBtcTxhashIsAlreadyProcessed(tx.getHash()).isPresent());
}
use of co.rsk.peg.btcLockSender.BtcLockSenderProvider in project rskj by rsksmart.
the class BridgeSupportTestPowerMock method registerBtcTransactionLockTxWhitelisted.
@Test
public void registerBtcTransactionLockTxWhitelisted() throws Exception {
ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class);
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(FederationTestUtils.getFederationMembersWithBtcKeys(federation1Keys), Instant.ofEpochMilli(1000L), 0L, btcParams);
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(FederationTestUtils.getFederationMembersWithBtcKeys(federation2Keys), Instant.ofEpochMilli(2000L), 0L, btcParams);
Repository repository = createRepository();
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(btcParams);
tx1.addOutput(Coin.COIN.multiply(5), federation1.getAddress());
BtcECKey srcKey1 = new BtcECKey();
tx1.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey1));
// Second transaction goes only to the second federation
BtcTransaction tx2 = new BtcTransaction(btcParams);
tx2.addOutput(Coin.COIN.multiply(10), federation2.getAddress());
BtcECKey srcKey2 = new BtcECKey();
tx2.addInput(PegTestUtils.createHash(1), 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(btcParams);
tx3.addOutput(Coin.COIN.multiply(2), federation1.getAddress());
tx3.addOutput(Coin.COIN.multiply(3), federation2.getAddress());
BtcECKey srcKey3 = new BtcECKey();
tx3.addInput(PegTestUtils.createHash(1), 0, ScriptBuilder.createInputScript(null, srcKey3));
BtcBlockStoreWithCache btcBlockStore = mock(BtcBlockStoreWithCache.class);
BridgeStorageProvider provider = new BridgeStorageProvider(track, contractAddress, bridgeConstants, activationsBeforeForks);
provider.setNewFederation(federation1);
provider.setOldFederation(federation2);
// Whitelist the addresses
LockWhitelist whitelist = provider.getLockWhitelist();
Address address1 = srcKey1.toAddress(btcParams);
Address address2 = srcKey2.toAddress(btcParams);
Address address3 = srcKey3.toAddress(btcParams);
whitelist.put(address1, new OneOffWhiteListEntry(address1, Coin.COIN.multiply(5)));
whitelist.put(address2, new OneOffWhiteListEntry(address2, Coin.COIN.multiply(10)));
whitelist.put(address3, new OneOffWhiteListEntry(address3, Coin.COIN.multiply(2).add(Coin.COIN.multiply(3))));
BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class);
when(mockFactory.newInstance(track, bridgeConstants, provider, activations)).thenReturn(btcBlockStore);
BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, provider, track, mock(BridgeEventLogger.class), new BtcLockSenderProvider(), executionBlock, mockFactory, activations);
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 registerHeader = new co.rsk.bitcoinj.core.BtcBlock(btcParams, 1, PegTestUtils.createHash(1), merkleRoot, 1, 1, 1, new ArrayList<>());
int height = 30;
mockChainOfStoredBlocks(btcBlockStore, registerHeader, 35, height);
bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx1.bitcoinSerialize(), height, pmt.bitcoinSerialize());
bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx2.bitcoinSerialize(), height, pmt.bitcoinSerialize());
bridgeSupport.registerBtcTransaction(mock(Transaction.class), tx3.bitcoinSerialize(), height, pmt.bitcoinSerialize());
bridgeSupport.save();
track.commit();
Assert.assertThat(whitelist.isWhitelisted(address1), is(false));
Assert.assertThat(whitelist.isWhitelisted(address2), is(false));
Assert.assertThat(whitelist.isWhitelisted(address3), is(false));
co.rsk.core.Coin amountToHaveBeenCreditedToSrc1 = co.rsk.core.Coin.fromBitcoin(Coin.valueOf(5, 0));
co.rsk.core.Coin amountToHaveBeenCreditedToSrc2 = co.rsk.core.Coin.fromBitcoin(Coin.valueOf(10, 0));
co.rsk.core.Coin amountToHaveBeenCreditedToSrc3 = co.rsk.core.Coin.fromBitcoin(Coin.valueOf(5, 0));
co.rsk.core.Coin totalAmountExpectedToHaveBeenLocked = amountToHaveBeenCreditedToSrc1.add(amountToHaveBeenCreditedToSrc2).add(amountToHaveBeenCreditedToSrc3);
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(amountToHaveBeenCreditedToSrc1, repository.getBalance(srcKey1RskAddress));
Assert.assertEquals(amountToHaveBeenCreditedToSrc2, repository.getBalance(srcKey2RskAddress));
Assert.assertEquals(amountToHaveBeenCreditedToSrc3, repository.getBalance(srcKey3RskAddress));
Assert.assertEquals(LIMIT_MONETARY_BASE.subtract(totalAmountExpectedToHaveBeenLocked), repository.getBalance(PrecompiledContracts.BRIDGE_ADDR));
BridgeStorageProvider provider2 = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activationsBeforeForks);
Assert.assertEquals(2, provider2.getNewFederationBtcUTXOs().size());
Assert.assertEquals(2, provider2.getOldFederationBtcUTXOs().size());
Assert.assertEquals(Coin.COIN.multiply(5), provider2.getNewFederationBtcUTXOs().get(0).getValue());
Assert.assertEquals(Coin.COIN.multiply(2), provider2.getNewFederationBtcUTXOs().get(1).getValue());
Assert.assertEquals(Coin.COIN.multiply(10), provider2.getOldFederationBtcUTXOs().get(0).getValue());
Assert.assertEquals(Coin.COIN.multiply(3), provider2.getOldFederationBtcUTXOs().get(1).getValue());
Assert.assertEquals(0, provider2.getReleaseRequestQueue().getEntries().size());
Assert.assertEquals(0, provider2.getReleaseTransactionSet().getEntries().size());
Assert.assertTrue(provider2.getRskTxsWaitingForSignatures().isEmpty());
Assert.assertTrue(provider2.getHeightIfBtcTxhashIsAlreadyProcessed(tx1.getHash()).isPresent());
Assert.assertTrue(provider2.getHeightIfBtcTxhashIsAlreadyProcessed(tx2.getHash()).isPresent());
Assert.assertTrue(provider2.getHeightIfBtcTxhashIsAlreadyProcessed(tx3.getHash()).isPresent());
}
use of co.rsk.peg.btcLockSender.BtcLockSenderProvider in project rskj by rsksmart.
the class BridgeSupportTest method assertRefundInProcessPegInVersion1.
private void assertRefundInProcessPegInVersion1(TxSenderAddressType lockSenderAddressType, Optional<Address> btcRefundAddress, List<ConsensusRule> consensusRules) throws IOException, RegisterBtcTransactionException, PeginInstructionsException {
// Arrange
ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class);
for (ConsensusRule consensusRule : consensusRules) {
when(activations.isActive(consensusRule)).thenReturn(true);
}
Repository repository = createRepository();
BtcECKey srcKey1 = new BtcECKey();
ECKey key = ECKey.fromPublicOnly(srcKey1.getPubKey());
RskAddress rskAddress = new RskAddress(key.getAddress());
Address btcSenderAddress = null;
if (lockSenderAddressType != TxSenderAddressType.UNKNOWN) {
btcSenderAddress = srcKey1.toAddress(btcParams);
}
BtcTransaction btcTx = new BtcTransaction(btcParams);
btcTx.addOutput(Coin.COIN.multiply(10), bridgeConstants.getGenesisFederation().getAddress());
btcTx.addInput(PegTestUtils.createHash(1), 0, new Script(new byte[] {}));
BridgeStorageProvider provider = mock(BridgeStorageProvider.class);
ReleaseTransactionSet releaseTransactionSet = new ReleaseTransactionSet(new HashSet<>());
when(provider.getReleaseTransactionSet()).thenReturn(releaseTransactionSet);
when(provider.getLockingCap()).thenReturn(Coin.COIN.multiply(1));
BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(lockSenderAddressType, btcSenderAddress, rskAddress);
if (!btcRefundAddress.isPresent() && btcSenderAddress != null) {
btcRefundAddress = Optional.of(btcSenderAddress);
}
PeginInstructionsProvider peginInstructionsProvider = getPeginInstructionsProviderForVersion1(rskAddress, btcRefundAddress);
BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, provider, repository, btcLockSenderProvider, peginInstructionsProvider, mock(Block.class), mock(BtcBlockStoreWithCache.Factory.class), activations);
// Act
bridgeSupport.processPegIn(btcTx, mock(Transaction.class), 0, mock(Sha256Hash.class));
// Assert
if (lockSenderAddressType == TxSenderAddressType.UNKNOWN && !btcRefundAddress.isPresent()) {
// Unknown sender and no refund address. Can't refund
Assert.assertEquals(0, releaseTransactionSet.getEntries().size());
} else {
Assert.assertEquals(1, releaseTransactionSet.getEntries().size());
// Check rejection tx input was created from btc tx and sent to the btc refund address indicated by the user
boolean successfulRejection = false;
for (ReleaseTransactionSet.Entry e : releaseTransactionSet.getEntries()) {
BtcTransaction refundTx = e.getTransaction();
if (refundTx.getInput(0).getOutpoint().getHash() == btcTx.getHash() && refundTx.getOutput(0).getScriptPubKey().getToAddress(btcParams).equals(btcRefundAddress.get())) {
successfulRejection = true;
break;
}
}
Assert.assertTrue(successfulRejection);
}
}
use of co.rsk.peg.btcLockSender.BtcLockSenderProvider in project rskj by rsksmart.
the class BridgeSupportTest method registerFastBridgeBtcTransaction_surpasses_locking_cap_and_shouldTransfer_is_false.
@Test
public void registerFastBridgeBtcTransaction_surpasses_locking_cap_and_shouldTransfer_is_false() throws IOException, BlockStoreException, BridgeIllegalArgumentException {
ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class);
when(activations.isActive(ConsensusRule.RSKIP176)).thenReturn(true);
when(activations.isActive(ConsensusRule.RSKIP134)).thenReturn(true);
ReleaseTransactionSet releaseTransactionSet = new ReleaseTransactionSet(new HashSet<>());
BridgeStorageProvider provider = mock(BridgeStorageProvider.class);
when(provider.getReleaseTransactionSet()).thenReturn(releaseTransactionSet);
when(provider.isFastBridgeFederationDerivationHashUsed(any(), any())).thenReturn(false);
BtcLockSender btcLockSender = mock(BtcLockSender.class);
BtcLockSenderProvider btcLockSenderProvider = mock(BtcLockSenderProvider.class);
when(btcLockSenderProvider.tryGetBtcLockSender(any())).thenReturn(Optional.of(btcLockSender));
Repository repository = mock(Repository.class);
when(repository.getBalance(any())).thenReturn(co.rsk.core.Coin.valueOf(1));
Context btcContext = mock(Context.class);
when(btcContext.getParams()).thenReturn(bridgeConstants.getBtcParams());
BridgeSupport bridgeSupport = spy(new BridgeSupport(bridgeConstants, provider, mock(BridgeEventLogger.class), btcLockSenderProvider, new PeginInstructionsProvider(), repository, mock(Block.class), btcContext, mock(FederationSupport.class), mock(BtcBlockStoreWithCache.Factory.class), activations));
doReturn(bridgeConstants.getGenesisFederation()).when(bridgeSupport).getActiveFederation();
doReturn(true).when(bridgeSupport).validationsForRegisterBtcTransaction(any(), anyInt(), any(), any());
doReturn(Coin.COIN).when(bridgeSupport).getLockingCap();
doReturn(PegTestUtils.createHash3(1)).when(bridgeSupport).getFastBridgeDerivationHash(any(Keccak256.class), any(Address.class), any(Address.class), any(RskAddress.class));
Address btcAddress = Address.fromBase58(btcParams, "n3PLxDiwWqa5uH7fSbHCxS6VAjD9Y7Rwkj");
ECKey key = ECKey.fromPublicOnly(new BtcECKey().getPubKey());
RskAddress lbcAddress = new RskAddress(key.getAddress());
BtcTransaction tx = createBtcTransactionWithOutputToAddress(Coin.COIN, getFastBridgeFederationAddress());
byte[] pmtSerialized = Hex.decode("ab");
InternalTransaction rskTx = new InternalTransaction(Keccak256.ZERO_HASH.getBytes(), 0, 0, null, null, null, lbcAddress.getBytes(), null, null, null, null);
BigInteger result = bridgeSupport.registerFastBridgeBtcTransaction(rskTx, tx.bitcoinSerialize(), 100, pmtSerialized, PegTestUtils.createHash3(0), btcAddress, lbcAddress, btcAddress, false);
Assert.assertEquals(BigInteger.valueOf(BridgeSupport.FAST_BRIDGE_REFUNDED_USER_ERROR_CODE), result);
}
use of co.rsk.peg.btcLockSender.BtcLockSenderProvider in project rskj by rsksmart.
the class BridgeSupportTest method getBtcLockSenderProvider.
private BtcLockSenderProvider getBtcLockSenderProvider(TxSenderAddressType txSenderAddressType, Address btcAddress, RskAddress rskAddress) {
BtcLockSender btcLockSender = mock(BtcLockSender.class);
when(btcLockSender.getTxSenderAddressType()).thenReturn(txSenderAddressType);
when(btcLockSender.getBTCAddress()).thenReturn(btcAddress);
when(btcLockSender.getRskAddress()).thenReturn(rskAddress);
BtcLockSenderProvider btcLockSenderProvider = mock(BtcLockSenderProvider.class);
when(btcLockSenderProvider.tryGetBtcLockSender(any())).thenReturn(Optional.of(btcLockSender));
return btcLockSenderProvider;
}
Aggregations