diff --git a/rskj-core/src/main/java/co/rsk/peg/federation/FederationStorageProviderImpl.java b/rskj-core/src/main/java/co/rsk/peg/federation/FederationStorageProviderImpl.java index 39e52bdd764..a4c44058834 100644 --- a/rskj-core/src/main/java/co/rsk/peg/federation/FederationStorageProviderImpl.java +++ b/rskj-core/src/main/java/co/rsk/peg/federation/FederationStorageProviderImpl.java @@ -22,10 +22,11 @@ public class FederationStorageProviderImpl implements FederationStorageProvider { private final StorageAccessor bridgeStorageAccessor; + private final HashMap> storageVersionEntries; + private List newFederationBtcUTXOs; private List oldFederationBtcUTXOs; private Federation newFederation; - private HashMap> storageVersionEntries; private Federation oldFederation; private boolean shouldSaveOldFederation = false; diff --git a/rskj-core/src/test/java/co/rsk/RskTestUtils.java b/rskj-core/src/test/java/co/rsk/RskTestUtils.java index b37793efa2d..c383f54b171 100644 --- a/rskj-core/src/test/java/co/rsk/RskTestUtils.java +++ b/rskj-core/src/test/java/co/rsk/RskTestUtils.java @@ -1,5 +1,6 @@ package co.rsk; +import co.rsk.crypto.Keccak256; import org.ethereum.crypto.ECKey; import org.ethereum.crypto.HashUtil; import java.nio.charset.StandardCharsets; @@ -8,6 +9,15 @@ import java.util.stream.Collectors; public class RskTestUtils { + + public static Keccak256 createHash(int nHash) { + byte[] bytes = new byte[32]; + bytes[0] = (byte) (nHash & 0xFF); + bytes[1] = (byte) (nHash >>8 & 0xFF); + + return new Keccak256(bytes); + } + public static List getEcKeysFromSeeds(String[] seeds) { return Arrays.stream(seeds) .map(seed -> seed.getBytes(StandardCharsets.UTF_8)) diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeStorageProviderTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeStorageProviderTest.java index 553712e46b5..23558ccc883 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeStorageProviderTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeStorageProviderTest.java @@ -31,9 +31,7 @@ import co.rsk.crypto.Keccak256; import co.rsk.db.MutableTrieCache; import co.rsk.db.MutableTrieImpl; -import co.rsk.peg.bitcoin.BitcoinTestUtils; -import co.rsk.peg.bitcoin.CoinbaseInformation; -import co.rsk.peg.bitcoin.SimpleBtcTransaction; +import co.rsk.peg.bitcoin.*; import co.rsk.peg.constants.*; import co.rsk.peg.flyover.FlyoverFederationInformation; import co.rsk.trie.Trie; @@ -43,9 +41,7 @@ import java.math.BigInteger; import java.util.*; import org.bouncycastle.util.encoders.Hex; -import org.ethereum.config.blockchain.upgrades.ActivationConfig; -import org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest; -import org.ethereum.config.blockchain.upgrades.ConsensusRule; +import org.ethereum.config.blockchain.upgrades.*; import org.ethereum.core.Repository; import org.ethereum.datasource.HashMapDB; import org.ethereum.db.MutableRepository; diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportAddSignatureTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportAddSignatureTest.java index 325d72a477a..ff78acb4576 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportAddSignatureTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportAddSignatureTest.java @@ -1,5 +1,7 @@ package co.rsk.peg; +import co.rsk.RskTestUtils; +import co.rsk.peg.bitcoin.BitcoinTestUtils; import co.rsk.peg.federation.constants.FederationConstants; import co.rsk.peg.feeperkb.FeePerKbSupport; import co.rsk.peg.lockingcap.LockingCapSupport; @@ -88,7 +90,7 @@ class BridgeSupportAddSignatureTest { void setUpOnEachTest() { activationsBeforeForks = ActivationConfigsForTest.genesis().forBlock(0); activationsAfterForks = ActivationConfigsForTest.all().forBlock(0); - bridgeSupportBuilder = new BridgeSupportBuilder(); + bridgeSupportBuilder = BridgeSupportBuilder.builder(); whitelistSupport = mock(WhitelistSupport.class); lockingCapSupport = mock(LockingCapSupport.class); } @@ -327,7 +329,7 @@ void addSignatureToMissingTransaction() throws Exception { bridgeSupport.addSignature( genesisFederation.getBtcPublicKeys().get(0), null, - createHash().getBytes() + BitcoinTestUtils.createHash(1).getBytes() ); bridgeSupport.save(); @@ -355,7 +357,11 @@ void addSignatureFromInvalidFederator() throws Exception { .withRepository(repository) .build(); - bridgeSupport.addSignature(new BtcECKey(), null, createHash().getBytes()); + bridgeSupport.addSignature( + new BtcECKey(), + null, + BitcoinTestUtils.createHash(1).getBytes() + ); bridgeSupport.save(); BridgeStorageProvider provider = new BridgeStorageProvider(repository, bridgeAddress, @@ -436,7 +442,7 @@ private void test_addSignature_EventEmitted(boolean rskip326Active, boolean useV BtcECKey privateKeyToSignWith = REGTEST_FEDERATION_PRIVATE_KEYS.get(indexOfKeyToSignWith); - List derEncodedSigs; + List derEncodedSigs; if (useValidSignature) { Script inputScript = btcTx.getInputs().get(0).getScriptSig(); @@ -719,7 +725,7 @@ void addSignature(ActivationConfig.ForBlock activations, FederationMember federa Script redeemScript = new Script(program); Sha256Hash sigHash = btcTx.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false); BtcECKey.ECDSASignature sig = privateKeyToSignWith.sign(sigHash); - List derEncodedSigs = Collections.singletonList(sig.encodeToDER()); + List derEncodedSigs = Collections.singletonList(sig.encodeToDER()); // Act bridgeSupport.addSignature(federationMemberToSignWith.getBtcPublicKey(), derEncodedSigs, rskTxHash.getBytes()); @@ -728,7 +734,13 @@ void addSignature(ActivationConfig.ForBlock activations, FederationMember federa commonAssertLogs(eventLogs); assertTopics(3, eventLogs); - assertEvent(eventLogs, 0, BridgeEvents.ADD_SIGNATURE.getEvent(), new Object[]{rskTxHash.getBytes(), expectedRskAddress}, new Object[]{federatorBtcPubKey.getPubKey()}); + assertEvent( + eventLogs, + 0, + BridgeEvents.ADD_SIGNATURE.getEvent(), + new Object[]{rskTxHash.getBytes(), expectedRskAddress}, + new Object[]{federatorBtcPubKey.getPubKey()} + ); } private static void assertEvent(List logs, int index, CallTransaction.Function event, Object[] topics, Object[] params) { @@ -764,7 +776,7 @@ private void addSignatureFromValidFederator(List privateKeysToSignWith Federation genesisFederation = FederationTestUtils.getGenesisFederation(bridgeRegTestConstants.getFederationConstants()); Repository repository = createRepository(); - final Keccak256 keccak256 = PegTestUtils.createHash3(); + final Keccak256 keccak256 = RskTestUtils.createHash(1); Repository track = repository.startTracking(); BridgeStorageProvider provider = new BridgeStorageProvider(track, bridgeAddress, btcRegTestParams, activationsBeforeForks); @@ -815,7 +827,7 @@ private void addSignatureFromValidFederator(List privateKeysToSignWith } byte[] derEncodedSig = sig.encodeToDER(); - List derEncodedSigs = new ArrayList(); + List derEncodedSigs = new ArrayList<>(); for (int i = 0; i < numberOfInputsToSign; i++) { derEncodedSigs.add(derEncodedSig); } @@ -823,9 +835,9 @@ private void addSignatureFromValidFederator(List privateKeysToSignWith if (signTwice) { // Create another valid signature with the same private key ECDSASigner signer = new ECDSASigner(); - X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1"); - ECDomainParameters CURVE = new ECDomainParameters(CURVE_PARAMS.getCurve(), CURVE_PARAMS.getG(), CURVE_PARAMS.getN(), CURVE_PARAMS.getH()); - ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeysToSignWith.get(0).getPrivKey(), CURVE); + X9ECParameters curveParams = CustomNamedCurves.getByName("secp256k1"); + ECDomainParameters curve = new ECDomainParameters(curveParams.getCurve(), curveParams.getG(), curveParams.getN(), curveParams.getH()); + ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeysToSignWith.get(0).getPrivKey(), curve); signer.init(true, privKey); BigInteger[] components = signer.generateSignature(sighash.getBytes()); BtcECKey.ECDSASignature sig2 = new BtcECKey.ECDSASignature(components[0], components[1]).toCanonicalised(); @@ -836,11 +848,15 @@ private void addSignatureFromValidFederator(List privateKeysToSignWith if (privateKeysToSignWith.size() > 1) { BtcECKey.ECDSASignature sig2 = privateKeysToSignWith.get(1).sign(sighash); byte[] derEncodedSig2 = sig2.encodeToDER(); - List derEncodedSigs2 = new ArrayList(); + List derEncodedSigs2 = new ArrayList<>(); for (int i = 0; i < numberOfInputsToSign; i++) { derEncodedSigs2.add(derEncodedSig2); } - bridgeSupport.addSignature(findPublicKeySignedBy(genesisFederation.getBtcPublicKeys(), privateKeysToSignWith.get(1)), derEncodedSigs2, keccak256.getBytes()); + bridgeSupport.addSignature( + findPublicKeySignedBy(genesisFederation.getBtcPublicKeys(), privateKeysToSignWith.get(1)), + derEncodedSigs2, + keccak256.getBytes() + ); } bridgeSupport.save(); track.commit(); diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportFlyoverTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportFlyoverTest.java index 5ad61c3762e..70da4396cc5 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportFlyoverTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportFlyoverTest.java @@ -92,10 +92,10 @@ void setUpOnEachTest() { signatureCache = new BlockTxSignatureCache(new ReceivedTxSignatureCache()); when(activations.isActive(ConsensusRule.RSKIP176)).thenReturn(true); when(activations.isActive(ConsensusRule.RSKIP219)).thenReturn(true); - bridgeSupportBuilder = new BridgeSupportBuilder(); + bridgeSupportBuilder = BridgeSupportBuilder.builder(); lockingCapSupport = mock(LockingCapSupport.class); whitelistSupport = mock(WhitelistSupport.class); - federationSupportBuilder = new FederationSupportBuilder(); + federationSupportBuilder = FederationSupportBuilder.builder(); } private BtcTransaction createBtcTransactionWithOutputToAddress(Coin amount, Address btcAddress) { diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportIT.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportIT.java index 278dc839795..c78d444191c 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportIT.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportIT.java @@ -45,10 +45,7 @@ import co.rsk.peg.federation.FederationMember.KeyType; import co.rsk.peg.federation.constants.FederationConstants; import co.rsk.peg.feeperkb.FeePerKbSupport; -import co.rsk.peg.lockingcap.LockingCapStorageProvider; -import co.rsk.peg.lockingcap.LockingCapStorageProviderImpl; -import co.rsk.peg.lockingcap.LockingCapSupport; -import co.rsk.peg.lockingcap.LockingCapSupportImpl; +import co.rsk.peg.lockingcap.*; import co.rsk.peg.lockingcap.constants.LockingCapMainNetConstants; import co.rsk.peg.pegininstructions.PeginInstructionsProvider; import co.rsk.peg.simples.SimpleBlockChain; @@ -101,8 +98,8 @@ @MockitoSettings(strictness = Strictness.LENIENT) public class BridgeSupportIT { private static final co.rsk.core.Coin LIMIT_MONETARY_BASE = new co.rsk.core.Coin(new BigInteger("21000000000000000000000000")); - private static final RskAddress contractAddress = PrecompiledContracts.BRIDGE_ADDR; - public static final BlockDifficulty TEST_DIFFICULTY = new BlockDifficulty(BigInteger.ONE); + private static final RskAddress BRIDGE_ADDRESS = PrecompiledContracts.BRIDGE_ADDR; + private static final BlockDifficulty TEST_DIFFICULTY = new BlockDifficulty(BigInteger.ONE); private static final String TO_ADDRESS = "0000000000000000000000000000000000000006"; private static final BigInteger DUST_AMOUNT = new BigInteger("1"); @@ -118,14 +115,15 @@ public class BridgeSupportIT { BtcECKey.fromPrivate(Hex.decode("bed0af2ce8aa8cb2bc3f9416c9d518fdee15d1ff15b8ded28376fcb23db6db69")) ); + private final BridgeSupportBuilder bridgeSupportBuilder = BridgeSupportBuilder.builder(); + private final FederationSupportBuilder federationSupportBuilder = FederationSupportBuilder.builder(); + private BridgeConstants bridgeConstants; private FederationConstants federationConstants; private NetworkParameters btcParams; private ActivationConfig.ForBlock activationsBeforeForks; private ActivationConfig.ForBlock activations; - private BridgeSupportBuilder bridgeSupportBuilder; - private FederationSupportBuilder federationSupportBuilder; private SignatureCache signatureCache; private FeePerKbSupport feePerKbSupport; private WhitelistSupport whitelistSupport; @@ -139,8 +137,6 @@ void setUpOnEachTest() { btcParams = bridgeConstants.getBtcParams(); activationsBeforeForks = ActivationConfigsForTest.genesis().forBlock(0); activations = mock(ActivationConfig.ForBlock.class); - bridgeSupportBuilder = new BridgeSupportBuilder(); - federationSupportBuilder = new FederationSupportBuilder(); signatureCache = new BlockTxSignatureCache(new ReceivedTxSignatureCache()); feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); @@ -194,13 +190,13 @@ void testInitialChainHeadWithoutBtcCheckpoints() throws Exception { @Test void testInitialChainHeadWithBtcCheckpoints() throws Exception { - BridgeConstants bridgeConstants = BridgeTestNetConstants.getInstance(); + BridgeConstants bridgeTestNetConstants = BridgeTestNetConstants.getInstance(); Repository repository = createRepository(); Repository track = repository.startTracking(); - BtcBlockStoreWithCache.Factory btcBlockStoreFactory = new RepositoryBtcBlockStoreWithCache.Factory(bridgeConstants.getBtcParams()); - BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants.getBtcParams(), activationsBeforeForks); + BtcBlockStoreWithCache.Factory btcBlockStoreFactory = new RepositoryBtcBlockStoreWithCache.Factory(bridgeTestNetConstants.getBtcParams()); + BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR, bridgeTestNetConstants.getBtcParams(), activationsBeforeForks); FederationStorageProvider federationStorageProvider = createFederationStorageProvider(track); FederationSupport federationSupport = federationSupportBuilder @@ -210,7 +206,7 @@ void testInitialChainHeadWithBtcCheckpoints() throws Exception { .build(); BridgeSupport bridgeSupport = bridgeSupportBuilder - .withBridgeConstants(bridgeConstants) + .withBridgeConstants(bridgeTestNetConstants) .withProvider(provider) .withRepository(track) .withBtcBlockStoreFactory(btcBlockStoreFactory) @@ -221,7 +217,7 @@ void testInitialChainHeadWithBtcCheckpoints() throws Exception { bridgeSupport.getBtcBlockchainBestChainHeight(); InputStream checkpointsStream = bridgeSupport.getCheckPoints(); - CheckpointManager manager = new CheckpointManager(bridgeConstants.getBtcParams(), checkpointsStream); + CheckpointManager manager = new CheckpointManager(bridgeTestNetConstants.getBtcParams(), checkpointsStream); long time = bridgeSupport.getActiveFederation().getCreationTime().toEpochMilli() - 604800L; // The magic number is a substraction CheckpointManager does when getting the checkpoints. StoredBlock checkpoint = manager.getCheckpointBefore(time); @@ -357,11 +353,11 @@ InputStream getCheckPoints() { assertEquals(checkpoints.get(9).getHash(), locator.get(5)); } - private List createBtcBlocks(NetworkParameters _networkParameters, BtcBlock parent, int numberOfBlocksToCreate) { + private List createBtcBlocks(NetworkParameters networkParameters, BtcBlock parent, int numberOfBlocksToCreate) { List list = new ArrayList<>(); for (int i = 0; i < numberOfBlocksToCreate; i++) { BtcBlock block = new BtcBlock( - _networkParameters, + networkParameters, 2L, parent.getHash(), Sha256Hash.ZERO_HASH, @@ -377,14 +373,14 @@ private List createBtcBlocks(NetworkParameters _networkParameters, Btc return list; } - private InputStream getCheckpoints(NetworkParameters _networkParameters, List checkpoints) { + private InputStream getCheckpoints(NetworkParameters networkParameters, List checkpoints) { try { ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); MessageDigest digest = Sha256Hash.newDigest(); final DigestOutputStream digestOutputStream = new DigestOutputStream(baOutputStream, digest); digestOutputStream.on(false); final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream); - StoredBlock storedBlock = new StoredBlock(_networkParameters.getGenesisBlock(), _networkParameters.getGenesisBlock().getWork(), 0); + StoredBlock storedBlock = new StoredBlock(networkParameters.getGenesisBlock(), networkParameters.getGenesisBlock().getWork(), 0); try { dataOutputStream.writeBytes("CHECKPOINTS 1"); dataOutputStream.writeInt(0); // Number of signatures to read. Do this later. @@ -1027,11 +1023,10 @@ void callUpdateCollectionsWithTransactionsWaitingForConfirmationWithEnoughConfir void sendOrphanBlockHeader() throws IOException, BlockStoreException { Repository repository = createRepository(); Repository track = repository.startTracking(); - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); BridgeStorageProvider provider = new BridgeStorageProvider( track, - contractAddress, + BRIDGE_ADDRESS, bridgeConstants.getBtcParams(), activationsBeforeForks ); @@ -1078,12 +1073,11 @@ void sendOrphanBlockHeader() throws IOException, BlockStoreException { void addBlockHeaderToBlockchain() throws IOException, BlockStoreException { Repository repository = createRepository(); Repository track = repository.startTracking(); - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); Context btcContext = new Context(btcParams); BridgeStorageProvider provider = new BridgeStorageProvider( track, - contractAddress, + BRIDGE_ADDRESS, bridgeConstants.getBtcParams(), activationsBeforeForks ); @@ -1404,7 +1398,6 @@ void registerBtcTransactionOfTransactionInMerkleTreeWithNotEnoughtHeight() throw @Test void registerBtcTransactionWithoutInputs() throws BlockStoreException { - NetworkParameters btcParams = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); BtcTransaction noInputsTx = new BtcTransaction(btcParams); byte[] bits = new byte[1]; @@ -1415,9 +1408,9 @@ void registerBtcTransactionWithoutInputs() throws BlockStoreException { int btcTxHeight = 2; - BridgeConstants bridgeConstants = mock(BridgeConstants.class); - doReturn(btcParams).when(bridgeConstants).getBtcParams(); - doReturn(0).when(bridgeConstants).getBtc2RskMinimumAcceptableConfirmations(); + BridgeConstants bridgeConstantsMock = mock(BridgeConstants.class); + doReturn(btcParams).when(bridgeConstantsMock).getBtcParams(); + doReturn(0).when(bridgeConstantsMock).getBtc2RskMinimumAcceptableConfirmations(); StoredBlock storedBlock = mock(StoredBlock.class); doReturn(btcTxHeight - 1).when(storedBlock).getHeight(); BtcBlock btcBlock = mock(BtcBlock.class); @@ -1429,18 +1422,22 @@ void registerBtcTransactionWithoutInputs() throws BlockStoreException { when(mockFactory.newInstance(any(), any(), any(), any())).thenReturn(btcBlockStore); BridgeSupport bridgeSupport = bridgeSupportBuilder - .withBridgeConstants(bridgeConstants) + .withBridgeConstants(bridgeConstantsMock) .withBtcBlockStoreFactory(mockFactory) .build(); - Assertions.assertThrows(VerificationException.EmptyInputsOrOutputs.class, () -> bridgeSupport.registerBtcTransaction(mock(Transaction.class), noInputsTx.bitcoinSerialize(), btcTxHeight, pmt.bitcoinSerialize())); + assertThrows(VerificationException.EmptyInputsOrOutputs.class, () -> bridgeSupport.registerBtcTransaction( + mock(Transaction.class), + noInputsTx.bitcoinSerialize(), + btcTxHeight, + pmt.bitcoinSerialize()) + ); } @Test void registerBtcTransactionTxNotLockNorReleaseTx() throws BlockStoreException, AddressFormatException, IOException, BridgeIllegalArgumentException { Repository repository = createRepository(); Repository track = repository.startTracking(); - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); BtcTransaction tx = new BtcTransaction(btcParams); Address address = ScriptBuilder.createP2SHOutputScript(2, Lists.newArrayList(new BtcECKey(), new BtcECKey(), new BtcECKey())).getToAddress(btcParams); @@ -1450,7 +1447,7 @@ void registerBtcTransactionTxNotLockNorReleaseTx() throws BlockStoreException, A Context btcContext = new Context(btcParams); BridgeStorageProvider provider = new BridgeStorageProvider( track, - contractAddress, + BRIDGE_ADDRESS, bridgeConstants.getBtcParams(), activationsBeforeForks ); @@ -1515,7 +1512,6 @@ void registerBtcTransactionReleaseTx() throws BlockStoreException, AddressFormat 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); @@ -1548,7 +1544,7 @@ void registerBtcTransactionReleaseTx() throws BlockStoreException, AddressFormat BridgeStorageProvider provider = new BridgeStorageProvider( track, - contractAddress, + BRIDGE_ADDRESS, bridgeConstants.getBtcParams(), activationsBeforeForks ); @@ -1616,7 +1612,6 @@ void registerBtcTransactionReleaseTx() throws BlockStoreException, AddressFormat @Test void registerBtcTransactionMigrationTx() throws BlockStoreException, AddressFormatException, IOException, BridgeIllegalArgumentException { NetworkParameters parameters = bridgeConstants.getBtcParams(); - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); List activeFederationKeys = Stream.of( BtcECKey.fromPrivate(Hex.decode("fa01")), @@ -1683,7 +1678,7 @@ void registerBtcTransactionMigrationTx() throws BlockStoreException, AddressForm BridgeStorageProvider provider = new BridgeStorageProvider( track, - contractAddress, + BRIDGE_ADDRESS, bridgeConstants.getBtcParams(), activationsBeforeForks ); @@ -1929,7 +1924,7 @@ void registerBtcTransactionLockTxWhitelisted() throws Exception { BridgeStorageProvider provider = new BridgeStorageProvider( track, - contractAddress, + BRIDGE_ADDRESS, bridgeConstants.getBtcParams(), activationsBeforeForks ); @@ -2025,7 +2020,7 @@ void registerBtcTransactionLockTxWhitelisted() throws Exception { } @Test - void isBtcTxHashAlreadyProcessed() throws IOException, BlockStoreException { + void isBtcTxHashAlreadyProcessed() throws IOException { BridgeSupport bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) .withProvider(getBridgeStorageProviderMockWithProcessedHashes()) @@ -2039,7 +2034,7 @@ void isBtcTxHashAlreadyProcessed() throws IOException, BlockStoreException { } @Test - void getBtcTxHashProcessedHeight() throws IOException, BlockStoreException { + void getBtcTxHashProcessedHeight() throws IOException { BridgeSupport bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) .withProvider(getBridgeStorageProviderMockWithProcessedHashes()) @@ -2190,7 +2185,6 @@ void getFederationMethods_newActivated() { @Test void getFederationMethods_newNotActivated() { - NetworkParameters btcParams = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); FederationArgs newFederationArgs = new FederationArgs( FederationTestUtils.getFederationMembers(3), Instant.ofEpochMilli(1000), @@ -2250,7 +2244,6 @@ void getRetiringFederationMethods_none() { @Test void getRetiringFederationMethods_presentNewInactive() { - NetworkParameters btcParams = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); FederationArgs mockedNewFedArgs = new FederationArgs( FederationTestUtils.getFederationMembers(2), Instant.ofEpochMilli(1000), @@ -2294,7 +2287,6 @@ void getRetiringFederationMethods_presentNewInactive() { @Test void getRetiringFederationMethods_presentNewActive() { - NetworkParameters btcParams = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); FederationArgs mockedNewFedArgs = new FederationArgs( FederationTestUtils.getFederationMembers(2), Instant.ofEpochMilli(1000), @@ -2538,8 +2530,7 @@ void createFederation_pendingExists() { @Test void createFederation_withPendingActivation() { - VotingMocksProvider mocksProvider = new VotingMocksProvider("create", new byte[][]{}, false); - NetworkParameters btcParams = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); + VotingMocksProvider mocksProvider = new VotingMocksProvider(FederationChangeFunction.CREATE.getKey(), new byte[][]{}, false); FederationArgs mockedNewFedArgs = new FederationArgs( FederationTestUtils.getFederationMembers(2), @@ -2590,8 +2581,7 @@ void createFederation_withPendingActivation() { @Test void createFederation_withExistingRetiringFederation() { - VotingMocksProvider mocksProvider = new VotingMocksProvider("create", new byte[][]{}, false); - NetworkParameters btcParams = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); + VotingMocksProvider mocksProvider = new VotingMocksProvider(FederationChangeFunction.CREATE.getKey(), new byte[][]{}, false); FederationArgs mockedNewFedArgs = new FederationArgs( FederationTestUtils.getFederationMembers(2), @@ -3195,7 +3185,6 @@ void rollbackFederation_noPendingFederation() { @Test void commitFederation_ok() { - NetworkParameters btcParams = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); PendingFederation pendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersWithKeys(Arrays.asList( BtcECKey.fromPublicOnly(Hex.decode("036bb9eab797eadc8b697f0e82a01d01cabbfaaca37e5bafc06fdc6fdd38af894a")), BtcECKey.fromPublicOnly(Hex.decode("031da807c71c2f303b7f409dd2605b297ac494a563be3b9ca5f52d95a43d183cc5")), @@ -3251,11 +3240,8 @@ void commitFederation_ok() { when(federationStorageProvider.getFederationElection(any())).thenReturn(mocksProvider.getElection()); BridgeSupport bridgeSupport = getBridgeSupportWithMocksForFederationTests( - false, federationStorageProvider, newFederation, - null, - null, pendingFederation, mocksProvider.getElection(), executionBlock, @@ -3360,14 +3346,16 @@ void commitFederation_incompleteFederation() { @Test void commitFederation_hashMismatch() { - PendingFederation pendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersWithKeys(Arrays.asList(new BtcECKey[]{ + PendingFederation pendingFederation = new PendingFederation(FederationTestUtils.getFederationMembersWithKeys(Arrays.asList( BtcECKey.fromPublicOnly(Hex.decode("031da807c71c2f303b7f409dd2605b297ac494a563be3b9ca5f52d95a43d183cc5")), BtcECKey.fromPublicOnly(Hex.decode("025eefeeeed5cdc40822880c7db1d0a88b7b986945ed3fc05a0b45fe166fe85e12")) - }))); + ))); - VotingMocksProvider mocksProvider = new VotingMocksProvider("commit", new byte[][]{ - new Keccak256(HashUtil.keccak256(Hex.decode("aabbcc"))).getBytes() - }, true); + VotingMocksProvider mocksProvider = new VotingMocksProvider( + FederationChangeFunction.COMMIT.getKey(), + new byte[][]{new Keccak256(HashUtil.keccak256(Hex.decode("aabbcc"))).getBytes()}, + true + ); BridgeSupport bridgeSupport = getBridgeSupportWithMocksForFederationTests( false, @@ -3379,9 +3367,9 @@ void commitFederation_hashMismatch() { null ); - Assertions.assertArrayEquals(pendingFederation.getHash().getBytes(), bridgeSupport.getPendingFederationHash().getBytes()); + assertArrayEquals(pendingFederation.getHash().getBytes(), bridgeSupport.getPendingFederationHash().getBytes()); assertEquals(-3, mocksProvider.execute(bridgeSupport)); - Assertions.assertArrayEquals(pendingFederation.getHash().getBytes(), bridgeSupport.getPendingFederationHash().getBytes()); + assertArrayEquals(pendingFederation.getHash().getBytes(), bridgeSupport.getPendingFederationHash().getBytes()); verify(mocksProvider.getElection(), never()).clearWinners(); verify(mocksProvider.getElection(), never()).clear(); verify(mocksProvider.getElection(), never()).vote(mocksProvider.getSpec(), mocksProvider.getVoter()); @@ -3389,13 +3377,10 @@ void commitFederation_hashMismatch() { @Test void getActiveFederationWallet() { - List expectedFederationMembers = - FederationTestUtils.getFederationMembersWithBtcKeys( - Arrays.asList( - BtcECKey.fromPublicOnly(Hex.decode("036bb9eab797eadc8b697f0e82a01d01cabbfaaca37e5bafc06fdc6fdd38af894a")), - BtcECKey.fromPublicOnly(Hex.decode("031da807c71c2f303b7f409dd2605b297ac494a563be3b9ca5f52d95a43d183cc5")) - ) - ); + List expectedFederationMembers = FederationTestUtils.getFederationMembersWithBtcKeys(Arrays.asList( + BtcECKey.fromPublicOnly(Hex.decode("036bb9eab797eadc8b697f0e82a01d01cabbfaaca37e5bafc06fdc6fdd38af894a")), + BtcECKey.fromPublicOnly(Hex.decode("031da807c71c2f303b7f409dd2605b297ac494a563be3b9ca5f52d95a43d183cc5")) + )); FederationArgs expectedFederationArgs = new FederationArgs(expectedFederationMembers, Instant.ofEpochMilli(5005L), 0L, @@ -3430,7 +3415,7 @@ void getActiveFederationWallet() { return expectedWallet; }); - Assertions.assertSame(expectedWallet, bridgeSupport.getActiveFederationWallet(false)); + assertSame(expectedWallet, bridgeSupport.getActiveFederationWallet(false)); } } @@ -3546,8 +3531,6 @@ void getBtcTransactionConfirmations_inexistentBlockHash() throws BlockStoreExcep @Test void getBtcTransactionConfirmations_blockNotInBestChain() throws BlockStoreException, IOException { - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - Repository repository = createRepository(); Repository track = repository.startTracking(); @@ -3593,8 +3576,6 @@ void getBtcTransactionConfirmations_blockNotInBestChain() throws BlockStoreExcep @Test void getBtcTransactionConfirmations_blockNotInBestChainBlockWithHeightNotFound() throws BlockStoreException, IOException { - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - Repository repository = createRepository(); Repository track = repository.startTracking(); @@ -3639,8 +3620,6 @@ void getBtcTransactionConfirmations_blockNotInBestChainBlockWithHeightNotFound() @Test void getBtcTransactionConfirmations_blockTooOld() throws BlockStoreException, IOException { - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - Repository repository = createRepository(); Repository track = repository.startTracking(); @@ -3684,8 +3663,6 @@ void getBtcTransactionConfirmations_blockTooOld() throws BlockStoreException, IO @Test void getBtcTransactionConfirmations_heightInconsistency() throws BlockStoreException, IOException { - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - Repository repository = createRepository(); Repository track = repository.startTracking(); @@ -3730,8 +3707,6 @@ void getBtcTransactionConfirmations_heightInconsistency() throws BlockStoreExcep @Test void getBtcTransactionConfirmations_merkleBranchDoesNotProve() throws BlockStoreException, IOException { - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - Repository repository = createRepository(); Repository track = repository.startTracking(); @@ -3780,8 +3755,6 @@ void getBtcTransactionConfirmations_merkleBranchDoesNotProve() throws BlockStore @Test void getBtcTransactionConfirmationsGetCost_ok() throws BlockStoreException { - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - Repository repository = createRepository(); Repository track = repository.startTracking(); @@ -3856,8 +3829,6 @@ void getBtcTransactionConfirmationsGetCost_blockDoesNotExist() { @Test void getBtcTransactionConfirmationsGetCost_getBestChainHeightError() { - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - Repository repository = createRepository(); Repository track = repository.startTracking(); @@ -3919,8 +3890,6 @@ void getBtcTransactionConfirmationsGetCost_blockTooDeep() { @Test void getBtcBlockchainBlockHashAtDepth() throws Exception { - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - Repository repository = createRepository(); Repository track = repository.startTracking(); @@ -3954,31 +3923,17 @@ void getBtcBlockchainBlockHashAtDepth() throws Exception { assertEquals(btcParams.getGenesisBlock(), chainHead.getHeader()); assertEquals(btcParams.getGenesisBlock().getHash(), bridgeSupport.getBtcBlockchainBlockHashAtDepth(0)); - try { - bridgeSupport.getBtcBlockchainBlockHashAtDepth(-1); - Assertions.fail(); - } catch (IndexOutOfBoundsException e) { - } - try { - bridgeSupport.getBtcBlockchainBlockHashAtDepth(1); - Assertions.fail(); - } catch (IndexOutOfBoundsException e) { - } + + assertThrows(IndexOutOfBoundsException.class, () -> bridgeSupport.getBtcBlockchainBlockHashAtDepth(-1)); + assertThrows(IndexOutOfBoundsException.class, () -> bridgeSupport.getBtcBlockchainBlockHashAtDepth(1)); List blocks = createBtcBlocks(btcParams, btcParams.getGenesisBlock(), 10); bridgeSupport.receiveHeaders(blocks.toArray(new BtcBlock[]{})); assertEquals(btcParams.getGenesisBlock().getHash(), bridgeSupport.getBtcBlockchainBlockHashAtDepth(10)); - try { - bridgeSupport.getBtcBlockchainBlockHashAtDepth(-1); - Assertions.fail(); - } catch (IndexOutOfBoundsException e) { - } - try { - bridgeSupport.getBtcBlockchainBlockHashAtDepth(11); - Assertions.fail(); - } catch (IndexOutOfBoundsException e) { - } + assertThrows(IndexOutOfBoundsException.class, () -> bridgeSupport.getBtcBlockchainBlockHashAtDepth(-1)); + assertThrows(IndexOutOfBoundsException.class, () -> bridgeSupport.getBtcBlockchainBlockHashAtDepth(11)); + for (int i = 0; i < 10; i++) { assertEquals(blocks.get(i).getHash(), bridgeSupport.getBtcBlockchainBlockHashAtDepth(9 - i)); } @@ -4005,28 +3960,6 @@ private BridgeSupport getBridgeSupportWithMocksForFederationTests( ABICallElection mockedFederationElection, Block executionBlock) { - return getBridgeSupportWithMocksForFederationTests( - genesis, - mockedNewFederation, - mockedGenesisFederation, - mockedOldFederation, - mockedPendingFederation, - mockedFederationElection, - executionBlock, - null - ); - } - - private BridgeSupport getBridgeSupportWithMocksForFederationTests( - boolean genesis, - Federation mockedNewFederation, - Federation mockedGenesisFederation, - Federation mockedOldFederation, - PendingFederation mockedPendingFederation, - ABICallElection mockedFederationElection, - Block executionBlock, - BridgeEventLogger eventLogger) { - BridgeConstants constantsMock = mock(BridgeConstants.class); FederationConstants federationConstantsMock = mock(FederationConstants.class); @@ -4038,7 +3971,6 @@ private BridgeSupport getBridgeSupportWithMocksForFederationTests( when(federationConstantsMock.getBtcParams()).thenReturn(NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); when(federationConstantsMock.getFederationChangeAuthorizer()).thenReturn(federationConstants.getFederationChangeAuthorizer()); - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); long federationActivationAge = federationConstants.getFederationActivationAge(activations); when(federationConstantsMock.getFederationActivationAge(any())).thenReturn(federationActivationAge); @@ -4133,18 +4065,14 @@ public void setFederationElection(ABICallElection federationElection) { return bridgeSupportBuilder .withBridgeConstants(constantsMock) .withProvider(providerMock) - .withEventLogger(eventLogger) .withFederationSupport(federationSupport) .withExecutionBlock(executionBlock) .build(); } private BridgeSupport getBridgeSupportWithMocksForFederationTests( - boolean genesis, FederationStorageProvider federationStorageProvider, Federation mockedNewFederation, - Federation mockedGenesisFederation, - Federation mockedOldFederation, PendingFederation mockedPendingFederation, ABICallElection mockedFederationElection, Block executionBlock, @@ -4153,15 +4081,9 @@ private BridgeSupport getBridgeSupportWithMocksForFederationTests( BridgeConstants constantsMock = mock(BridgeConstants.class); FederationConstants federationConstantsMock = mock(FederationConstants.class); - if (mockedGenesisFederation != null) { - when(federationConstantsMock.getGenesisFederationCreationTime()).thenReturn(mockedGenesisFederation.getCreationTime()); - when(federationConstantsMock.getGenesisFederationPublicKeys()).thenReturn(mockedGenesisFederation.getBtcPublicKeys()); - } - when(federationConstantsMock.getBtcParams()).thenReturn(NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); when(federationConstantsMock.getFederationChangeAuthorizer()).thenReturn(federationConstants.getFederationChangeAuthorizer()); - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); long federationActivationAge = federationConstants.getFederationActivationAge(activations); when(federationConstantsMock.getFederationActivationAge(any())).thenReturn(federationActivationAge); @@ -4215,8 +4137,7 @@ public void setFederationElection(ABICallElection federationElection) { when(federationStorageProvider.getOldFederationBtcUTXOs()).then((InvocationOnMock m) -> holder.retiringUTXOs); when(federationStorageProvider.getNewFederationBtcUTXOs(any(), any())).then((InvocationOnMock m) -> holder.activeUTXOs); - holder.setActiveFederation(genesis ? null : mockedNewFederation); - holder.setRetiringFederation(mockedOldFederation); + holder.setActiveFederation(mockedNewFederation); when(federationStorageProvider.getNewFederation(any(), any())).then((InvocationOnMock m) -> holder.getActiveFederation()); when(federationStorageProvider.getOldFederation(any(), any())).then((InvocationOnMock m) -> holder.getRetiringFederation()); when(federationStorageProvider.getPendingFederation()).then((InvocationOnMock m) -> holder.getPendingFederation()); @@ -4226,7 +4147,7 @@ public void setFederationElection(ABICallElection federationElection) { } if (holder.getFederationElection() == null) { - AddressBasedAuthorizer auth = m.getArgument(0); + AddressBasedAuthorizer auth = m.getArgument(0); holder.setFederationElection(new ABICallElection(auth)); } diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportPegoutTransactionCreatedEventTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportPegoutTransactionCreatedEventTest.java index af2f8992158..2ab9526a692 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportPegoutTransactionCreatedEventTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportPegoutTransactionCreatedEventTest.java @@ -104,7 +104,7 @@ void updateCollections_whenPegoutBatchIsCreated_shouldLogPegoutTransactionCreate activations ); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withProvider(provider) .withEventLogger(eventLogger) @@ -179,7 +179,7 @@ void updateCollections_whenPegoutMigrationIsCreated_shouldLogPegoutTransactionCr rskCurrentBlock, activations ); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withProvider(provider) .withEventLogger(eventLogger) @@ -263,7 +263,7 @@ void updateCollections_whenPegoutMigrationAndBatchAreCreated_shouldLogPegoutTran rskCurrentBlock, activations ); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withProvider(provider) .withEventLogger(eventLogger) diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportProcessFundsMigrationTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportProcessFundsMigrationTest.java index 3420a677b38..dd4bdbd38f3 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportProcessFundsMigrationTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportProcessFundsMigrationTest.java @@ -156,15 +156,14 @@ void test_processFundsMigration( FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupportBuilder federationSupportBuilder = new FederationSupportBuilder(); - FederationSupport federationSupport = federationSupportBuilder + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(federationConstants) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(rskCurrentBlock) .withActivations(activations) .build(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeConstants) .withProvider(provider) .withEventLogger(bridgeEventLogger) @@ -223,21 +222,21 @@ void test_processFundsMigration( private Transaction buildUpdateCollectionsTransaction() { final String TO_ADDRESS = "0000000000000000000000000000000000000006"; - final BigInteger DUST_AMOUNT = new BigInteger("1"); - final BigInteger NONCE = new BigInteger("0"); - final BigInteger GAS_PRICE = new BigInteger("100"); - final BigInteger GAS_LIMIT = new BigInteger("1000"); + final BigInteger dustAmount = new BigInteger("1"); + final BigInteger nonce = new BigInteger("0"); + final BigInteger gasPrice = new BigInteger("100"); + final BigInteger gasLimit = new BigInteger("1000"); final String DATA = "80af2871"; return Transaction .builder() - .nonce(NONCE) - .gasPrice(GAS_PRICE) - .gasLimit(GAS_LIMIT) + .nonce(nonce) + .gasPrice(gasPrice) + .gasLimit(gasLimit) .destination(Hex.decode(TO_ADDRESS)) .data(Hex.decode(DATA)) .chainId(Constants.REGTEST_CHAIN_ID) - .value(DUST_AMOUNT) + .value(dustAmount) .build(); } } diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportRSKIP220NewMethodsTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportRSKIP220NewMethodsTest.java index c44caa48da5..fe4cf6386a0 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportRSKIP220NewMethodsTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportRSKIP220NewMethodsTest.java @@ -61,7 +61,7 @@ void setUpOnEachTest() throws BlockStoreException { when(btcBlockStore.getStoredBlockAtMainChainHeight(height)).thenReturn(new StoredBlock(btcBlock, BigInteger.ONE, height)); - bridgeSupport = new BridgeSupportBuilder() + bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeConstants) .withBtcBlockStoreFactory(btcBlockStoreFactory) .withActivations(activationsAfterForks) diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportRegisterBtcTransactionTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportRegisterBtcTransactionTest.java index eb01b9a7a7b..b0667b443a5 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportRegisterBtcTransactionTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportRegisterBtcTransactionTest.java @@ -56,7 +56,6 @@ import org.junit.jupiter.params.provider.MethodSource; class BridgeSupportRegisterBtcTransactionTest { - private static final BridgeConstants bridgeMainnetConstants = BridgeMainNetConstants.getInstance(); private static final FederationConstants federationMainnetConstants = bridgeMainnetConstants.getFederationConstants(); private static final NetworkParameters btcMainnetParams = bridgeMainnetConstants.getBtcParams(); @@ -549,15 +548,14 @@ private BridgeSupport buildBridgeSupport(ActivationConfig.ForBlock activations) when(lockWhitelist.isWhitelistedFor(any(Address.class), any(Coin.class), any(int.class))).thenReturn(true); when(whitelistStorageProvider.getLockWhitelist(activations, btcMainnetParams)).thenReturn(lockWhitelist); - FederationSupportBuilder federationSupportBuilder = new FederationSupportBuilder(); - FederationSupport federationSupport = federationSupportBuilder + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(federationMainnetConstants) .withFederationStorageProvider(federationStorageProvider) .withActivations(activations) .withRskExecutionBlock(rskExecutionBlock) .build(); - return new BridgeSupportBuilder() + return BridgeSupportBuilder.builder() .withBtcBlockStoreFactory(mockFactory) .withBridgeConstants(bridgeMainnetConstants) .withRepository(repository) @@ -1224,11 +1222,7 @@ void pegin_v1_two_rsk_op_return_cannot_be_registered( verify(bridgeEventLogger, never()).logPeginBtc(any(), any(), any(), anyInt()); verify(bridgeEventLogger, never()).logUnrefundablePegin(any(), any()); - if (activations == fingerrootActivations) { - verify(bridgeEventLogger, times(1)).logRejectedPegin(btcTransaction, PEGIN_V1_INVALID_PAYLOAD); - } else { - verify(bridgeEventLogger, times(1)).logRejectedPegin(btcTransaction, PEGIN_V1_INVALID_PAYLOAD); - } + verify(bridgeEventLogger, times(1)).logRejectedPegin(btcTransaction, PEGIN_V1_INVALID_PAYLOAD); verify(provider, times(1)).setHeightBtcTxhashAlreadyProcessed(btcTransaction.getHash(false), rskExecutionBlock.getNumber()); assertTrue(retiringFederationUtxos.isEmpty()); } @@ -2530,26 +2524,23 @@ void old_fed_migration( NetworkParameters btcRegTestsParams = bridgeRegTestConstants.getBtcParams(); Context.propagate(new Context(btcRegTestsParams)); - final List REGTEST_OLD_FEDERATION_PRIVATE_KEYS = Arrays.asList( + final List regtestOldFederationPrivateKeys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("47129ffed2c0273c75d21bb8ba020073bb9a1638df0e04853407461fdd9e8b83")), BtcECKey.fromPrivate(Hex.decode("9f72d27ba603cfab5a0201974a6783ca2476ec3d6b4e2625282c682e0e5f1c35")), BtcECKey.fromPrivate(Hex.decode("e1b17fcd0ef1942465eee61b20561b16750191143d365e71de08b33dd84a9788")) ); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); when(provider.getHeightIfBtcTxhashIsAlreadyProcessed(any(Sha256Hash.class))).thenReturn(Optional.empty()); LockWhitelist lockWhitelist = mock(LockWhitelist.class); when(lockWhitelist.isWhitelistedFor(any(Address.class), any(Coin.class), any(int.class))).thenReturn(true); when(whitelistStorageProvider.getLockWhitelist(lovell700Activations, btcMainnetParams)).thenReturn(lockWhitelist); - FederationStorageProvider federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(btcRegTestsParams, activations)).thenReturn(activeFederationUtxos); pegoutsWaitingForConfirmations = new PegoutsWaitingForConfirmations(new HashSet<>()); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(pegoutsWaitingForConfirmations); - Federation oldFederation = createFederation(bridgeRegTestConstants, REGTEST_OLD_FEDERATION_PRIVATE_KEYS); - Federation activeFederation = FederationTestUtils.getGenesisFederation(bridgeRegTestConstants.getFederationConstants()); + Federation oldFederation = createFederation(bridgeRegTestConstants, regtestOldFederationPrivateKeys); BtcTransaction migrationTx = new BtcTransaction(btcRegTestsParams); Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(null, oldFederation.getRedeemScript()); @@ -2562,12 +2553,12 @@ void old_fed_migration( when(federationStorageProvider.getLastRetiredFederationP2SHScript(activations)).thenReturn(Optional.ofNullable(inputScript)); - FederationTestUtils.addSignatures(oldFederation, REGTEST_OLD_FEDERATION_PRIVATE_KEYS, migrationTx); + FederationTestUtils.addSignatures(oldFederation, regtestOldFederationPrivateKeys, migrationTx); PartialMerkleTree pmt = new PartialMerkleTree(btcRegTestsParams, new byte[]{0x3f}, Collections.singletonList(migrationTx.getHash()), 1); Sha256Hash blockMerkleRoot = pmt.getTxnHashAndMerkleRoot(new ArrayList<>()); - co.rsk.bitcoinj.core.BtcBlock registerHeader = new co.rsk.bitcoinj.core.BtcBlock( + registerHeader = new co.rsk.bitcoinj.core.BtcBlock( btcRegTestsParams, 1, BitcoinTestUtils.createHash(1), @@ -2624,8 +2615,7 @@ void old_fed_migration( FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupportBuilder federationSupportBuilder = new FederationSupportBuilder(); - FederationSupport federationSupport = federationSupportBuilder + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(bridgeRegTestConstants.getFederationConstants()) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(rskExecutionBlock) @@ -2633,7 +2623,7 @@ void old_fed_migration( .build(); // act - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBtcBlockStoreFactory(mockFactory) .withBridgeConstants(bridgeRegTestConstants) .withProvider(provider) diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportReleaseBtcTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportReleaseBtcTest.java index 4d70c9bd9a8..6628e71992d 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportReleaseBtcTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportReleaseBtcTest.java @@ -101,7 +101,7 @@ class BridgeSupportReleaseBtcTest { private FeePerKbSupport feePerKbSupport; @BeforeEach - void setUpOnEachTest() throws IOException { + void setUpOnEachTest() { signatureCache = new BlockTxSignatureCache(new ReceivedTxSignatureCache()); bridgeConstants = new BridgeRegTestConstants(); federationConstants = bridgeConstants.getFederationConstants(); @@ -113,7 +113,7 @@ void setUpOnEachTest() throws IOException { utxo = buildUTXO(); provider = initProvider(repository, activationMock); federationStorageProvider = initFederationStorageProvider(repository, activationMock); - bridgeSupportBuilder = new BridgeSupportBuilder(); + bridgeSupportBuilder = BridgeSupportBuilder.builder(); feePerKbSupport = mock(FeePerKbSupportImpl.class); when(feePerKbSupport.getFeePerKb()).thenReturn(bridgeConstants.getFeePerKbConstants().getGenesisFeePerKb()); bridgeSupport = spy(initBridgeSupport(eventLogger, activationMock)); @@ -231,8 +231,8 @@ void handmade_release_after_rskip_146() throws IOException { when(activationMock.isActive(ConsensusRule.RSKIP185)).thenReturn(false); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); bridgeSupport.releaseBtc(releaseTx); @@ -243,7 +243,7 @@ void handmade_release_after_rskip_146() throws IOException { verify(repository, never()).transfer(any(), any(), any()); assertEquals(1, provider.getPegoutsWaitingForConfirmations().getEntries().size()); assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); - verify(eventLogger, times(1)).logReleaseBtcRequested( + verify(bridgeEventLogger, times(1)).logReleaseBtcRequested( any(byte[].class), any(BtcTransaction.class), any(Coin.class) @@ -257,8 +257,8 @@ void handmade_release_after_rskip_146_185() throws IOException { when(activationMock.isActive(ConsensusRule.RSKIP326)).thenReturn(false); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); bridgeSupport.releaseBtc(releaseTx); @@ -272,13 +272,13 @@ void handmade_release_after_rskip_146_185() throws IOException { assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); assertEquals(3, logInfo.size()); - verify(eventLogger, times(1)).logReleaseBtcRequested( + verify(bridgeEventLogger, times(1)).logReleaseBtcRequested( any(byte[].class), any(BtcTransaction.class), any(Coin.class) ); - verify(eventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); - verify(eventLogger, times(1)).logUpdateCollections(any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logUpdateCollections(any()); LogInfo logInfo1 = logInfo.get(0); CallTransaction.Function event = BridgeEvents.RELEASE_REQUEST_RECEIVED_LEGACY.getEvent(); @@ -294,8 +294,8 @@ void handmade_release_after_rskip_146_185_326() throws IOException { List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); bridgeSupport.releaseBtc(releaseTx); @@ -309,14 +309,14 @@ void handmade_release_after_rskip_146_185_326() throws IOException { assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); assertEquals(3, logInfo.size()); - verify(eventLogger, times(1)).logReleaseBtcRequested( + verify(bridgeEventLogger, times(1)).logReleaseBtcRequested( any(byte[].class), any(BtcTransaction.class), any(Coin.class) ); - verify(eventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); - verify(eventLogger, times(1)).logUpdateCollections(any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logUpdateCollections(any()); LogInfo logInfo1 = logInfo.get(0); CallTransaction.Function event = BridgeEvents.RELEASE_REQUEST_RECEIVED.getEvent(); @@ -331,8 +331,8 @@ void handmade_release_after_rskip_146_rejected_lowAmount() throws IOException { List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); releaseTx = buildReleaseRskTx(Coin.ZERO); bridgeSupport.releaseBtc(releaseTx); @@ -345,11 +345,11 @@ void handmade_release_after_rskip_146_rejected_lowAmount() throws IOException { assertEquals(0, provider.getPegoutsWaitingForConfirmations().getEntries().size()); assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); - verify(eventLogger, never()).logReleaseBtcRequestRejected(any(), any(), any()); + verify(bridgeEventLogger, never()).logReleaseBtcRequestRejected(any(), any(), any()); assertEquals(1, logInfo.size()); - verify(eventLogger, times(1)).logUpdateCollections(any()); + verify(bridgeEventLogger, times(1)).logUpdateCollections(any()); } @Test @@ -357,10 +357,9 @@ void handmade_release_after_rskip_146_185_rejected_lowAmount() throws IOExceptio when(activationMock.isActive(ConsensusRule.RSKIP146)).thenReturn(true); when(activationMock.isActive(ConsensusRule.RSKIP185)).thenReturn(true); - List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); releaseTx = buildReleaseRskTx(Coin.ZERO); bridgeSupport.releaseBtc(releaseTx); @@ -379,9 +378,9 @@ void handmade_release_after_rskip_146_185_rejected_lowAmount() throws IOExceptio assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); assertEquals(2, logInfo.size()); - verify(eventLogger, never()).logReleaseBtcRequestReceived(any(), any(), any()); - verify(eventLogger, times(1)).logReleaseBtcRequestRejected(any(), any(), any()); - verify(eventLogger, times(1)).logUpdateCollections(any()); + verify(bridgeEventLogger, never()).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestRejected(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logUpdateCollections(any()); } @@ -392,8 +391,8 @@ void handmade_release_after_rskip_146_185_rejected_contractCaller() throws IOExc List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); releaseTx = buildReleaseRskTx_fromContract(Coin.COIN); bridgeSupport.releaseBtc(releaseTx); @@ -409,11 +408,11 @@ void handmade_release_after_rskip_146_185_rejected_contractCaller() throws IOExc assertEquals(0, provider.getPegoutsWaitingForConfirmations().getEntries().size()); assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); - verify(eventLogger, never()).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, never()).logReleaseBtcRequestReceived(any(), any(), any()); assertEquals(2, logInfo.size()); - verify(eventLogger, times(1)).logReleaseBtcRequestRejected(any(), any(), any()); - verify(eventLogger, times(1)).logUpdateCollections(any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestRejected(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logUpdateCollections(any()); } @Test @@ -423,8 +422,8 @@ void handmade_release_after_rskip_146_rejected_contractCaller() throws IOExcepti when(activationMock.isActive(ConsensusRule.RSKIP185)).thenReturn(false); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); releaseTx = buildReleaseRskTx_fromContract(Coin.COIN); try { @@ -442,8 +441,8 @@ void release_after_rskip_219() throws IOException { when(activationMock.isActive(ConsensusRule.RSKIP219)).thenReturn(true); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); // Get a value between old and new minimum pegout values Coin middle = bridgeConstants.getLegacyMinimumPegoutTxValue().subtract(bridgeConstants.getMinimumPegoutTxValue()).div(2); @@ -460,7 +459,7 @@ void release_after_rskip_219() throws IOException { assertEquals(1, provider.getReleaseRequestQueue().getEntries().size()); assertEquals(1, logInfo.size()); - verify(eventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); LogInfo logInfo1 = logInfo.get(0); CallTransaction.Function event = BridgeEvents.RELEASE_REQUEST_RECEIVED_LEGACY.getEvent(); @@ -476,8 +475,8 @@ void release_after_rskip_219_326() throws IOException { when(activationMock.isActive(ConsensusRule.RSKIP326)).thenReturn(true); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); // Get a value between old and new minimum pegout values Coin middle = bridgeConstants.getLegacyMinimumPegoutTxValue().subtract(bridgeConstants.getMinimumPegoutTxValue()).div(2); @@ -494,7 +493,7 @@ void release_after_rskip_219_326() throws IOException { assertEquals(1, provider.getReleaseRequestQueue().getEntries().size()); assertEquals(1, logInfo.size()); - verify(eventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); LogInfo logInfo1 = logInfo.get(0); CallTransaction.Function event = BridgeEvents.RELEASE_REQUEST_RECEIVED.getEvent(); @@ -509,8 +508,8 @@ void release_before_rskip_219() throws IOException { when(activationMock.isActive(ConsensusRule.RSKIP219)).thenReturn(false); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); // Get a value between old and new minimum pegout values Coin middle = bridgeConstants.getLegacyMinimumPegoutTxValue().subtract(bridgeConstants.getMinimumPegoutTxValue()).div(2); @@ -525,8 +524,8 @@ void release_before_rskip_219() throws IOException { assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); assertEquals(1, logInfo.size()); - verify(eventLogger, never()).logReleaseBtcRequestReceived(any(), any(), any()); - verify(eventLogger, times(1)).logReleaseBtcRequestRejected(any(), any(), any()); + verify(bridgeEventLogger, never()).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestRejected(any(), any(), any()); } @Test @@ -536,8 +535,8 @@ void release_before_rskip_219_minimum_exclusive() throws IOException { when(activationMock.isActive(ConsensusRule.RSKIP219)).thenReturn(false); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); // Get a value exactly to legacy minimum Coin value = bridgeConstants.getLegacyMinimumPegoutTxValue(); @@ -549,8 +548,8 @@ void release_before_rskip_219_minimum_exclusive() throws IOException { assertEquals(0, provider.getReleaseRequestQueue().getEntries().size()); assertEquals(1, logInfo.size()); - verify(eventLogger, never()).logReleaseBtcRequestReceived(any(), any(), any()); - verify(eventLogger, times(1)).logReleaseBtcRequestRejected(any(), any(), any()); + verify(bridgeEventLogger, never()).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestRejected(any(), any(), any()); } @Test @@ -560,8 +559,8 @@ void release_after_rskip_219_minimum_inclusive() throws IOException { when(activationMock.isActive(ConsensusRule.RSKIP219)).thenReturn(true); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); // Get a value exactly to current minimum Coin value = bridgeConstants.getMinimumPegoutTxValue(); @@ -575,7 +574,7 @@ void release_after_rskip_219_minimum_inclusive() throws IOException { assertEquals(1, provider.getReleaseRequestQueue().getEntries().size()); assertEquals(1, logInfo.size()); - verify(eventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); LogInfo logInfo1 = logInfo.get(0); CallTransaction.Function event = BridgeEvents.RELEASE_REQUEST_RECEIVED_LEGACY.getEvent(); @@ -591,8 +590,8 @@ void release_after_rskip_219_326_minimum_inclusive() throws IOException { when(activationMock.isActive(ConsensusRule.RSKIP326)).thenReturn(true); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); - bridgeSupport = initBridgeSupport(eventLogger, activationMock); + BridgeEventLoggerImpl bridgeEventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + bridgeSupport = initBridgeSupport(bridgeEventLogger, activationMock); // Get a value exactly to current minimum Coin value = bridgeConstants.getMinimumPegoutTxValue(); @@ -606,7 +605,7 @@ void release_after_rskip_219_326_minimum_inclusive() throws IOException { assertEquals(1, provider.getReleaseRequestQueue().getEntries().size()); assertEquals(1, logInfo.size()); - verify(eventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); + verify(bridgeEventLogger, times(1)).logReleaseBtcRequestReceived(any(), any(), any()); LogInfo logInfo1 = logInfo.get(0); CallTransaction.Function event = BridgeEvents.RELEASE_REQUEST_RECEIVED.getEvent(); @@ -665,16 +664,16 @@ void test_processPegoutsIndividually_before_RSKIP271_activation() throws IOExcep federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); - when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Arrays.asList( + BridgeStorageProvider bridgeStorageProvider = mock(BridgeStorageProvider.class); + when(bridgeStorageProvider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Arrays.asList( new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "one"), Coin.COIN), new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "two"), Coin.COIN)) )); - when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); + when(bridgeStorageProvider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) - .withProvider(provider) + .withProvider(bridgeStorageProvider) .withActivations(activationMock) .build(); @@ -682,11 +681,11 @@ void test_processPegoutsIndividually_before_RSKIP271_activation() throws IOExcep bridgeSupport.updateCollections(rskTx); // assert pegouts were not batched - assertEquals(1, provider.getReleaseRequestQueue().getEntries().size()); - assertEquals(1, provider.getPegoutsWaitingForConfirmations().getEntries().size()); + assertEquals(1, bridgeStorageProvider.getReleaseRequestQueue().getEntries().size()); + assertEquals(1, bridgeStorageProvider.getPegoutsWaitingForConfirmations().getEntries().size()); - verify(provider, never()).getNextPegoutHeight(); - verify(provider, never()).setNextPegoutHeight(any(Long.class)); + verify(bridgeStorageProvider, never()).getNextPegoutHeight(); + verify(bridgeStorageProvider, never()).setNextPegoutHeight(any(Long.class)); } @Test @@ -707,7 +706,7 @@ void test_processPegoutsInBatch_after_RSKIP271() throws IOException { federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); + provider = mock(BridgeStorageProvider.class); when(provider.getReleaseRequestQueue()).thenReturn(pegoutRequests); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); @@ -721,7 +720,7 @@ void test_processPegoutsInBatch_after_RSKIP271() throws IOException { .map(ReleaseRequestQueue.Entry::getRskTxHash) .collect(Collectors.toList()); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withActivations(activationMock) .withBridgeConstants(bridgeConstants) .withProvider(provider) @@ -753,7 +752,7 @@ void test_processPegoutsInBatch_after_RSKIP271_activation_next_pegout_height_not long executionBlockNumber = executionBlock.getNumber(); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); + provider = mock(BridgeStorageProvider.class); when(provider.getNextPegoutHeight()).thenReturn(Optional.of(executionBlockNumber + bridgeConstants.getNumberOfBlocksBetweenPegouts() - 1)); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Arrays.asList( new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "one"), Coin.MILLICOIN), @@ -761,7 +760,7 @@ void test_processPegoutsInBatch_after_RSKIP271_activation_next_pegout_height_not ))); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) .withProvider(provider) .withExecutionBlock(executionBlock) @@ -780,10 +779,9 @@ void test_processPegoutsInBatch_after_RSKIP271_activation_next_pegout_height_not @Test void test_processPegoutsInBatch_after_RSKIP271_activation_no_requests_in_queue_updates_next_pegout_height() throws IOException { - when(activationMock.isActive(ConsensusRule.RSKIP271)).thenReturn(true); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); + provider = mock(BridgeStorageProvider.class); when(provider.getNextPegoutHeight()).thenReturn(Optional.of(100L)); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Collections.emptyList())); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); @@ -791,7 +789,7 @@ void test_processPegoutsInBatch_after_RSKIP271_activation_no_requests_in_queue_u Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(100L); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withActivations(activationMock) .withBridgeConstants(bridgeConstants) .withProvider(provider) @@ -817,10 +815,9 @@ void test_processPegoutsInBatch_after_rskip_271_Insufficient_Money() throws IOEx federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); - when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); + + provider = mock(BridgeStorageProvider.class); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Arrays.asList( new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "one"), Coin.COIN), new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "two"), Coin.COIN), @@ -830,7 +827,7 @@ void test_processPegoutsInBatch_after_rskip_271_Insufficient_Money() throws IOEx ))); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withActivations(activationMock) .withBridgeConstants(bridgeConstants) .withProvider(provider) @@ -854,17 +851,17 @@ void test_processPegoutsInBatch_after_rskip_271_divide_transaction_when_max_size federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - FederationSupport federationSupport = new FederationSupportBuilder() + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(federationConstants) .withFederationStorageProvider(federationStorageProvider) .withActivations(activationMock) .build(); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); + provider = mock(BridgeStorageProvider.class); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(PegTestUtils.createReleaseRequestQueueEntries(600))); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withActivations(activationMock) .withBridgeConstants(bridgeConstants) .withProvider(provider) @@ -896,13 +893,13 @@ void test_processPegoutsInBatch_after_rskip_271_when_max_size_exceeded_for_one_p federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); + provider = mock(BridgeStorageProvider.class); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Collections.singletonList( new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "one"), Coin.COIN.multiply(700)) ))); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withActivations(activationMock) .withBridgeConstants(bridgeConstants) .withProvider(provider) @@ -925,14 +922,14 @@ void test_processPegoutsInBatch_after_rskip_271_when_max_size_exceeded_for_two_p federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); + provider = mock(BridgeStorageProvider.class); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Arrays.asList( new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "one"), Coin.COIN.multiply(700)), new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "two"), Coin.COIN.multiply(700)) ))); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withActivations(activationMock) .withBridgeConstants(bridgeConstants) .withProvider(provider) @@ -966,12 +963,11 @@ void test_processPegoutsIndividually_before_rskip_271_no_funds_to_process_any_re federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); - when(provider.getReleaseRequestQueue()) - .thenReturn(pegoutRequests); + provider = mock(BridgeStorageProvider.class); + when(provider.getReleaseRequestQueue()).thenReturn(pegoutRequests); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) .withProvider(provider) .withActivations(activationMock) @@ -1015,12 +1011,11 @@ void test_processPegoutsIndividually_before_rskip_271_no_funds_to_process_any_re federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); - when(provider.getReleaseRequestQueue()) - .thenReturn(pegoutRequests); + provider = mock(BridgeStorageProvider.class); + when(provider.getReleaseRequestQueue()).thenReturn(pegoutRequests); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) .withProvider(provider) .withActivations(activationMock) @@ -1030,9 +1025,7 @@ void test_processPegoutsIndividually_before_rskip_271_no_funds_to_process_any_re bridgeSupport.updateCollections(rskTx); assertNotEquals(originalPegoutRequests, provider.getReleaseRequestQueue()); - assertEquals(expectedPegoutRequests, provider.getReleaseRequestQueue()); - assertEquals(0, provider.getPegoutsWaitingForConfirmations().getEntries().size()); } @@ -1047,7 +1040,7 @@ void test_check_wallet_balance_before_rskip_271_process_at_least_one_request() t federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); + provider = mock(BridgeStorageProvider.class); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Arrays.asList( new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "one"), Coin.COIN.multiply(4)), new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "two"), Coin.COIN.multiply(3)), @@ -1055,7 +1048,7 @@ void test_check_wallet_balance_before_rskip_271_process_at_least_one_request() t ))); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) .withProvider(provider) .withActivations(activationMock) @@ -1082,7 +1075,7 @@ void test_check_wallet_balance_after_rskip_271_process_no_requests() throws IOEx federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); + provider = mock(BridgeStorageProvider.class); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Arrays.asList( new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "one"), Coin.COIN.multiply(5)), new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "two"), Coin.COIN.multiply(4)), @@ -1090,7 +1083,7 @@ void test_check_wallet_balance_after_rskip_271_process_no_requests() throws IOEx ))); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) .withProvider(provider) .withActivations(activationMock) @@ -1120,7 +1113,7 @@ void test_check_wallet_balance_after_rskip_271_process_all_requests_when_utxos_a federationStorageProvider = mock(FederationStorageProvider.class); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); + provider = mock(BridgeStorageProvider.class); when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Arrays.asList( new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "one"), Coin.COIN.multiply(5)), new ReleaseRequestQueue.Entry(BitcoinTestUtils.createP2PKHAddress(bridgeConstants.getBtcParams(), "two"), Coin.COIN.multiply(4)), @@ -1128,7 +1121,7 @@ void test_check_wallet_balance_after_rskip_271_process_all_requests_when_utxos_a ))); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - BridgeSupport bridgeSupport = bridgeSupportBuilder + bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) .withProvider(provider) .withActivations(activationMock) @@ -1147,7 +1140,7 @@ void test_check_wallet_balance_after_rskip_271_process_all_requests_when_utxos_a utxos.add(PegTestUtils.createUTXO(4, 3, Coin.COIN.multiply(1), genesisFederation.getAddress())); when(federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock)).thenReturn(utxos); - FederationSupport federationSupport = new FederationSupportBuilder() + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(federationConstants) .withFederationStorageProvider(federationStorageProvider) .withActivations(activationMock) @@ -1179,7 +1172,7 @@ private void testPegoutMinimumWithFeeVerificationPass(Coin feePerKB, Coin value) when(activationMock.isActive(ConsensusRule.RSKIP219)).thenReturn(true); List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); bridgeSupport = initBridgeSupport(eventLogger, activationMock); when(feePerKbSupport.getFeePerKb()).thenReturn(feePerKB); @@ -1213,7 +1206,7 @@ private void testPegoutMinimumWithFeeVerificationRejectedByLowAmount(Coin feePer RskAddress bridgeAddress = PrecompiledContracts.BRIDGE_ADDR; List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); bridgeSupport = initBridgeSupport(eventLogger, activationMock); when(feePerKbSupport.getFeePerKb()).thenReturn(feePerKB); @@ -1254,7 +1247,7 @@ private void testPegoutMinimumWithFeeVerificationRejectedByFeeAboveValue(Coin fe RskAddress bridgeAddress = PrecompiledContracts.BRIDGE_ADDR; List logInfo = new ArrayList<>(); - BridgeEventLoggerImpl eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); + eventLogger = spy(new BridgeEventLoggerImpl(bridgeConstants, activationMock, logInfo, signatureCache)); bridgeSupport = initBridgeSupport(eventLogger, activationMock); when(feePerKbSupport.getFeePerKb()).thenReturn(feePerKB); @@ -1301,7 +1294,7 @@ private Transaction buildReleaseRskTx() { } private Transaction buildReleaseRskTx(Coin coin) { - Transaction releaseTx = Transaction + Transaction releaseTransaction = Transaction .builder() .nonce(NONCE) .gasPrice(GAS_PRICE) @@ -1311,12 +1304,12 @@ private Transaction buildReleaseRskTx(Coin coin) { .chainId(Constants.REGTEST_CHAIN_ID) .value(co.rsk.core.Coin.fromBitcoin(coin).asBigInteger()) .build(); - releaseTx.sign(SENDER.getPrivKeyBytes()); - return releaseTx; + releaseTransaction.sign(SENDER.getPrivKeyBytes()); + return releaseTransaction; } private Transaction buildReleaseRskTx_fromContract(Coin coin) { - Transaction releaseTx = Transaction + Transaction releaseTransaction = Transaction .builder() .nonce(NONCE) .gasPrice(GAS_PRICE) @@ -1326,8 +1319,8 @@ private Transaction buildReleaseRskTx_fromContract(Coin coin) { .chainId(Constants.REGTEST_CHAIN_ID) .value(co.rsk.core.Coin.fromBitcoin(coin).asBigInteger()) .build(); - releaseTx.sign(SENDER.getPrivKeyBytes()); - return new InternalTransaction(releaseTx.getHash().getBytes(), 400, 0, NONCE.toByteArray(), + releaseTransaction.sign(SENDER.getPrivKeyBytes()); + return new InternalTransaction(releaseTransaction.getHash().getBytes(), 400, 0, NONCE.toByteArray(), DataWord.valueOf(GAS_PRICE.intValue()), DataWord.valueOf(GAS_LIMIT.intValue()), SENDER.getAddress(), PrecompiledContracts.BRIDGE_ADDR.getBytes(), co.rsk.core.Coin.fromBitcoin(Coin.COIN).getBytes(), Hex.decode(DATA), "", new BlockTxSignatureCache(new ReceivedTxSignatureCache())); @@ -1347,7 +1340,7 @@ private Transaction buildUpdateTx() { } private BridgeSupport initBridgeSupport(BridgeEventLogger eventLogger, ActivationConfig.ForBlock activationMock) { - FederationSupport federationSupport = new FederationSupportBuilder() + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(federationConstants) .withFederationStorageProvider(federationStorageProvider) .build(); @@ -1370,10 +1363,11 @@ private BridgeStorageProvider initProvider(Repository repository, ActivationConf private FederationStorageProvider initFederationStorageProvider(Repository repository, ActivationConfig.ForBlock activationMock) { StorageAccessor bridgeStorageAccessor = new BridgeStorageAccessorImpl(repository); - FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(bridgeStorageAccessor); - federationStorageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock).add(utxo); - federationStorageProvider.setNewFederation(activeFederation); - return federationStorageProvider; + FederationStorageProvider storageProvider = new FederationStorageProviderImpl(bridgeStorageAccessor); + storageProvider.getNewFederationBtcUTXOs(networkParameters, activationMock).add(utxo); + storageProvider.setNewFederation(activeFederation); + + return storageProvider; } private static Repository createRepository() { diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportSigHashTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportSigHashTest.java index fa5f96ecd26..93012d2cd69 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportSigHashTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportSigHashTest.java @@ -80,13 +80,13 @@ void test_pegoutTxIndex_when_pegout_batch_is_created(ActivationConfig.ForBlock a FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = new FederationSupportBuilder() + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(federationMainnetConstants) .withFederationStorageProvider(federationStorageProvider) .withActivations(activations) .build(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withProvider(provider) .withActivations(activations) @@ -150,14 +150,14 @@ void test_pegoutTxIndex_when_migration_tx_is_created(ActivationConfig.ForBlock a FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = new FederationSupportBuilder() + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(federationMainnetConstants) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(rskCurrentBlock) .withActivations(activations) .build(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withProvider(provider) .withExecutionBlock(rskCurrentBlock) @@ -234,14 +234,14 @@ void test_pegoutTxIndex_when_migration_and_pegout_batch_tx_are_created(Activatio FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = new FederationSupportBuilder() + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(federationMainnetConstants) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(rskCurrentBlock) .withActivations(activations) .build(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withProvider(provider) .withExecutionBlock(rskCurrentBlock) diff --git a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportTest.java b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportTest.java index 87c76d07591..edcb52e2eae 100644 --- a/rskj-core/src/test/java/co/rsk/peg/BridgeSupportTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/BridgeSupportTest.java @@ -89,13 +89,19 @@ class BridgeSupportTest { private final BridgeConstants bridgeConstantsRegtest = new BridgeRegTestConstants(); private final BridgeConstants bridgeMainNetConstants = BridgeMainNetConstants.getInstance(); private final FederationConstants federationConstantsRegtest = bridgeConstantsRegtest.getFederationConstants(); + private final FederationConstants federationConstantsMainnet = bridgeMainNetConstants.getFederationConstants(); + private final NetworkParameters btcRegTestParams = bridgeConstantsRegtest.getBtcParams(); private final NetworkParameters btcMainnetParams = bridgeMainNetConstants.getBtcParams(); - private BridgeSupportBuilder bridgeSupportBuilder; - private WhitelistSupport whitelistSupport; + + private final BridgeSupportBuilder bridgeSupportBuilder = BridgeSupportBuilder.builder(); + private final FederationSupportBuilder federationSupportBuilder = FederationSupportBuilder.builder(); + private WhitelistStorageProvider whitelistStorageProvider; - private FederationSupportBuilder federationSupportBuilder; + private WhitelistSupport whitelistSupport; private LockingCapSupport lockingCapSupport; + private FederationSupport federationSupport; + private FeePerKbSupport feePerKbSupport; private static final String TO_ADDRESS = "0000000000000000000000000000000000000006"; private static final BigInteger DUST_AMOUNT = new BigInteger("1"); @@ -106,34 +112,45 @@ class BridgeSupportTest { private static final co.rsk.core.Coin LIMIT_MONETARY_BASE = new co.rsk.core.Coin(new BigInteger("21000000000000000000000000")); private static final RskAddress contractAddress = PrecompiledContracts.BRIDGE_ADDR; - protected ActivationConfig.ForBlock activationsBeforeForks; - protected ActivationConfig.ForBlock activationsAfterForks; + private ActivationConfig.ForBlock activationsBeforeForks; + private ActivationConfig.ForBlock activationsAfterForks; - protected SignatureCache signatureCache; + private SignatureCache signatureCache; @BeforeEach void setUpOnEachTest() { activationsBeforeForks = ActivationConfigsForTest.genesis().forBlock(0); activationsAfterForks = ActivationConfigsForTest.all().forBlock(0); signatureCache = new BlockTxSignatureCache(new ReceivedTxSignatureCache()); - bridgeSupportBuilder = new BridgeSupportBuilder(); - StorageAccessor inMemoryStorageAccessor = new InMemoryStorage(); - whitelistStorageProvider = new WhitelistStorageProviderImpl(inMemoryStorageAccessor); + + StorageAccessor bridgeStorageAccessor = new InMemoryStorage(); + FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(bridgeStorageAccessor); + whitelistStorageProvider = new WhitelistStorageProviderImpl(bridgeStorageAccessor); + LockingCapStorageProvider lockingCapStorageProvider = new LockingCapStorageProviderImpl(bridgeStorageAccessor); + + feePerKbSupport = mock(FeePerKbSupport.class); + federationSupport = federationSupportBuilder + .withFederationConstants(federationConstantsMainnet) + .withFederationStorageProvider(federationStorageProvider) + .withActivations(activationsAfterForks) + .build(); whitelistSupport = new WhitelistSupportImpl( WhitelistMainNetConstants.getInstance(), whitelistStorageProvider, - mock(ActivationConfig.ForBlock.class), + activationsAfterForks, + signatureCache + ); + lockingCapSupport = new LockingCapSupportImpl( + lockingCapStorageProvider, + activationsAfterForks, + LockingCapMainNetConstants.getInstance(), signatureCache ); - federationSupportBuilder = new FederationSupportBuilder(); - LockingCapStorageProvider lockingCapStorageProvider = new LockingCapStorageProviderImpl(inMemoryStorageAccessor); - lockingCapSupport = new LockingCapSupportImpl(lockingCapStorageProvider, mock(ActivationConfig.ForBlock.class), LockingCapMainNetConstants.getInstance(), signatureCache); } @Test void getFeePerKb() { Coin feePerKb = Coin.valueOf(10_000L); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(feePerKb); BridgeSupport bridgeSupport = bridgeSupportBuilder @@ -147,7 +164,6 @@ void getFeePerKb() { @Test void voteFeePerKbChange_success() { - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.voteFeePerKbChange(any(), any(), any())).thenReturn(1); BridgeSupport bridgeSupport = bridgeSupportBuilder @@ -245,9 +261,6 @@ void setLockWhitelistDisableBlockDelay() throws BlockStoreException, IOException BridgeConstants bridgeConstantsMainNet = BridgeMainNetConstants.getInstance(); BtcBlockStoreWithCache.Factory btcBlockStoreFactory = mock(BtcBlockStoreWithCache.Factory.class); ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - FederationSupport federationSupport = federationSupportBuilder - .withFederationConstants(bridgeConstantsMainNet.getFederationConstants()) - .build(); bridgeSupport = bridgeSupportBuilder .withWhitelistSupport(whitelistSupport) @@ -284,10 +297,10 @@ void setLockWhitelistDisableBlockDelay() throws BlockStoreException, IOException class FederationSupportTests { FederationSupport federationSupport; BridgeConstants bridgeMainnetConstants = BridgeMainNetConstants.getInstance(); - BridgeSupportBuilder bridgeSupportBuilder = new BridgeSupportBuilder(); + BridgeSupportBuilder bridgeSupportBuilder = BridgeSupportBuilder.builder(); BridgeSupport bridgeSupport; - Federation federation = new P2shErpFederationBuilder().build(); + Federation federation = P2shErpFederationBuilder.builder().build(); @BeforeEach void setUp() { @@ -459,7 +472,7 @@ void getRetiringFederatorPublicKeyOfType() { @Test void getPendingFederationHash() { - PendingFederation pendingFederation = new PendingFederationBuilder().build(); + PendingFederation pendingFederation = PendingFederationBuilder.builder().build(); Keccak256 hash = pendingFederation.getHash(); when(federationSupport.getPendingFederationHash()).thenReturn(hash); @@ -500,7 +513,7 @@ void getPendingFederatorPublicKeyOfType() { } @Test - void voteFederationChange() throws BridgeIllegalArgumentException { + void voteFederationChange() { Transaction tx = mock(Transaction.class); ABICallSpec callSpec = mock(ABICallSpec.class); int result = 1; @@ -662,12 +675,12 @@ void isBtcTxHashAlreadyProcessed() throws IOException { Sha256Hash hash1 = Sha256Hash.ZERO_HASH; Sha256Hash hash2 = Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000001"); - BridgeStorageProvider bridgeStorageProvider = mock(BridgeStorageProvider.class); - when(bridgeStorageProvider.getHeightIfBtcTxhashIsAlreadyProcessed(hash1)).thenReturn(Optional.of(1L)); + BridgeStorageProvider bridgeStorageProviderMock = mock(BridgeStorageProvider.class); + when(bridgeStorageProviderMock.getHeightIfBtcTxhashIsAlreadyProcessed(hash1)).thenReturn(Optional.of(1L)); BridgeSupport bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) - .withProvider(bridgeStorageProvider) + .withProvider(bridgeStorageProviderMock) .withActivations(activations) .build(); @@ -683,12 +696,12 @@ void getBtcTxHashProcessedHeight() throws IOException { Sha256Hash hash1 = Sha256Hash.ZERO_HASH; Sha256Hash hash2 = Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000001"); - BridgeStorageProvider bridgeStorageProvider = mock(BridgeStorageProvider.class); - when(bridgeStorageProvider.getHeightIfBtcTxhashIsAlreadyProcessed(hash1)).thenReturn(Optional.of(1L)); + BridgeStorageProvider bridgeStorageProviderMock = mock(BridgeStorageProvider.class); + when(bridgeStorageProviderMock.getHeightIfBtcTxhashIsAlreadyProcessed(hash1)).thenReturn(Optional.of(1L)); BridgeSupport bridgeSupport = bridgeSupportBuilder .withBridgeConstants(bridgeConstants) - .withProvider(bridgeStorageProvider) + .withProvider(bridgeStorageProviderMock) .withActivations(activations) .build(); @@ -754,13 +767,13 @@ void eventLoggerLogLockBtc_before_rskip_146_activation() throws Exception { height ); - FeePerKbSupport feePerKbSupport = new FeePerKbSupportImpl( + feePerKbSupport = new FeePerKbSupportImpl( bridgeMainNetConstants.getFeePerKbConstants(), mock(FeePerKbStorageProvider.class) ); when(mockBridgeStorageProvider.getPegoutsWaitingForConfirmations()).thenReturn(mock(PegoutsWaitingForConfirmations.class)); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(executionBlock) @@ -862,7 +875,7 @@ void eventLoggerLogLockBtc_after_rskip_146_activation() throws Exception { height ); - FeePerKbSupport feePerKbSupport = new FeePerKbSupportImpl( + feePerKbSupport = new FeePerKbSupportImpl( bridgeMainNetConstants.getFeePerKbConstants(), mock(FeePerKbStorageProvider.class) ); @@ -870,7 +883,7 @@ void eventLoggerLogLockBtc_after_rskip_146_activation() throws Exception { Transaction rskTx = mock(Transaction.class); when(rskTx.getHash()).thenReturn(Keccak256.ZERO_HASH); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(executionBlock) @@ -965,7 +978,7 @@ void eventLoggerLogPeginRejectionEvents_before_rskip_181_activation() throws Exc PeginInstructionsProvider peginInstructionsProvider = mock(PeginInstructionsProvider.class); when(peginInstructionsProvider.buildPeginInstructions(any(BtcTransaction.class))).thenReturn(Optional.empty()); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(executionBlock) @@ -1056,7 +1069,7 @@ void eventLoggerLogPeginRejectionEvents_after_rskip_181_activation() throws Exce PeginInstructionsProvider peginInstructionsProvider = mock(PeginInstructionsProvider.class); when(peginInstructionsProvider.buildPeginInstructions(any(BtcTransaction.class))).thenReturn(Optional.empty()); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(executionBlock) @@ -1153,12 +1166,12 @@ void eventLoggerLogPeginBtc_before_rskip_170_activation() throws Exception { height ); - FeePerKbSupport feePerKbSupport = new FeePerKbSupportImpl(bridgeMainNetConstants.getFeePerKbConstants(), mock(FeePerKbStorageProvider.class)); + feePerKbSupport = new FeePerKbSupportImpl(bridgeMainNetConstants.getFeePerKbConstants(), mock(FeePerKbStorageProvider.class)); when(mockBridgeStorageProvider.getPegoutsWaitingForConfirmations()).thenReturn(mock(PegoutsWaitingForConfirmations.class)); Transaction rskTx = mock(Transaction.class); when(rskTx.getHash()).thenReturn(Keccak256.ZERO_HASH); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(executionBlock) @@ -1241,12 +1254,12 @@ void eventLoggerLogPeginBtc_after_rskip_170_activation() throws Exception { mockChainOfStoredBlocks(btcBlockStore, btcBlock, height + bridgeMainNetConstants.getBtc2RskMinimumAcceptableConfirmations(), height); - FeePerKbSupport feePerKbSupport = new FeePerKbSupportImpl(bridgeMainNetConstants.getFeePerKbConstants(), mock(FeePerKbStorageProvider.class)); + feePerKbSupport = new FeePerKbSupportImpl(bridgeMainNetConstants.getFeePerKbConstants(), mock(FeePerKbStorageProvider.class)); when(mockBridgeStorageProvider.getPegoutsWaitingForConfirmations()).thenReturn(mock(PegoutsWaitingForConfirmations.class)); Transaction rskTx = mock(Transaction.class); when(rskTx.getHash()).thenReturn(Keccak256.ZERO_HASH); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(executionBlock) @@ -1347,10 +1360,9 @@ void registerBtcTransactionLockTxNotWhitelisted_before_rskip_146_activation() th BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository, bridgeConstantsRegtest, provider, activations)).thenReturn(btcBlockStore); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -1535,10 +1547,9 @@ void registerBtcTransactionLockTxNotWhitelisted_after_rskip_146_activation() thr BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository, bridgeConstantsRegtest, provider, activations)).thenReturn(btcBlockStore); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -1746,13 +1757,13 @@ void registerBtcTransaction_sending_segwit_tx_twice_locks_just_once() throws Blo Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(666L); - FeePerKbSupport feePerKbSupport = new FeePerKbSupportImpl( + feePerKbSupport = new FeePerKbSupportImpl( bridgeConstantsRegtest.getFeePerKbConstants(), mock(FeePerKbStorageProvider.class) ); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(mock(PegoutsWaitingForConfirmations.class)); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(executionBlock) @@ -1809,7 +1820,6 @@ void callProcessFundsMigration_is_migrating_before_rskip_146_activation() throws BridgeStorageProvider provider = mock(BridgeStorageProvider.class); FederationStorageProvider federationStorageProviderMock = mock(FederationStorageProvider.class); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); when(provider.getReleaseRequestQueue()) @@ -1835,7 +1845,7 @@ void callProcessFundsMigration_is_migrating_before_rskip_146_activation() throws .value(DUST_AMOUNT) .build(); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(rskCurrentBlock) @@ -1884,18 +1894,12 @@ void callProcessFundsMigration_is_migrating_after_rskip_146_activation() throws BridgeStorageProvider provider = mock(BridgeStorageProvider.class); FederationStorageProvider federationStorageProviderMock = mock(FederationStorageProvider.class); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); - when(feePerKbSupport.getFeePerKb()) - .thenReturn(Coin.MILLICOIN); - when(provider.getReleaseRequestQueue()) - .thenReturn(new ReleaseRequestQueue(Collections.emptyList())); - when(provider.getPegoutsWaitingForConfirmations()) - .thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - when(federationStorageProviderMock.getOldFederation(any(), any())) - .thenReturn(oldFederation); - when(federationStorageProviderMock.getNewFederation(any(), any())) - .thenReturn(newFederation); + when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); + when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Collections.emptyList())); + when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); + when(federationStorageProviderMock.getOldFederation(any(), any())).thenReturn(oldFederation); + when(federationStorageProviderMock.getNewFederation(any(), any())).thenReturn(newFederation); BlockGenerator blockGenerator = new BlockGenerator(); // Old federation will be in migration age at block 18500 since we are using mainnet constants @@ -1912,7 +1916,7 @@ void callProcessFundsMigration_is_migrating_after_rskip_146_activation() throws .build(); tx.sign(new ECKey().getPrivKeyBytes()); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(rskCurrentBlock) @@ -1931,8 +1935,7 @@ void callProcessFundsMigration_is_migrating_after_rskip_146_activation() throws List sufficientUTXOsForMigration1 = new ArrayList<>(); sufficientUTXOsForMigration1.add(createUTXO(Coin.COIN, oldFederation.getAddress())); - when(federationStorageProviderMock.getOldFederationBtcUTXOs()) - .thenReturn(sufficientUTXOsForMigration1); + when(federationStorageProviderMock.getOldFederationBtcUTXOs()).thenReturn(sufficientUTXOsForMigration1); bridgeSupport.updateCollections(tx); @@ -1968,18 +1971,12 @@ void callProcessFundsMigration_is_migrated_before_rskip_146_activation() throws BridgeStorageProvider provider = mock(BridgeStorageProvider.class); FederationStorageProvider federationStorageProviderMock = mock(FederationStorageProvider.class); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); - when(feePerKbSupport.getFeePerKb()) - .thenReturn(Coin.MILLICOIN); - when(provider.getReleaseRequestQueue()) - .thenReturn(new ReleaseRequestQueue(Collections.emptyList())); - when(provider.getPegoutsWaitingForConfirmations()) - .thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - when(federationStorageProviderMock.getOldFederation(any(), any())) - .thenReturn(oldFederation); - when(federationStorageProviderMock.getNewFederation(any(), any())) - .thenReturn(newFederation); + when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); + when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Collections.emptyList())); + when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); + when(federationStorageProviderMock.getOldFederation(any(), any())).thenReturn(oldFederation); + when(federationStorageProviderMock.getNewFederation(any(), any())).thenReturn(newFederation); BlockGenerator blockGenerator = new BlockGenerator(); // Old federation will be in migration age at block 18500 since we are using mainnet constants @@ -1995,7 +1992,7 @@ void callProcessFundsMigration_is_migrated_before_rskip_146_activation() throws .value(DUST_AMOUNT) .build(); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(rskCurrentBlock) @@ -2044,18 +2041,12 @@ void callProcessFundsMigration_is_migrated_after_rskip_146_activation() throws I BridgeStorageProvider provider = mock(BridgeStorageProvider.class); FederationStorageProvider federationStorageProviderMock = mock(FederationStorageProvider.class); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); - when(feePerKbSupport.getFeePerKb()) - .thenReturn(Coin.MILLICOIN); - when(provider.getReleaseRequestQueue()) - .thenReturn(new ReleaseRequestQueue(Collections.emptyList())); - when(provider.getPegoutsWaitingForConfirmations()) - .thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); - when(federationStorageProviderMock.getOldFederation(any(), any())) - .thenReturn(oldFederation); - when(federationStorageProviderMock.getNewFederation(any(), any())) - .thenReturn(newFederation); + when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); + when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Collections.emptyList())); + when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); + when(federationStorageProviderMock.getOldFederation(any(), any())).thenReturn(oldFederation); + when(federationStorageProviderMock.getNewFederation(any(), any())).thenReturn(newFederation); BlockGenerator blockGenerator = new BlockGenerator(); // Old federation will be in migration age at block 18500 since we are using mainnet constants @@ -2071,7 +2062,7 @@ void callProcessFundsMigration_is_migrated_after_rskip_146_activation() throws I .value(DUST_AMOUNT) .build(); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(rskCurrentBlock) @@ -2123,7 +2114,6 @@ void updateFederationCreationBlockHeights_before_rskip_186_activation() throws I ); Federation newFederation = FederationFactory.buildStandardMultiSigFederation(newFederationArgs); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); @@ -2152,7 +2142,7 @@ void updateFederationCreationBlockHeights_before_rskip_186_activation() throws I .value(DUST_AMOUNT) .build(); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(rskCurrentBlock) @@ -2198,21 +2188,15 @@ void updateFederationCreationBlockHeights_after_rskip_186_activation() throws IO ); Federation newFederation = FederationFactory.buildStandardMultiSigFederation(newFederationArgs); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); - when(feePerKbSupport.getFeePerKb()) - .thenReturn(Coin.MILLICOIN); + when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); BridgeStorageProvider provider = mock(BridgeStorageProvider.class); - when(provider.getReleaseRequestQueue()) - .thenReturn(new ReleaseRequestQueue(Collections.emptyList())); - when(provider.getPegoutsWaitingForConfirmations()) - .thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); + when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(Collections.emptyList())); + when(provider.getPegoutsWaitingForConfirmations()).thenReturn(new PegoutsWaitingForConfirmations(Collections.emptySet())); FederationStorageProvider federationStorageProviderMock = mock(FederationStorageProvider.class); - when(federationStorageProviderMock.getOldFederation(any(), any())) - .thenReturn(oldFederation); - when(federationStorageProviderMock.getNewFederation(any(), any())) - .thenReturn(newFederation); + when(federationStorageProviderMock.getOldFederation(any(), any())).thenReturn(oldFederation); + when(federationStorageProviderMock.getNewFederation(any(), any())).thenReturn(newFederation); BlockGenerator blockGenerator = new BlockGenerator(); // Old federation will be in migration age at block 18500 since we are using mainnet constants @@ -2228,7 +2212,7 @@ void updateFederationCreationBlockHeights_after_rskip_186_activation() throws IO .value(DUST_AMOUNT) .build(); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(rskCurrentBlock) @@ -2286,7 +2270,7 @@ void rskTxWaitingForSignature_uses_updateCollection_rskTxHash_before_rskip_146_a Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -2338,7 +2322,7 @@ void rskTxWaitingForSignature_postRSKIP326_emitNewPegoutConfirmedEvent() throws BridgeEventLogger eventLogger = mock(BridgeEventLogger.class); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -2391,7 +2375,7 @@ void rskTxWaitingForSignature_preRSKIP326_noPegoutConfirmedEventEmitted() throws BridgeEventLogger eventLogger = mock(BridgeEventLogger.class); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -2441,7 +2425,7 @@ void rskTxWaitingForSignature_postRSKIP326NoTxWithEnoughConfirmation_pegoutConfi BridgeEventLogger eventLogger = mock(BridgeEventLogger.class); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -2490,7 +2474,7 @@ void rskTxWaitingForSignature_uses_updateCollection_rskTxHash_after_rskip_146_ac Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -2540,7 +2524,7 @@ void rskTxWaitingForSignature_uses_release_transaction_rstTxHash_after_rskip_146 Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -2591,7 +2575,7 @@ void rskTxWaitingForSignature_uses_updateCollection_rskTxHash_after_rskip_176_ac Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -2644,12 +2628,9 @@ void rskTxWaitingForSignature_fail_adding_an_already_existing_key_after_rskip_37 BridgeStorageProvider provider = mock(BridgeStorageProvider.class); FederationStorageProvider federationStorageProviderMock = mock(FederationStorageProvider.class); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); - when(feePerKbSupport.getFeePerKb()) - .thenReturn(Coin.MILLICOIN); - when(provider.getReleaseRequestQueue()) - .thenReturn(new ReleaseRequestQueue(PegTestUtils.createReleaseRequestQueueEntries(3))); + when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); + when(provider.getReleaseRequestQueue()).thenReturn(new ReleaseRequestQueue(PegTestUtils.createReleaseRequestQueueEntries(3))); PegoutsWaitingForConfirmations pegoutsWaitingForConfirmations = new PegoutsWaitingForConfirmations(new HashSet<>()); when(provider.getPegoutsWaitingForConfirmations()).thenReturn(pegoutsWaitingForConfirmations); @@ -2676,7 +2657,7 @@ void rskTxWaitingForSignature_fail_adding_an_already_existing_key_after_rskip_37 BlockGenerator blockGenerator = new BlockGenerator(); org.ethereum.core.Block rskCurrentBlock = blockGenerator.createBlock(180, 1); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(bridgeConstants.getFederationConstants()) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(rskCurrentBlock) @@ -2849,7 +2830,7 @@ void rskTxWaitingForSignature_uses_pegoutCreation_rskTxHash_after_rskip_375_acti Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L + bridgeConstants.getRsk2BtcMinimumAcceptableConfirmations()); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(bridgeConstants.getFederationConstants()) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -2899,7 +2880,7 @@ void rskTxWaitingForSignature_override_entry_is_allowed_before_rskip_375_activat Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L + bridgeConstants.getRsk2BtcMinimumAcceptableConfirmations()); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(bridgeConstants.getFederationConstants()) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -2966,7 +2947,7 @@ void rskTxWaitingForSignature_override_entry_attempt_after_rskip_375_activation( Block executionBlock = mock(Block.class); when(executionBlock.getNumber()).thenReturn(2L); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -3029,7 +3010,7 @@ void when_registerBtcTransaction_sender_not_recognized_before_rskip170_no_lock_a BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository, bridgeConstantsRegtest, provider, activations)).thenReturn(btcBlockStore); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -3126,7 +3107,7 @@ void when_registerBtcTransaction_sender_not_recognized_after_rskip170_lock() thr BtcBlockStoreWithCache.Factory mockFactory = mock(BtcBlockStoreWithCache.Factory.class); when(mockFactory.newInstance(repository, bridgeConstantsRegtest, provider, activations)).thenReturn(btcBlockStore); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -3225,7 +3206,7 @@ void when_registerBtcTransaction_usesLegacyType_beforeFork_lock_and_no_refund() BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(TxSenderAddressType.P2PKH, btcAddress, rskAddress); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -3322,10 +3303,9 @@ void when_registerBtcTransaction_usesLegacyType_afterFork_notWhitelisted_no_lock BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(TxSenderAddressType.P2PKH, btcAddress, rskAddress); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -3433,7 +3413,7 @@ void when_registerBtcTransaction_usesLegacyType_afterFork_lock_and_no_refund() t BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(TxSenderAddressType.P2PKH, btcAddress, rskAddress); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -3525,7 +3505,7 @@ void when_registerBtcTransaction_usesSegCompatibilityType_beforeFork_no_lock_and BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(TxSenderAddressType.P2SHP2WPKH, btcAddress, rskAddress); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -3618,7 +3598,7 @@ void when_registerBtcTransaction_usesSegCompatibilityType_afterFork_lock_and_no_ BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(TxSenderAddressType.P2SHP2WPKH, btcAddress, rskAddress); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withActivations(activations) @@ -3719,10 +3699,9 @@ void when_registerBtcTransaction_usesSegCompatibilityType_afterFork_notWhitelist rskAddress ); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -3830,7 +3809,7 @@ void when_registerBtcTransaction_usesMultisigType_beforeFork_no_lock_and_no_refu BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(TxSenderAddressType.P2SHMULTISIG, btcAddress, rskAddress); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -3917,10 +3896,9 @@ void when_registerBtcTransaction_usesMultisigType_afterFork_no_lock_and_refund() BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(TxSenderAddressType.P2SHMULTISIG, btcAddress, null); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -4023,7 +4001,7 @@ void when_registerBtcTransaction_usesMultisigWithWitnessType_beforeFork_no_lock_ BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(TxSenderAddressType.P2SHP2WSH, btcAddress, rskAddress); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withRskExecutionBlock(executionBlock) .withActivations(activations) @@ -4113,10 +4091,9 @@ void when_registerBtcTransaction_usesMultisigWithWitnessType_afterFork_no_lock_a null ); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -4342,7 +4319,7 @@ void registerBtcTransaction_accepts_lock_tx_with_witness_after_rskip_143_activat LockWhitelist whitelist = whitelistStorageProvider.getLockWhitelist(activationsBeforeForks, btcRegTestParams); whitelist.put(btcAddress, new OneOffWhiteListEntry(btcAddress, Coin.COIN.multiply(10))); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withActivations(activations) @@ -4630,7 +4607,7 @@ void registerBtcTransaction_rejects_tx_without_witness_unequal_roots_after_rskip activations) ); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withActivations(activations) .build(); @@ -4723,7 +4700,7 @@ void registerBtcTransaction_accepts_lock_tx_without_witness_after_rskip_143_acti LockWhitelist whitelist = whitelistStorageProvider.getLockWhitelist(activationsBeforeForks, btcRegTestParams); whitelist.put(btcAddress, new OneOffWhiteListEntry(btcAddress, Coin.COIN.multiply(10))); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withActivations(activations) @@ -4835,7 +4812,7 @@ void registerBtcTransaction_accepts_lock_tx_version1_after_rskip_170_activation( Optional.empty() ); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withActivations(activations) @@ -4957,7 +4934,7 @@ void registerBtcTransaction_ignores_pegin_instructions_before_rskip_170_activati Optional.empty() ); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withActivations(activations) @@ -5080,10 +5057,10 @@ void when_registerBtcTransaction_invalidPeginProtocolVersion_afterFork_no_lock_a PeginInstructionsProvider peginInstructionsProvider = mock(PeginInstructionsProvider.class); when(peginInstructionsProvider.buildPeginInstructions(any())).thenReturn(Optional.of(peginInstructions)); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); + feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProvider) .withActivations(activations) @@ -6526,7 +6503,6 @@ void validationsForRegisterBtcTransaction_invalid_block_merkle_root() throws IOE mockChainOfStoredBlocks(btcBlockStore, btcBlock, height + bridgeConstantsRegtest.getBtc2RskMinimumAcceptableConfirmations(), height); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); BridgeSupport bridgeSupport = new BridgeSupport( bridgeConstantsRegtest, mockBridgeStorageProvider, @@ -6597,24 +6573,17 @@ void validationsForRegisterBtcTransaction_successful() throws IOException, Block height + bridgeConstantsRegtest.getBtc2RskMinimumAcceptableConfirmations(), height ); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); - BridgeSupport bridgeSupport = new BridgeSupport( - bridgeConstantsRegtest, - mockBridgeStorageProvider, - mock(BridgeEventLogger.class), - new BtcLockSenderProvider(), - new PeginInstructionsProvider(), - mock(Repository.class), - mock(Block.class), - mock(Context.class), - feePerKbSupport, - whitelistSupport, - mock(FederationSupport.class), - lockingCapSupport, - btcBlockStoreFactory, - mock(ActivationConfig.ForBlock.class), - signatureCache - ); + BridgeSupport bridgeSupport = bridgeSupportBuilder + .withBridgeConstants(bridgeConstantsRegtest) + .withProvider(mockBridgeStorageProvider) + .withBtcLockSenderProvider(new BtcLockSenderProvider()) + .withPeginInstructionsProvider(new PeginInstructionsProvider()) + .withFeePerKbSupport(feePerKbSupport) + .withWhitelistSupport(whitelistSupport) + .withLockingCapSupport(lockingCapSupport) + .withBtcBlockStoreFactory(btcBlockStoreFactory) + .withSignatureCache(signatureCache) + .build(); assertTrue(bridgeSupport.validationsForRegisterBtcTransaction( tx.getHash(), @@ -6692,7 +6661,7 @@ void processPegIn_version1_tx_no_lockable_by_surpassing_locking_cap_unknown_send @Test void processPegIn_noPeginInstructions() { - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .build(); @@ -6734,7 +6703,7 @@ void processPegIn_errorParsingPeginInstructions_beforeRskip170_dontRefundSender( BtcLockSenderProvider btcLockSenderProvider = mock(BtcLockSenderProvider.class); when(btcLockSenderProvider.tryGetBtcLockSender(btcTx)).thenReturn(Optional.empty()); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withActivations(activations) .build(); @@ -6750,22 +6719,18 @@ void processPegIn_errorParsingPeginInstructions_beforeRskip170_dontRefundSender( .build(); // Act - try { - bridgeSupport.processPegIn(btcTx, PegTestUtils.createHash3(1), 0); - fail(); // Should have thrown a RegisterBtcTransactionException - } catch (Exception e) { - // Assert - assertInstanceOf(RegisterBtcTransactionException.class, e); - assertEquals(0, pegoutsWaitingForConfirmations.getEntries().size()); - } + assertThrows(RegisterBtcTransactionException.class, () -> bridgeSupport.processPegIn( + btcTx, + PegTestUtils.createHash3(1), + 0 + )); + assertEquals(0, pegoutsWaitingForConfirmations.getEntries().size()); } @Test void processPegIn_errorParsingPeginInstructions_afterRskip170_refundSender() throws IOException, PeginInstructionsException { // Arrange - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - when(activations.isActive(ConsensusRule.RSKIP170)).thenReturn(true); - + ActivationConfig.ForBlock irisActivations = ActivationConfigsForTest.iris300().forBlock(0L); Repository repository = createRepository(); BtcECKey srcKey1 = new BtcECKey(); @@ -6793,12 +6758,12 @@ void processPegIn_errorParsingPeginInstructions_afterRskip170_refundSender() thr PeginInstructionsProvider peginInstructionsProvider = mock(PeginInstructionsProvider.class); when(peginInstructionsProvider.buildPeginInstructions(btcTx)).thenThrow(PeginInstructionsException.class); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); + feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) - .withActivations(activations) + .withActivations(irisActivations) .build(); BridgeSupport bridgeSupport = bridgeSupportBuilder @@ -6807,7 +6772,7 @@ void processPegIn_errorParsingPeginInstructions_afterRskip170_refundSender() thr .withRepository(repository) .withBtcLockSenderProvider(btcLockSenderProvider) .withPeginInstructionsProvider(peginInstructionsProvider) - .withActivations(activations) + .withActivations(irisActivations) .withSignatureCache(signatureCache) .withFederationSupport(federationSupport) .withFeePerKbSupport(feePerKbSupport) @@ -6898,8 +6863,8 @@ void receiveHeader_time_exceed_X() throws IOException, BlockStoreException { activationsAfterForks ); - long timeStamp_old = executionBlockMock.getTimestamp() - (bridgeConstantsRegtest.getMinSecondsBetweenCallsToReceiveHeader() * 2L); - doReturn(Optional.of(timeStamp_old)).when(provider).getReceiveHeadersLastTimestamp(); + long timeStampOld = executionBlockMock.getTimestamp() - (bridgeConstantsRegtest.getMinSecondsBetweenCallsToReceiveHeader() * 2L); + doReturn(Optional.of(timeStampOld)).when(provider).getReceiveHeadersLastTimestamp(); StoredBlock storedBlock2 = mock(StoredBlock.class); when(storedBlock.build(btcBlock2)).thenReturn(storedBlock2); @@ -6939,8 +6904,8 @@ void receiveHeader_time_less_than_X() throws IOException, BlockStoreException { activationsAfterForks ); - long timeStamp_old = executionBlockMock.getTimestamp() - (bridgeConstantsRegtest.getMinSecondsBetweenCallsToReceiveHeader() / 2L); - doReturn(Optional.of(timeStamp_old)).when(provider).getReceiveHeadersLastTimestamp(); + long timeStampOld = executionBlockMock.getTimestamp() - (bridgeConstantsRegtest.getMinSecondsBetweenCallsToReceiveHeader() / 2L); + doReturn(Optional.of(timeStampOld)).when(provider).getReceiveHeadersLastTimestamp(); int result = bridgeSupport.receiveHeader(btcBlock2); @@ -7104,7 +7069,7 @@ class ChainWorkTests { BtcBlockStoreWithCache btcBlockStoreWithCachePreRSKIP434; BtcBlockStoreWithCache btcBlockStoreWithCachePostRSKIP434; - BridgeSupportBuilder bridgeSupportBuilder = new BridgeSupportBuilder(); + BridgeSupportBuilder bridgeSupportBuilder = BridgeSupportBuilder.builder(); BridgeSupport bridgeSupportPreRSKIP434; BridgeSupport bridgeSupportPostRSKIP434; @@ -7188,7 +7153,7 @@ void receiveHeader_beforeRSKIP434_returnsUnexpectedExceptionResponseCodeAndDoesN assertEquals(btcBlockStoreWithCachePreRSKIP434.getChainHead().getHeader().getHash(), block849137ToStore.getHeader().getHash()); // assert receive header returns an exception and does not save the block - Integer RECEIVE_HEADER_UNEXPECTED_EXCEPTION = -99; + final Integer RECEIVE_HEADER_UNEXPECTED_EXCEPTION = -99; assertThat(bridgeSupportPreRSKIP434.receiveHeader(blockWithTooMuchWork), is(RECEIVE_HEADER_UNEXPECTED_EXCEPTION)); assertNull(btcBlockStoreWithCachePreRSKIP434.get(blockWithTooMuchWork.getHash())); } @@ -7231,7 +7196,7 @@ void receiveHeader_afterRSKIP434_returnsSuccessfulAndSavesTheBlock() throws Bloc assertEquals(btcBlockStoreWithCachePostRSKIP434.getChainHead().getHeader().getHash(), block849137ToStore.getHeader().getHash()); // assert receive header returns successful response and saves the block - Integer RECEIVE_HEADER_SUCCESSFUL = 0; + final Integer RECEIVE_HEADER_SUCCESSFUL = 0; assertThat(bridgeSupportPostRSKIP434.receiveHeader(blockWithTooMuchWork), is(RECEIVE_HEADER_SUCCESSFUL)); assertNotNull(btcBlockStoreWithCachePostRSKIP434.get(blockWithTooMuchWork.getHash())); } @@ -7289,7 +7254,7 @@ void receiveHeader_networkNotMainnet_returnsSuccessfulAndSavesTheBlock(Activatio assertEquals(btcBlockStoreWithCache.getChainHead().getHeader().getHash(), block849137ToStore.getHeader().getHash()); // assert receive header returns successful response and saves the block - Integer RECEIVE_HEADER_SUCCESSFUL = 0; + final Integer RECEIVE_HEADER_SUCCESSFUL = 0; assertThat(bridgeSupport.receiveHeader(blockWithTooMuchWork), is(RECEIVE_HEADER_SUCCESSFUL)); assertNotNull(btcBlockStoreWithCache.get(blockWithTooMuchWork.getHash())); } @@ -7388,10 +7353,10 @@ private void assertRefundInProcessPegInVersionLegacy( BtcLockSenderProvider btcLockSenderProvider = getBtcLockSenderProvider(lockSenderAddressType, btcAddress, rskAddress); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); + feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withActivations(activations) .build(); @@ -7510,10 +7475,10 @@ private void test_migrating_many_utxos(boolean isRskip294Active, int utxosToCrea when(federationStorageProviderMock.getOldFederation(any(), any())).thenReturn(oldFed); when(federationStorageProviderMock.getOldFederationBtcUTXOs()).thenReturn(utxosToMigrate); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); + feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withRskExecutionBlock(block) @@ -7632,9 +7597,7 @@ private static Stream getEstimatedFeesForNextPegOutEventArgsProvider_ FederationConstants federationConstants = bridgeConstants.getFederationConstants(); Federation standardFederation = FederationTestUtils.getGenesisFederation(federationConstants); - ActivationConfig.ForBlock preRSKIP271_activations = mock(ActivationConfig.ForBlock.class); - when(preRSKIP271_activations.isActive(ConsensusRule.RSKIP271)).thenReturn(false); - when(preRSKIP271_activations.isActive(ConsensusRule.RSKIP385)).thenReturn(false); + ActivationConfig.ForBlock irisActivations = ActivationConfigsForTest.iris300().forBlock(0L); FederationArgs p2shFedArgs = new FederationArgs(members, Instant.now(), 1L, bridgeConstants.getBtcParams()); Federation p2shFed = @@ -7643,42 +7606,42 @@ private static Stream getEstimatedFeesForNextPegOutEventArgsProvider_ return Stream.of( // active fed is standard and pegoutRequestsCount is equal to zero Arguments.of( - preRSKIP271_activations, + irisActivations, standardFederation, 0, Coin.valueOf(0L) ), // active fed is standard and pegoutRequestsCount is equal to one Arguments.of( - preRSKIP271_activations, + irisActivations, standardFederation, 1, Coin.valueOf(0L) ), // active fed is standard and there are many pegout requests Arguments.of( - preRSKIP271_activations, + irisActivations, standardFederation, 150, Coin.valueOf(0L) ), // active fed is p2sh and there are zero pegout requests Arguments.of( - preRSKIP271_activations, + irisActivations, p2shFed, 0, Coin.valueOf(0L) ), // active fed is p2sh and there is one pegout request Arguments.of( - preRSKIP271_activations, + irisActivations, p2shFed, 1, Coin.valueOf(0L) ), // active fed is p2sh and there are many pegout requests Arguments.of( - preRSKIP271_activations, + irisActivations, p2shFed, 150, Coin.valueOf(0L) @@ -7694,57 +7657,58 @@ private static Stream getEstimatedFeesForNextPegOutEventArgsProvider_ FederationConstants federationConstants = bridgeConstants.getFederationConstants(); Federation standardFederation = FederationTestUtils.getGenesisFederation(federationConstants); - ActivationConfig.ForBlock preRSKIP385_activations = mock(ActivationConfig.ForBlock.class); - when(preRSKIP385_activations.isActive(ConsensusRule.RSKIP271)).thenReturn(true); - when(preRSKIP385_activations.isActive(ConsensusRule.RSKIP385)).thenReturn(false); + ActivationConfig.ForBlock hopActivations = ActivationConfigsForTest.hop400().forBlock(0L); FederationArgs p2shFedArgs = new FederationArgs(members, Instant.now(), 1L, bridgeConstants.getBtcParams() ); - Federation p2shFed = - FederationFactory.buildP2shErpFederation(p2shFedArgs, federationConstants.getErpFedPubKeysList(), federationConstants.getErpFedActivationDelay()); + Federation p2shFed = FederationFactory.buildP2shErpFederation( + p2shFedArgs, + federationConstants.getErpFedPubKeysList(), + federationConstants.getErpFedActivationDelay() + ); return Stream.of( // active fed is standard and pegoutRequestsCount is equal to zero Arguments.of( - preRSKIP385_activations, + hopActivations, standardFederation, 0, Coin.valueOf(0L) ), // active fed is standard and pegoutRequestsCount is equal to one Arguments.of( - preRSKIP385_activations, + hopActivations, standardFederation, 1, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 237000L: 68600L) ), // active fed is standard and there are many pegout requests Arguments.of( - preRSKIP385_activations, + hopActivations, standardFederation, 150, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 713800L: 545400L) ), // active fed is p2sh and there are zero pegout requests Arguments.of( - preRSKIP385_activations, + hopActivations, p2shFed, 0, Coin.valueOf(0L) ), // active fed is p2sh and there is one pegout request Arguments.of( - preRSKIP385_activations, + hopActivations, p2shFed, 1, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 154600L: 161200L) ), // active fed is p2sh and there are many pegout requests Arguments.of( - preRSKIP385_activations, + hopActivations, p2shFed, 150, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 631400L: 638000L) @@ -7753,9 +7717,7 @@ private static Stream getEstimatedFeesForNextPegOutEventArgsProvider_ } private static Stream getEstimatedFeesForNextPegOutEventArgsProvider_post_RSKIP385(BridgeConstants bridgeConstants) { - ActivationConfig.ForBlock postRSKIP385_activations = mock(ActivationConfig.ForBlock.class); - when(postRSKIP385_activations.isActive(ConsensusRule.RSKIP271)).thenReturn(true); - when(postRSKIP385_activations.isActive(ConsensusRule.RSKIP385)).thenReturn(true); + ActivationConfig.ForBlock fingerrootActivations = ActivationConfigsForTest.fingerroot500().forBlock(0L); FederationConstants federationConstants = bridgeConstants.getFederationConstants(); Federation standardFederation = FederationTestUtils.getGenesisFederation(federationConstants); @@ -7774,42 +7736,42 @@ private static Stream getEstimatedFeesForNextPegOutEventArgsProvider_ return Stream.of( // active fed is standard and pegoutRequestsCount is equal to zero Arguments.of( - postRSKIP385_activations, + fingerrootActivations, standardFederation, 0, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 233800L: 65400L) ), // active fed is standard and pegoutRequestsCount is equal to one Arguments.of( - postRSKIP385_activations, + fingerrootActivations, standardFederation, 1, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 237000L: 68600L) ), // active fed is standard and there are many pegout requests Arguments.of( - postRSKIP385_activations, + fingerrootActivations, standardFederation, 150, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 713800L: 545400L) ), // active fed is p2sh and there are zero pegout requests Arguments.of( - postRSKIP385_activations, + fingerrootActivations, p2shFed, 0, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 151400L: 158000L) ), // active fed is p2sh and there is one pegout request Arguments.of( - postRSKIP385_activations, + fingerrootActivations, p2shFed, 1, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 154600L: 161200L) ), // active fed is p2sh and there are many pegout requests Arguments.of( - postRSKIP385_activations, + fingerrootActivations, p2shFed, 150, Coin.valueOf(bridgeConstants instanceof BridgeMainNetConstants? 631400L: 638000L) @@ -7855,10 +7817,10 @@ void getEstimatedFeesForNextPegOutEvent( when(provider.getReleaseRequestQueueSize()).thenReturn(pegoutRequestsCount); when(federationStorageProviderMock.getNewFederation(any(), any())).thenReturn(federation); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); + feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withFederationStorageProvider(federationStorageProviderMock) .withActivations(activations) @@ -7924,10 +7886,10 @@ private void assertRefundInProcessPegInVersion1( btcRefundAddress ); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); + feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(federationConstantsRegtest) .withActivations(activations) .build(); @@ -8116,10 +8078,10 @@ private void assertLockingCap( // The address is whitelisted assertThat(whitelist.isWhitelisted(address), is(true)); - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); + feePerKbSupport = mock(FeePerKbSupport.class); when(feePerKbSupport.getFeePerKb()).thenReturn(Coin.MILLICOIN); - FederationSupport federationSupport = federationSupportBuilder + federationSupport = federationSupportBuilder .withFederationConstants(bridgeConstants.getFederationConstants()) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(executionBlock) @@ -8205,8 +8167,8 @@ private BridgeSupport getBridgeSupport(BridgeConstants constants, BridgeStorageP if (blockStoreFactory == null) { blockStoreFactory = mock(BtcBlockStoreWithCache.Factory.class); } - FeePerKbSupport feePerKbSupport = mock(FeePerKbSupport.class); - FederationSupport federationSupport = mock(FederationSupport.class); + feePerKbSupport = mock(FeePerKbSupport.class); + federationSupport = mock(FederationSupport.class); return new BridgeSupport( constants, diff --git a/rskj-core/src/test/java/co/rsk/peg/PegUtilsGetTransactionTypeTest.java b/rskj-core/src/test/java/co/rsk/peg/PegUtilsGetTransactionTypeTest.java index 1c87079e2c1..e2642f351ef 100644 --- a/rskj-core/src/test/java/co/rsk/peg/PegUtilsGetTransactionTypeTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/PegUtilsGetTransactionTypeTest.java @@ -9,36 +9,21 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import co.rsk.bitcoinj.core.Address; -import co.rsk.bitcoinj.core.BtcECKey; -import co.rsk.bitcoinj.core.BtcTransaction; -import co.rsk.bitcoinj.core.Coin; -import co.rsk.bitcoinj.core.Context; -import co.rsk.bitcoinj.core.NetworkParameters; -import co.rsk.bitcoinj.core.Sha256Hash; -import co.rsk.bitcoinj.core.TransactionWitness; +import co.rsk.bitcoinj.core.*; import co.rsk.bitcoinj.script.Script; import co.rsk.bitcoinj.script.ScriptBuilder; -import co.rsk.peg.constants.BridgeConstants; -import co.rsk.peg.constants.BridgeMainNetConstants; -import co.rsk.peg.constants.BridgeRegTestConstants; import co.rsk.core.RskAddress; import co.rsk.crypto.Keccak256; import co.rsk.peg.bitcoin.BitcoinTestUtils; import co.rsk.peg.bitcoin.BitcoinUtils; -import co.rsk.peg.federation.ErpFederation; -import co.rsk.peg.federation.Federation; -import co.rsk.peg.federation.FederationTestUtils; +import co.rsk.peg.constants.*; +import co.rsk.peg.federation.*; import co.rsk.peg.federation.constants.FederationConstants; import co.rsk.test.builders.BridgeSupportBuilder; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; +import java.util.*; import java.util.stream.Stream; import org.bouncycastle.util.encoders.Hex; -import org.ethereum.config.blockchain.upgrades.ActivationConfig; -import org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest; -import org.ethereum.config.blockchain.upgrades.ConsensusRule; +import org.ethereum.config.blockchain.upgrades.*; import org.ethereum.crypto.ECKey; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -729,7 +714,7 @@ void pegin_below_minimum_active_fed() { @Test void anyAddressToAnyAddress_pegin_before_RSKIP379() { // Arrange - ActivationConfig.ForBlock fingerrootActivations = ActivationConfigsForTest.fingerroot500().forBlock(0); + ActivationConfig.ForBlock fingerrootActivations = ActivationConfigsForTest.fingerroot500().forBlock(0L); Coin minimumPeginTxValue = bridgeMainnetConstants.getMinimumPeginTxValue(fingerrootActivations); @@ -737,8 +722,6 @@ void anyAddressToAnyAddress_pegin_before_RSKIP379() { anyToAnyTx.addInput(BitcoinTestUtils.createHash(1), 0, new Script(new byte[]{})); anyToAnyTx.addOutput(minimumPeginTxValue, new Script(new byte[]{}) ); - Federation activeFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); - // Act PegTxType transactionType = PegUtils.getTransactionType( fingerrootActivations, @@ -766,8 +749,6 @@ void pegin_anyAddressToAnyAddress_below_minimum_pegin_before_RSIP379() { anyToAnyTx.addInput(BitcoinTestUtils.createHash(1), 0, new Script(new byte[]{})); anyToAnyTx.addOutput(belowMinimum, new Script(new byte[]{})); - Federation activeFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); - // Act PegTxType transactionType = PegUtils.getTransactionType( fingerrootActivations, @@ -787,19 +768,17 @@ void pegin_anyAddressToAnyAddress_below_minimum_pegin_before_RSIP379() { @Test void unknown_anyAddressToAnyAddress_unknown_after_RSIP379_and_using_pegout_tx_index() { // Arrange - ActivationConfig.ForBlock activations = ActivationConfigsForTest.arrowhead600().forBlock(0); + ActivationConfig.ForBlock arrowheadActivations = ActivationConfigsForTest.arrowhead600().forBlock(0); - Coin minimumPeginTxValue = bridgeMainnetConstants.getMinimumPeginTxValue(activations); + Coin minimumPeginTxValue = bridgeMainnetConstants.getMinimumPeginTxValue(arrowheadActivations); BtcTransaction anyToAnyTx = new BtcTransaction(btcMainnetParams); anyToAnyTx.addInput(BitcoinTestUtils.createHash(1), 0, new Script(new byte[]{})); anyToAnyTx.addOutput(minimumPeginTxValue, new Script(new byte[]{}) ); - Federation activeFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); - // Act PegTxType transactionType = PegUtils.getTransactionType( - activations, + arrowheadActivations, mock(BridgeStorageProvider.class), bridgeMainnetConstants, activeFederation, @@ -816,19 +795,17 @@ void unknown_anyAddressToAnyAddress_unknown_after_RSIP379_and_using_pegout_tx_in @Test void unknown_anyAddressToAnyAddress_below_minimum_unknown_after_RSIP379_and_using_pegout_tx_index() { // Arrange - ActivationConfig.ForBlock activations = ActivationConfigsForTest.arrowhead600().forBlock(0); + ActivationConfig.ForBlock arrowheadActivations = ActivationConfigsForTest.arrowhead600().forBlock(0); - Coin belowMinimum = bridgeMainnetConstants.getMinimumPeginTxValue(activations).minus(Coin.SATOSHI); + Coin belowMinimum = bridgeMainnetConstants.getMinimumPeginTxValue(arrowheadActivations).minus(Coin.SATOSHI); BtcTransaction anyToAnyTx = new BtcTransaction(btcMainnetParams); anyToAnyTx.addInput(BitcoinTestUtils.createHash(1), 0, new Script(new byte[]{})); anyToAnyTx.addOutput(belowMinimum, new Script(new byte[]{})); - Federation activeFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); - // Act PegTxType transactionType = PegUtils.getTransactionType( - activations, + arrowheadActivations, mock(BridgeStorageProvider.class), bridgeMainnetConstants, activeFederation, @@ -873,11 +850,8 @@ void sending_funds_below_minimum_active_fed( PegTxType expectedType ) { // Arrange - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Coin belowMinimumPeginTxValue = bridgeMainnetConstants.getMinimumPeginTxValue(activations).div(10); - Federation activeFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); - BtcTransaction peginTx = new BtcTransaction(btcMainnetParams); peginTx.addInput(BitcoinTestUtils.createHash(1), 0, new Script(new byte[]{})); @@ -909,11 +883,8 @@ void sending_funds_below_and_above_minimum_active_fed( PegTxType expectedType ) { // Arrange - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Coin belowMinimumPeginTxValue = bridgeMainnetConstants.getMinimumPeginTxValue(activations).div(10); - Federation activeFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); - BtcTransaction peginTx = new BtcTransaction(btcMainnetParams); peginTx.addInput(BitcoinTestUtils.createHash(1), 0, new Script(new byte[]{})); @@ -966,11 +937,8 @@ void sending_funds_equal_to_minimum_active_fed( boolean shouldUsePegoutTxIndex ) { // Arrange - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Coin minimumPeginTxValue = bridgeMainnetConstants.getMinimumPeginTxValue(activations); - Federation activeFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); - BtcTransaction peginTx = new BtcTransaction(btcMainnetParams); peginTx.addInput(BitcoinTestUtils.createHash(1), 0, new Script(new byte[]{})); peginTx.addOutput(minimumPeginTxValue, activeFederation.getAddress()); @@ -998,11 +966,8 @@ void sending_funds_above_minimum_active_fed( boolean shouldUsePegoutTxIndex ) { // Arrange - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); Coin minimumPeginTxValue = bridgeMainnetConstants.getMinimumPeginTxValue(activations).add(Coin.CENT); - Federation activeFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); - BtcTransaction peginTx = new BtcTransaction(btcMainnetParams); peginTx.addInput(BitcoinTestUtils.createHash(1), 0, new Script(new byte[]{})); peginTx.addOutput(minimumPeginTxValue, activeFederation.getAddress()); @@ -1734,7 +1699,7 @@ void flyover_pegin( Keccak256 derivationArgumentsHash = PegTestUtils.createHash3(0); RskAddress lbcAddress = PegTestUtils.createRandomRskAddress(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withActivations(activations) .build(); @@ -1794,7 +1759,7 @@ void flyover_segwit_pegin( Keccak256 derivationArgumentsHash = PegTestUtils.createHash3(0); RskAddress lbcAddress = PegTestUtils.createRandomRskAddress(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withActivations(activations) .build(); @@ -1868,7 +1833,7 @@ void flyover_segwit_migration( Keccak256 derivationArgumentsHash = PegTestUtils.createHash3(0); RskAddress lbcAddress = PegTestUtils.createRandomRskAddress(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withActivations(activations) .build(); @@ -1942,7 +1907,7 @@ void flyover_segwit_with_other_inputs_migration( Keccak256 derivationArgumentsHash = PegTestUtils.createHash3(0); RskAddress lbcAddress = PegTestUtils.createRandomRskAddress(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withActivations(activations) .build(); @@ -2022,7 +1987,7 @@ void flyover_segwit_with_many_inputs_and_outputs_migration( Keccak256 derivationArgumentsHash = PegTestUtils.createHash3(0); RskAddress lbcAddress = PegTestUtils.createRandomRskAddress(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withBridgeConstants(bridgeMainnetConstants) .withActivations(activations) .build(); @@ -2128,17 +2093,13 @@ void old_fed_to_live_fed( NetworkParameters btcRegTestsParams = bridgeRegTestConstants.getBtcParams(); Context.propagate(new Context(btcRegTestsParams)); - final List REGTEST_OLD_FEDERATION_PRIVATE_KEYS = Arrays.asList( + final List regtestOldFederationPrivateKeys = Arrays.asList( BtcECKey.fromPrivate(Hex.decode("47129ffed2c0273c75d21bb8ba020073bb9a1638df0e04853407461fdd9e8b83")), BtcECKey.fromPrivate(Hex.decode("9f72d27ba603cfab5a0201974a6783ca2476ec3d6b4e2625282c682e0e5f1c35")), BtcECKey.fromPrivate(Hex.decode("e1b17fcd0ef1942465eee61b20561b16750191143d365e71de08b33dd84a9788")) ); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); - - Federation oldFederation = createFederation(bridgeRegTestConstants, REGTEST_OLD_FEDERATION_PRIVATE_KEYS); - Federation activeFederation = FederationTestUtils.getGenesisFederation(bridgeRegTestConstants.getFederationConstants()); - + Federation oldFederation = createFederation(bridgeRegTestConstants, regtestOldFederationPrivateKeys); assertEquals(oldFederation.getAddress().toString(), bridgeRegTestConstants.getFederationConstants().getOldFederationAddress()); BtcTransaction migrationTx = new BtcTransaction(btcRegTestsParams); @@ -2150,7 +2111,7 @@ void old_fed_to_live_fed( ); migrationTx.addOutput(Coin.COIN, activeFederation.getAddress()); - FederationTestUtils.addSignatures(oldFederation, REGTEST_OLD_FEDERATION_PRIVATE_KEYS, migrationTx); + FederationTestUtils.addSignatures(oldFederation, regtestOldFederationPrivateKeys, migrationTx); assertTrue(PegUtilsLegacy.txIsFromOldFederation(migrationTx, oldFederation.getAddress())); @@ -2203,8 +2164,6 @@ void last_retired_fed_to_live_fed( PegTxType expectedType ) { // Arrange - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); - Script lastRetiredFederationP2SHScript = retiredFed.getDefaultP2SHScript(); BtcTransaction migrationTx = new BtcTransaction(btcMainnetParams); @@ -2272,14 +2231,10 @@ void retired_fed_no_existing_in_the_storage_to_live_fed( // Arrange Context.propagate(new Context(btcMainnetParams)); - BridgeStorageProvider provider = mock(BridgeStorageProvider.class); - List fedKeys = BitcoinTestUtils.getBtcEcKeysFromSeeds( new String[]{"fa01", "fa02", "fa03"}, true ); Federation retiredFederation = createFederation(bridgeMainnetConstants, fedKeys); - Federation activeFederation = FederationTestUtils.getGenesisFederation(bridgeMainnetConstants.getFederationConstants()); - BtcTransaction migrationTx = new BtcTransaction(btcMainnetParams); migrationTx.addInput( diff --git a/rskj-core/src/test/java/co/rsk/peg/PegUtilsTest.java b/rskj-core/src/test/java/co/rsk/peg/PegUtilsTest.java index 5ac9093f4a9..4f11f52cda9 100644 --- a/rskj-core/src/test/java/co/rsk/peg/PegUtilsTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/PegUtilsTest.java @@ -46,7 +46,6 @@ class PegUtilsTest { private Federation retiringFederation; private Federation activeFederation; - @BeforeEach void init() { provider = mock(BridgeStorageProvider.class); @@ -103,7 +102,6 @@ void test_getTransactionType_tx_sending_funds_to_unknown_address() { @Test void test_getTransactionType_pegin_below_minimum_active_fed() { // Arrange - Federation activeFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); Wallet liveFederationWallet = new BridgeBtcWallet(context, Collections.singletonList(activeFederation)); Coin minimumPeginTxValue = bridgeMainnetConstants.getMinimumPeginTxValue(activations); @@ -195,8 +193,6 @@ void test_getTransactionType_pegin_multiple_outputs_to_active_fed() { @Test void test_getTransactionType_pegin_output_to_retiring_fed_and_other_addresses() { // Arrange - Federation retiringFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); - List signers = BitcoinTestUtils.getBtcEcKeysFromSeeds( new String[]{"fa01", "fa02", "fa03"}, true ); @@ -556,7 +552,7 @@ void test_getTransactionType_flyover() { Keccak256 derivationArgumentsHash = PegTestUtils.createHash3(0); RskAddress lbcAddress = PegTestUtils.createRandomRskAddress(); - BridgeSupport bridgeSupport = new BridgeSupportBuilder().build(); + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder().build(); Keccak256 flyoverDerivationHash = bridgeSupport.getFlyoverDerivationHash( derivationArgumentsHash, userRefundBtcAddress, @@ -595,9 +591,6 @@ void test_getTransactionType_flyover_segwit() { // Arrange BridgeConstants bridgeTestNetConstants = BridgeTestNetConstants.getInstance(); NetworkParameters btcTestNetParams = bridgeTestNetConstants.getBtcParams(); - Context context = new Context(bridgeTestNetConstants.getBtcParams()); - - Federation retiringFederation = FederationTestUtils.getGenesisFederation(federationMainNetConstants); List signers = BitcoinTestUtils.getBtcEcKeysFromSeeds( new String[]{"fa01", "fa02", "fa03"}, true diff --git a/rskj-core/src/test/java/co/rsk/peg/bitcoin/BitcoinTestUtils.java b/rskj-core/src/test/java/co/rsk/peg/bitcoin/BitcoinTestUtils.java index 35b044993d5..ac33b329e5e 100644 --- a/rskj-core/src/test/java/co/rsk/peg/bitcoin/BitcoinTestUtils.java +++ b/rskj-core/src/test/java/co/rsk/peg/bitcoin/BitcoinTestUtils.java @@ -109,4 +109,20 @@ public static BtcTransaction createBtcTransactionWithOutputToAddress( return tx; } + + public static byte[] flatKeysAsByteArray(List keys) { + List pubKeys = keys.stream() + .map(BtcECKey::getPubKey) + .collect(Collectors.toList()); + int pubKeysLength = pubKeys.stream().mapToInt(key -> key.length).sum(); + + byte[] flatPubKeys = new byte[pubKeysLength]; + int copyPos = 0; + for (byte[] key : pubKeys) { + System.arraycopy(key, 0, flatPubKeys, copyPos, key.length); + copyPos += key.length; + } + + return flatPubKeys; + } } diff --git a/rskj-core/src/test/java/co/rsk/peg/federation/FederationStorageProviderImplTests.java b/rskj-core/src/test/java/co/rsk/peg/federation/FederationStorageProviderImplTests.java index c0e38fcd15f..e1f67898e79 100644 --- a/rskj-core/src/test/java/co/rsk/peg/federation/FederationStorageProviderImplTests.java +++ b/rskj-core/src/test/java/co/rsk/peg/federation/FederationStorageProviderImplTests.java @@ -1,57 +1,48 @@ package co.rsk.peg.federation; +import static co.rsk.bitcoinj.core.NetworkParameters.ID_MAINNET; +import static co.rsk.bitcoinj.core.NetworkParameters.ID_TESTNET; +import static co.rsk.peg.BridgeSerializationUtils.serializeElection; +import static co.rsk.peg.federation.FederationFormatVersion.*; +import static co.rsk.peg.federation.FederationStorageIndexKey.*; +import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; -import static java.util.Objects.isNull; -import java.math.BigInteger; -import java.util.*; -import org.ethereum.util.RLP; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.mockito.verification.VerificationMode; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; -import static co.rsk.bitcoinj.core.NetworkParameters.ID_TESTNET; -import static co.rsk.bitcoinj.core.NetworkParameters.ID_MAINNET; -import static co.rsk.peg.federation.FederationFormatVersion.*; -import static co.rsk.peg.federation.FederationStorageIndexKey.*; -import static co.rsk.peg.BridgeSerializationUtils.serializeElection; +import co.rsk.bitcoinj.core.*; import co.rsk.bitcoinj.script.Script; import co.rsk.core.RskAddress; -import co.rsk.peg.vote.ABICallElection; -import co.rsk.peg.vote.ABICallSpec; -import co.rsk.peg.vote.AddressBasedAuthorizer; -import co.rsk.bitcoinj.core.Address; -import co.rsk.bitcoinj.core.BtcECKey; -import co.rsk.bitcoinj.core.NetworkParameters; import co.rsk.peg.BridgeSerializationUtils; -import co.rsk.peg.storage.InMemoryStorage; import co.rsk.peg.PegTestUtils; import co.rsk.peg.bitcoin.BitcoinTestUtils; -import co.rsk.peg.constants.BridgeConstants; -import co.rsk.peg.constants.BridgeMainNetConstants; -import co.rsk.peg.constants.BridgeRegTestConstants; +import co.rsk.peg.constants.*; import co.rsk.peg.federation.constants.FederationConstants; -import co.rsk.peg.storage.BridgeStorageAccessorImpl; -import co.rsk.peg.storage.StorageAccessor; +import co.rsk.peg.storage.*; +import co.rsk.peg.vote.ABICallElection; +import co.rsk.peg.vote.ABICallSpec; +import co.rsk.peg.vote.AddressBasedAuthorizer; +import java.math.BigInteger; +import java.time.Instant; +import java.util.*; +import java.util.stream.Stream; import org.ethereum.config.blockchain.upgrades.ActivationConfig; import org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest; import org.ethereum.config.blockchain.upgrades.ConsensusRule; import org.ethereum.core.Repository; +import org.ethereum.util.RLP; import org.ethereum.vm.DataWord; import org.ethereum.vm.PrecompiledContracts; -import co.rsk.bitcoinj.core.UTXO; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.verification.VerificationMode; class FederationStorageProviderImplTests { - private static final int STANDARD_MULTISIG_FEDERATION_FORMAT_VERSION = STANDARD_MULTISIG_FEDERATION.getFormatVersion(); private static final int NON_STANDARD_ERP_FEDERATION_FORMAT_VERSION = NON_STANDARD_ERP_FEDERATION.getFormatVersion(); private static final int P2SH_ERP_FEDERATION_FORMAT_VERSION = P2SH_ERP_FEDERATION.getFormatVersion(); @@ -60,23 +51,29 @@ class FederationStorageProviderImplTests { private static final BridgeConstants bridgeConstantsRegtest = new BridgeRegTestConstants(); private static final NetworkParameters regtestBtcParams = bridgeConstantsRegtest.getBtcParams(); - private static ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); private static final BridgeConstants bridgeConstants = BridgeMainNetConstants.getInstance(); private static final FederationConstants federationConstants = bridgeConstants.getFederationConstants(); private static final NetworkParameters networkParameters = federationConstants.getBtcParams(); + private static ActivationConfig.ForBlock activations; + + @BeforeEach + void setup() { + activations = ActivationConfigsForTest.all().forBlock(0L); + } + private static Stream provideFederationAndFormatArguments() { return Stream.of( - Arguments.of(P2SH_ERP_FEDERATION_FORMAT_VERSION, new P2shErpFederationBuilder().build()), + Arguments.of(P2SH_ERP_FEDERATION_FORMAT_VERSION, P2shErpFederationBuilder.builder().build()), Arguments.of(NON_STANDARD_ERP_FEDERATION_FORMAT_VERSION, createNonStandardErpFederation()), - Arguments.of(STANDARD_MULTISIG_FEDERATION_FORMAT_VERSION, new StandardMultiSigFederationBuilder().build()), + Arguments.of(STANDARD_MULTISIG_FEDERATION_FORMAT_VERSION, StandardMultiSigFederationBuilder.builder().build()), Arguments.of(STANDARD_MULTISIG_FEDERATION_FORMAT_VERSION, null), Arguments.of(NON_STANDARD_ERP_FEDERATION_FORMAT_VERSION, null), Arguments.of(P2SH_ERP_FEDERATION_FORMAT_VERSION, null), Arguments.of(INVALID_FEDERATION_FORMAT, null), Arguments.of(EMPTY_FEDERATION_FORMAT, null), - Arguments.of(INVALID_FEDERATION_FORMAT, new StandardMultiSigFederationBuilder().build()), - Arguments.of(EMPTY_FEDERATION_FORMAT, new StandardMultiSigFederationBuilder().build()) + Arguments.of(INVALID_FEDERATION_FORMAT, StandardMultiSigFederationBuilder.builder().build()), + Arguments.of(EMPTY_FEDERATION_FORMAT, StandardMultiSigFederationBuilder.builder().build()) ); } @@ -127,15 +124,15 @@ void testGetOldFederation( Federation obtainedFederation = federationStorageProvider.getOldFederation(federationConstants, activations); // Directly saving a null federation in storage to then assert that the method returns the cached federation - if(nonNull(expectedFederation)) { + if (nonNull(expectedFederation)) { storageAccessor.saveToRepository(OLD_FEDERATION_KEY.getKey(), null); } // Assert + assertEquals(expectedFederation, obtainedFederation); // Call the method again and assert the same cached federation is returned assertEquals(obtainedFederation, federationStorageProvider.getOldFederation(federationConstants, activations)); - assertEquals(expectedFederation, obtainedFederation); } @Test @@ -149,9 +146,9 @@ void getOldFederation_previouslySetToNull_returnsNull() { private static Stream providePendingFederationAndFormatArguments() { return Stream.of( - Arguments.of(P2SH_ERP_FEDERATION_FORMAT_VERSION, new PendingFederationBuilder().build()), - Arguments.of(NON_STANDARD_ERP_FEDERATION_FORMAT_VERSION, new PendingFederationBuilder().build()), - Arguments.of(STANDARD_MULTISIG_FEDERATION_FORMAT_VERSION, new PendingFederationBuilder().build()) + Arguments.of(P2SH_ERP_FEDERATION_FORMAT_VERSION, PendingFederationBuilder.builder().build()), + Arguments.of(NON_STANDARD_ERP_FEDERATION_FORMAT_VERSION, PendingFederationBuilder.builder().build()), + Arguments.of(STANDARD_MULTISIG_FEDERATION_FORMAT_VERSION, PendingFederationBuilder.builder().build()) ); } @@ -162,10 +159,6 @@ void testGetPendingFederation( PendingFederation expectedFederation ) { // Arrange - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - - when(activations.isActive(ConsensusRule.RSKIP123)).thenReturn(true); - StorageAccessor storageAccessor = new InMemoryStorage(); byte[] federationFormatSerialized = getFederationFormatSerialized(federationFormat); storageAccessor.saveToRepository(PENDING_FEDERATION_FORMAT_VERSION.getKey(), federationFormatSerialized); @@ -188,15 +181,11 @@ void testGetPendingFederation( } @Test - void getPendingFederation_whenStorageVersionIsNotAvailable_deserializeFromBtcKeysOnly( - ) { - - PendingFederation expectedFederation = new PendingFederationBuilder().build(); + void getPendingFederation_whenStorageVersionIsNotAvailable_deserializeFromBtcKeysOnly() { + PendingFederation expectedFederation = PendingFederationBuilder.builder().build(); // Arrange - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - - when(activations.isActive(ConsensusRule.RSKIP123)).thenReturn(false); + activations = ActivationConfigsForTest.orchid().forBlock(0L); StorageAccessor storageAccessor = new InMemoryStorage(); byte[] federationFormatSerialized = getFederationFormatSerialized(INVALID_FEDERATION_FORMAT); @@ -223,7 +212,7 @@ void getPendingFederation_whenStorageVersionIsNotAvailable_deserializeFromBtcKey void getPendingFederation_previouslySet_returnsCachedPendingFederation() { // Arrange - PendingFederation expectedPendingFederation = new PendingFederationBuilder().build(); + PendingFederation expectedPendingFederation = PendingFederationBuilder.builder().build(); // Act FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(null); @@ -252,9 +241,7 @@ void getPendingFederation_previouslySetToNull_returnsNull() { @Test void getPendingFederation_nullPendingFederationInStorage_returnsNull() { // Arrange - ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - - when(activations.isActive(ConsensusRule.RSKIP123)).thenReturn(false); + activations = ActivationConfigsForTest.orchid().forBlock(0L); StorageAccessor storageAccessor = new InMemoryStorage(); byte[] federationFormatSerialized = getFederationFormatSerialized(STANDARD_MULTISIG_FEDERATION_FORMAT_VERSION); @@ -274,9 +261,9 @@ private static Stream provideSaveFederationTestArguments() { ActivationConfig.ForBlock papyrusActivations = ActivationConfigsForTest.papyrus200().forBlock(0L); ActivationConfig.ForBlock irisActivations = ActivationConfigsForTest.iris300().forBlock(0L); - Federation standardFederation = new StandardMultiSigFederationBuilder().build(); + Federation standardFederation = StandardMultiSigFederationBuilder.builder().build(); Federation nonStandardFederation = createNonStandardErpFederation(); - Federation ps2hErpFederation = new P2shErpFederationBuilder().build(); + Federation ps2hErpFederation = P2shErpFederationBuilder.builder().build(); return Stream.of( // When iris is not active, should allow to save any fed type but not the version @@ -293,13 +280,12 @@ private static Stream provideSaveFederationTestArguments() { @Test void saveNewFederation_before_RSKIP123_should_not_save_null() { Repository repository = mock(Repository.class); - activations = mock(ActivationConfig.ForBlock.class); - when(activations.isActive(ConsensusRule.RSKIP123)).thenReturn(false); + ActivationConfig.ForBlock orchidActivations = ActivationConfigsForTest.orchid().forBlock(0L); // Act FederationStorageProvider federationStorageProvider = createFederationStorageProvider(repository); federationStorageProvider.setNewFederation(null); - federationStorageProvider.save(regtestBtcParams, activations); + federationStorageProvider.save(regtestBtcParams, orchidActivations); verify(repository, never()).addStorageBytes( any(), @@ -458,7 +444,6 @@ void getNewFederationBtcUTXOs( @Test void getNewFederationBtcUTXOs_calledTwice_returnCachedUtxos() { - ActivationConfig.ForBlock activations = ActivationConfigsForTest.only(ConsensusRule.RSKIP123).forBlock(0); StorageAccessor storageAccessor = new InMemoryStorage(); FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(storageAccessor); @@ -620,7 +605,7 @@ void getFederationElection_whenElectionIsNotInStorage_shouldReturnDefault() { @Test void getNextFederationCreationBlockHeight_preIris300_storageIsNotAccessedAndReturnsEmpty() { // Arrange - ActivationConfig.ForBlock activations = ActivationConfigsForTest.papyrus200().forBlock(0L); + ActivationConfig.ForBlock papyrusActivations = ActivationConfigsForTest.papyrus200().forBlock(0L); StorageAccessor storageAccessor = new InMemoryStorage(); // Putting some value in the storage just to then assert that before fork, the storage won't be accessed. @@ -633,13 +618,13 @@ void getNextFederationCreationBlockHeight_preIris300_storageIsNotAccessedAndRetu FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(storageAccessor); // Assert - assertEquals(Optional.empty(), federationStorageProvider.getNextFederationCreationBlockHeight(activations)); + assertEquals(Optional.empty(), federationStorageProvider.getNextFederationCreationBlockHeight(papyrusActivations)); } @Test void getNextFederationCreationBlockHeight_postIris300_getsValueFromStorage() { // Arrange - ActivationConfig.ForBlock activations = ActivationConfigsForTest.iris300().forBlock(0L); + ActivationConfig.ForBlock irisActivations = ActivationConfigsForTest.iris300().forBlock(0L); StorageAccessor storageAccessor = new InMemoryStorage(); long expectedValue = 1_000_000L; @@ -648,7 +633,7 @@ void getNextFederationCreationBlockHeight_postIris300_getsValueFromStorage() { // Act FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(storageAccessor); - Optional actualValue = federationStorageProvider.getNextFederationCreationBlockHeight(activations); + Optional actualValue = federationStorageProvider.getNextFederationCreationBlockHeight(irisActivations); // Assert assertTrue(actualValue.isPresent()); @@ -657,7 +642,7 @@ void getNextFederationCreationBlockHeight_postIris300_getsValueFromStorage() { // Setting in storage a different value to assert that calling the method again should return cached value storageAccessor.saveToRepository(NEXT_FEDERATION_CREATION_BLOCK_HEIGHT_KEY.getKey(), RLP.encodeBigInteger(BigInteger.valueOf(2_000_000L))); - Optional actualCachedValue = federationStorageProvider.getNextFederationCreationBlockHeight(activations); + Optional actualCachedValue = federationStorageProvider.getNextFederationCreationBlockHeight(irisActivations); assertTrue(actualCachedValue.isPresent()); assertEquals(expectedValue, actualCachedValue.get()); @@ -666,14 +651,14 @@ void getNextFederationCreationBlockHeight_postIris300_getsValueFromStorage() { @Test void getNextFederationCreationBlockHeight_postIris300AndNoValueInStorage_returnsEmpty() { // Arrange - ActivationConfig.ForBlock activations = ActivationConfigsForTest.iris300().forBlock(0L); + ActivationConfig.ForBlock irisActivations = ActivationConfigsForTest.iris300().forBlock(0L); StorageAccessor storageAccessor = new InMemoryStorage(); storageAccessor.saveToRepository(NEXT_FEDERATION_CREATION_BLOCK_HEIGHT_KEY.getKey(), null); // Act FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(storageAccessor); - Optional actualValue = federationStorageProvider.getNextFederationCreationBlockHeight(activations); + Optional actualValue = federationStorageProvider.getNextFederationCreationBlockHeight(irisActivations); // Assert assertFalse(actualValue.isPresent()); @@ -783,7 +768,7 @@ void testSaveOldFederation( void savePendingFederation_preWasabi_shouldBeSavedInStorageSerializedFromBtcKeysOnly() { // Arrange ActivationConfig.ForBlock orchidActivation = ActivationConfigsForTest.orchid().forBlock(0L); - PendingFederation expectedPendingFederation = new PendingFederationBuilder().build(); + PendingFederation expectedPendingFederation = PendingFederationBuilder.builder().build(); StorageAccessor storageAccessor = new InMemoryStorage(); FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(storageAccessor); federationStorageProvider.setPendingFederation(expectedPendingFederation); @@ -807,7 +792,7 @@ void savePendingFederation_preWasabi_shouldBeSavedInStorageSerializedFromBtcKeys void savePendingFederation_postWasabi_shouldBeSavedInStorageWithFormatVersion() { // Arrange ActivationConfig.ForBlock wasabiActivations = ActivationConfigsForTest.wasabi100().forBlock(0L); - PendingFederation expectedPendingFederation = new PendingFederationBuilder().build(); + PendingFederation expectedPendingFederation = PendingFederationBuilder.builder().build(); StorageAccessor storageAccessor = new InMemoryStorage(); FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(storageAccessor); federationStorageProvider.setPendingFederation(expectedPendingFederation); @@ -877,7 +862,7 @@ void saveLastRetiredFederationP2SHScript_postIris_getsValueFromStorage() { // Arrange ActivationConfig.ForBlock irisActivations = ActivationConfigsForTest.iris300().forBlock(0L); - Script expectedScript = new P2shErpFederationBuilder().build().getDefaultP2SHScript(); + Script expectedScript = P2shErpFederationBuilder.builder().build().getDefaultP2SHScript(); StorageAccessor storageAccessor = new InMemoryStorage(); FederationStorageProvider federationStorageProvider = new FederationStorageProviderImpl(storageAccessor); @@ -941,7 +926,7 @@ private static Federation createNonStandardErpFederation() { federationArgs, erpPubKeys, activationDelay, - activations + ActivationConfigsForTest.all().forBlock(0L) ); } @@ -962,11 +947,11 @@ private byte[] getFederationFormatSerialized(int federationFormat) { } private byte[] getSerializedFederation(Federation federation, int federationFormat) { - if(isNull(federation)) { + if (isNull(federation)) { return null; } - if(federationFormat == INVALID_FEDERATION_FORMAT || federationFormat == EMPTY_FEDERATION_FORMAT) { + if (federationFormat == INVALID_FEDERATION_FORMAT || federationFormat == EMPTY_FEDERATION_FORMAT) { return BridgeSerializationUtils.serializeFederationOnlyBtcKeys(federation); } diff --git a/rskj-core/src/test/java/co/rsk/peg/federation/FederationSupportImplTest.java b/rskj-core/src/test/java/co/rsk/peg/federation/FederationSupportImplTest.java index be6bdc7161b..fb41da4d362 100644 --- a/rskj-core/src/test/java/co/rsk/peg/federation/FederationSupportImplTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/federation/FederationSupportImplTest.java @@ -70,7 +70,7 @@ class FederationSupportImplTest { private ErpFederation newFederation; private StorageAccessor storageAccessor; private FederationStorageProvider storageProvider; - private final FederationSupportBuilder federationSupportBuilder = new FederationSupportBuilder(); + private final FederationSupportBuilder federationSupportBuilder = FederationSupportBuilder.builder(); private FederationSupport federationSupport; private SignatureCache signatureCache; @@ -244,16 +244,13 @@ void setUp() { storageProvider = new FederationStorageProviderImpl(storageAccessor); // create new federation - P2shErpFederationBuilder p2shErpFederationBuilder = new P2shErpFederationBuilder(); - newFederation = p2shErpFederationBuilder - .build(); + newFederation = P2shErpFederationBuilder.builder().build(); storageProvider.setNewFederation(newFederation); federationSupport = federationSupportBuilder .withFederationConstants(federationMainnetConstants) .withFederationStorageProvider(storageProvider) .build(); - } @Test @@ -371,7 +368,7 @@ void getActiveFederatorPublicKeyOfType_withSpecificRskKeys_returnsFederatorFromN List rskECKeys = RskTestUtils.getEcKeysFromSeeds( new String[]{"rsk01", "rsk02", "rsk03", "rsk04", "rsk05", "rsk06", "rsk07", "rsk08", "rsk09"} ); - newFederation = new P2shErpFederationBuilder() + newFederation = P2shErpFederationBuilder.builder() .withMembersRskPublicKeys(rskECKeys) .build(); storageProvider.setNewFederation(newFederation); @@ -405,7 +402,7 @@ void getActiveFederatorPublicKeyOfType_withSpecificRskAndMstKeys_returnsFederato List mstECKeys = RskTestUtils.getEcKeysFromSeeds( new String[]{"mst01", "mst02", "mst03", "mst04", "mst05", "mst06", "mst07", "mst08", "mst09"} ); - newFederation = new P2shErpFederationBuilder() + newFederation = P2shErpFederationBuilder.builder() .withMembersRskPublicKeys(rskECKeys) .withMembersMstPublicKeys(mstECKeys) .build(); @@ -447,13 +444,13 @@ class ActiveFederationTestsWithNonNullFederations { // create old and new federations long oldFederationCreationBlockNumber = 20; long newFederationCreationBlockNumber = 65; - Federation oldFederation = new P2shErpFederationBuilder() + Federation oldFederation = P2shErpFederationBuilder.builder() .withCreationBlockNumber(oldFederationCreationBlockNumber) .build(); List newFederationKeys = BitcoinTestUtils.getBtcEcKeysFromSeeds( new String[]{"fa01", "fa02", "fa03", "fa04", "fa05", "fa06", "fa07", "fa08", "fa09"}, true ); - Federation newFederation = new P2shErpFederationBuilder() + Federation newFederation = P2shErpFederationBuilder.builder() .withMembersBtcPublicKeys(newFederationKeys) .withCreationBlockNumber(newFederationCreationBlockNumber) .build(); @@ -1212,9 +1209,7 @@ void setUp() { storageProvider = new FederationStorageProviderImpl(storageAccessor); // create new federation - P2shErpFederationBuilder p2shErpFederationBuilder = new P2shErpFederationBuilder(); - newFederation = p2shErpFederationBuilder - .build(); + newFederation = P2shErpFederationBuilder.builder().build(); storageProvider.setNewFederation(newFederation); federationSupport = federationSupportBuilder @@ -1308,13 +1303,13 @@ class RetiringFederationTestsWithNonNullFederations { // create old and new federations long oldFederationCreationBlockNumber = 20; long newFederationCreationBlockNumber = 65; - Federation oldFederation = new P2shErpFederationBuilder() + Federation oldFederation = P2shErpFederationBuilder.builder() .withCreationBlockNumber(oldFederationCreationBlockNumber) .build(); List newFederationKeys = BitcoinTestUtils.getBtcEcKeysFromSeeds( new String[]{"fa01", "fa02", "fa03", "fa04", "fa05", "fa06", "fa07", "fa08", "fa09"}, true ); - Federation newFederation = new P2shErpFederationBuilder() + Federation newFederation = P2shErpFederationBuilder.builder() .withMembersBtcPublicKeys(newFederationKeys) .withCreationBlockNumber(newFederationCreationBlockNumber) .build(); @@ -1762,7 +1757,7 @@ void getRetiringFederatorPublicKeyOfType_withSpecificRskKeysAndNewFederationActi List rskECKeys = RskTestUtils.getEcKeysFromSeeds( new String[]{"rsk01", "rsk02", "rsk03", "rsk04", "rsk05", "rsk06", "rsk07", "rsk08", "rsk09"} ); - Federation oldFederationWithRskKeys = new P2shErpFederationBuilder() + Federation oldFederationWithRskKeys = P2shErpFederationBuilder.builder() .withMembersRskPublicKeys(rskECKeys) .build(); storageProvider.setOldFederation(oldFederationWithRskKeys); @@ -1810,7 +1805,7 @@ void getRetiringFederatorPublicKeyOfType_withSpecificRskAndMstKeysAndNewFederati List mstECKeys = RskTestUtils.getEcKeysFromSeeds( new String[]{"mst01", "mst02", "mst03", "mst04", "mst05", "mst06", "mst07", "mst08", "mst09"} ); - Federation oldFederationWithRskAndMstKeys = new P2shErpFederationBuilder() + Federation oldFederationWithRskAndMstKeys = P2shErpFederationBuilder.builder() .withMembersRskPublicKeys(rskECKeys) .withMembersMstPublicKeys(mstECKeys) .build(); @@ -1957,7 +1952,7 @@ void getPendingFederatorPublicKeyOfType_returnsNull() { @TestInstance(TestInstance.Lifecycle.PER_CLASS) class PendingFederationTestsWithNonNullFederation { - PendingFederation pendingFederation = new PendingFederationBuilder().build(); + PendingFederation pendingFederation = PendingFederationBuilder.builder().build(); @BeforeEach void setUp() { @@ -2040,7 +2035,7 @@ void getPendingFederatorPublicKeyOfType_withSpecificRskKeys_returnsFederatorFrom List rskECKeys = RskTestUtils.getEcKeysFromSeeds( new String[]{"rsk01", "rsk02", "rsk03", "rsk04", "rsk05", "rsk06", "rsk07", "rsk08", "rsk09"} ); - PendingFederation pendingFederationWithRskKeys = new PendingFederationBuilder() + PendingFederation pendingFederationWithRskKeys = PendingFederationBuilder.builder() .withMembersRskPublicKeys(rskECKeys) .build(); storageProvider.setPendingFederation(pendingFederationWithRskKeys); @@ -2074,7 +2069,7 @@ void getPendingFederatorPublicKeyOfType_withSpecificRskAndMstKeys_returnsFederat List mstECKeys = RskTestUtils.getEcKeysFromSeeds( new String[]{"mst01", "mst02", "mst03", "mst04", "mst05", "mst06", "mst07", "mst08", "mst09"} ); - PendingFederation pendingFederationWithRskAndMstKeys = new PendingFederationBuilder() + PendingFederation pendingFederationWithRskAndMstKeys = PendingFederationBuilder.builder() .withMembersRskPublicKeys(rskECKeys) .withMembersMstPublicKeys(mstECKeys) .build(); @@ -2159,8 +2154,7 @@ void getLastRetiredFederationP2SHScript_afterRSKIP186_whenSavingScript_returnsSc .build(); // get a real p2sh script - ErpFederation federation = new P2shErpFederationBuilder() - .build(); + ErpFederation federation = P2shErpFederationBuilder.builder().build(); Script p2shScript = federation.getDefaultP2SHScript(); storageProvider.setLastRetiredFederationP2SHScript(p2shScript); @@ -2175,7 +2169,7 @@ void getLastRetiredFederationP2SHScript_afterRSKIP186_whenSavingScript_returnsSc void clearRetiredFederation_whenHavingOldFederation_removesOldFederation() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); - ErpFederation federation = new P2shErpFederationBuilder().build(); + ErpFederation federation = P2shErpFederationBuilder.builder().build(); storageProvider.setOldFederation(federation); // check the old federation was correctly saved diff --git a/rskj-core/src/test/java/co/rsk/peg/federation/FederationTestUtils.java b/rskj-core/src/test/java/co/rsk/peg/federation/FederationTestUtils.java index fe4a36a8d10..a4dc2543109 100644 --- a/rskj-core/src/test/java/co/rsk/peg/federation/FederationTestUtils.java +++ b/rskj-core/src/test/java/co/rsk/peg/federation/FederationTestUtils.java @@ -46,11 +46,12 @@ public static ErpFederation getErpFederation(NetworkParameters networkParameters new String[]{"fa01", "fa02", "fa03", "fa04", "fa05", "fa06", "fa07", "fa08", "fa09"}, true ); final List erpSigners = BitcoinTestUtils.getBtcEcKeysFromSeeds( - new String[]{"fb01", "fb02", "fb03"}, true + new String[]{"fb01", "fb02", "fb03", "fb04"}, true ); List fedMember = FederationTestUtils.getFederationMembersWithBtcKeys( - fedSigners); + fedSigners + ); FederationArgs federationArgs = new FederationArgs( fedMember, @@ -59,7 +60,7 @@ public static ErpFederation getErpFederation(NetworkParameters networkParameters networkParameters ); - long erpFedActivationDelay = 100L; + long erpFedActivationDelay = 52_560; // Mainnet value return FederationFactory.buildP2shErpFederation( federationArgs, diff --git a/rskj-core/src/test/java/co/rsk/peg/federation/P2shErpFederationBuilder.java b/rskj-core/src/test/java/co/rsk/peg/federation/P2shErpFederationBuilder.java index 91eb2727c2b..fe247efbafe 100644 --- a/rskj-core/src/test/java/co/rsk/peg/federation/P2shErpFederationBuilder.java +++ b/rskj-core/src/test/java/co/rsk/peg/federation/P2shErpFederationBuilder.java @@ -22,10 +22,18 @@ public class P2shErpFederationBuilder { private long creationBlockNumber; private NetworkParameters networkParameters; - public P2shErpFederationBuilder() { - this.membersBtcPublicKeys = BitcoinTestUtils.getBtcEcKeysFromSeeds( - new String[]{"member01", "member02", "member03", "member04", "member05", "member06", "member07", "member08", "member09"}, true - ); + private P2shErpFederationBuilder() { + this.membersBtcPublicKeys = BitcoinTestUtils.getBtcEcKeysFromSeeds(new String[]{ + "member01", + "member02", + "member03", + "member04", + "member05", + "member06", + "member07", + "member08", + "member09" + }, true); this.membersRskPublicKeys = new ArrayList<>(); this.membersMstPublicKeys = new ArrayList<>(); this.erpPublicKeys = FederationMainNetConstants.getInstance().getErpFedPubKeysList(); @@ -35,6 +43,10 @@ public P2shErpFederationBuilder() { this.networkParameters = NetworkParameters.fromID(NetworkParameters.ID_MAINNET); } + public static P2shErpFederationBuilder builder() { + return new P2shErpFederationBuilder(); + } + public P2shErpFederationBuilder withMembersBtcPublicKeys(List btcPublicKeys) { this.membersBtcPublicKeys = btcPublicKeys; return this; @@ -92,12 +104,10 @@ private List getFederationMembers() { membersMstPublicKeys = new ArrayList<>(membersRskPublicKeys); } - return IntStream.range(0, membersBtcPublicKeys.size()) - .mapToObj(i -> new FederationMember( - membersBtcPublicKeys.get(i), - membersRskPublicKeys.get(i), - membersMstPublicKeys.get(i) - )) - .collect(Collectors.toList()); + return IntStream.range(0, membersBtcPublicKeys.size()).mapToObj(i -> new FederationMember( + membersBtcPublicKeys.get(i), + membersRskPublicKeys.get(i), + membersMstPublicKeys.get(i) + )).collect(Collectors.toList()); } } diff --git a/rskj-core/src/test/java/co/rsk/peg/federation/PendingFederationBuilder.java b/rskj-core/src/test/java/co/rsk/peg/federation/PendingFederationBuilder.java index c021ad3989e..e64b34fdede 100644 --- a/rskj-core/src/test/java/co/rsk/peg/federation/PendingFederationBuilder.java +++ b/rskj-core/src/test/java/co/rsk/peg/federation/PendingFederationBuilder.java @@ -13,7 +13,7 @@ public class PendingFederationBuilder { private List membersRskPublicKeys; private List membersMstPublicKeys; - public PendingFederationBuilder() { + private PendingFederationBuilder() { this.membersBtcPublicKeys = BitcoinTestUtils.getBtcEcKeysFromSeeds( new String[]{"member01", "member02", "member03", "member04", "member05", "member06", "member07", "member08", "member09"}, true ); @@ -21,6 +21,10 @@ public PendingFederationBuilder() { this.membersMstPublicKeys = new ArrayList<>(); } + public static PendingFederationBuilder builder() { + return new PendingFederationBuilder(); + } + public PendingFederationBuilder withMembersBtcPublicKeys(List btcPublicKeys) { this.membersBtcPublicKeys = btcPublicKeys; return this; diff --git a/rskj-core/src/test/java/co/rsk/peg/federation/PowpegMigrationTest.java b/rskj-core/src/test/java/co/rsk/peg/federation/PowpegMigrationTest.java index 6d27819f97e..ff18d88d035 100644 --- a/rskj-core/src/test/java/co/rsk/peg/federation/PowpegMigrationTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/federation/PowpegMigrationTest.java @@ -145,10 +145,10 @@ private void testChangePowpeg( btcParams ); switch (oldPowPegFederationType) { - case nonStandardErp: + case NON_STANDARD_ERP: originalPowpeg = FederationFactory.buildNonStandardErpFederation(federationArgs, erpPubKeys, activationDelay, activations); break; - case p2shErp: + case P2SH_ERP: originalPowpeg = FederationFactory.buildP2shErpFederation(federationArgs, erpPubKeys, activationDelay); // TODO: CHECK REDEEMSCRIPT break; @@ -203,11 +203,11 @@ private void testChangePowpeg( Federation newPowPeg = argumentCaptor.getValue(); assertEquals(newPowPegAddress, newPowPeg.getAddress()); switch (newPowPegFederationType) { - case nonStandardErp: + case NON_STANDARD_ERP: assertSame(ErpFederation.class, newPowPeg.getClass()); assertTrue(((ErpFederation) newPowPeg).getErpRedeemScriptBuilder() instanceof NonStandardErpRedeemScriptBuilder); break; - case p2shErp: + case P2SH_ERP: assertSame(ErpFederation.class, newPowPeg.getClass()); assertTrue(((ErpFederation) newPowPeg).getErpRedeemScriptBuilder() instanceof P2shErpRedeemScriptBuilder); // TODO: CHECK REDEEMSCRIPT @@ -238,7 +238,7 @@ private void testChangePowpeg( // Trying to create a new powpeg again should fail // -2 corresponds to a new powpeg was elected and the Bridge is waiting for this new powpeg to activate - BridgeSupport bridgeSupport = new BridgeSupportBuilder() + BridgeSupport bridgeSupport = BridgeSupportBuilder.builder() .withProvider(bridgeStorageProvider) .withRepository(repository) .withEventLogger(bridgeEventLogger) @@ -327,7 +327,7 @@ private void testChangePowpeg( Block legacyFedActivationBlock = mock(Block.class); doReturn(legacyFedActivationBlockNumber).when(legacyFedActivationBlock).getNumber(); - bridgeSupport = new BridgeSupportBuilder() + bridgeSupport = BridgeSupportBuilder.builder() .withProvider(bridgeStorageProvider) .withRepository(repository) .withEventLogger(bridgeEventLogger) @@ -344,13 +344,13 @@ private void testChangePowpeg( assertNull(bridgeSupport.getRetiringFederation()); } - FederationSupport federationSupport = new FederationSupportBuilder() + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(bridgeConstants.getFederationConstants()) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(activationBlock) .build(); - bridgeSupport = new BridgeSupportBuilder() + bridgeSupport = BridgeSupportBuilder.builder() .withProvider(bridgeStorageProvider) .withRepository(repository) .withEventLogger(bridgeEventLogger) @@ -415,13 +415,13 @@ private void testChangePowpeg( // Adding 1 as the migration is exclusive doReturn(blockNumber).when(migrationBlock).getNumber(); - federationSupport = new FederationSupportBuilder() + federationSupport = FederationSupportBuilder.builder() .withFederationConstants(bridgeConstants.getFederationConstants()) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(migrationBlock) .build(); - bridgeSupport = new BridgeSupportBuilder() + bridgeSupport = BridgeSupportBuilder.builder() .withProvider(bridgeStorageProvider) .withRepository(repository) .withEventLogger(bridgeEventLogger) @@ -575,13 +575,13 @@ private void testChangePowpeg( bridgeConstants.getFederationConstants().getFundsMigrationAgeSinceActivationEnd(activations) ); - federationSupport = new FederationSupportBuilder() + federationSupport = FederationSupportBuilder.builder() .withFederationConstants(bridgeConstants.getFederationConstants()) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(migrationFinishingBlock) .build(); - bridgeSupport = new BridgeSupportBuilder() + bridgeSupport = BridgeSupportBuilder.builder() .withProvider(bridgeStorageProvider) .withRepository(repository) .withEventLogger(bridgeEventLogger) @@ -615,13 +615,13 @@ private void testChangePowpeg( bridgeConstants.getFederationConstants().getFundsMigrationAgeSinceActivationEnd(activations) ); - federationSupport = new FederationSupportBuilder() + federationSupport = FederationSupportBuilder.builder() .withFederationConstants(bridgeConstants.getFederationConstants()) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(migrationFinishedBlock) .build(); - bridgeSupport = new BridgeSupportBuilder() + bridgeSupport = BridgeSupportBuilder.builder() .withProvider(bridgeStorageProvider) .withRepository(repository) .withEventLogger(bridgeEventLogger) @@ -677,12 +677,14 @@ private void testChangePowpeg( Script lastRetiredFederationP2SHScript = lastRetiredFederationP2SHScriptOptional.get(); if (activations.isActive(ConsensusRule.RSKIP377)){ - if (oldPowPegFederationType == FederationType.nonStandardErp || oldPowPegFederationType == FederationType.p2shErp){ + if (oldPowPegFederationType == FederationType.NON_STANDARD_ERP + || oldPowPegFederationType == FederationType.P2SH_ERP){ assertNotEquals(lastRetiredFederationP2SHScript, originalPowpeg.getP2SHScript()); } assertEquals(lastRetiredFederationP2SHScript, getFederationDefaultP2SHScript(originalPowpeg)); } else { - if (oldPowPegFederationType == FederationType.nonStandardErp || oldPowPegFederationType == FederationType.p2shErp){ + if (oldPowPegFederationType == FederationType.NON_STANDARD_ERP + || oldPowPegFederationType == FederationType.P2SH_ERP){ assertEquals(lastRetiredFederationP2SHScript, originalPowpeg.getP2SHScript()); assertNotEquals(lastRetiredFederationP2SHScript, getFederationDefaultP2SHScript(originalPowpeg)); } else { @@ -797,14 +799,14 @@ private void testPegouts( // Adding 1 as the migration is exclusive doReturn(blockNumber).when(nextPegoutEventBlock).getNumber(); - FederationSupport federationSupport = new FederationSupportBuilder() + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(bridgeConstants.getFederationConstants()) .withFederationStorageProvider(federationStorageProvider) .withRskExecutionBlock(nextPegoutEventBlock) .withActivations(activations) .build(); - bridgeSupport = new BridgeSupportBuilder() + bridgeSupport = BridgeSupportBuilder.builder() .withProvider(bridgeStorageProvider) .withRepository(repository) .withEventLogger(bridgeEventLogger) @@ -879,12 +881,12 @@ private void testPegouts( // Adding 1 as the migration is exclusive doReturn(blockNumber).when(confirmedPegoutBlock).getNumber(); - FederationSupport federationSupport = new FederationSupportBuilder() + FederationSupport federationSupport = FederationSupportBuilder.builder() .withFederationConstants(bridgeConstants.getFederationConstants()) .withFederationStorageProvider(federationStorageProvider) .build(); - bridgeSupport = new BridgeSupportBuilder() + bridgeSupport = BridgeSupportBuilder.builder() .withProvider(bridgeStorageProvider) .withRepository(repository) .withEventLogger(bridgeEventLogger) @@ -1468,11 +1470,11 @@ void test_change_powpeg_from_erpFederation_with_mainnet_powpeg_pre_RSKIP_353_cre ); testChangePowpeg( - FederationType.nonStandardErp, + FederationType.NON_STANDARD_ERP, getMainnetPowpegKeys(), originalPowpegAddress, utxos, - FederationType.nonStandardErp, + FederationType.NON_STANDARD_ERP, newPowpegKeys, newPowpegAddress, bridgeMainnetConstants, @@ -1494,11 +1496,11 @@ void test_change_powpeg_from_erpFederation_with_mainnet_powpeg_post_RSKIP_353_cr ); testChangePowpeg( - FederationType.nonStandardErp, + FederationType.NON_STANDARD_ERP, getMainnetPowpegKeys(), originalPowpegAddress, utxos, - FederationType.p2shErp, + FederationType.P2SH_ERP, getMainnetPowpegKeys(), // Using same keys as the original powpeg, should result in a different address since it will create a p2sh erp federation newPowpegAddress, bridgeMainnetConstants, @@ -1540,11 +1542,11 @@ void test_change_powpeg_from_p2shErpFederation_with_mainnet_powpeg_post_RSKIP_35 ); testChangePowpeg( - FederationType.p2shErp, + FederationType.P2SH_ERP, getMainnetPowpegKeys(), originalPowpegAddress, utxos, - FederationType.p2shErp, + FederationType.P2SH_ERP, newPowPegKeys, newPowPegAddress, bridgeMainnetConstants, @@ -1605,11 +1607,11 @@ void test_change_powpeg_from_p2shErpFederation_with_mainnet_powpeg(ActivationCon ); testChangePowpeg( - FederationType.p2shErp, + FederationType.P2SH_ERP, getMainnetPowpegKeys(), originalPowpegAddress, utxos, - FederationType.p2shErp, + FederationType.P2SH_ERP, newPowPegKeys, newPowPegAddress, bridgeMainnetConstants, @@ -1653,11 +1655,11 @@ void test_change_powpeg_from_p2shErpFederation_with_mainnet_powpeg_post_RSKIP_37 ); testChangePowpeg( - FederationType.p2shErp, + FederationType.P2SH_ERP, getMainnetPowpegKeys(), originalPowpegAddress, utxos, - FederationType.p2shErp, + FederationType.P2SH_ERP, newPowPegKeys, newPowPegAddress, bridgeMainnetConstants, @@ -1701,11 +1703,11 @@ void test_change_powpeg_from_p2shErpFederation_with_mainnet_powpeg_post_RSKIP_37 ); testChangePowpeg( - FederationType.p2shErp, + FederationType.P2SH_ERP, getMainnetPowpegKeys(), originalPowpegAddress, utxos, - FederationType.p2shErp, + FederationType.P2SH_ERP, newPowPegKeys, newPowPegAddress, bridgeMainnetConstants, @@ -1749,11 +1751,11 @@ void test_change_powpeg_from_p2shErpFederation_with_mainnet_powpeg_post_RSKIP428 ); testChangePowpeg( - FederationType.p2shErp, + FederationType.P2SH_ERP, getMainnetPowpegKeys(), originalPowpegAddress, utxos, - FederationType.p2shErp, + FederationType.P2SH_ERP, newPowPegKeys, newPowPegAddress, bridgeMainnetConstants, @@ -1763,9 +1765,9 @@ void test_change_powpeg_from_p2shErpFederation_with_mainnet_powpeg_post_RSKIP428 } private enum FederationType { - nonStandardErp, - p2shErp, - standardMultisig + NON_STANDARD_ERP, + P2SH_ERP, + STANDARD_MULTISIG } private static Script getFederationDefaultRedeemScript(Federation federation) { diff --git a/rskj-core/src/test/java/co/rsk/peg/federation/StandardMultiSigFederationBuilder.java b/rskj-core/src/test/java/co/rsk/peg/federation/StandardMultiSigFederationBuilder.java index c7bd8ca7a01..fbd0a379a7c 100644 --- a/rskj-core/src/test/java/co/rsk/peg/federation/StandardMultiSigFederationBuilder.java +++ b/rskj-core/src/test/java/co/rsk/peg/federation/StandardMultiSigFederationBuilder.java @@ -3,13 +3,12 @@ import co.rsk.bitcoinj.core.BtcECKey; import co.rsk.bitcoinj.core.NetworkParameters; import co.rsk.peg.bitcoin.BitcoinTestUtils; -import org.ethereum.crypto.ECKey; - import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; +import org.ethereum.crypto.ECKey; public class StandardMultiSigFederationBuilder { private List membersBtcPublicKeys; @@ -19,10 +18,18 @@ public class StandardMultiSigFederationBuilder { private long creationBlockNumber; private NetworkParameters networkParameters; - public StandardMultiSigFederationBuilder() { - this.membersBtcPublicKeys = BitcoinTestUtils.getBtcEcKeysFromSeeds( - new String[]{"member01", "member02", "member03", "member04", "member05", "member06", "member07", "member08", "member09"}, true - ); + private StandardMultiSigFederationBuilder() { + this.membersBtcPublicKeys = BitcoinTestUtils.getBtcEcKeysFromSeeds(new String[]{ + "member01", + "member02", + "member03", + "member04", + "member05", + "member06", + "member07", + "member08", + "member09" + }, true); this.membersRskPublicKeys = new ArrayList<>(); this.membersMstPublicKeys = new ArrayList<>(); this.creationTime = Instant.ofEpochMilli(10L); @@ -30,6 +37,10 @@ public StandardMultiSigFederationBuilder() { this.networkParameters = NetworkParameters.fromID(NetworkParameters.ID_MAINNET); } + public static StandardMultiSigFederationBuilder builder() { + return new StandardMultiSigFederationBuilder(); + } + public StandardMultiSigFederationBuilder withMembersBtcPublicKeys(List membersPublicKeys) { this.membersBtcPublicKeys = membersPublicKeys; return this; diff --git a/rskj-core/src/test/java/co/rsk/peg/utils/BridgeEventLoggerImplTest.java b/rskj-core/src/test/java/co/rsk/peg/utils/BridgeEventLoggerImplTest.java index 557d31014a0..bff03605651 100644 --- a/rskj-core/src/test/java/co/rsk/peg/utils/BridgeEventLoggerImplTest.java +++ b/rskj-core/src/test/java/co/rsk/peg/utils/BridgeEventLoggerImplTest.java @@ -17,179 +17,156 @@ */ package co.rsk.peg.utils; +import static co.rsk.peg.bitcoin.BitcoinTestUtils.coinListOf; +import static co.rsk.peg.bitcoin.BitcoinTestUtils.flatKeysAsByteArray; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import co.rsk.RskTestUtils; import co.rsk.bitcoinj.core.*; import co.rsk.bitcoinj.script.ScriptBuilder; -import co.rsk.peg.constants.BridgeMainNetConstants; -import co.rsk.peg.constants.BridgeRegTestConstants; import co.rsk.core.RskAddress; import co.rsk.crypto.Keccak256; -import co.rsk.peg.*; -import co.rsk.peg.bitcoin.BitcoinTestUtils; -import co.rsk.peg.bitcoin.InvalidOutpointValueException; -import co.rsk.peg.bitcoin.UtxoUtils; +import co.rsk.peg.BridgeEvents; +import co.rsk.peg.bitcoin.*; +import co.rsk.peg.constants.BridgeConstants; +import co.rsk.peg.constants.BridgeMainNetConstants; import co.rsk.peg.federation.*; -import co.rsk.peg.PegTestUtils; import co.rsk.peg.federation.constants.FederationConstants; import co.rsk.peg.pegin.RejectedPeginReason; -import java.util.ArrayList; -import java.util.Collections; +import java.math.BigInteger; +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.bouncycastle.util.encoders.Hex; -import org.ethereum.config.blockchain.upgrades.ActivationConfig; -import org.ethereum.config.blockchain.upgrades.ActivationConfigsForTest; -import org.ethereum.config.blockchain.upgrades.ConsensusRule; +import org.ethereum.config.blockchain.upgrades.*; import org.ethereum.core.*; import org.ethereum.core.CallTransaction.Function; import org.ethereum.crypto.ECKey; import org.ethereum.vm.LogInfo; import org.ethereum.vm.PrecompiledContracts; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.*; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; - -import java.math.BigInteger; -import java.time.Instant; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static co.rsk.peg.bitcoin.BitcoinTestUtils.coinListOf; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.junit.jupiter.params.provider.*; /** * Test class for BridgeEventLoggerImpl. * * @author martin.medina */ - class BridgeEventLoggerImplTest { - - private static final BridgeRegTestConstants bridgeRegtestConstants = new BridgeRegTestConstants(); - private static final FederationConstants federationRegtestConstants = bridgeRegtestConstants.getFederationConstants(); - private static final NetworkParameters regtestParameters = bridgeRegtestConstants.getBtcParams(); - private final ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); + private static final BridgeConstants BRIDGE_CONSTANTS = BridgeMainNetConstants.getInstance(); + private static final FederationConstants FEDERATION_CONSTANTS = BRIDGE_CONSTANTS.getFederationConstants(); + private static final NetworkParameters NETWORK_PARAMETERS = BRIDGE_CONSTANTS.getBtcParams(); + private static final BtcTransaction BTC_TRANSACTION = new BtcTransaction(NETWORK_PARAMETERS); + private static final RskAddress RSK_ADDRESS = new RskAddress("0x0000000000000000000000000000000000000000"); + private static final Keccak256 RSK_TX_HASH = RskTestUtils.createHash(1); private List eventLogs; private BridgeEventLogger eventLogger; - private BtcTransaction btcTxMock; - private BtcTransaction btcTx; private SignatureCache signatureCache; @BeforeEach void setup() { + ActivationConfig.ForBlock activations = ActivationConfigsForTest.all().forBlock(0L); + signatureCache = new BlockTxSignatureCache(new ReceivedTxSignatureCache()); eventLogs = new LinkedList<>(); - eventLogger = new BridgeEventLoggerImpl(bridgeRegtestConstants, activations, eventLogs, signatureCache); - btcTxMock = mock(BtcTransaction.class); - btcTx = new BtcTransaction(regtestParameters); + eventLogger = new BridgeEventLoggerImpl(BRIDGE_CONSTANTS, activations, eventLogs, signatureCache); } @Test void logLockBtc() { - Address senderAddress = mock(Address.class); - when(senderAddress.toString()).thenReturn("mixzLp4xx5bUsHuYUEyPpL42BzEDp8kSTv"); - - RskAddress rskAddress = mock(RskAddress.class); - when(rskAddress.toString()).thenReturn("0x00000000000000000000000000000000000000"); - - // Mock btc transaction - when(btcTxMock.getHash()).thenReturn(PegTestUtils.createHash(0)); - + Address senderAddress = Address.fromBase58(NETWORK_PARAMETERS, "1MvSMVpP6PY6XZtxenGXoFcH575JUWkzoP"); Coin amount = Coin.SATOSHI; // Act - eventLogger.logLockBtc(rskAddress, btcTxMock, senderAddress, amount); + eventLogger.logLockBtc(RSK_ADDRESS, BTC_TRANSACTION, senderAddress, amount); commonAssertLogs(eventLogs); assertTopics(2, eventLogs); - assertEvent(eventLogs, 0, BridgeEvents.LOCK_BTC.getEvent(), new Object[]{rskAddress.toString()}, new Object[]{btcTxMock.getHash().getBytes(), senderAddress.toString(), amount.getValue()}); + assertEvent( + eventLogs, + 0, + BridgeEvents.LOCK_BTC.getEvent(), + new Object[]{RSK_ADDRESS.toString()}, + new Object[]{BTC_TRANSACTION.getHash().getBytes(), senderAddress.toString(), amount.getValue()} + ); } @Test void logLockBtc_with_segwit_address() { - Address senderAddress = new Address(regtestParameters, regtestParameters.getP2SHHeader(), Hex.decode("c99a8f22127007255b4a9d8d57b0892ae2103f2d")); - - RskAddress rskAddress = mock(RskAddress.class); - when(rskAddress.toString()).thenReturn("0x00000000000000000000000000000000000000"); - - // Mock btc transaction - when(btcTxMock.getHash()).thenReturn(PegTestUtils.createHash(0)); - + Address senderAddress = new Address( + NETWORK_PARAMETERS, + NETWORK_PARAMETERS.getP2SHHeader(), + Hex.decode("c99a8f22127007255b4a9d8d57b0892ae2103f2d") + ); Coin amount = Coin.SATOSHI; // Act - eventLogger.logLockBtc(rskAddress, btcTxMock, senderAddress, amount); + eventLogger.logLockBtc(RSK_ADDRESS, BTC_TRANSACTION, senderAddress, amount); commonAssertLogs(eventLogs); assertTopics(2, eventLogs); - assertEvent(eventLogs, 0, BridgeEvents.LOCK_BTC.getEvent(), new Object[]{rskAddress.toString()}, new Object[]{btcTxMock.getHash().getBytes(), "2NBdCxoCY6wx1NHpwGWfJThHk9K2tVdNx1A", amount.getValue()}); + assertEvent( + eventLogs, + 0, + BridgeEvents.LOCK_BTC.getEvent(), + new Object[]{RSK_ADDRESS.toString()}, + new Object[]{BTC_TRANSACTION.getHash().getBytes(), "3L4zu4GWVVSfAWCPbP3RqkJUvxpiiQebPX", amount.getValue()} + ); } @Test void logPeginBtc() { - // Setup event logger - List eventLogs = new LinkedList<>(); - BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(null, activations, eventLogs, signatureCache); - - RskAddress rskAddress = mock(RskAddress.class); - when(rskAddress.toString()).thenReturn("0x00000000000000000000000000000000000000"); - - // Mock btc transaction - BtcTransaction mockedTx = mock(BtcTransaction.class); - when(mockedTx.getHash()).thenReturn(PegTestUtils.createHash(0)); - Coin amount = Coin.SATOSHI; int protocolVersion = 1; // Act - eventLogger.logPeginBtc(rskAddress, mockedTx, amount, protocolVersion); + eventLogger.logPeginBtc(RSK_ADDRESS, BTC_TRANSACTION, amount, protocolVersion); // Assert log size - Assertions.assertEquals(1, eventLogs.size()); + assertEquals(1, eventLogs.size()); LogInfo logResult = eventLogs.get(0); CallTransaction.Function event = BridgeEvents.PEGIN_BTC.getEvent(); // Assert address that made the log - Assertions.assertEquals(PrecompiledContracts.BRIDGE_ADDR, new RskAddress(logResult.getAddress())); + assertEquals(PrecompiledContracts.BRIDGE_ADDR, new RskAddress(logResult.getAddress())); // Assert log topics - Assertions.assertEquals(3, logResult.getTopics().size()); - byte[][] topics = event.encodeEventTopics(rskAddress.toString(), mockedTx.getHash().getBytes()); + assertEquals(3, logResult.getTopics().size()); + byte[][] topics = event.encodeEventTopics(RSK_ADDRESS.toString(), BTC_TRANSACTION.getHash().getBytes()); for (int i=0; i logAddSignatureArgProvider() { @@ -200,8 +177,8 @@ private static Stream logAddSignatureArgProvider() { ECKey rskKey = ECKey.fromPrivate(Hex.decode("000000000000000000000000000000000000000000000000000000000000015f")); // 351 ECKey mstKey = ECKey.fromPrivate(Hex.decode("0000000000000000000000000000000000000000000000000000000000000160")); // 352 - String addressDerivedFromBtcKey = "dbc29273d4de3d5645e308c7e629d28d4499b3d3"; - String addressDerivedFromRskKey = "74891a05ad4d7ec87c1cffe9bd00bb4e1382b586"; + RskAddress addressDerivedFromBtcKey = new RskAddress(ECKey.fromPrivate(btcKey.getPrivKeyBytes()).getAddress()); + RskAddress addressDerivedFromRskKey = new RskAddress(rskKey.getAddress()); FederationMember singleKeyFedMember = new FederationMember( btcKey, @@ -225,30 +202,25 @@ private static Stream logAddSignatureArgProvider() { @ParameterizedTest() @MethodSource("logAddSignatureArgProvider") - void logAddSignature(ActivationConfig.ForBlock activations, FederationMember federationMember, String expectedRskAddress) { + void logAddSignature(ActivationConfig.ForBlock activations, FederationMember federationMember, RskAddress expectedRskAddress) { // Arrange - BridgeMainNetConstants bridgeMainNetConstants = BridgeMainNetConstants.getInstance(); - BlockTxSignatureCache signatureCache = new BlockTxSignatureCache(new ReceivedTxSignatureCache()); - LinkedList eventLogs = new LinkedList<>(); - BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(bridgeMainNetConstants, activations, eventLogs, signatureCache); - + BridgeEventLogger bridgeEventLogger = new BridgeEventLoggerImpl( + BRIDGE_CONSTANTS, + activations, + eventLogs, + signatureCache + ); BtcECKey federatorBtcPubKey = federationMember.getBtcPublicKey(); - Keccak256 rskTxHash = PegTestUtils.createHash3(1); - - BtcTransaction btcTxMock = mock(BtcTransaction.class); - when(btcTxMock.getHash()).thenReturn(BitcoinTestUtils.createHash(1)); - when(btcTxMock.getHashAsString()).thenReturn(rskTxHash.toHexString()); - // Act - eventLogger.logAddSignature(federationMember, btcTxMock, rskTxHash.getBytes()); + bridgeEventLogger.logAddSignature(federationMember, BTC_TRANSACTION, RSK_TX_HASH.getBytes()); // Assert commonAssertLogs(eventLogs); assertTopics(3, eventLogs); CallTransaction.Function bridgeEvent = BridgeEvents.ADD_SIGNATURE.getEvent(); - Object[] eventTopics = new Object[]{rskTxHash.getBytes(), expectedRskAddress}; + Object[] eventTopics = new Object[]{RSK_TX_HASH.getBytes(), expectedRskAddress.toString()}; Object[] eventParams = new Object[]{federatorBtcPubKey.getPubKey()}; assertEvent(eventLogs, 0, bridgeEvent, eventTopics, eventParams); @@ -256,22 +228,34 @@ void logAddSignature(ActivationConfig.ForBlock activations, FederationMember fed @Test void logReleaseBtc() { - // Setup Btc transaction - Keccak256 rskTxHash = PegTestUtils.createHash3(1); - // Act - eventLogger.logReleaseBtc(btcTx, rskTxHash.getBytes()); + eventLogger.logReleaseBtc(BTC_TRANSACTION, RSK_TX_HASH.getBytes()); commonAssertLogs(eventLogs); assertTopics(2, eventLogs); - assertEvent(eventLogs, 0, BridgeEvents.RELEASE_BTC.getEvent(), new Object[]{rskTxHash.getBytes()}, new Object[]{btcTx.bitcoinSerialize()}); + assertEvent( + eventLogs, + 0, + BridgeEvents.RELEASE_BTC.getEvent(), + new Object[]{RSK_TX_HASH.getBytes()}, + new Object[]{BTC_TRANSACTION.bitcoinSerialize()} + ); } @ParameterizedTest @ValueSource(booleans = {false, true}) void logCommitFederation(boolean isRSKIP383Active) { - when(activations.isActive(ConsensusRule.RSKIP383)).thenReturn(isRSKIP383Active); + ActivationConfig.ForBlock hopActivations = ActivationConfigsForTest.hop400().forBlock(0); + ActivationConfig.ForBlock allActivations = ActivationConfigsForTest.all().forBlock(0L); + if (!isRSKIP383Active) { + eventLogger = new BridgeEventLoggerImpl(BRIDGE_CONSTANTS, hopActivations, eventLogs, signatureCache); + } + + long federationActivationAgePreRskip383 = FEDERATION_CONSTANTS.getFederationActivationAge(hopActivations); + long federationActivationAgePostRskip383 = FEDERATION_CONSTANTS.getFederationActivationAge(allActivations); + // Setup parameters for test method call + Instant creationTime = Instant.ofEpochMilli(15005L); Block executionBlock = mock(Block.class); when(executionBlock.getTimestamp()).thenReturn(15005L); when(executionBlock.getNumber()).thenReturn(15L); @@ -284,8 +268,13 @@ void logCommitFederation(boolean isRSKIP383Active) { ); List oldFederationMembers = FederationTestUtils.getFederationMembersWithBtcKeys(oldFederationKeys); - NetworkParameters btcParams = NetworkParameters.fromID(NetworkParameters.ID_REGTEST); - FederationArgs oldFedArgs = new FederationArgs(oldFederationMembers, Instant.ofEpochMilli(15005L), 15L, btcParams); + NetworkParameters btcParams = BRIDGE_CONSTANTS.getBtcParams(); + FederationArgs oldFedArgs = new FederationArgs( + oldFederationMembers, + creationTime, + 15L, + btcParams + ); Federation oldFederation = FederationFactory.buildStandardMultiSigFederation(oldFedArgs); @@ -295,22 +284,28 @@ void logCommitFederation(boolean isRSKIP383Active) { BtcECKey.fromPublicOnly(Hex.decode("026192d8ab41bd402eb0431457f6756a3f3ce15c955c534d2b87f1e0372d8ba338")) ); List newFederationMembers = FederationTestUtils.getFederationMembersWithBtcKeys(newFederationKeys); - FederationArgs newFedArgs = new FederationArgs(newFederationMembers, Instant.ofEpochMilli(15005L), 15L, btcParams); + FederationArgs newFedArgs = new FederationArgs( + newFederationMembers, + creationTime, + 15L, + btcParams + ); Federation newFederation = FederationFactory.buildStandardMultiSigFederation(newFedArgs); // Act eventLogger.logCommitFederation(executionBlock, oldFederation, newFederation); - commonAssertLogs(eventLogs); - assertTopics(1, eventLogs); + // Assert log data byte[] oldFederationFlatPubKeys = flatKeysAsByteArray(oldFederation.getBtcPublicKeys()); String oldFederationBtcAddress = oldFederation.getAddress().toBase58(); byte[] newFederationFlatPubKeys = flatKeysAsByteArray(newFederation.getBtcPublicKeys()); String newFederationBtcAddress = newFederation.getAddress().toBase58(); - long newFedActivationBlockNumber = executionBlock.getNumber() + federationRegtestConstants.getFederationActivationAge(activations); + long newFedActivationBlockNumber = isRSKIP383Active ? + executionBlock.getNumber() + federationActivationAgePostRskip383 : + executionBlock.getNumber() + federationActivationAgePreRskip383; Object[] data = new Object[]{ oldFederationFlatPubKeys, @@ -332,191 +327,220 @@ void logCommitFederation(boolean isRSKIP383Active) { // assert fed activation has different values before and after RSKIP383 respectively if (isRSKIP383Active){ - ActivationConfig.ForBlock activationsForLegacyFedActivationAge = mock(ActivationConfig.ForBlock.class); - when(activationsForLegacyFedActivationAge.isActive(ConsensusRule.RSKIP383)).thenReturn(false); - - long legacyFedActivationBlockNumber = executionBlock.getNumber() + federationRegtestConstants.getFederationActivationAge(activationsForLegacyFedActivationAge); - + long legacyFedActivationBlockNumber = executionBlock.getNumber() + federationActivationAgePreRskip383; assertNotEquals(loggedFedActivationBlockNumber, legacyFedActivationBlockNumber); } else { - ActivationConfig.ForBlock activationsForDefaultFedActivationAge = mock(ActivationConfig.ForBlock.class); - when(activationsForDefaultFedActivationAge.isActive(ConsensusRule.RSKIP383)).thenReturn(true); - - long defaultFedActivationBlockNumber = executionBlock.getNumber() + federationRegtestConstants.getFederationActivationAge(activationsForDefaultFedActivationAge); + long defaultFedActivationBlockNumber = executionBlock.getNumber() + federationActivationAgePostRskip383; assertNotEquals(loggedFedActivationBlockNumber, defaultFedActivationBlockNumber); } } @Test void logReleaseBtcRequested() { - Keccak256 rskTxHash = PegTestUtils.createHash3(0); Coin amount = Coin.SATOSHI; - eventLogger.logReleaseBtcRequested(rskTxHash.getBytes(), btcTx, amount); + eventLogger.logReleaseBtcRequested(RSK_TX_HASH.getBytes(), BTC_TRANSACTION, amount); commonAssertLogs(eventLogs); - assertTopics(3, eventLogs); - assertEvent(eventLogs, 0, BridgeEvents.RELEASE_REQUESTED.getEvent(), new Object[]{rskTxHash.getBytes(), btcTx.getHash().getBytes()}, new Object[]{amount.getValue()}); + assertEvent( + eventLogs, + 0, + BridgeEvents.RELEASE_REQUESTED.getEvent(), + new Object[]{RSK_TX_HASH.getBytes(), BTC_TRANSACTION.getHash().getBytes()}, + new Object[]{amount.getValue()} + ); } @Test void logRejectedPegin() { - // Setup event logger - List eventLogs = new LinkedList<>(); - - BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(null, activations, eventLogs, signatureCache); - - BtcTransaction btcTx = new BtcTransaction(regtestParameters); + eventLogger.logRejectedPegin(BTC_TRANSACTION, RejectedPeginReason.PEGIN_CAP_SURPASSED); - eventLogger.logRejectedPegin(btcTx, RejectedPeginReason.PEGIN_CAP_SURPASSED); - - Assertions.assertEquals(1, eventLogs.size()); + assertEquals(1, eventLogs.size()); LogInfo entry = eventLogs.get(0); - Assertions.assertEquals(PrecompiledContracts.BRIDGE_ADDR, new RskAddress(entry.getAddress())); + assertEquals(PrecompiledContracts.BRIDGE_ADDR, new RskAddress(entry.getAddress())); // Assert address that made the log LogInfo result = eventLogs.get(0); - Assertions.assertArrayEquals(PrecompiledContracts.BRIDGE_ADDR.getBytes(), result.getAddress()); + assertArrayEquals(PrecompiledContracts.BRIDGE_ADDR.getBytes(), result.getAddress()); // Assert log topics - Assertions.assertEquals(2, result.getTopics().size()); + assertEquals(2, result.getTopics().size()); CallTransaction.Function event = BridgeEvents.REJECTED_PEGIN.getEvent(); - byte[][] topics = event.encodeEventTopics(btcTx.getHash().getBytes()); + byte[][] topics = event.encodeEventTopics(BTC_TRANSACTION.getHash().getBytes()); for (int i=0; i eventLogs = new LinkedList<>(); - - BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(null, activations, eventLogs, signatureCache); + eventLogger.logUnrefundablePegin(BTC_TRANSACTION, UnrefundablePeginReason.LEGACY_PEGIN_UNDETERMINED_SENDER); - BtcTransaction btcTx = new BtcTransaction(regtestParameters); - - eventLogger.logUnrefundablePegin(btcTx, UnrefundablePeginReason.LEGACY_PEGIN_UNDETERMINED_SENDER); - - Assertions.assertEquals(1, eventLogs.size()); + assertEquals(1, eventLogs.size()); LogInfo entry = eventLogs.get(0); - Assertions.assertEquals(PrecompiledContracts.BRIDGE_ADDR, new RskAddress(entry.getAddress())); + assertEquals(PrecompiledContracts.BRIDGE_ADDR, new RskAddress(entry.getAddress())); // Assert address that made the log LogInfo result = eventLogs.get(0); - Assertions.assertArrayEquals(PrecompiledContracts.BRIDGE_ADDR.getBytes(), result.getAddress()); + assertArrayEquals(PrecompiledContracts.BRIDGE_ADDR.getBytes(), result.getAddress()); // Assert log topics - Assertions.assertEquals(2, result.getTopics().size()); + assertEquals(2, result.getTopics().size()); CallTransaction.Function event = BridgeEvents.UNREFUNDABLE_PEGIN.getEvent(); - byte[][] topics = event.encodeEventTopics(btcTx.getHash().getBytes()); + byte[][] topics = event.encodeEventTopics(BTC_TRANSACTION.getHash().getBytes()); for (int i=0; i rskTxHashes = Arrays.asList(PegTestUtils.createHash3(0), PegTestUtils.createHash3(1), PegTestUtils.createHash3(2)); + List rskTxHashes = Arrays.asList( + RskTestUtils.createHash(0), + RskTestUtils.createHash(1), + RskTestUtils.createHash(2) + ); - eventLogger.logBatchPegoutCreated(btcTx.getHash(), rskTxHashes); + eventLogger.logBatchPegoutCreated(BTC_TRANSACTION.getHash(), rskTxHashes); commonAssertLogs(eventLogs); - assertTopics(2, eventLogs); - - assertEvent(eventLogs, 0, BridgeEvents.BATCH_PEGOUT_CREATED.getEvent(), new Object[]{btcTx.getHash().getBytes()}, new Object[]{serializeRskTxHashes(rskTxHashes)}); + assertEvent( + eventLogs, + 0, + BridgeEvents.BATCH_PEGOUT_CREATED.getEvent(), + new Object[]{BTC_TRANSACTION.getHash().getBytes()}, + new Object[]{serializeRskTxHashes(rskTxHashes)} + ); } @Test void logBatchPegoutCreatedWithWitness() { - List rskTxHashes = Arrays.asList(PegTestUtils.createHash3(0), PegTestUtils.createHash3(1), PegTestUtils.createHash3(2)); + List rskTxHashes = Arrays.asList( + RskTestUtils.createHash(0), + RskTestUtils.createHash(1), + RskTestUtils.createHash(2) + ); TransactionWitness txWitness = new TransactionWitness(1); - btcTx.addInput( - Sha256Hash.ZERO_HASH, - 0, ScriptBuilder.createInputScript(null, new BtcECKey()) + BTC_TRANSACTION.addInput( + Sha256Hash.ZERO_HASH, + 0, + ScriptBuilder.createInputScript(null, new BtcECKey()) ); txWitness.setPush(0, new byte[]{ 0x1 }); - btcTx.setWitness(0, txWitness); - eventLogger.logBatchPegoutCreated(btcTx.getHash(true), rskTxHashes); + BTC_TRANSACTION.setWitness(0, txWitness); + eventLogger.logBatchPegoutCreated(BTC_TRANSACTION.getHash(true), rskTxHashes); commonAssertLogs(eventLogs); - assertTopics(2, eventLogs); - - assertEvent(eventLogs, 0, BridgeEvents.BATCH_PEGOUT_CREATED.getEvent(), new Object[]{btcTx.getHash(true).getBytes()}, new Object[]{serializeRskTxHashes(rskTxHashes)}); - + assertEvent( + eventLogs, + 0, + BridgeEvents.BATCH_PEGOUT_CREATED.getEvent(), + new Object[]{BTC_TRANSACTION.getHash(true).getBytes()}, + new Object[]{serializeRskTxHashes(rskTxHashes)} + ); } @Test void logPegoutConfirmed() { long pegoutCreationRskBlockNumber = 50; - eventLogger.logPegoutConfirmed(btcTx.getHash(), pegoutCreationRskBlockNumber); + eventLogger.logPegoutConfirmed(BTC_TRANSACTION.getHash(), pegoutCreationRskBlockNumber); commonAssertLogs(eventLogs); - assertTopics(2, eventLogs); - - assertEvent(eventLogs, 0, BridgeEvents.PEGOUT_CONFIRMED.getEvent(), new Object[]{btcTx.getHash().getBytes()}, new Object[]{pegoutCreationRskBlockNumber}); + assertEvent( + eventLogs, + 0, + BridgeEvents.PEGOUT_CONFIRMED.getEvent(), + new Object[]{BTC_TRANSACTION.getHash().getBytes()}, + new Object[]{pegoutCreationRskBlockNumber} + ); } private static Stream logPegoutTransactionCreatedValidArgProvider() { @@ -567,7 +591,6 @@ void logPegoutTransactionCreated_invalidBtcTxHashOrOutpointValues_shouldFail(Sha /********************************** * ------- UTILS ------- * *********************************/ - private static void assertEvent(List logs, int index, CallTransaction.Function event, Object[] topics, Object[] params) { final LogInfo log = logs.get(index); assertEquals(LogInfo.byteArrayToList(event.encodeEventTopics(topics)), log.getTopics()); @@ -587,22 +610,6 @@ private void commonAssertLogs(List logs) { assertArrayEquals(PrecompiledContracts.BRIDGE_ADDR.getBytes(), entry.getAddress()); } - private byte[] flatKeysAsByteArray(List keys) { - List pubKeys = keys.stream() - .map(BtcECKey::getPubKey) - .collect(Collectors.toList()); - int pubKeysLength = pubKeys.stream().mapToInt(key -> key.length).sum(); - - byte[] flatPubKeys = new byte[pubKeysLength]; - int copyPos = 0; - for (byte[] key : pubKeys) { - System.arraycopy(key, 0, flatPubKeys, copyPos, key.length); - copyPos += key.length; - } - - return flatPubKeys; - } - private byte[] serializeRskTxHashes(List rskTxHashes) { List rskTxHashesList = rskTxHashes.stream() .map(Keccak256::getBytes) @@ -611,9 +618,15 @@ private byte[] serializeRskTxHashes(List rskTxHashes) { byte[] serializedRskTxHashes = new byte[rskTxHashesLength]; int copyPos = 0; - for (byte[] rskTxHash : rskTxHashesList) { - System.arraycopy(rskTxHash, 0, serializedRskTxHashes, copyPos, rskTxHash.length); - copyPos += rskTxHash.length; + for (byte[] serializedRskTxHash : rskTxHashesList) { + System.arraycopy( + serializedRskTxHash, + 0, + serializedRskTxHashes, + copyPos, + serializedRskTxHash.length + ); + copyPos += serializedRskTxHash.length; } return serializedRskTxHashes; diff --git a/rskj-core/src/test/java/co/rsk/test/builders/BridgeBuilder.java b/rskj-core/src/test/java/co/rsk/test/builders/BridgeBuilder.java index a11b6f05284..23dc7397192 100644 --- a/rskj-core/src/test/java/co/rsk/test/builders/BridgeBuilder.java +++ b/rskj-core/src/test/java/co/rsk/test/builders/BridgeBuilder.java @@ -37,7 +37,7 @@ public class BridgeBuilder { public BridgeBuilder() { contractAddress = PrecompiledContracts.BRIDGE_ADDR; constants = Constants.mainnet(); - bridgeSupport = new BridgeSupportBuilder().build(); + bridgeSupport = BridgeSupportBuilder.builder().build(); signatureCache = new BlockTxSignatureCache(new ReceivedTxSignatureCache()); transaction = mock(Transaction.class); diff --git a/rskj-core/src/test/java/co/rsk/test/builders/BridgeSupportBuilder.java b/rskj-core/src/test/java/co/rsk/test/builders/BridgeSupportBuilder.java index 913d4ef13f5..33359283180 100644 --- a/rskj-core/src/test/java/co/rsk/test/builders/BridgeSupportBuilder.java +++ b/rskj-core/src/test/java/co/rsk/test/builders/BridgeSupportBuilder.java @@ -33,7 +33,7 @@ public class BridgeSupportBuilder { private ActivationConfig.ForBlock activations; private SignatureCache signatureCache; - public BridgeSupportBuilder() { + private BridgeSupportBuilder() { this.bridgeConstants = mock(BridgeConstants.class); this.provider = mock(BridgeStorageProvider.class); this.eventLogger = mock(BridgeEventLogger.class); @@ -50,6 +50,10 @@ public BridgeSupportBuilder() { this.signatureCache = mock(BlockTxSignatureCache.class); } + public static BridgeSupportBuilder builder() { + return new BridgeSupportBuilder(); + } + public BridgeSupportBuilder withBridgeConstants(BridgeConstants bridgeConstants) { this.bridgeConstants = bridgeConstants; return this; diff --git a/rskj-core/src/test/java/co/rsk/test/builders/FederationSupportBuilder.java b/rskj-core/src/test/java/co/rsk/test/builders/FederationSupportBuilder.java index 2da807cef1e..cb0de651828 100644 --- a/rskj-core/src/test/java/co/rsk/test/builders/FederationSupportBuilder.java +++ b/rskj-core/src/test/java/co/rsk/test/builders/FederationSupportBuilder.java @@ -15,13 +15,17 @@ public class FederationSupportBuilder { private Block rskExecutionBlock; private ActivationConfig.ForBlock activations; - public FederationSupportBuilder() { + private FederationSupportBuilder() { this.federationConstants = mock(FederationConstants.class); this.federationStorageProvider = mock(FederationStorageProvider.class); this.rskExecutionBlock = mock(Block.class); this.activations = mock(ActivationConfig.ForBlock.class); } + public static FederationSupportBuilder builder() { + return new FederationSupportBuilder(); + } + public FederationSupportBuilder withFederationConstants(FederationConstants federationConstants) { this.federationConstants = federationConstants; return this;