diff --git a/src/main/java/co/rsk/federate/BridgeTransactionSender.java b/src/main/java/co/rsk/federate/BridgeTransactionSender.java index c346654e7..e1830510a 100644 --- a/src/main/java/co/rsk/federate/BridgeTransactionSender.java +++ b/src/main/java/co/rsk/federate/BridgeTransactionSender.java @@ -11,7 +11,7 @@ import co.rsk.federate.signing.hsm.message.SignerMessageV1; import co.rsk.federate.signing.hsm.SignerException; import org.ethereum.core.*; -import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import org.ethereum.facade.Ethereum; import org.ethereum.vm.PrecompiledContracts; import org.ethereum.vm.program.ProgramResult; @@ -111,7 +111,7 @@ public synchronized void sendRskTx(RskAddress federatorAddress, functionArgs); try { SignerMessageV1 messageToSign = new SignerMessageV1(rskTx.getRawHash().getBytes()); - ECKey.ECDSASignature txSignature = signer.sign(RSK_KEY_ID.getKeyId(), messageToSign); + ECDSASignature txSignature = signer.sign(RSK_KEY_ID.getKeyId(), messageToSign); rskTx.setSignature(txSignature); LOGGER.debug("[tx={} | nonce={} | method={}] Submit to Bridge", rskTx.getHash(), nonce, function.name); ethereum.submitTransaction(rskTx); diff --git a/src/main/java/co/rsk/federate/FedNodeContext.java b/src/main/java/co/rsk/federate/FedNodeContext.java index d9f405295..7e38da2e9 100644 --- a/src/main/java/co/rsk/federate/FedNodeContext.java +++ b/src/main/java/co/rsk/federate/FedNodeContext.java @@ -21,7 +21,7 @@ import co.rsk.RskContext; import co.rsk.config.ConfigLoader; import co.rsk.config.RskSystemProperties; -import co.rsk.federate.btcreleaseclient.BtcReleaseClient; +import co.rsk.federate.btcreleaseclient.BtcPegoutClient; import co.rsk.federate.config.FedNodeSystemProperties; import co.rsk.federate.log.FederateLogger; import co.rsk.federate.log.RskLogMonitor; @@ -56,7 +56,7 @@ public NodeRunner buildNodeRunner() { return new FedNodeRunner( getBtcToRskClientActive(), getBtcToRskClientRetiring(), - new BtcReleaseClient( + new BtcPegoutClient( getRsk(), getFederatorSupport(), getFedNodeSystemProperties(), diff --git a/src/main/java/co/rsk/federate/FedNodeRunner.java b/src/main/java/co/rsk/federate/FedNodeRunner.java index 529d037b7..4d816ecc2 100644 --- a/src/main/java/co/rsk/federate/FedNodeRunner.java +++ b/src/main/java/co/rsk/federate/FedNodeRunner.java @@ -24,9 +24,9 @@ import co.rsk.federate.bitcoin.BitcoinWrapper; import co.rsk.federate.bitcoin.BitcoinWrapperImpl; import co.rsk.federate.bitcoin.Kit; -import co.rsk.federate.btcreleaseclient.BtcReleaseClient; -import co.rsk.federate.btcreleaseclient.BtcReleaseClientStorageAccessor; -import co.rsk.federate.btcreleaseclient.BtcReleaseClientStorageSynchronizer; +import co.rsk.federate.btcreleaseclient.BtcPegoutClient; +import co.rsk.federate.btcreleaseclient.BtcPegoutClientStorageAccessor; +import co.rsk.federate.btcreleaseclient.BtcPegoutClientStorageSynchronizer; import co.rsk.federate.config.FedNodeSystemProperties; import co.rsk.federate.config.PowHSMBookkeepingConfig; import co.rsk.federate.config.SignerConfig; @@ -43,10 +43,10 @@ import co.rsk.federate.signing.hsm.client.HSMBookkeepingClient; import co.rsk.federate.signing.hsm.client.HSMClientProtocol; import co.rsk.federate.signing.hsm.client.HSMClientProtocolFactory; -import co.rsk.federate.signing.hsm.message.ReleaseCreationInformationGetter; +import co.rsk.federate.signing.hsm.message.PegoutCreationInformationGetter; import co.rsk.federate.signing.hsm.message.SignerMessageBuilderFactory; import co.rsk.federate.signing.hsm.requirements.AncestorBlockUpdater; -import co.rsk.federate.signing.hsm.requirements.ReleaseRequirementsEnforcer; +import co.rsk.federate.signing.hsm.requirements.PegoutSigningRequirementsEnforcer; import co.rsk.peg.federation.Federation; import co.rsk.peg.federation.FederationMember; import co.rsk.peg.btcLockSender.BtcLockSenderProvider; @@ -75,7 +75,7 @@ public class FedNodeRunner implements NodeRunner { private static final Logger LOGGER = LoggerFactory.getLogger(FedNodeRunner.class); private final BtcToRskClient btcToRskClientActive; private final BtcToRskClient btcToRskClientRetiring; - private final BtcReleaseClient btcReleaseClient; + private final BtcPegoutClient btcPegoutClient; private final FederatorSupport federatorSupport; private final FederationWatcher federationWatcher; private final FederateLogger federateLogger; @@ -97,7 +97,7 @@ public class FedNodeRunner implements NodeRunner { public FedNodeRunner( BtcToRskClient btcToRskClientActive, BtcToRskClient btcToRskClientRetiring, - BtcReleaseClient btcReleaseClient, + BtcPegoutClient btcPegoutClient, FederationWatcher federationWatcher, FederatorSupport federatorSupport, FederateLogger federateLogger, @@ -110,7 +110,7 @@ public FedNodeRunner( ) { this.btcToRskClientActive = btcToRskClientActive; this.btcToRskClientRetiring = btcToRskClientRetiring; - this.btcReleaseClient = btcReleaseClient; + this.btcPegoutClient = btcPegoutClient; this.federationWatcher = federationWatcher; this.federatorSupport = federatorSupport; this.federateLogger = federateLogger; @@ -313,30 +313,30 @@ private void startFederate() throws Exception { hsmBookkeepingService.start(); } federateLogger.log(); - BtcReleaseClientStorageAccessor btcReleaseClientStorageAccessor = new BtcReleaseClientStorageAccessor(config); - btcReleaseClient.setup( + BtcPegoutClientStorageAccessor btcPegoutClientStorageAccessor = new BtcPegoutClientStorageAccessor(config); + btcPegoutClient.setup( signer, config.getActivationConfig(), new SignerMessageBuilderFactory( fedNodeContext.getReceiptStore() ), - new ReleaseCreationInformationGetter( + new PegoutCreationInformationGetter( fedNodeContext.getReceiptStore(), fedNodeContext.getBlockStore() ), - new ReleaseRequirementsEnforcer( + new PegoutSigningRequirementsEnforcer( new AncestorBlockUpdater( fedNodeContext.getBlockStore(), hsmBookkeepingClient ) ), - btcReleaseClientStorageAccessor, - new BtcReleaseClientStorageSynchronizer( + btcPegoutClientStorageAccessor, + new BtcPegoutClientStorageSynchronizer( fedNodeContext.getBlockStore(), fedNodeContext.getReceiptStore(), fedNodeContext.getNodeBlockProcessor(), - btcReleaseClientStorageAccessor, - config.getBtcReleaseClientInitializationMaxDepth() + btcPegoutClientStorageAccessor, + config.getBtcPegoutClientInitializationMaxDepth() ) ); federationWatcher.setup(federationProvider); @@ -384,14 +384,14 @@ private void shutdown() { // TODO: This this method (and this whole class) private void triggerClientChange(BtcToRskClient client, Optional federation) { client.stop(); - federation.ifPresent(btcReleaseClient::stop); + federation.ifPresent(btcPegoutClient::stop); // Only start if this federator is part of the new federation if (federation.isPresent() && federation.get().isMember(this.member)) { String federationAddress = federation.get().getAddress().toString(); - LOGGER.debug("[triggerClientChange] Starting lock and release clients since I belong to federation {}", federationAddress); + LOGGER.debug("[triggerClientChange] Starting pegin and pegout clients since I belong to federation {}", federationAddress); LOGGER.info("[triggerClientChange] Joined to {} federation", federationAddress); client.start(federation.get()); - btcReleaseClient.start(federation.get()); + btcPegoutClient.start(federation.get()); } else { LOGGER.warn("[triggerClientChange] This federator node is not part of the new federation. Check your configuration for signers BTC, RSK and MST keys"); } diff --git a/src/main/java/co/rsk/federate/bitcoin/BitcoinWrapperImpl.java b/src/main/java/co/rsk/federate/bitcoin/BitcoinWrapperImpl.java index e233694a0..480722d34 100644 --- a/src/main/java/co/rsk/federate/bitcoin/BitcoinWrapperImpl.java +++ b/src/main/java/co/rsk/federate/bitcoin/BitcoinWrapperImpl.java @@ -349,7 +349,7 @@ protected void coinsReceivedOrSent(Transaction tx) { listener.onTransaction(tx); } if (PegUtilsLegacy.isPegOutTx(btcTx, Collections.singletonList(watchedFederation), federatorSupport.getConfigForBestBlock())) { - LOGGER.debug("[coinsReceivedOrSent] [btctx:{}] is a release", tx.getWTxId()); + LOGGER.debug("[coinsReceivedOrSent] [btctx:{}] is a pegout", tx.getWTxId()); listener.onTransaction(tx); } } diff --git a/src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClient.java b/src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClient.java similarity index 61% rename from src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClient.java rename to src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClient.java index ae82ab092..ce592a8e5 100644 --- a/src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClient.java +++ b/src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClient.java @@ -18,15 +18,15 @@ import co.rsk.federate.signing.FederatorAlreadySignedException; import co.rsk.federate.signing.hsm.HSMClientException; import co.rsk.federate.signing.hsm.SignerException; -import co.rsk.federate.signing.hsm.message.HSMReleaseCreationInformationException; -import co.rsk.federate.signing.hsm.message.ReleaseCreationInformation; -import co.rsk.federate.signing.hsm.message.ReleaseCreationInformationGetter; +import co.rsk.federate.signing.hsm.message.HSMPegoutCreationInformationException; +import co.rsk.federate.signing.hsm.message.PegoutCreationInformation; +import co.rsk.federate.signing.hsm.message.PegoutCreationInformationGetter; import co.rsk.federate.signing.hsm.message.SignerMessage; import co.rsk.federate.signing.hsm.message.SignerMessageBuilder; import co.rsk.federate.signing.hsm.message.SignerMessageBuilderException; import co.rsk.federate.signing.hsm.message.SignerMessageBuilderFactory; -import co.rsk.federate.signing.hsm.requirements.ReleaseRequirementsEnforcer; -import co.rsk.federate.signing.hsm.requirements.ReleaseRequirementsEnforcerException; +import co.rsk.federate.signing.hsm.requirements.PegoutSigningRequirementsEnforcer; +import co.rsk.federate.signing.hsm.requirements.PegoutSigningRequirementsEnforcerException; import co.rsk.net.NodeBlockProcessor; import co.rsk.panic.PanicProcessor; import co.rsk.peg.Bridge; @@ -56,7 +56,7 @@ import org.ethereum.config.blockchain.upgrades.ActivationConfig; import org.ethereum.config.blockchain.upgrades.ConsensusRule; import org.ethereum.core.TransactionReceipt; -import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import org.ethereum.facade.Ethereum; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.util.RLP; @@ -70,11 +70,11 @@ import static co.rsk.federate.signing.PowPegNodeKeyId.BTC_KEY_ID; /** - * Manages signing and broadcasting release txs + * Manages signing and broadcasting pegouts * @author Oscar Guindzberg */ -public class BtcReleaseClient { - private static final Logger logger = LoggerFactory.getLogger(BtcReleaseClient.class); +public class BtcPegoutClient { + private static final Logger logger = LoggerFactory.getLogger(BtcPegoutClient.class); private static final PanicProcessor panicProcessor = new PanicProcessor(); private static final List SINGLE_RELEASE_BTC_TOPIC_RLP = Collections.singletonList(Bridge.RELEASE_BTC_TOPIC); private static final DataWord SINGLE_RELEASE_BTC_TOPIC_SOLIDITY = DataWord.valueOf(BridgeEvents.RELEASE_BTC.getEvent().encodeSignatureLong()); @@ -91,16 +91,16 @@ public class BtcReleaseClient { private final boolean isPegoutEnabled; private ECDSASigner signer; - private BtcReleaseEthereumListener blockListener; + private PegoutWaitingForSignatureEthereumListener blockListener; private SignerMessageBuilderFactory signerMessageBuilderFactory; - private ReleaseCreationInformationGetter releaseCreationInformationGetter; - private ReleaseRequirementsEnforcer releaseRequirementsEnforcer; + private PegoutCreationInformationGetter pegoutCreationInformationGetter; + private PegoutSigningRequirementsEnforcer pegoutSigningRequirementsEnforcer; - private BtcReleaseClientStorageAccessor storageAccessor; - private BtcReleaseClientStorageSynchronizer storageSynchronizer; + private BtcPegoutClientStorageAccessor storageAccessor; + private BtcPegoutClientStorageSynchronizer storageSynchronizer; - public BtcReleaseClient( + public BtcPegoutClient( Ethereum ethereum, FederatorSupport federatorSupport, FedNodeSystemProperties systemProperties, @@ -110,7 +110,7 @@ public BtcReleaseClient( this.federatorSupport = federatorSupport; this.systemProperties = systemProperties; this.observedFederations = new HashSet<>(); - this.blockListener = new BtcReleaseEthereumListener(); + this.blockListener = new PegoutWaitingForSignatureEthereumListener(); this.bridgeConstants = this.systemProperties.getNetworkConstants().getBridgeConstants(); this.isPegoutEnabled = this.systemProperties.isPegoutEnabled(); this.nodeBlockProcessor = nodeBlockProcessor; @@ -120,11 +120,11 @@ public void setup( ECDSASigner signer, ActivationConfig activationConfig, SignerMessageBuilderFactory signerMessageBuilderFactory, - ReleaseCreationInformationGetter releaseCreationInformationGetter, - ReleaseRequirementsEnforcer releaseRequirementsEnforcer, - BtcReleaseClientStorageAccessor storageAccessor, - BtcReleaseClientStorageSynchronizer storageSynchronizer - ) throws BtcReleaseClientException { + PegoutCreationInformationGetter pegoutCreationInformationGetter, + PegoutSigningRequirementsEnforcer pegoutSigningRequirementsEnforcer, + BtcPegoutClientStorageAccessor storageAccessor, + BtcPegoutClientStorageSynchronizer storageSynchronizer + ) throws BtcPegoutClientException { this.signer = signer; this.activationConfig = activationConfig; logger.debug("[setup] Signer: {}", signer.getClass()); @@ -139,14 +139,14 @@ public void setup( peerGroup.setMaxConnections(federatorSupport.getBitcoinPeerAddresses().size()); } } catch(Exception e) { - throw new BtcReleaseClientException("Error configuring peerSupport", e); + throw new BtcPegoutClientException("Error configuring peerSupport", e); } peerGroup.start(); - blockListener = new BtcReleaseEthereumListener(); + blockListener = new PegoutWaitingForSignatureEthereumListener(); this.signerMessageBuilderFactory = signerMessageBuilderFactory; - this.releaseCreationInformationGetter = releaseCreationInformationGetter; - this.releaseRequirementsEnforcer = releaseRequirementsEnforcer; + this.pegoutCreationInformationGetter = pegoutCreationInformationGetter; + this.pegoutSigningRequirementsEnforcer = pegoutSigningRequirementsEnforcer; this.storageAccessor = storageAccessor; this.storageSynchronizer = storageSynchronizer; @@ -160,7 +160,7 @@ public void start(Federation federation) { logger.debug("[start] observing Federation {}", federation.getAddress()); } if (observedFederations.size() == 1) { - // If there is just one observed Federation, it means the btcReleaseClient wasn't started + // If there is just one observed Federation, it means the btcPegoutClient wasn't started logger.debug("[start] Starting"); ethereum.addListener(this.blockListener); } @@ -172,7 +172,7 @@ public void stop(Federation federation) { logger.debug("[stop] not observing Federation {}", federation.getAddress()); } if (observedFederations.isEmpty()) { - // If there are no more observed Federations, the btcReleaseClient should stop + // If there are no more observed Federations, the btcPegoutClient should stop logger.debug("[stop] Stopping"); ethereum.removeListener(this.blockListener); } @@ -185,14 +185,14 @@ public void tearDown() { peerGroup = null; } - private class BtcReleaseEthereumListener extends EthereumListenerAdapter { + private class PegoutWaitingForSignatureEthereumListener extends EthereumListenerAdapter { @Override public void onBestBlock(org.ethereum.core.Block block, List receipts) { boolean hasBetterBlockToSync = nodeBlockProcessor.hasBetterBlockToSync(); boolean isStorageSynced = storageSynchronizer.isSynced(); if (hasBetterBlockToSync || !isStorageSynced) { logger.trace( - "[onBestBlock] Node is not ready to process releases. hasBetterBlockToSync: {} isStorageSynced: {}", + "[onBestBlock] Node is not ready to process pegouts. hasBetterBlockToSync: {} isStorageSynced: {}", hasBetterBlockToSync, isStorageSynced ); @@ -205,9 +205,9 @@ public void onBestBlock(org.ethereum.core.Block block, List storageSynchronizer.processBlock(block, receipts); // Delegate processing to our own method - logger.trace("[onBestBlock] Got {} releases", stateForFederator.getRskTxsWaitingForSignatures().entrySet().size()); + logger.trace("[onBestBlock] Got {} pegouts", stateForFederator.getRskTxsWaitingForSignatures().entrySet().size()); if (isPegoutEnabled) { - processReleases(stateForFederator.getRskTxsWaitingForSignatures().entrySet()); + processPegouts(stateForFederator.getRskTxsWaitingForSignatures().entrySet()); } } @@ -216,22 +216,22 @@ public void onBlock(org.ethereum.core.Block block, List rece if (!isPegoutEnabled || nodeBlockProcessor.hasBetterBlockToSync()) { return; } - // BTC-release events must be processed on an every-single-block basis, - // since otherwise we could be missing release transactions potentially mined + // Pegout events must be processed on an every-single-block basis, + // since otherwise we could be missing pegouts potentially mined // on what originally were side-chains and then turned into best-chains. Stream transactionLogs = receipts.stream().map(TransactionReceipt::getLogInfoList).flatMap(Collection::stream); Stream bridgeLogs = transactionLogs.filter(info -> Arrays.equals(info.getAddress(), PrecompiledContracts.BRIDGE_ADDR.getBytes())); boolean solidityFormatIsActive = activationConfig.isActive(ConsensusRule.RSKIP146, block.getNumber()); - Stream releaseBtcLogs = bridgeLogs.filter(info -> solidityFormatIsActive ? + Stream pegoutLogs = bridgeLogs.filter(info -> solidityFormatIsActive ? SINGLE_RELEASE_BTC_TOPIC_SOLIDITY.equals(info.getTopics().get(0)) : SINGLE_RELEASE_BTC_TOPIC_RLP.equals(info.getTopics())); - Stream btcTransactionsToRelease = releaseBtcLogs.map(info -> solidityFormatIsActive ? + Stream pegoutBtcTxs = pegoutLogs.map(info -> solidityFormatIsActive ? convertToBtcTxFromSolidityData(info.getData()) : convertToBtcTxFromRLPData(info.getData())); - btcTransactionsToRelease.forEach(BtcReleaseClient.this::onBtcRelease); + pegoutBtcTxs.forEach(BtcPegoutClient.this::onBroadcastingSignedPegout); } private BtcTransaction convertToBtcTxFromRLPData(byte[] dataFromBtcReleaseTopic) { @@ -246,92 +246,92 @@ private BtcTransaction convertToBtcTxFromSolidityData(byte[] dataFromBtcReleaseT } } - protected void processReleases(Set> releases) { + protected void processPegouts(Set> pegouts) { try { - logger.debug("[processReleases] Starting process with {} releases", releases.size()); + logger.debug("[processPegouts] Starting process with {} pegouts", pegouts.size()); int version = signer.getVersionForKeyId(BTC_KEY_ID.getKeyId()); - // Get release information and store it in a new list - List releasesReadyToSign = new ArrayList<>(); - for (Map.Entry release : releases) { - BtcTransaction releaseTx = release.getValue(); - tryGetReleaseInformation(version, release.getKey(), releaseTx) - .ifPresent(releasesReadyToSign::add); + // Get pegout information and store it in a new list + List pegoutsReadyToSign = new ArrayList<>(); + for (Map.Entry pegout : pegouts) { + BtcTransaction pegoutBtcTx = pegout.getValue(); + tryGetPegoutInformation(version, pegout.getKey(), pegoutBtcTx) + .ifPresent(pegoutsReadyToSign::add); } - logger.debug("[processReleases] Going to sign {} releases", releasesReadyToSign.size()); - // TODO: Sorting and then looping again is not efficient but we are making a compromise on performance here as we don't have that many release txs + logger.debug("[processPegouts] Going to sign {} pegouts", pegoutsReadyToSign.size()); + // TODO: Sorting and then looping again is not efficient but we are making a compromise on performance here as we don't have that many pegouts // Sort descending - releasesReadyToSign.sort((a, b) -> (int) (b.getBlock().getNumber() - a.getBlock().getNumber())); + pegoutsReadyToSign.sort((a, b) -> (int) (b.getPegoutCreationRskBlock().getNumber() - a.getPegoutCreationRskBlock().getNumber())); // Sign only the first element - if (releasesReadyToSign.size() > 0) { - signRelease(version, releasesReadyToSign.get(0)); + if (!pegoutsReadyToSign.isEmpty()) { + signConfirmedPegout(version, pegoutsReadyToSign.get(0)); } } catch (Exception e) { - logger.error("[processReleases] There was an error trying to process releases", e); + logger.error("[processPegouts] There was an error trying to process pegouts", e); } - logger.trace("[processReleases] Finished processing releases"); + logger.trace("[processPegouts] Finished processing pegouts"); } - protected Optional tryGetReleaseInformation( + protected Optional tryGetPegoutInformation( int signerVersion, - Keccak256 rskTxHash, - BtcTransaction releaseTx + Keccak256 pegoutConfirmationRskTxHash, + BtcTransaction pegoutBtcTx ) { try { // Discard transactions this fed already signed or cannot be signed by the observed federations - logger.trace("[tryGetReleaseInformation] Validating tx {} can be signed by observed federations and " + - "that it is not already signed by current fed", releaseTx.getHash()); - validateTxCanBeSigned(releaseTx); + logger.trace("[tryGetPegoutInformation] Validating if pegoutBtcTxHash {} can be signed by observed federations and " + + "that it is not already signed by current fed", pegoutBtcTx.getHash()); + validatePegoutBtcTxCanBeSigned(pegoutBtcTx); - // IMPORTANT: As per the current behaviour of the bridge, no release tx should have inputs to be signed + // IMPORTANT: As per the current behaviour of the bridge, no pegout should have inputs to be signed // by different federations. Taking this into account, when removing the signatures from the tx new // scriptSigs are created that all spend from the same federation - logger.trace("[tryGetReleaseInformation] Removing possible signatures from tx {}", releaseTx.getHash()); - Federation spendingFed = getSpendingFederation(releaseTx); - removeSignaturesFromTransaction(releaseTx, spendingFed); - logger.trace("[tryGetReleaseInformation] Tx hash without signatures {}", releaseTx.getHash()); + logger.trace("[tryGetPegoutInformation] Removing possible signatures from pegout btcTxHash {}", pegoutBtcTx.getHash()); + Federation spendingFed = getSpendingFederation(pegoutBtcTx); + removeSignaturesFromPegoutBtcTx(pegoutBtcTx, spendingFed); + logger.trace("[tryGetPegoutInformation] pegout btcTxHash without signatures {}", pegoutBtcTx.getHash()); - logger.trace("[tryGetReleaseInformation] Is tx in storage? {}", storageAccessor.hasBtcTxHash(releaseTx.getHash())); - // Try to get the rskTxHash from the map in memory - Keccak256 actualRskTxHash = storageAccessor.hasBtcTxHash(releaseTx.getHash()) ? - storageAccessor.getRskTxHash(releaseTx.getHash()) : - rskTxHash; + logger.trace("[tryGetPegoutInformation] Is pegout btc tx in storage? {}", storageAccessor.hasBtcTxHash(pegoutBtcTx.getHash())); + // Try to get the pegoutCreationRskTxHash from the map in memory, and if not found then use pegoutConfirmationRskTxHash + Keccak256 pegoutCreationRskTxHash = storageAccessor.hasBtcTxHash(pegoutBtcTx.getHash()) ? + storageAccessor.getRskTxHash(pegoutBtcTx.getHash()) : + pegoutConfirmationRskTxHash; - logger.debug("[tryGetReleaseInformation] Going to lookup tx to sign {}", actualRskTxHash); + logger.debug("[tryGetPegoutInformation] Going to lookup pegoutCreationRskTxHash {} to sign", pegoutCreationRskTxHash); // [-- Ignore punished transactions] --> this won't be done for now but should be taken into consideration // -- Get Real Block where release_requested was emmited - logger.trace("[tryGetReleaseInformation] Getting release information"); - return Optional.of(releaseCreationInformationGetter.getTxInfoToSign( + logger.trace("[tryGetPegoutInformation] Getting pegout information"); + return Optional.of(pegoutCreationInformationGetter.getPegoutCreationInformationToSign( signerVersion, - actualRskTxHash, - releaseTx, - rskTxHash + pegoutCreationRskTxHash, + pegoutBtcTx, + pegoutConfirmationRskTxHash )); - } catch (HSMReleaseCreationInformationException | FederationCantSignException e) { + } catch (HSMPegoutCreationInformationException | FederationCantSignException e) { String message = String.format( - "[tryGetReleaseInformation] There was an error trying to process release for BTC tx %s", - releaseTx.getHash() + "[tryGetPegoutInformation] There was an error trying to process pegout with btcTxHash %s", + pegoutBtcTx.getHash() ); logger.error(message, e); } catch (FederatorAlreadySignedException e) { - logger.info("[tryGetReleaseInformation] {}", e.getMessage()); + logger.info("[tryGetPegoutInformation] {}", e.getMessage()); } return Optional.empty(); } - protected void validateTxCanBeSigned(BtcTransaction btcTx) throws FederatorAlreadySignedException, FederationCantSignException { + protected void validatePegoutBtcTxCanBeSigned(BtcTransaction pegoutBtcTx) throws FederatorAlreadySignedException, FederationCantSignException { try { BtcECKey federatorPublicKey = signer.getPublicKey(BTC_KEY_ID.getKeyId()).toBtcKey(); - logger.trace("[validateTxCanBeSigned] Federator public key {}", federatorPublicKey); + logger.trace("[validatePegoutBtcTxCanBeSigned] Federator public key {}", federatorPublicKey); - for (int inputIndex = 0; inputIndex < btcTx.getInputs().size(); inputIndex++) { - TransactionInput txIn = btcTx.getInput(inputIndex); + for (int inputIndex = 0; inputIndex < pegoutBtcTx.getInputs().size(); inputIndex++) { + TransactionInput txIn = pegoutBtcTx.getInput(inputIndex); Script redeemScript = getRedeemScriptFromInput(txIn); Script standardRedeemScript = extractStandardRedeemScript(redeemScript); // Check if input is not already signed by the current federator - logger.trace("[validateTxCanBeSigned] Checking if the input {} is not already signed by the current federator", inputIndex); - co.rsk.bitcoinj.core.Sha256Hash sigHash = btcTx.hashForSignature( + logger.trace("[validatePegoutBtcTxCanBeSigned] Checking if the input {} is not already signed by the current federator", inputIndex); + co.rsk.bitcoinj.core.Sha256Hash sigHash = pegoutBtcTx.hashForSignature( inputIndex, redeemScript, BtcTransaction.SigHash.ALL, @@ -339,8 +339,8 @@ protected void validateTxCanBeSigned(BtcTransaction btcTx) throws FederatorAlrea ); if (BridgeUtils.isInputSignedByThisFederator(federatorPublicKey, sigHash, txIn)) { String message = String.format( - "Btc tx %s input %d already signed by current federator with public key %s", - btcTx.getHashAsString(), + "PegoutBtcTxHash %s input %d already signed by current federator with public key %s", + pegoutBtcTx.getHashAsString(), inputIndex, federatorPublicKey ); @@ -348,69 +348,71 @@ protected void validateTxCanBeSigned(BtcTransaction btcTx) throws FederatorAlrea } // Check if any of the observed federations can sign the tx - logger.trace("[validateTxCanBeSigned] Checking if any of the observed federations can sign the tx input {}", inputIndex); + logger.trace("[validatePegoutBtcTxCanBeSigned] Checking if any of the observed federations can sign the pegout btc tx input {}", inputIndex); observedFederations.stream() - .forEach(f -> logger.trace("[validateTxCanBeSigned] federation p2sh redeem script {}", f.getRedeemScript())); + .forEach(f -> logger.trace("[validatePegoutBtcTxCanBeSigned] federation p2sh redeem script {}", f.getRedeemScript())); List spendingFedFilter = observedFederations.stream() .filter(f -> (extractDefaultRedeemScript(f)).equals(standardRedeemScript)).collect(Collectors.toList()); - logger.debug("[validateTxCanBeSigned] spendingFedFilter size {}", spendingFedFilter.size()); + logger.debug("[validatePegoutBtcTxCanBeSigned] spendingFedFilter size {}", spendingFedFilter.size()); if (spendingFedFilter.isEmpty()) { String message = String.format( - "Transaction %s can't be signed by any of the observed federations", - btcTx.getHash() + "PegoutBtcTxHash %s can't be signed by any of the observed federations", + pegoutBtcTx.getHash() ); throw new FederationCantSignException(message); } } } catch (SignerException e) { - String message = String.format("[validateTxCanBeSigned] Error validating tx %s, " + - "failed to get current federator public key", btcTx.getHashAsString()); + String message = String.format("[validatePegoutBtcTxCanBeSigned] Error validating pegoutBtcTxHash %s, " + + "failed to get current federator public key", pegoutBtcTx.getHashAsString()); logger.error(message, e); } } - protected void signRelease(int signerVersion, ReleaseCreationInformation releaseCreationInformation) { + protected void signConfirmedPegout(int signerVersion, PegoutCreationInformation pegoutCreationInformation) { + final String topic = "pegoutbtctx"; try { - logger.debug("[signRelease] HSM signer version {}", signerVersion); - logger.debug("[signRelease] Going to sign tx {}", releaseCreationInformation.getInformingRskTxHash()); - logger.trace("[signRelease] Enforce signer requirements"); - releaseRequirementsEnforcer.enforce(signerVersion, releaseCreationInformation); + logger.debug("[signConfirmedPegout] HSM signer version {}", signerVersion); + logger.debug("[signConfirmedPegout] Going to sign pegout with creationRskTxHash: {}", pegoutCreationInformation.getPegoutConfirmationRskTxHash()); + logger.trace("[signConfirmedPegout] Enforce signer requirements"); + pegoutSigningRequirementsEnforcer.enforce(signerVersion, pegoutCreationInformation); SignerMessageBuilder messageBuilder = signerMessageBuilderFactory.buildFromConfig( signerVersion, - releaseCreationInformation + pegoutCreationInformation ); co.rsk.bitcoinj.core.Context.propagate(new co.rsk.bitcoinj.core.Context(bridgeConstants.getBtcParams())); List signatures = new ArrayList<>(); - for (int inputIndex = 0; inputIndex < releaseCreationInformation.getBtcTransaction().getInputs().size(); inputIndex++) { + for (int inputIndex = 0; inputIndex < pegoutCreationInformation.getPegoutBtcTx().getInputs().size(); inputIndex++) { SignerMessage messageToSign = messageBuilder.buildMessageForIndex(inputIndex); - logger.trace("[signRelease] Message to sign: {}", messageToSign.getClass()); - ECKey.ECDSASignature ethSig = signer.sign(BTC_KEY_ID.getKeyId(), messageToSign); - logger.debug("[signRelease] Message successfully signed"); - BtcECKey.ECDSASignature sig = new BtcECKey.ECDSASignature(ethSig.r, ethSig.s); + logger.trace("[signConfirmedPegout] Message to sign: {}", messageToSign.getClass()); + ECDSASignature ethSig = signer.sign(BTC_KEY_ID.getKeyId(), messageToSign); + logger.debug("[signConfirmedPegout] Message successfully signed"); + BtcECKey.ECDSASignature sig = new BtcECKey.ECDSASignature(ethSig.getR(), ethSig.getS()); signatures.add(sig.encodeToDER()); } - logger.info("[signRelease] Signed Tx {}", releaseCreationInformation.getInformingRskTxHash()); - federatorSupport.addSignature(signatures, releaseCreationInformation.getInformingRskTxHash().getBytes()); + logger.info("[signConfirmedPegout] Signed pegoutRskTxHash {}", pegoutCreationInformation.getPegoutConfirmationRskTxHash()); + federatorSupport.addSignature(signatures, pegoutCreationInformation.getPegoutConfirmationRskTxHash().getBytes()); } catch (SignerException e) { - String message = String.format("Error signing Tx %s", releaseCreationInformation.getInformingRskTxHash()); + String message = String.format("Error signing pegoutRskTxHash %s", pegoutCreationInformation.getPegoutConfirmationRskTxHash()); logger.error(message, e); - panicProcessor.panic("btcrelease", message); - } catch (HSMClientException | SignerMessageBuilderException | ReleaseRequirementsEnforcerException e) { - logger.error("[signRelease] {}", e.getMessage()); - panicProcessor.panic("btcrelease", e.getMessage()); + panicProcessor.panic(topic, message); + } catch (HSMClientException | SignerMessageBuilderException | PegoutSigningRequirementsEnforcerException e) { + logger.error("[signConfirmedPegout] {}", e.getMessage()); + panicProcessor.panic(topic, e.getMessage()); } catch (Exception e) { String message = String.format( - "[signRelease] There was an error trying to sign release for BTC tx %s", - releaseCreationInformation.getBtcTransaction().getHash() + "[signConfirmedPegout] There was an error trying to sign pegout with createRskTxHash: %s and btcTxHash: %s", + pegoutCreationInformation.getPegoutCreationRskTxHash(), + pegoutCreationInformation.getPegoutBtcTx().getHash() ); logger.error(message, e); - panicProcessor.panic("btcrelease", e.getMessage()); + panicProcessor.panic(topic, e.getMessage()); } } // Executed when a tx is ready for broadcasting - public void onBtcRelease(BtcTransaction signedBtcTx) { + public void onBroadcastingSignedPegout(BtcTransaction signedBtcTx) { NetworkParameters btcParams = ThinConverter.toOriginalInstance(bridgeConstants.getBtcParamsString()); org.bitcoinj.core.Context.propagate(new org.bitcoinj.core.Context(btcParams)); // broadcast signedBtcTx to the btc network @@ -424,24 +426,24 @@ public void onBtcRelease(BtcTransaction signedBtcTx) { } else if (ScriptPattern.isP2PKH(txo.getScriptPubKey())) { destination = LegacyAddress.fromPubKeyHash(btcParams, ScriptPattern.extractHashFromP2PKH(txo.getScriptPubKey())); } - logger.info("Broadcasted {} to {} in tx {}", txo.getValue(), destination, signedBtcTx2.getTxId()); + logger.info("[onBroadcastingSignedPegout] Broadcasted {} to {} in pegoutBtcTxId {}", txo.getValue(), destination, signedBtcTx2.getTxId()); }); } /* - Received tx inputs are replaced by base inputs without signatures that spend from the given federation. - This way the tx has the same hash as the one registered in release_requested event topics. + Received pegoutBtcTx inputs are replaced by base inputs without signatures that spend from the given federation. + This way the pegoutBtcTx has the same hash as the one registered in release_requested event topics. */ - protected void removeSignaturesFromTransaction(BtcTransaction tx, Federation spendingFed) { - for (int inputIndex = 0; inputIndex < tx.getInputs().size(); inputIndex++) { + protected void removeSignaturesFromPegoutBtcTx(BtcTransaction pegoutBtcTx, Federation spendingFed) { + for (int inputIndex = 0; inputIndex < pegoutBtcTx.getInputs().size(); inputIndex++) { //Get redeem script for current input - TransactionInput txInput = tx.getInput(inputIndex); + TransactionInput txInput = pegoutBtcTx.getInput(inputIndex); Script inputRedeemScript = getRedeemScriptFromInput(txInput); - logger.trace("[removeSignaturesFromTransaction] input {} scriptSig {}", inputIndex, tx.getInput(inputIndex).getScriptSig()); - logger.trace("[removeSignaturesFromTransaction] input {} redeem script {}", inputIndex, inputRedeemScript); + logger.trace("[removeSignaturesFromPegoutBtcTx] input {} scriptSig {}", inputIndex, pegoutBtcTx.getInput(inputIndex).getScriptSig()); + logger.trace("[removeSignaturesFromPegoutBtcTx] input {} redeem script {}", inputIndex, inputRedeemScript); txInput.setScriptSig(createBaseInputScriptThatSpendsFromTheFederation(spendingFed, inputRedeemScript)); - logger.debug("[removeSignaturesFromTransaction] Updated input {} scriptSig with base input script that " + + logger.debug("[removeSignaturesFromPegoutBtcTx] Updated input {} scriptSig with base input script that " + "spends from the federation {}", inputIndex, spendingFed.getAddress()); } } diff --git a/src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientException.java b/src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientException.java new file mode 100644 index 000000000..cfefab240 --- /dev/null +++ b/src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientException.java @@ -0,0 +1,12 @@ +package co.rsk.federate.btcreleaseclient; + +public class BtcPegoutClientException extends Exception { + + public BtcPegoutClientException(String message, Exception e) { + super(message, e); + } + + public BtcPegoutClientException(String message) { + super(message); + } +} diff --git a/src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageAccessor.java b/src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageAccessor.java similarity index 67% rename from src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageAccessor.java rename to src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageAccessor.java index 15b675145..5251f92a8 100644 --- a/src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageAccessor.java +++ b/src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageAccessor.java @@ -3,11 +3,11 @@ import co.rsk.bitcoinj.core.Sha256Hash; import co.rsk.crypto.Keccak256; import co.rsk.federate.config.FedNodeSystemProperties; -import co.rsk.federate.io.btcreleaseclientstorage.BtcReleaseClientFileData; -import co.rsk.federate.io.btcreleaseclientstorage.BtcReleaseClientFileReadResult; -import co.rsk.federate.io.btcreleaseclientstorage.BtcReleaseClientFileStorage; -import co.rsk.federate.io.btcreleaseclientstorage.BtcReleaseClientFileStorageImpl; -import co.rsk.federate.io.btcreleaseclientstorage.BtcReleaseClientFileStorageInfo; +import co.rsk.federate.io.btcreleaseclientstorage.BtcPegoutClientFileData; +import co.rsk.federate.io.btcreleaseclientstorage.BtcPegoutClientFileReadResult; +import co.rsk.federate.io.btcreleaseclientstorage.BtcPegoutClientFileStorage; +import co.rsk.federate.io.btcreleaseclientstorage.BtcPegoutClientFileStorageImpl; +import co.rsk.federate.io.btcreleaseclientstorage.BtcPegoutClientFileStorageInfo; import java.io.IOException; import java.util.Optional; import java.util.concurrent.Executors; @@ -17,54 +17,54 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class BtcReleaseClientStorageAccessor { - private static final Logger logger = LoggerFactory.getLogger(BtcReleaseClientStorageAccessor.class); +public class BtcPegoutClientStorageAccessor { + private static final Logger logger = LoggerFactory.getLogger(BtcPegoutClientStorageAccessor.class); private static final int DEFAULT_DELAY_IN_MS = 5; private static final int DEFAULT_MAX_DELAYS = 5; - private final BtcReleaseClientFileStorage btcReleaseClientFileStorage; - private final BtcReleaseClientFileData fileData; + private final BtcPegoutClientFileStorage btcPegoutClientFileStorage; + private final BtcPegoutClientFileData fileData; private final int maxDelays; private final int delayInMs; // Delay writing to avoid slowing down operations private final ScheduledExecutorService writeTimer; - private ScheduledFuture task; + private ScheduledFuture task; private int delays; - public BtcReleaseClientStorageAccessor(FedNodeSystemProperties systemProperties) throws InvalidStorageFileException { + public BtcPegoutClientStorageAccessor(FedNodeSystemProperties systemProperties) throws InvalidStorageFileException { this( Executors.newSingleThreadScheduledExecutor(), - new BtcReleaseClientFileStorageImpl( - new BtcReleaseClientFileStorageInfo(systemProperties) + new BtcPegoutClientFileStorageImpl( + new BtcPegoutClientFileStorageInfo(systemProperties) ), DEFAULT_DELAY_IN_MS, DEFAULT_MAX_DELAYS ); } - public BtcReleaseClientStorageAccessor( + public BtcPegoutClientStorageAccessor( ScheduledExecutorService executorService, - BtcReleaseClientFileStorage btcReleaseClientFileStorage, + BtcPegoutClientFileStorage btcPegoutClientFileStorage, int delaysInMs, int maxDelays ) throws InvalidStorageFileException { - this.btcReleaseClientFileStorage = btcReleaseClientFileStorage; + this.btcPegoutClientFileStorage = btcPegoutClientFileStorage; this.delayInMs = delaysInMs; this.maxDelays = maxDelays; - BtcReleaseClientFileReadResult readResult; + BtcPegoutClientFileReadResult readResult; synchronized (this) { try { - readResult = this.btcReleaseClientFileStorage.read(); + readResult = this.btcPegoutClientFileStorage.read(); } catch (Exception e) { - String message = "Error reading storage file for BtcReleaseClient"; + String message = "Error reading storage file for BtcPegoutClient"; logger.error(message); throw new InvalidStorageFileException(message, e); } } - if (!readResult.getSuccess()) { - String message = "Error reading storage file for BtcReleaseClient"; + if (Boolean.FALSE.equals(readResult.getSuccess())) { + String message = "Error reading storage file for BtcPegoutClient"; logger.error(message); throw new InvalidStorageFileException(message); } @@ -77,9 +77,9 @@ public BtcReleaseClientStorageAccessor( private void writeFile() { synchronized (this) { try { - this.btcReleaseClientFileStorage.write(fileData); + this.btcPegoutClientFileStorage.write(fileData); } catch(IOException e) { - String message = "[writeFile] Error writing storage file for BtcReleaseClient"; + String message = "[writeFile] Error writing storage file for BtcPegoutClient"; logger.error(message, e); } } @@ -118,20 +118,20 @@ public void setBestBlockHash(Keccak256 bestBlockHash) { } public boolean hasBtcTxHash(Sha256Hash btcTxHash) { - return fileData.getReleaseHashesMap().containsKey(btcTxHash); + return fileData.getPegoutHashesMap().containsKey(btcTxHash); } public Keccak256 getRskTxHash(Sha256Hash btcTxHash) { - return fileData.getReleaseHashesMap().get(btcTxHash); + return fileData.getPegoutHashesMap().get(btcTxHash); } public void putBtcTxHashRskTxHash(Sha256Hash btcTxHash, Keccak256 rskTxHash) { logger.trace("[putBtcTxHashRskTxHash] btc tx hash {} => rsk tx hash {}", btcTxHash, rskTxHash); - fileData.getReleaseHashesMap().put(btcTxHash, rskTxHash); + fileData.getPegoutHashesMap().put(btcTxHash, rskTxHash); signalWriting(); } public int getMapSize() { - return fileData.getReleaseHashesMap().size(); + return fileData.getPegoutHashesMap().size(); } } diff --git a/src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageSynchronizer.java b/src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageSynchronizer.java similarity index 59% rename from src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageSynchronizer.java rename to src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageSynchronizer.java index 1fe0de263..8a00f052a 100644 --- a/src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageSynchronizer.java +++ b/src/main/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageSynchronizer.java @@ -20,8 +20,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class BtcReleaseClientStorageSynchronizer { - private static final Logger logger = LoggerFactory.getLogger(BtcReleaseClientStorageSynchronizer.class); +public class BtcPegoutClientStorageSynchronizer { + private static final Logger logger = LoggerFactory.getLogger(BtcPegoutClientStorageSynchronizer.class); private static final DataWord RELEASE_REQUESTED_TOPIC = DataWord.valueOf( BridgeEvents.RELEASE_REQUESTED.getEvent().encodeSignatureLong()); @@ -34,16 +34,16 @@ public class BtcReleaseClientStorageSynchronizer { private final int timerDelay; private final int maxInitializationDepth; - private BtcReleaseClientStorageAccessor storageAccessor; + private BtcPegoutClientStorageAccessor storageAccessor; private ScheduledExecutorService syncTimer; private boolean isSynced; - public BtcReleaseClientStorageSynchronizer( + public BtcPegoutClientStorageSynchronizer( BlockStore blockStore, ReceiptStore receiptStore, NodeBlockProcessor nodeBlockProcessor, - BtcReleaseClientStorageAccessor storageAccessor, + BtcPegoutClientStorageAccessor storageAccessor, int maxInitializationDepth ) { this( @@ -57,11 +57,11 @@ public BtcReleaseClientStorageSynchronizer( maxInitializationDepth); } - public BtcReleaseClientStorageSynchronizer( + public BtcPegoutClientStorageSynchronizer( BlockStore blockStore, ReceiptStore receiptStore, NodeBlockProcessor nodeBlockProcessor, - BtcReleaseClientStorageAccessor storageAccessor, + BtcPegoutClientStorageAccessor storageAccessor, ScheduledExecutorService executorService, int timerInitialDelayInMs, int timerDelayInMs, @@ -93,63 +93,36 @@ private void sync() { try { Optional storageBestBlockHash = this.storageAccessor.getBestBlockHash(); + Block storageBestBlock = null; if (storageBestBlockHash.isPresent()) { - storageBestBlock = blockStore.getBlockByHash(storageBestBlockHash.get().getBytes()); - if (storageBestBlock == null) { - logger.warn( - "BtcReleaseClientStorage best block hash doesn't exist in blockchain. {}", - storageBestBlockHash.get() - ); - } else { - Block blockInMainchain = blockStore.getChainBlockByNumber(storageBestBlock.getNumber()); - if (blockInMainchain == null || - !blockInMainchain.getHash().equals(storageBestBlockHash.get()) - ) { - logger.warn( - "BtcReleaseClientStorage best block hash doesn't belong to mainchain. ({})", - storageBestBlockHash - ); - storageBestBlock = null; - logger.info("refreshing file"); - } - } + storageBestBlock = getStorageBestBlock(storageBestBlockHash.get()); } else { - logger.info("no data in file"); + logger.info("[sync] no data in file"); + } + + if (isStorageSync(storageBestBlock)) { + logger.info("[sync] Storage already on sync"); + return; } - Block blockToSearch = storageBestBlock; - // If there is no data in the file, set a limit to avoid looking up all the blockchain + Block fromBlock; + /* If there is no data in the file, set a limit to avoid looking up all the blockchain */ if (storageBestBlock == null) { long lastBlockNumberToSearch = blockStore.getBestBlock().getNumber() - this.maxInitializationDepth; - blockToSearch = blockStore.getChainBlockByNumber(Math.max(lastBlockNumberToSearch, 0)); + fromBlock = blockStore.getChainBlockByNumber(Math.max(lastBlockNumberToSearch, 0)); } else { - if (blockToSearch.getNumber() == blockStore.getBestBlock().getNumber()) { - logger.info("[sync] Storage already on sync"); - this.isSynced = true; - this.syncTimer.shutdown(); - return; - } - blockToSearch = blockStore.getChainBlockByNumber(blockToSearch.getNumber() + 1); + fromBlock = blockStore.getChainBlockByNumber(storageBestBlock.getNumber() + 1); } logger.info( - "going to sync from block {} ({})", - blockToSearch.getNumber(), - blockToSearch.getHash() + "[sync] going to sync from block {} ({})", + fromBlock.getNumber(), + fromBlock.getHash() ); - while(blockToSearch != null && blockStore.getBestBlock().getNumber() >= blockToSearch.getNumber()) { - logger.trace("[sync] going to fetch block {}({})", blockToSearch.getNumber(), blockToSearch.getHash()); - List receipts = new ArrayList<>(); - for(Transaction transaction: blockToSearch.getTransactionsList()) { - TransactionReceipt receipt = receiptStore.getInMainChain(transaction.getHash().getBytes(), blockStore).orElseThrow(NullPointerException::new).getReceipt(); - receipt.setTransaction(transaction); - receipts.add(receipt); - } - checkLogsForReleaseRequested(blockToSearch, receipts); - blockToSearch = blockStore.getChainBlockByNumber(blockToSearch.getNumber() + 1); - } + fetchNewBlocks(fromBlock); + logger.info( "[sync] Finished sync, storage has {} elements, and its best block is {}", storageAccessor.getMapSize(), @@ -158,8 +131,55 @@ private void sync() { this.isSynced = true; this.syncTimer.shutdown(); } catch (Exception e) { - logger.error("[sync] Problem syncing BtcReleaseClientStorage", e); + logger.error("[sync] Problem syncing BtcPegoutClientStorage", e); + } + } + + private void fetchNewBlocks(Block blockToSearch) { + Block blockToFetch = blockToSearch; + while(blockToFetch != null && blockStore.getBestBlock().getNumber() >= blockToFetch.getNumber()) { + logger.trace("[sync] going to fetch block {}({})", blockToFetch.getNumber(), blockToFetch.getHash()); + List receipts = new ArrayList<>(); + for(Transaction transaction: blockToFetch.getTransactionsList()) { + TransactionReceipt receipt = receiptStore.getInMainChain(transaction.getHash().getBytes(), blockStore).orElseThrow(NullPointerException::new).getReceipt(); + receipt.setTransaction(transaction); + receipts.add(receipt); + } + checkLogsForReleaseRequested(blockToFetch, receipts); + blockToFetch = blockStore.getChainBlockByNumber(blockToFetch.getNumber() + 1); + } + } + + private boolean isStorageSync(Block storageBestBlock) { + if (storageBestBlock != null && storageBestBlock.getNumber() == blockStore.getBestBlock().getNumber()) { + this.isSynced = true; + this.syncTimer.shutdown(); + return true; + } + return false; + } + + private Block getStorageBestBlock(Keccak256 storageBestBlockHash) { + Block storageBestBlock = blockStore.getBlockByHash(storageBestBlockHash.getBytes()); + if (storageBestBlock == null) { + logger.warn( + "[sync] BtcPegoutClientStorage best block hash doesn't exist in blockchain. {}", + storageBestBlockHash + ); + } else { + Block blockInMainchain = blockStore.getChainBlockByNumber(storageBestBlock.getNumber()); + if (blockInMainchain == null || + !blockInMainchain.getHash().equals(storageBestBlockHash) + ) { + logger.warn( + "[sync] BtcPegoutClientStorage best block hash doesn't belong to mainchain. ({})", + storageBestBlockHash + ); + storageBestBlock = null; + logger.info("refreshing file"); + } } + return storageBestBlock; } private void checkLogsForReleaseRequested(Block block, List receipts) { diff --git a/src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientException.java b/src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientException.java deleted file mode 100644 index 070d40396..000000000 --- a/src/main/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientException.java +++ /dev/null @@ -1,12 +0,0 @@ -package co.rsk.federate.btcreleaseclient; - -public class BtcReleaseClientException extends Exception { - - public BtcReleaseClientException(String message, Exception e) { - super(message, e); - } - - public BtcReleaseClientException(String message) { - super(message); - } -} diff --git a/src/main/java/co/rsk/federate/btcreleaseclient/InvalidStorageFileException.java b/src/main/java/co/rsk/federate/btcreleaseclient/InvalidStorageFileException.java index 1979b2e2a..fd78e0cdb 100644 --- a/src/main/java/co/rsk/federate/btcreleaseclient/InvalidStorageFileException.java +++ b/src/main/java/co/rsk/federate/btcreleaseclient/InvalidStorageFileException.java @@ -1,6 +1,6 @@ package co.rsk.federate.btcreleaseclient; -public class InvalidStorageFileException extends BtcReleaseClientException { +public class InvalidStorageFileException extends BtcPegoutClientException { public InvalidStorageFileException(String message, Exception e) { super(message, e); diff --git a/src/main/java/co/rsk/federate/config/FedNodeSystemProperties.java b/src/main/java/co/rsk/federate/config/FedNodeSystemProperties.java index 1cb13202c..217fa8301 100644 --- a/src/main/java/co/rsk/federate/config/FedNodeSystemProperties.java +++ b/src/main/java/co/rsk/federate/config/FedNodeSystemProperties.java @@ -78,7 +78,7 @@ public int getAmountOfHeadersToSend() { // 6000 blocks is 150% the amount of blocks the Bridge waits before confirming a peg-out. // If this powpeg-node was shutdown for 48hs this depth will be enough to resync all the information. // If this powpeg-node was shutdown for longer periods, most likely the transaction was signed by other functionaries. - public int getBtcReleaseClientInitializationMaxDepth() { + public int getBtcPegoutClientInitializationMaxDepth() { return configFromFiles.hasPath("federator.pegoutStorageInitializationDepth") ? configFromFiles.getInt("federator.pegoutStorageInitializationDepth") : 6_000; diff --git a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileData.java b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileData.java similarity index 62% rename from src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileData.java rename to src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileData.java index 783e2c043..dc5b8c6ef 100644 --- a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileData.java +++ b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileData.java @@ -6,17 +6,17 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; -public class BtcReleaseClientFileData { +public class BtcPegoutClientFileData { - private final Map releaseHashesMap; + private final Map pegoutHashesMap; private Keccak256 bestBlockHash; - public BtcReleaseClientFileData() { - releaseHashesMap = new ConcurrentHashMap<>(); + public BtcPegoutClientFileData() { + pegoutHashesMap = new ConcurrentHashMap<>(); } - public Map getReleaseHashesMap() { - return this.releaseHashesMap; + public Map getPegoutHashesMap() { + return this.pegoutHashesMap; } public void setBestBlockHash(Keccak256 bestBlockHash) { diff --git a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileReadResult.java b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileReadResult.java similarity index 51% rename from src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileReadResult.java rename to src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileReadResult.java index b264201e4..cc5b4522c 100644 --- a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileReadResult.java +++ b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileReadResult.java @@ -1,12 +1,12 @@ package co.rsk.federate.io.btcreleaseclientstorage; -public class BtcReleaseClientFileReadResult { +public class BtcPegoutClientFileReadResult { private final Boolean success; - private final BtcReleaseClientFileData data; + private final BtcPegoutClientFileData data; - public BtcReleaseClientFileReadResult(Boolean success, BtcReleaseClientFileData data) { + public BtcPegoutClientFileReadResult(Boolean success, BtcPegoutClientFileData data) { this.success = success; this.data = data; } @@ -15,7 +15,7 @@ public Boolean getSuccess() { return success; } - public BtcReleaseClientFileData getData() { + public BtcPegoutClientFileData getData() { return data; } } diff --git a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorage.java b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorage.java new file mode 100644 index 000000000..5248d434f --- /dev/null +++ b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorage.java @@ -0,0 +1,13 @@ +package co.rsk.federate.io.btcreleaseclientstorage; + +import co.rsk.federate.io.FileStorageInfo; +import java.io.IOException; + +public interface BtcPegoutClientFileStorage { + + FileStorageInfo getInfo(); + + void write(BtcPegoutClientFileData data) throws IOException; + + BtcPegoutClientFileReadResult read() throws IOException; +} diff --git a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageImpl.java b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageImpl.java similarity index 65% rename from src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageImpl.java rename to src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageImpl.java index 4c4212e11..c6177263e 100644 --- a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageImpl.java +++ b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageImpl.java @@ -9,16 +9,20 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; + import org.apache.commons.io.FileUtils; import org.ethereum.util.RLP; import org.ethereum.util.RLPElement; import org.ethereum.util.RLPList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -public class BtcReleaseClientFileStorageImpl implements BtcReleaseClientFileStorage { +public class BtcPegoutClientFileStorageImpl implements BtcPegoutClientFileStorage { + private static final Logger logger = LoggerFactory.getLogger(BtcPegoutClientFileStorageImpl.class); private final FileStorageInfo storageInfo; - public BtcReleaseClientFileStorageImpl(FileStorageInfo storageInfo) { + public BtcPegoutClientFileStorageImpl(FileStorageInfo storageInfo) { this.storageInfo = storageInfo; } @@ -28,7 +32,7 @@ public FileStorageInfo getInfo() { } @Override - public void write(BtcReleaseClientFileData data) throws IOException { + public void write(BtcPegoutClientFileData data) throws IOException { if (data == null) { throw new IOException("Data is null"); } @@ -39,7 +43,7 @@ public void write(BtcReleaseClientFileData data) throws IOException { File dataFile = new File(storageInfo.getFilePath()); - byte[] serializedMap = this.serializeReleaseHashes(data.getReleaseHashesMap()); + byte[] serializedMap = this.serializePegoutHashes(data.getPegoutHashesMap()); Optional optionalblockHash = data.getBestBlockHash(); byte[] serializedBlockHash = RLP.encodeElement( optionalblockHash.isPresent() ? optionalblockHash.get().getBytes() : new byte[]{} @@ -51,34 +55,34 @@ public void write(BtcReleaseClientFileData data) throws IOException { } @Override - public BtcReleaseClientFileReadResult read() throws IOException { + public BtcPegoutClientFileReadResult read() throws IOException { File file = new File(this.storageInfo.getFilePath()); if (!file.exists()) { - return new BtcReleaseClientFileReadResult(Boolean.TRUE, new BtcReleaseClientFileData()); + return new BtcPegoutClientFileReadResult(Boolean.TRUE, new BtcPegoutClientFileData()); } return this.readFromRlp(FileUtils.readFileToByteArray(file)); } - private BtcReleaseClientFileReadResult readFromRlp(byte[] fileData) { - BtcReleaseClientFileData data = new BtcReleaseClientFileData(); + private BtcPegoutClientFileReadResult readFromRlp(byte[] fileData) { + BtcPegoutClientFileData data = new BtcPegoutClientFileData(); if (fileData.length == 0) { - return new BtcReleaseClientFileReadResult(Boolean.TRUE, data); + return new BtcPegoutClientFileReadResult(Boolean.TRUE, data); } try { ArrayList elements = RLP.decode2(fileData); if (elements.isEmpty()) { - return new BtcReleaseClientFileReadResult(Boolean.TRUE, data); + return new BtcPegoutClientFileReadResult(Boolean.TRUE, data); } RLPList rlpList = (RLPList)elements.get(0); if (rlpList.size() == 0) { - return new BtcReleaseClientFileReadResult(Boolean.TRUE, data); + return new BtcPegoutClientFileReadResult(Boolean.TRUE, data); } // Map byte[] mapData = rlpList.get(0).getRLPData(); RLPList mapList = (RLPList)RLP.decode2(mapData).get(0); - data.getReleaseHashesMap().putAll(this.deserializeReleaseHashes(mapList)); + data.getPegoutHashesMap().putAll(this.deserializePegoutHashes(mapList)); // Block hash if (rlpList.size() == 2) { byte[] blockHashData = rlpList.get(1).getRLPData(); @@ -87,17 +91,18 @@ private BtcReleaseClientFileReadResult readFromRlp(byte[] fileData) { } } } catch (Exception e) { - return new BtcReleaseClientFileReadResult(Boolean.FALSE, null); + logger.error("[readFromRlp] error trying to read file data.", e); + return new BtcPegoutClientFileReadResult(Boolean.FALSE, null); } - return new BtcReleaseClientFileReadResult(Boolean.TRUE, data); + return new BtcPegoutClientFileReadResult(Boolean.TRUE, data); } - private byte[] serializeReleaseHashes(Map releaseHashesMap) { - int items = releaseHashesMap.size(); + private byte[] serializePegoutHashes(Map pegoutHashesMap) { + int items = pegoutHashesMap.size(); byte[][] bytes = new byte[items * 2][]; int n = 0; - for (Map.Entry entry : releaseHashesMap.entrySet()) { + for (Map.Entry entry : pegoutHashesMap.entrySet()) { bytes[n] = RLP.encodeElement(entry.getKey().getBytes()); bytes[n + 1] = RLP.encodeElement(entry.getValue().getBytes()); n += 2; @@ -105,7 +110,7 @@ private byte[] serializeReleaseHashes(Map releaseHashesMa return RLP.encodeList(bytes); } - private Map deserializeReleaseHashes(RLPList rlpList) { + private Map deserializePegoutHashes(RLPList rlpList) { Map result = new HashMap<>(); for (int k = 0; k < rlpList.size(); k += 2) { diff --git a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageInfo.java b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageInfo.java similarity index 79% rename from src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageInfo.java rename to src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageInfo.java index 6fc31f39a..7cd90ce79 100644 --- a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageInfo.java +++ b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageInfo.java @@ -4,13 +4,13 @@ import co.rsk.federate.io.FileStorageInfo; import java.io.File; -public class BtcReleaseClientFileStorageInfo implements FileStorageInfo { +public class BtcPegoutClientFileStorageInfo implements FileStorageInfo { private String pegDirectoryPath; private String filePath; - public BtcReleaseClientFileStorageInfo(FedNodeSystemProperties config) { + public BtcPegoutClientFileStorageInfo(FedNodeSystemProperties config) { this.pegDirectoryPath = config.databaseDir() + File.separator + "peg"; this.filePath = this.pegDirectoryPath + File.separator + "btcReleaseClient.rlp"; } diff --git a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorage.java b/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorage.java deleted file mode 100644 index 5487e5706..000000000 --- a/src/main/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorage.java +++ /dev/null @@ -1,13 +0,0 @@ -package co.rsk.federate.io.btcreleaseclientstorage; - -import co.rsk.federate.io.FileStorageInfo; -import java.io.IOException; - -public interface BtcReleaseClientFileStorage { - - FileStorageInfo getInfo(); - - void write(BtcReleaseClientFileData data) throws IOException; - - BtcReleaseClientFileReadResult read() throws IOException; -} diff --git a/src/main/java/co/rsk/federate/signing/ECDSACompositeSigner.java b/src/main/java/co/rsk/federate/signing/ECDSACompositeSigner.java index 502b171bd..a9c898bb6 100644 --- a/src/main/java/co/rsk/federate/signing/ECDSACompositeSigner.java +++ b/src/main/java/co/rsk/federate/signing/ECDSACompositeSigner.java @@ -21,7 +21,7 @@ import co.rsk.federate.UnrecoverableErrorEventListener; import co.rsk.federate.signing.hsm.SignerException; import co.rsk.federate.signing.hsm.message.SignerMessage; -import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import java.util.ArrayList; import java.util.List; @@ -83,7 +83,7 @@ public int getVersionForKeyId(KeyId keyId) throws SignerException { } @Override - public ECKey.ECDSASignature sign(KeyId keyId, SignerMessage message) throws SignerException { + public ECDSASignature sign(KeyId keyId, SignerMessage message) throws SignerException { return findSignerFor(keyId).sign(keyId, message); } diff --git a/src/main/java/co/rsk/federate/signing/ECDSAHSMSigner.java b/src/main/java/co/rsk/federate/signing/ECDSAHSMSigner.java index c7f890977..a20fd7115 100644 --- a/src/main/java/co/rsk/federate/signing/ECDSAHSMSigner.java +++ b/src/main/java/co/rsk/federate/signing/ECDSAHSMSigner.java @@ -26,7 +26,7 @@ import co.rsk.federate.signing.hsm.client.HSMSigningClientProvider; import co.rsk.federate.signing.hsm.client.HSMSignature; import co.rsk.federate.signing.hsm.message.SignerMessage; -import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -121,7 +121,7 @@ public int getVersionForKeyId(KeyId keyId) throws SignerException { } @Override - public ECKey.ECDSASignature sign(KeyId keyId, SignerMessage message) throws SignerException { + public ECDSASignature sign(KeyId keyId, SignerMessage message) throws SignerException { return invokeWithVersionRetry(keyId, client1 -> { HSMSignature signature = client1.sign(keyIdMapping.get(keyId), message); return signature.toEthSignature(); diff --git a/src/main/java/co/rsk/federate/signing/ECDSASigner.java b/src/main/java/co/rsk/federate/signing/ECDSASigner.java index 6961eff08..69f93ce4a 100644 --- a/src/main/java/co/rsk/federate/signing/ECDSASigner.java +++ b/src/main/java/co/rsk/federate/signing/ECDSASigner.java @@ -21,7 +21,7 @@ import co.rsk.federate.UnrecoverableErrorEventDispatcher; import co.rsk.federate.signing.hsm.SignerException; import co.rsk.federate.signing.hsm.message.SignerMessage; -import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import java.util.List; @@ -42,7 +42,7 @@ public interface ECDSASigner extends UnrecoverableErrorEventDispatcher { int getVersionForKeyId(KeyId keyId) throws SignerException; - ECKey.ECDSASignature sign(KeyId keyId, SignerMessage message) throws SignerException; + ECDSASignature sign(KeyId keyId, SignerMessage message) throws SignerException; String getVersionString() throws SignerException; diff --git a/src/main/java/co/rsk/federate/signing/ECDSASignerFromFileKey.java b/src/main/java/co/rsk/federate/signing/ECDSASignerFromFileKey.java index 95b962989..7aa9206f6 100644 --- a/src/main/java/co/rsk/federate/signing/ECDSASignerFromFileKey.java +++ b/src/main/java/co/rsk/federate/signing/ECDSASignerFromFileKey.java @@ -25,6 +25,7 @@ import co.rsk.federate.signing.keyfile.KeyFileChecker; import co.rsk.federate.signing.keyfile.KeyFileHandler; import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -98,14 +99,14 @@ public int getVersionForKeyId(KeyId keyId) throws SignerException { } @Override - public ECKey.ECDSASignature sign(KeyId keyId, SignerMessage message) throws SignerException { + public ECDSASignature sign(KeyId keyId, SignerMessage message) throws SignerException { if (!canSignWith(keyId)) { logger.error("Can't sign with that key id. Requested {}", keyId); throw new SignerException(String.format("Can't sign with the requested signing key: %s", keyId)); } // Sign and return the wrapped signature. - return getPrivateKey().sign(((SignerMessageV1)message).getBytes()); + return ECDSASignature.fromSignature(getPrivateKey().sign(((SignerMessageV1)message).getBytes())); } @Override diff --git a/src/main/java/co/rsk/federate/signing/FederationCantSignException.java b/src/main/java/co/rsk/federate/signing/FederationCantSignException.java index 2f68f1462..5fc1000f1 100644 --- a/src/main/java/co/rsk/federate/signing/FederationCantSignException.java +++ b/src/main/java/co/rsk/federate/signing/FederationCantSignException.java @@ -1,7 +1,7 @@ package co.rsk.federate.signing; /** - * An exception produced when BtcReleaseClient receives a btc tx with inputs + * An exception produced when BtcPegoutClient receives a btc tx with inputs * that can't be signed by any of the observed federations * * @author Marcos Irisarri diff --git a/src/main/java/co/rsk/federate/signing/hsm/advanceblockchain/HSMBookkeepingService.java b/src/main/java/co/rsk/federate/signing/hsm/advanceblockchain/HSMBookkeepingService.java index 314de7af6..1e2d5694f 100644 --- a/src/main/java/co/rsk/federate/signing/hsm/advanceblockchain/HSMBookkeepingService.java +++ b/src/main/java/co/rsk/federate/signing/hsm/advanceblockchain/HSMBookkeepingService.java @@ -172,7 +172,7 @@ protected void informConfirmedBlockHeaders() { hsmCurrentBestBlock.getHash(), hsmCurrentBestBlock.getNumber() ); - // TODO: contact BtcReleaseClient to let it try to sign transactions now + // TODO: contact BtcPegoutClient to let it try to sign transactions now } catch (HSMBlockchainBookkeepingRelatedException e) { logger.error("[informConfirmedBlockHeaders] {}", e.getMessage()); } catch (Exception exception) { diff --git a/src/main/java/co/rsk/federate/signing/hsm/client/HSMSignature.java b/src/main/java/co/rsk/federate/signing/hsm/client/HSMSignature.java index a82be2fe0..e0bb77d3d 100644 --- a/src/main/java/co/rsk/federate/signing/hsm/client/HSMSignature.java +++ b/src/main/java/co/rsk/federate/signing/hsm/client/HSMSignature.java @@ -18,7 +18,7 @@ package co.rsk.federate.signing.hsm.client; -import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; /** * Represents a signature as gathered @@ -64,13 +64,13 @@ public byte[] getPublicKey() { return publicKey; } - public ECKey.ECDSASignature toEthSignature() { + public ECDSASignature toEthSignature() { if (v != null) { - return ECKey.ECDSASignature.fromComponents(r, s, v); + return ECDSASignature.fromComponents(r, s, v); } // Calculate 'v' - return ECKey.ECDSASignature.fromComponentsWithRecoveryCalculation( + return ECDSASignature.fromComponentsWithRecoveryCalculation( r, s, hash, publicKey ); } diff --git a/src/main/java/co/rsk/federate/signing/hsm/message/HSMPegoutCreationInformationException.java b/src/main/java/co/rsk/federate/signing/hsm/message/HSMPegoutCreationInformationException.java new file mode 100644 index 000000000..325486363 --- /dev/null +++ b/src/main/java/co/rsk/federate/signing/hsm/message/HSMPegoutCreationInformationException.java @@ -0,0 +1,15 @@ +package co.rsk.federate.signing.hsm.message; + +/** + * An exception produced when the event from the pegout can not be found. + * + * @author Pamela Gonzalezt + */ +public class HSMPegoutCreationInformationException extends Exception { + public HSMPegoutCreationInformationException(String message) { + super(message); + } + public HSMPegoutCreationInformationException(String message, Throwable e) { + super(message, e); + } +} diff --git a/src/main/java/co/rsk/federate/signing/hsm/message/HSMReleaseCreationInformationException.java b/src/main/java/co/rsk/federate/signing/hsm/message/HSMReleaseCreationInformationException.java deleted file mode 100644 index d6d01eea3..000000000 --- a/src/main/java/co/rsk/federate/signing/hsm/message/HSMReleaseCreationInformationException.java +++ /dev/null @@ -1,15 +0,0 @@ -package co.rsk.federate.signing.hsm.message; - -/** - * An exception produced when the the event from the release can not be found. - * - * @author Pamela Gonzalezt - */ -public class HSMReleaseCreationInformationException extends Exception { - public HSMReleaseCreationInformationException(String message) { - super(message); - } - public HSMReleaseCreationInformationException(String message, Throwable e) { - super(message, e); - } -} diff --git a/src/main/java/co/rsk/federate/signing/hsm/message/PegoutCreationInformation.java b/src/main/java/co/rsk/federate/signing/hsm/message/PegoutCreationInformation.java new file mode 100644 index 000000000..b81e9d528 --- /dev/null +++ b/src/main/java/co/rsk/federate/signing/hsm/message/PegoutCreationInformation.java @@ -0,0 +1,79 @@ +package co.rsk.federate.signing.hsm.message; + +import co.rsk.bitcoinj.core.BtcTransaction; +import co.rsk.crypto.Keccak256; +import org.ethereum.core.Block; +import org.ethereum.core.TransactionReceipt; + +public class PegoutCreationInformation { + private final Block pegoutCreationRskBlock; + private final TransactionReceipt transactionReceipt; + private final Keccak256 pegoutCreationRskTxHash; + private final Keccak256 pegoutConfirmationRskTxHash; + private final BtcTransaction pegoutBtcTx; + + + /** + * + * @param pegoutCreationRskBlock The rsk block where pegout was created + * @param transactionReceipt The rsk transaction receipt where pegout was created + * @param pegoutCreationRskTxHash The rsk transaction hash where the pegout was created + * @param pegoutBtcTx The BTC transaction to sign + **/ + public PegoutCreationInformation( + Block pegoutCreationRskBlock, + TransactionReceipt transactionReceipt, + Keccak256 pegoutCreationRskTxHash, + BtcTransaction pegoutBtcTx + ) { + this(pegoutCreationRskBlock, transactionReceipt, pegoutCreationRskTxHash, pegoutBtcTx, pegoutCreationRskTxHash); + } + + /** + * + * @param pegoutCreationRskBlock The rsk block where the pegout was created + * @param transactionReceipt The rsk transaction receipt where the pegout was created + * @param pegoutCreationRskTxHash The rsk transaction hash where the pegout was created + * @param pegoutBtcTx The BTC transaction to sign + * @param pegoutConfirmationRskTxHash The rsk transaction hash where the pegout was confirmed to be signed + **/ + public PegoutCreationInformation( + Block pegoutCreationRskBlock, + TransactionReceipt transactionReceipt, + Keccak256 pegoutCreationRskTxHash, + BtcTransaction pegoutBtcTx, + Keccak256 pegoutConfirmationRskTxHash + ) { + this.pegoutCreationRskBlock = pegoutCreationRskBlock; + this.transactionReceipt = transactionReceipt; + this.pegoutCreationRskTxHash = pegoutCreationRskTxHash; + this.pegoutBtcTx = pegoutBtcTx; + this.pegoutConfirmationRskTxHash = pegoutConfirmationRskTxHash; + } + + public Block getPegoutCreationRskBlock() { + return pegoutCreationRskBlock; + } + + /** + * gets the receipt of the rsk transaction that created the pegout BTC transaction + **/ + public TransactionReceipt getTransactionReceipt() { + return transactionReceipt; + } + + /** + * gets the hash of the rsk transaction that originated the pegout + **/ + public Keccak256 getPegoutCreationRskTxHash() { + return pegoutCreationRskTxHash; + } + + public Keccak256 getPegoutConfirmationRskTxHash() { + return pegoutConfirmationRskTxHash; + } + + public BtcTransaction getPegoutBtcTx() { + return pegoutBtcTx; + } +} diff --git a/src/main/java/co/rsk/federate/signing/hsm/message/PegoutCreationInformationGetter.java b/src/main/java/co/rsk/federate/signing/hsm/message/PegoutCreationInformationGetter.java new file mode 100644 index 000000000..99c2aba80 --- /dev/null +++ b/src/main/java/co/rsk/federate/signing/hsm/message/PegoutCreationInformationGetter.java @@ -0,0 +1,210 @@ +package co.rsk.federate.signing.hsm.message; + +import co.rsk.bitcoinj.core.BtcTransaction; +import co.rsk.crypto.Keccak256; +import co.rsk.peg.BridgeEvents; +import org.ethereum.core.Block; +import org.ethereum.core.CallTransaction; +import org.ethereum.core.Transaction; +import org.ethereum.core.TransactionReceipt; +import org.ethereum.db.BlockStore; +import org.ethereum.db.ReceiptStore; +import org.ethereum.db.TransactionInfo; +import org.ethereum.vm.LogInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +// First the class tries to find the event associated with the transaction. If it cannot find it, it requests the following +// events until it is found or until it reaches the last block. +public class PegoutCreationInformationGetter { + private static final Logger logger = LoggerFactory.getLogger(PegoutCreationInformationGetter.class); + + private final BlockStore blockStore; + private final ReceiptStore receiptStore; + private final byte[] releaseRequestedSignatureTopic; + + public PegoutCreationInformationGetter( + ReceiptStore receiptStore, + BlockStore blockStore + ) { + this.blockStore = blockStore; + this.receiptStore = receiptStore; + + CallTransaction.Function releaseRequestedEvent = BridgeEvents.RELEASE_REQUESTED.getEvent(); + releaseRequestedSignatureTopic = releaseRequestedEvent.encodeSignatureLong(); + } + + /* Use this method if the originating rsk tx hash and the informing rsk tx hash match */ + public PegoutCreationInformation getPegoutCreationInformationToSign( + int version, + Keccak256 rskTxHash, + BtcTransaction btcTransaction + ) throws HSMPegoutCreationInformationException { + return getPegoutCreationInformationToSign(version, rskTxHash, btcTransaction, rskTxHash); + } + + public PegoutCreationInformation getPegoutCreationInformationToSign( + int version, + Keccak256 pegoutCreationRskTxHash, + BtcTransaction pegoutBtcTx, + Keccak256 pegoutConfirmationRskTxHash + ) throws HSMPegoutCreationInformationException { + if (version == 1) { + return getPegoutCreationInformation(pegoutCreationRskTxHash, pegoutBtcTx, pegoutConfirmationRskTxHash); + } else if (version >= 2) { + return getPegoutCreationInformationV2(pegoutCreationRskTxHash, pegoutBtcTx, pegoutConfirmationRskTxHash); + } else { + throw new HSMPegoutCreationInformationException("Unsupported version " + version); + } + } + + protected PegoutCreationInformation getPegoutCreationInformation( + Keccak256 pegoutCreationRskTxHash, + BtcTransaction pegoutBtcTx, + Keccak256 pegoutConfirmationRskTxHash + ) throws HSMPegoutCreationInformationException { + TransactionInfo transactionInfo = receiptStore.getInMainChain(pegoutCreationRskTxHash.getBytes(), blockStore).orElse(null); + if (transactionInfo == null) { + String message = String.format( + "pegoutCreationRskTxHash %s could not be found in best chain", + pegoutCreationRskTxHash + ); + logger.error("[getPegoutCreationInformationToSign] {}", message); + throw new HSMPegoutCreationInformationException(message); + } + TransactionReceipt transactionReceipt = transactionInfo.getReceipt(); + Block block = blockStore.getBlockByHash(transactionInfo.getBlockHash()); + + return new PegoutCreationInformation( + block, + transactionReceipt, + pegoutCreationRskTxHash, + pegoutBtcTx, + pegoutConfirmationRskTxHash + ); + } + + protected PegoutCreationInformation getPegoutCreationInformationV2( + Keccak256 pegoutCreationRskTxHash, + BtcTransaction pegoutBtcTx, + Keccak256 pegoutConfirmationRskTxHash + ) throws HSMPegoutCreationInformationException { + try { + PegoutCreationInformation basePegoutCreationInformation = + getPegoutCreationInformation(pegoutCreationRskTxHash, pegoutBtcTx, pegoutConfirmationRskTxHash); + Block block = basePegoutCreationInformation.getPegoutCreationRskBlock(); + TransactionReceipt transactionReceipt = basePegoutCreationInformation.getTransactionReceipt(); + + // Get transaction from the block, searching by pegoutCreationRskTxHash, and set it in the tx receipt + logger.trace("[getPegoutCreationInformationToSign] Searching for pegoutCreationRskTxHash {} in block {} ({})", pegoutCreationRskTxHash, block.getHash(), block.getNumber()); + List transactions = block.getTransactionsList().stream() + .filter(t -> t.getHash().equals(pegoutCreationRskTxHash)) + .collect(Collectors.toList()); + logger.trace("[getPegoutCreationInformationToSign] Transactions found {}", transactions.size()); + if(transactions.size() != 1) { + String message = String.format( + "pegoutCreationRskTxHash %s could not be found in block %s or more than 1 result obtained. Filter size: %d", + pegoutCreationRskTxHash, + block.getHash().toHexString(), + transactions.size() + ); + logger.error("[getPegoutCreationInformationToSign] {}", message); + throw new HSMPegoutCreationInformationException(message); + } + Transaction transaction = transactions.get(0); + transactionReceipt.setTransaction(transaction); + + return searchEventInFollowingBlocks(block.getNumber(), pegoutBtcTx, pegoutCreationRskTxHash, pegoutConfirmationRskTxHash); + } catch (Exception e) { + throw new HSMPegoutCreationInformationException("Unhandled exception occured", e); + } + } + + private PegoutCreationInformation searchEventInFollowingBlocks( + long blockNumber, + BtcTransaction pegoutBtcTx, + Keccak256 pegoutCreationRskTxHash, + Keccak256 pegoutConfirmationRskTxHash + ) throws HSMPegoutCreationInformationException { + Block block = blockStore.getChainBlockByNumber(blockNumber); + // If the block cannot be found by its number, the event cannot be searched further. + if (block == null) { + throw new HSMPegoutCreationInformationException( + String.format("[searchEventInFollowingBlocks] Block not found. pegoutCreationRskTxHash: [%s]", pegoutCreationRskTxHash) + ); + } + + logger.trace( + "[searchEventInFollowingBlocks] searching in block {}. Has {} transactions", + blockNumber, + block.getTransactionsList().size() + ); + for (Transaction transaction : block.getTransactionsList()) { + Optional transactionInfo = receiptStore.getInMainChain(transaction.getHash().getBytes(), blockStore); + if (transactionInfo.isPresent()) { + TransactionInfo txInfoFound = transactionInfo.get(); + TransactionReceipt transactionReceipt = txInfoFound.getReceipt(); + transactionReceipt.setTransaction(transaction); + Optional optionalPegoutCreationInformation = + getPegoutCreationInformationFromEvent(block, transactionReceipt, pegoutBtcTx, pegoutCreationRskTxHash, pegoutConfirmationRskTxHash); + if (optionalPegoutCreationInformation.isPresent()) { + return optionalPegoutCreationInformation.get(); + } + } + } + // If the block being checked is the last block, and was not found, then the event does not exist. + if (block.getNumber() == (blockStore.getBestBlock().getNumber())) { + throw new HSMPegoutCreationInformationException( + String.format("[searchEventInFollowingBlocks] Event not found. pegoutCreationRskTxHash: [%s]", pegoutCreationRskTxHash) + ); + } + // If the event was not found in this block, the next block is requested and the same search is performed. + return searchEventInFollowingBlocks(blockNumber + 1, pegoutBtcTx, pegoutCreationRskTxHash, pegoutConfirmationRskTxHash); + } + + private Optional getPegoutCreationInformationFromEvent( + Block block, + TransactionReceipt transactionReceipt, + BtcTransaction pegoutBtcTx, + Keccak256 pegoutCreationRskTxHash, + Keccak256 pegoutConfirmationRskTxHash + ) { + boolean hasLogs = !transactionReceipt.getLogInfoList().isEmpty(); + logger.trace( + "[getPegoutCreationInformationFromEvent] pegoutCreationRskTxHash ({}) in block ({} - {}). has logs? {}", + transactionReceipt.getTransaction().getHash(), + block.getNumber(), + block.getHash(), + hasLogs + ); + if (hasLogs) { + List logs = transactionReceipt.getLogInfoList(); + for (LogInfo logInfo : logs) { + // You should check that the event is a RELEASE_REQUESTED and contains the hash of the transaction. + boolean hasReleaseRequestEvent = Arrays.equals(logInfo.getTopics().get(0).getData(), releaseRequestedSignatureTopic); + if (hasReleaseRequestEvent && (Arrays.equals(logInfo.getTopics().get(2).getData(), pegoutBtcTx.getHash().getBytes()))) { + logger.debug( + "[getPegoutCreationInformationFromEvent] Found transaction {} and block {}", + transactionReceipt.getTransaction().getHash(), + block.getHash() + ); + return Optional.of( + new PegoutCreationInformation( + block, + transactionReceipt, + pegoutCreationRskTxHash, + pegoutBtcTx, + pegoutConfirmationRskTxHash + ) + ); + } + } + } + return Optional.empty(); + } +} diff --git a/src/main/java/co/rsk/federate/signing/hsm/message/PowHSMSignerMessageBuilder.java b/src/main/java/co/rsk/federate/signing/hsm/message/PowHSMSignerMessageBuilder.java index d6e78d249..78079b094 100644 --- a/src/main/java/co/rsk/federate/signing/hsm/message/PowHSMSignerMessageBuilder.java +++ b/src/main/java/co/rsk/federate/signing/hsm/message/PowHSMSignerMessageBuilder.java @@ -22,11 +22,11 @@ public class PowHSMSignerMessageBuilder extends SignerMessageBuilder { public PowHSMSignerMessageBuilder( ReceiptStore receiptStore, - ReleaseCreationInformation releaseCreationInformation) { - super(releaseCreationInformation.getBtcTransaction()); + PegoutCreationInformation pegoutCreationInformation) { + super(pegoutCreationInformation.getPegoutBtcTx()); - this.txReceipt = releaseCreationInformation.getTransactionReceipt(); - this.rskBlock = releaseCreationInformation.getBlock(); + this.txReceipt = pegoutCreationInformation.getTransactionReceipt(); + this.rskBlock = pegoutCreationInformation.getPegoutCreationRskBlock(); this.receiptStore = receiptStore; this.envelopeCreated = false; } diff --git a/src/main/java/co/rsk/federate/signing/hsm/message/ReleaseCreationInformation.java b/src/main/java/co/rsk/federate/signing/hsm/message/ReleaseCreationInformation.java deleted file mode 100644 index b5b73b9d9..000000000 --- a/src/main/java/co/rsk/federate/signing/hsm/message/ReleaseCreationInformation.java +++ /dev/null @@ -1,79 +0,0 @@ -package co.rsk.federate.signing.hsm.message; - -import co.rsk.bitcoinj.core.BtcTransaction; -import co.rsk.crypto.Keccak256; -import org.ethereum.core.Block; -import org.ethereum.core.TransactionReceipt; - -public class ReleaseCreationInformation { - private final Block block; - private final TransactionReceipt transactionReceipt; - private final Keccak256 releaseRskTxHash; - private final Keccak256 informingRskTxHash; - private final BtcTransaction btcTransaction; - - - /** - * - * @param block The rsk block where the BTC transaction was created - * @param transactionReceipt The rsk transaction receipt where the btc transaction was created - * @param releaseRskTxHash The rsk transaction hash where the release was requested - * @param btcTransaction The BTC transaction to sign - **/ - public ReleaseCreationInformation( - Block block, - TransactionReceipt transactionReceipt, - Keccak256 releaseRskTxHash, - BtcTransaction btcTransaction - ) { - this(block, transactionReceipt, releaseRskTxHash, btcTransaction, releaseRskTxHash); - } - - /** - * - * @param block The rsk block where the BTC transaction was created - * @param transactionReceipt The rsk transaction receipt where the btc transaction was created - * @param releaseRskTxHash The rsk transaction hash where the release was requested - * @param btcTransaction The BTC transaction to sign - * @param informingRskTxHash The rsk transaction hash where the release was confirmed to be signed - **/ - public ReleaseCreationInformation( - Block block, - TransactionReceipt transactionReceipt, - Keccak256 releaseRskTxHash, - BtcTransaction btcTransaction, - Keccak256 informingRskTxHash - ) { - this.block = block; - this.transactionReceipt = transactionReceipt; - this.releaseRskTxHash = releaseRskTxHash; - this.btcTransaction = btcTransaction; - this.informingRskTxHash = informingRskTxHash; - } - - public Block getBlock() { - return block; - } - - /** - * gets the receipt of the rsk transaction that created the release BTC transaction - **/ - public TransactionReceipt getTransactionReceipt() { - return transactionReceipt; - } - - /** - * gets the hash of the rsk transaction that originated the release - **/ - public Keccak256 getReleaseRskTxHash() { - return releaseRskTxHash; - } - - public Keccak256 getInformingRskTxHash() { - return informingRskTxHash; - } - - public BtcTransaction getBtcTransaction() { - return btcTransaction; - } -} diff --git a/src/main/java/co/rsk/federate/signing/hsm/message/ReleaseCreationInformationGetter.java b/src/main/java/co/rsk/federate/signing/hsm/message/ReleaseCreationInformationGetter.java deleted file mode 100644 index 9eda22a7f..000000000 --- a/src/main/java/co/rsk/federate/signing/hsm/message/ReleaseCreationInformationGetter.java +++ /dev/null @@ -1,208 +0,0 @@ -package co.rsk.federate.signing.hsm.message; - -import co.rsk.bitcoinj.core.BtcTransaction; -import co.rsk.crypto.Keccak256; -import co.rsk.peg.BridgeEvents; -import org.ethereum.core.Block; -import org.ethereum.core.CallTransaction; -import org.ethereum.core.Transaction; -import org.ethereum.core.TransactionReceipt; -import org.ethereum.db.BlockStore; -import org.ethereum.db.ReceiptStore; -import org.ethereum.db.TransactionInfo; -import org.ethereum.vm.LogInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -// First the class tries to find the event associated with the transaction. If it cannot find it, it requests the following -// events until it is found or until it reaches the last block. -public class ReleaseCreationInformationGetter { - private static final Logger logger = LoggerFactory.getLogger(ReleaseCreationInformationGetter.class); - - private final BlockStore blockStore; - private final ReceiptStore receiptStore; - private final byte[] releaseRequestedSignatureTopic; - - public ReleaseCreationInformationGetter( - ReceiptStore receiptStore, - BlockStore blockStore - ) { - this.blockStore = blockStore; - this.receiptStore = receiptStore; - - CallTransaction.Function releaseRequestedEvent = BridgeEvents.RELEASE_REQUESTED.getEvent(); - releaseRequestedSignatureTopic = releaseRequestedEvent.encodeSignatureLong(); - } - - /* Use this method if the originating rsk tx hash and the informing rsk tx hash match */ - public ReleaseCreationInformation getTxInfoToSign( - int version, - Keccak256 rskTxHash, - BtcTransaction btcTransaction - ) throws HSMReleaseCreationInformationException { - return getTxInfoToSign(version, rskTxHash, btcTransaction, rskTxHash); - } - - public ReleaseCreationInformation getTxInfoToSign( - int version, - Keccak256 rskTxHash, - BtcTransaction btcTransaction, - Keccak256 informingRskTxHash - ) throws HSMReleaseCreationInformationException { - if (version == 1) { - return getBaseReleaseCreationInformation(rskTxHash, btcTransaction, informingRskTxHash); - } else if (version >= 2) { - return getTxInfoToSignVersion2(rskTxHash, btcTransaction, informingRskTxHash); - } else { - throw new HSMReleaseCreationInformationException("Unsupported version " + version); - } - } - - protected ReleaseCreationInformation getBaseReleaseCreationInformation( - Keccak256 rskTxHash, - BtcTransaction btcTransaction, - Keccak256 informingRskTxHash - ) throws HSMReleaseCreationInformationException { - TransactionInfo transactionInfo = receiptStore.getInMainChain(rskTxHash.getBytes(), blockStore).orElse(null); - if (transactionInfo == null) { - String message = String.format( - "Transaction hash %s could not be found in best chain", - rskTxHash - ); - logger.error("[getTxInfoToSign] {}", message); - throw new HSMReleaseCreationInformationException(message); - } - TransactionReceipt transactionReceipt = transactionInfo.getReceipt(); - Block block = blockStore.getBlockByHash(transactionInfo.getBlockHash()); - - return new ReleaseCreationInformation( - block, - transactionReceipt, - rskTxHash, - btcTransaction, - informingRskTxHash - ); - } - - protected ReleaseCreationInformation getTxInfoToSignVersion2( - Keccak256 rskTxHash, - BtcTransaction btcTransaction, - Keccak256 informingRskTxHash - ) throws HSMReleaseCreationInformationException { - try { - ReleaseCreationInformation baseReleaseCreationInformation = - getBaseReleaseCreationInformation(rskTxHash, btcTransaction, informingRskTxHash); - Block block = baseReleaseCreationInformation.getBlock(); - TransactionReceipt transactionReceipt = baseReleaseCreationInformation.getTransactionReceipt(); - - // Get transaction from the block, searching by tx hash, and set it in the tx receipt - logger.trace("[getTxInfoToSign] Searching for transaction {} in block {} ({})", rskTxHash, block.getHash(), block.getNumber()); - List transactions = block.getTransactionsList().stream() - .filter(t -> t.getHash().equals(rskTxHash)) - .collect(Collectors.toList()); - logger.trace("[getTxInfoToSign] Transactions found {}", transactions.size()); - if(transactions.size() != 1) { - String message = String.format( - "Transaction hash %s could not be found in block %s or more than 1 result obtained. Filter size: %d", - rskTxHash, - block.getHash().toHexString(), - transactions.size() - ); - logger.error("[getTxInfoToSign] {}", message); - throw new HSMReleaseCreationInformationException(message); - } - Transaction transaction = transactions.get(0); - transactionReceipt.setTransaction(transaction); - - return searchEventInFollowingBlocks(block.getNumber(), btcTransaction, rskTxHash, informingRskTxHash); - } catch (Exception e) { - throw new HSMReleaseCreationInformationException("Unhandled exception occured", e); - } - } - - private ReleaseCreationInformation searchEventInFollowingBlocks( - long blockNumber, - BtcTransaction btcTransaction, - Keccak256 rskTxHash, - Keccak256 informingRskTxHash - ) throws HSMReleaseCreationInformationException { - Block block = blockStore.getChainBlockByNumber(blockNumber); - // If the block cannot be found by its number, the event cannot be searched further. - if (block == null) { - throw new HSMReleaseCreationInformationException( - String.format("[searchEventInFollowingBlocks] Block not found. Transaction hash: [%s]", rskTxHash) - ); - } - - logger.trace( - "[searchEventInFollowingBlocks] searching in block {}. Has {} transactions", - blockNumber, - block.getTransactionsList().size() - ); - for (Transaction transaction : block.getTransactionsList()) { - TransactionInfo transactionInfo = receiptStore.getInMainChain(transaction.getHash().getBytes(), blockStore).orElse(null); - TransactionReceipt transactionReceipt = transactionInfo.getReceipt(); - transactionReceipt.setTransaction(transaction); - Optional optionalReleaseCreationInformation = - getInformationFromEvent(block, transactionReceipt, btcTransaction, rskTxHash, informingRskTxHash); - if (optionalReleaseCreationInformation.isPresent()) { - return optionalReleaseCreationInformation.get(); - } - - } - // If the block being checked is the last block, and was not found, then the event does not exist. - if (block.getNumber() == (blockStore.getBestBlock().getNumber())) { - throw new HSMReleaseCreationInformationException( - String.format("[searchEventInFollowingBlocks] Event not found. Transaction hash: [%s]", rskTxHash) - ); - } - // If the event was not found in this block, the next block is requested and the same search is performed. - return searchEventInFollowingBlocks(blockNumber + 1, btcTransaction, rskTxHash, informingRskTxHash); - } - - private Optional getInformationFromEvent( - Block block, - TransactionReceipt transactionReceipt, - BtcTransaction btcTransaction, - Keccak256 releaseRskTxHash, - Keccak256 informingRskTxHash - ) { - boolean hasLogs = !transactionReceipt.getLogInfoList().isEmpty(); - logger.trace( - "[getInformationFromEvent] tx ({}) in block ({} - {}). has logs? {}", - transactionReceipt.getTransaction().getHash(), - block.getNumber(), - block.getHash(), - hasLogs - ); - if (hasLogs) { - List logs = transactionReceipt.getLogInfoList(); - for (LogInfo logInfo : logs) { - // You should check that the event is Release and contains the hash of the transaction. - boolean hasReleaseRequestEvent = Arrays.equals(logInfo.getTopics().get(0).getData(), releaseRequestedSignatureTopic); - if (hasReleaseRequestEvent && (Arrays.equals(logInfo.getTopics().get(2).getData(), btcTransaction.getHash().getBytes()))) { - logger.debug( - "[getInformationFromEvent] Found transaction {} and block {}", - transactionReceipt.getTransaction().getHash(), - block.getHash() - ); - return Optional.of( - new ReleaseCreationInformation( - block, - transactionReceipt, - releaseRskTxHash, - btcTransaction, - informingRskTxHash - ) - ); - } - } - } - return Optional.empty(); - } -} diff --git a/src/main/java/co/rsk/federate/signing/hsm/message/SignerMessageBuilderFactory.java b/src/main/java/co/rsk/federate/signing/hsm/message/SignerMessageBuilderFactory.java index da3295a40..6f0295b10 100644 --- a/src/main/java/co/rsk/federate/signing/hsm/message/SignerMessageBuilderFactory.java +++ b/src/main/java/co/rsk/federate/signing/hsm/message/SignerMessageBuilderFactory.java @@ -16,13 +16,13 @@ public SignerMessageBuilderFactory(ReceiptStore receiptStore) { public SignerMessageBuilder buildFromConfig( int version, - ReleaseCreationInformation releaseCreationInformation + PegoutCreationInformation pegoutCreationInformation ) throws HSMUnsupportedVersionException { SignerMessageBuilder messageBuilder; if (version == 1) { - messageBuilder = new SignerMessageBuilderV1(releaseCreationInformation.getBtcTransaction()); + messageBuilder = new SignerMessageBuilderV1(pegoutCreationInformation.getPegoutBtcTx()); } else if (version >= 2) { - messageBuilder = new PowHSMSignerMessageBuilder(receiptStore, releaseCreationInformation); + messageBuilder = new PowHSMSignerMessageBuilder(receiptStore, pegoutCreationInformation); } else { String message = String.format("Unsupported HSM signer version: %d", version); logger.debug("[buildFromConfig] {}", message); diff --git a/src/main/java/co/rsk/federate/signing/hsm/requirements/PegoutSigningRequirementsEnforcer.java b/src/main/java/co/rsk/federate/signing/hsm/requirements/PegoutSigningRequirementsEnforcer.java new file mode 100644 index 000000000..c271866af --- /dev/null +++ b/src/main/java/co/rsk/federate/signing/hsm/requirements/PegoutSigningRequirementsEnforcer.java @@ -0,0 +1,37 @@ +package co.rsk.federate.signing.hsm.requirements; + +import co.rsk.federate.signing.hsm.message.PegoutCreationInformation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PegoutSigningRequirementsEnforcer { + private static final Logger logger = LoggerFactory.getLogger(PegoutSigningRequirementsEnforcer.class); + + private final AncestorBlockUpdater ancestorBlockUpdater; + + public PegoutSigningRequirementsEnforcer(AncestorBlockUpdater ancestorBlockUpdater) { + this.ancestorBlockUpdater = ancestorBlockUpdater; + } + + public void enforce(int version, PegoutCreationInformation pegoutCreationInformation) + throws PegoutSigningRequirementsEnforcerException { + if (version == 1) { + logger.trace("[enforce] Version 1 doesn't have pegout requirements to enforce"); + } else if (version >= 2) { + logger.trace("[enforce] Version 2+ requires ancestor in position. ENFORCING"); + enforcePegoutRequirements(pegoutCreationInformation); + } else { + throw new PegoutSigningRequirementsEnforcerException("Unsupported version " + version); + } + } + + private void enforcePegoutRequirements(PegoutCreationInformation pegoutCreationInformation) throws PegoutSigningRequirementsEnforcerException { + try { + ancestorBlockUpdater.ensureAncestorBlockInPosition(pegoutCreationInformation.getPegoutCreationRskBlock()); + } catch (Exception e) { + String message = "error trying to enforce ancestor"; + logger.error("[enforce] " + message, e); + throw new PegoutSigningRequirementsEnforcerException(message, e); + } + } +} diff --git a/src/main/java/co/rsk/federate/signing/hsm/requirements/PegoutSigningRequirementsEnforcerException.java b/src/main/java/co/rsk/federate/signing/hsm/requirements/PegoutSigningRequirementsEnforcerException.java new file mode 100644 index 000000000..5bf455622 --- /dev/null +++ b/src/main/java/co/rsk/federate/signing/hsm/requirements/PegoutSigningRequirementsEnforcerException.java @@ -0,0 +1,11 @@ +package co.rsk.federate.signing.hsm.requirements; + +public class PegoutSigningRequirementsEnforcerException extends Exception { + public PegoutSigningRequirementsEnforcerException(String message) { + super(message); + } + + public PegoutSigningRequirementsEnforcerException(String message, Throwable t) { + super(message, t); + } +} diff --git a/src/main/java/co/rsk/federate/signing/hsm/requirements/ReleaseRequirementsEnforcer.java b/src/main/java/co/rsk/federate/signing/hsm/requirements/ReleaseRequirementsEnforcer.java deleted file mode 100644 index 81b47b10a..000000000 --- a/src/main/java/co/rsk/federate/signing/hsm/requirements/ReleaseRequirementsEnforcer.java +++ /dev/null @@ -1,37 +0,0 @@ -package co.rsk.federate.signing.hsm.requirements; - -import co.rsk.federate.signing.hsm.message.ReleaseCreationInformation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ReleaseRequirementsEnforcer { - private static final Logger logger = LoggerFactory.getLogger(ReleaseRequirementsEnforcer.class); - - private final AncestorBlockUpdater ancestorBlockUpdater; - - public ReleaseRequirementsEnforcer(AncestorBlockUpdater ancestorBlockUpdater) { - this.ancestorBlockUpdater = ancestorBlockUpdater; - } - - public void enforce(int version, ReleaseCreationInformation releaseCreationInformation) - throws ReleaseRequirementsEnforcerException { - if (version == 1) { - logger.trace("[enforce] Version 1 doesn't have release requirements to enforce"); - } else if (version >= 2) { - logger.trace("[enforce] Version 2+ requires ancestor in position. ENFORCING"); - enforceReleaseRequirements(releaseCreationInformation); - } else { - throw new ReleaseRequirementsEnforcerException("Unsupported version " + version); - } - } - - private void enforceReleaseRequirements(ReleaseCreationInformation releaseCreationInformation) throws ReleaseRequirementsEnforcerException { - try { - ancestorBlockUpdater.ensureAncestorBlockInPosition(releaseCreationInformation.getBlock()); - } catch (Exception e) { - String message = "error trying to enforce ancestor"; - logger.error("[enforce]" + message, e); - throw new ReleaseRequirementsEnforcerException(message, e); - } - } -} diff --git a/src/main/java/co/rsk/federate/signing/hsm/requirements/ReleaseRequirementsEnforcerException.java b/src/main/java/co/rsk/federate/signing/hsm/requirements/ReleaseRequirementsEnforcerException.java deleted file mode 100644 index 8421bb35b..000000000 --- a/src/main/java/co/rsk/federate/signing/hsm/requirements/ReleaseRequirementsEnforcerException.java +++ /dev/null @@ -1,11 +0,0 @@ -package co.rsk.federate.signing.hsm.requirements; - -public class ReleaseRequirementsEnforcerException extends Exception { - public ReleaseRequirementsEnforcerException(String message) { - super(message); - } - - public ReleaseRequirementsEnforcerException(String message, Throwable t) { - super(message, t); - } -} diff --git a/src/main/java/co/rsk/federate/util/HSMChecker.java b/src/main/java/co/rsk/federate/util/HSMChecker.java index d4e2a800d..7311dff20 100644 --- a/src/main/java/co/rsk/federate/util/HSMChecker.java +++ b/src/main/java/co/rsk/federate/util/HSMChecker.java @@ -30,6 +30,7 @@ import co.rsk.federate.signing.hsm.message.SignerMessageV1; import org.ethereum.crypto.ECKey; import org.bouncycastle.util.encoders.Hex; +import org.ethereum.crypto.signature.ECDSASignature; import java.util.Arrays; import java.util.Random; @@ -85,7 +86,7 @@ public static void main(String[] args) { System.out.printf("Public key: %s\n", Hex.toHexString(hsmPublicKey.getPubKey())); HSMSignature hsmSignature = client.sign(keyId, messageObject); - ECKey.ECDSASignature signature = hsmSignature.toEthSignature(); + ECDSASignature signature = hsmSignature.toEthSignature(); boolean signatureValid = hsmPublicKey.verify(MESSAGE_HASH.getBytes(), signature); diff --git a/src/test/java/co/rsk/federate/FedNodeRunnerTest.java b/src/test/java/co/rsk/federate/FedNodeRunnerTest.java index bbb8949ea..985ae6bdd 100644 --- a/src/test/java/co/rsk/federate/FedNodeRunnerTest.java +++ b/src/test/java/co/rsk/federate/FedNodeRunnerTest.java @@ -15,7 +15,7 @@ import co.rsk.NodeRunner; import co.rsk.bitcoinj.core.NetworkParameters; import co.rsk.config.BridgeConstants; -import co.rsk.federate.btcreleaseclient.BtcReleaseClient; +import co.rsk.federate.btcreleaseclient.BtcPegoutClient; import co.rsk.federate.config.FedNodeSystemProperties; import co.rsk.federate.config.SignerConfig; import co.rsk.federate.log.FederateLogger; @@ -85,7 +85,7 @@ void setUp() throws IOException, HSMClientException { fedNodeRunner = new FedNodeRunner( mock(BtcToRskClient.class), mock(BtcToRskClient.class), - mock(BtcReleaseClient.class), + mock(BtcPegoutClient.class), mock(FederationWatcher.class), mock(FederatorSupport.class), mock(FederateLogger.class), @@ -145,7 +145,7 @@ void test_with_hsm_v1_config() throws Exception { fedNodeRunner = new FedNodeRunner( mock(BtcToRskClient.class), mock(BtcToRskClient.class), - mock(BtcReleaseClient.class), + mock(BtcPegoutClient.class), mock(FederationWatcher.class), mock(FederatorSupport.class), mock(FederateLogger.class), diff --git a/src/test/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageAccessorTest.java b/src/test/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageAccessorTest.java similarity index 65% rename from src/test/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageAccessorTest.java rename to src/test/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageAccessorTest.java index 2d16c409f..07858e06b 100644 --- a/src/test/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageAccessorTest.java +++ b/src/test/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageAccessorTest.java @@ -18,9 +18,9 @@ import co.rsk.bitcoinj.core.Sha256Hash; import co.rsk.crypto.Keccak256; -import co.rsk.federate.io.btcreleaseclientstorage.BtcReleaseClientFileData; -import co.rsk.federate.io.btcreleaseclientstorage.BtcReleaseClientFileReadResult; -import co.rsk.federate.io.btcreleaseclientstorage.BtcReleaseClientFileStorage; +import co.rsk.federate.io.btcreleaseclientstorage.BtcPegoutClientFileData; +import co.rsk.federate.io.btcreleaseclientstorage.BtcPegoutClientFileReadResult; +import co.rsk.federate.io.btcreleaseclientstorage.BtcPegoutClientFileStorage; import java.io.IOException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -29,18 +29,18 @@ import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; -class BtcReleaseClientStorageAccessorTest { +class BtcPegoutClientStorageAccessorTest { @Test void invalid_file() throws IOException { - BtcReleaseClientFileStorage btcReleaseClientFileStorage = mock(BtcReleaseClientFileStorage.class); - when(btcReleaseClientFileStorage.read()).thenReturn( - new BtcReleaseClientFileReadResult(false, null) + BtcPegoutClientFileStorage btcPegoutClientFileStorage = mock(BtcPegoutClientFileStorage.class); + when(btcPegoutClientFileStorage.read()).thenReturn( + new BtcPegoutClientFileReadResult(false, null) ); - assertThrows(InvalidStorageFileException.class, () -> new BtcReleaseClientStorageAccessor( + assertThrows(InvalidStorageFileException.class, () -> new BtcPegoutClientStorageAccessor( getImmediateTaskExecutor(), - btcReleaseClientFileStorage, + btcPegoutClientFileStorage, 10, 1 )); @@ -48,14 +48,14 @@ void invalid_file() throws IOException { @Test void works_with_no_file() throws InvalidStorageFileException, IOException { - BtcReleaseClientFileStorage btcReleaseClientFileStorage = mock(BtcReleaseClientFileStorage.class); - when(btcReleaseClientFileStorage.read()).thenReturn( - new BtcReleaseClientFileReadResult(true, new BtcReleaseClientFileData()) + BtcPegoutClientFileStorage btcPegoutClientFileStorage = mock(BtcPegoutClientFileStorage.class); + when(btcPegoutClientFileStorage.read()).thenReturn( + new BtcPegoutClientFileReadResult(true, new BtcPegoutClientFileData()) ); - BtcReleaseClientStorageAccessor storageAccessor = new BtcReleaseClientStorageAccessor( + BtcPegoutClientStorageAccessor storageAccessor = new BtcPegoutClientStorageAccessor( getImmediateTaskExecutor(), - btcReleaseClientFileStorage, + btcPegoutClientFileStorage, 10, 1 ); @@ -68,17 +68,17 @@ void works_with_no_file() throws InvalidStorageFileException, IOException { void getBestBlockHash_ok() throws IOException, InvalidStorageFileException { Keccak256 bestBlockHash = createHash(1); - BtcReleaseClientFileData btcReleaseClientFileData = new BtcReleaseClientFileData(); - btcReleaseClientFileData.setBestBlockHash(bestBlockHash); + BtcPegoutClientFileData btcPegoutClientFileData = new BtcPegoutClientFileData(); + btcPegoutClientFileData.setBestBlockHash(bestBlockHash); - BtcReleaseClientFileStorage btcReleaseClientFileStorage = mock(BtcReleaseClientFileStorage.class); - when(btcReleaseClientFileStorage.read()).thenReturn( - new BtcReleaseClientFileReadResult(true, btcReleaseClientFileData) + BtcPegoutClientFileStorage btcPegoutClientFileStorage = mock(BtcPegoutClientFileStorage.class); + when(btcPegoutClientFileStorage.read()).thenReturn( + new BtcPegoutClientFileReadResult(true, btcPegoutClientFileData) ); - BtcReleaseClientStorageAccessor storageAccessor = new BtcReleaseClientStorageAccessor( + BtcPegoutClientStorageAccessor storageAccessor = new BtcPegoutClientStorageAccessor( getImmediateTaskExecutor(), - btcReleaseClientFileStorage, + btcPegoutClientFileStorage, 0, 0 ); @@ -91,14 +91,14 @@ void getBestBlockHash_ok() throws IOException, InvalidStorageFileException { void setBestBlockHash_ok() throws InvalidStorageFileException, IOException { Keccak256 bestBlockHash = createHash(1); - BtcReleaseClientFileStorage btcReleaseClientFileStorage = mock(BtcReleaseClientFileStorage.class); - when(btcReleaseClientFileStorage.read()).thenReturn( - new BtcReleaseClientFileReadResult(true, new BtcReleaseClientFileData()) + BtcPegoutClientFileStorage btcPegoutClientFileStorage = mock(BtcPegoutClientFileStorage.class); + when(btcPegoutClientFileStorage.read()).thenReturn( + new BtcPegoutClientFileReadResult(true, new BtcPegoutClientFileData()) ); - BtcReleaseClientStorageAccessor storageAccessor = new BtcReleaseClientStorageAccessor( + BtcPegoutClientStorageAccessor storageAccessor = new BtcPegoutClientStorageAccessor( getImmediateTaskExecutor(), - btcReleaseClientFileStorage, + btcPegoutClientFileStorage, 10, 1 ); @@ -114,17 +114,17 @@ void getRskTxHash_and_hasBtcTxHash_ok() throws IOException, InvalidStorageFileEx Sha256Hash btcTxHash = Sha256Hash.of(new byte[]{1}); Keccak256 rskTxHash = createHash(1); - BtcReleaseClientFileData btcReleaseClientFileData = new BtcReleaseClientFileData(); - btcReleaseClientFileData.getReleaseHashesMap().put(btcTxHash, rskTxHash); + BtcPegoutClientFileData btcPegoutClientFileData = new BtcPegoutClientFileData(); + btcPegoutClientFileData.getPegoutHashesMap().put(btcTxHash, rskTxHash); - BtcReleaseClientFileStorage btcReleaseClientFileStorage = mock(BtcReleaseClientFileStorage.class); - when(btcReleaseClientFileStorage.read()).thenReturn( - new BtcReleaseClientFileReadResult(true, btcReleaseClientFileData) + BtcPegoutClientFileStorage btcPegoutClientFileStorage = mock(BtcPegoutClientFileStorage.class); + when(btcPegoutClientFileStorage.read()).thenReturn( + new BtcPegoutClientFileReadResult(true, btcPegoutClientFileData) ); - BtcReleaseClientStorageAccessor storageAccessor = new BtcReleaseClientStorageAccessor( + BtcPegoutClientStorageAccessor storageAccessor = new BtcPegoutClientStorageAccessor( getImmediateTaskExecutor(), - btcReleaseClientFileStorage, + btcPegoutClientFileStorage, 0, 0 ); @@ -146,21 +146,21 @@ void putBtcTxHashRskTxHash_ok() throws InvalidStorageFileException, IOException return null; }).when(executorService).schedule(any(Runnable.class), anyLong(), any()); - BtcReleaseClientFileStorage btcReleaseClientFileStorage = mock(BtcReleaseClientFileStorage.class); - when(btcReleaseClientFileStorage.read()).thenReturn( - new BtcReleaseClientFileReadResult(true, new BtcReleaseClientFileData()) + BtcPegoutClientFileStorage btcPegoutClientFileStorage = mock(BtcPegoutClientFileStorage.class); + when(btcPegoutClientFileStorage.read()).thenReturn( + new BtcPegoutClientFileReadResult(true, new BtcPegoutClientFileData()) ); - BtcReleaseClientStorageAccessor storageAccessor = new BtcReleaseClientStorageAccessor( + BtcPegoutClientStorageAccessor storageAccessor = new BtcPegoutClientStorageAccessor( executorService, - btcReleaseClientFileStorage, + btcPegoutClientFileStorage, 10, 1 ); storageAccessor.putBtcTxHashRskTxHash(btcTxHash, rskTxHash); - verify(btcReleaseClientFileStorage, times(1)).write(any(BtcReleaseClientFileData.class)); + verify(btcPegoutClientFileStorage, times(1)).write(any(BtcPegoutClientFileData.class)); assertEquals(1, storageAccessor.getMapSize()); assertTrue(storageAccessor.hasBtcTxHash(btcTxHash)); @@ -180,14 +180,14 @@ void writes_to_file() throws InvalidStorageFileException, IOException { return null; }).when(executorService).schedule(any(Runnable.class), anyLong(), any()); - BtcReleaseClientFileStorage btcReleaseClientFileStorage = mock(BtcReleaseClientFileStorage.class); - when(btcReleaseClientFileStorage.read()).thenReturn( - new BtcReleaseClientFileReadResult(true, new BtcReleaseClientFileData()) + BtcPegoutClientFileStorage btcPegoutClientFileStorage = mock(BtcPegoutClientFileStorage.class); + when(btcPegoutClientFileStorage.read()).thenReturn( + new BtcPegoutClientFileReadResult(true, new BtcPegoutClientFileData()) ); - BtcReleaseClientStorageAccessor storageAccessor = new BtcReleaseClientStorageAccessor( + BtcPegoutClientStorageAccessor storageAccessor = new BtcPegoutClientStorageAccessor( executorService, - btcReleaseClientFileStorage, + btcPegoutClientFileStorage, 10, 2 ); @@ -196,7 +196,7 @@ void writes_to_file() throws InvalidStorageFileException, IOException { storageAccessor.setBestBlockHash(bestBlockHash); // As we are not using delays it writes for each call to the storage changing methods - verify(btcReleaseClientFileStorage, times(2)).write(any(BtcReleaseClientFileData.class)); + verify(btcPegoutClientFileStorage, times(2)).write(any(BtcPegoutClientFileData.class)); } @Test @@ -223,14 +223,14 @@ void multiple_sets_delay_writing() throws IOException, InvalidStorageFileExcepti return task; }).when(executorService).schedule(any(Runnable.class), anyLong(), any()); - BtcReleaseClientFileStorage btcReleaseClientFileStorage = mock(BtcReleaseClientFileStorage.class); - when(btcReleaseClientFileStorage.read()).thenReturn( - new BtcReleaseClientFileReadResult(true, new BtcReleaseClientFileData()) + BtcPegoutClientFileStorage btcPegoutClientFileStorage = mock(BtcPegoutClientFileStorage.class); + when(btcPegoutClientFileStorage.read()).thenReturn( + new BtcPegoutClientFileReadResult(true, new BtcPegoutClientFileData()) ); - BtcReleaseClientStorageAccessor storageAccessor = new BtcReleaseClientStorageAccessor( + BtcPegoutClientStorageAccessor storageAccessor = new BtcPegoutClientStorageAccessor( executorService, - btcReleaseClientFileStorage, + btcPegoutClientFileStorage, 400, maxDelays ); @@ -240,12 +240,12 @@ void multiple_sets_delay_writing() throws IOException, InvalidStorageFileExcepti storageAccessor.putBtcTxHashRskTxHash(btcTxHash2, rskTxHash2); - verify(btcReleaseClientFileStorage, never()).write(any(BtcReleaseClientFileData.class)); + verify(btcPegoutClientFileStorage, never()).write(any(BtcPegoutClientFileData.class)); // the forth call should trigger the writing storageAccessor.setBestBlockHash(bestBlockHash2); - verify(btcReleaseClientFileStorage, times(1)).write(any(BtcReleaseClientFileData.class)); + verify(btcPegoutClientFileStorage, times(1)).write(any(BtcPegoutClientFileData.class)); // It should have cancelled the overlapping tasks verify(task, times(3)).cancel(anyBoolean()); @@ -275,14 +275,14 @@ void forces_writing_after_max_delay() throws InvalidStorageFileException, IOExce return task; }).when(executorService).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); - BtcReleaseClientFileStorage btcReleaseClientFileStorage = mock(BtcReleaseClientFileStorage.class); - when(btcReleaseClientFileStorage.read()).thenReturn( - new BtcReleaseClientFileReadResult(true, new BtcReleaseClientFileData()) + BtcPegoutClientFileStorage btcPegoutClientFileStorage = mock(BtcPegoutClientFileStorage.class); + when(btcPegoutClientFileStorage.read()).thenReturn( + new BtcPegoutClientFileReadResult(true, new BtcPegoutClientFileData()) ); - BtcReleaseClientStorageAccessor storageAccessor = new BtcReleaseClientStorageAccessor( + BtcPegoutClientStorageAccessor storageAccessor = new BtcPegoutClientStorageAccessor( executorService, - btcReleaseClientFileStorage, + btcPegoutClientFileStorage, 500, maxDelays ); diff --git a/src/test/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageSynchronizerTest.java b/src/test/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageSynchronizerTest.java similarity index 91% rename from src/test/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageSynchronizerTest.java rename to src/test/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageSynchronizerTest.java index d92271d6f..ded0cdaf7 100644 --- a/src/test/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientStorageSynchronizerTest.java +++ b/src/test/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientStorageSynchronizerTest.java @@ -40,16 +40,16 @@ import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -class BtcReleaseClientStorageSynchronizerTest { +class BtcPegoutClientStorageSynchronizerTest { @Test void isSynced_returns_false_after_instantiation() { - BtcReleaseClientStorageSynchronizer storageSynchronizer = - new BtcReleaseClientStorageSynchronizer( + BtcPegoutClientStorageSynchronizer storageSynchronizer = + new BtcPegoutClientStorageSynchronizer( mock(BlockStore.class), mock(ReceiptStore.class), mock(NodeBlockProcessor.class), - mock(BtcReleaseClientStorageAccessor.class), + mock(BtcPegoutClientStorageAccessor.class), mock(ScheduledExecutorService.class), // Don't specify behavior for syncing to avoid syncing 1000, 100, @@ -61,10 +61,10 @@ void isSynced_returns_false_after_instantiation() { @Test void processBlock_before_sync_doesnt_do_anything() { - BtcReleaseClientStorageAccessor storageAccessor = mock(BtcReleaseClientStorageAccessor.class); + BtcPegoutClientStorageAccessor storageAccessor = mock(BtcPegoutClientStorageAccessor.class); - BtcReleaseClientStorageSynchronizer storageSynchronizer = - new BtcReleaseClientStorageSynchronizer( + BtcPegoutClientStorageSynchronizer storageSynchronizer = + new BtcPegoutClientStorageSynchronizer( mock(BlockStore.class), mock(ReceiptStore.class), mock(NodeBlockProcessor.class), @@ -102,12 +102,12 @@ void isSynced_returns_true_after_sync() { return null; }).when(mockedExecutor).scheduleAtFixedRate(any(), anyLong(), anyLong(), any()); - BtcReleaseClientStorageSynchronizer storageSynchronizer = - new BtcReleaseClientStorageSynchronizer( + BtcPegoutClientStorageSynchronizer storageSynchronizer = + new BtcPegoutClientStorageSynchronizer( blockStore, mock(ReceiptStore.class), mock(NodeBlockProcessor.class), - mock(BtcReleaseClientStorageAccessor.class), + mock(BtcPegoutClientStorageAccessor.class), mockedExecutor, 0, 1, @@ -133,7 +133,7 @@ void syncs_from_last_stored_block() { when(blockStore.getChainBlockByNumber(2L)).thenReturn(bestBlock); when(blockStore.getBestBlock()).thenReturn(bestBlock); - BtcReleaseClientStorageAccessor storageAccessor = mock(BtcReleaseClientStorageAccessor.class); + BtcPegoutClientStorageAccessor storageAccessor = mock(BtcPegoutClientStorageAccessor.class); when(storageAccessor.getBestBlockHash()).thenReturn(Optional.of(firstHash)); ScheduledExecutorService mockedExecutor = mock(ScheduledExecutorService.class); @@ -144,8 +144,8 @@ void syncs_from_last_stored_block() { }).when(mockedExecutor).scheduleAtFixedRate(any(), anyLong(), anyLong(), any()); - BtcReleaseClientStorageSynchronizer storageSynchronizer = - new BtcReleaseClientStorageSynchronizer( + BtcPegoutClientStorageSynchronizer storageSynchronizer = + new BtcPegoutClientStorageSynchronizer( blockStore, mock(ReceiptStore.class), mock(NodeBlockProcessor.class), @@ -218,7 +218,7 @@ void processBlock_ok() { when(blockStore.getBestBlock()).thenReturn(bestBlock); - BtcReleaseClientStorageAccessor storageAccessor = mock(BtcReleaseClientStorageAccessor.class); + BtcPegoutClientStorageAccessor storageAccessor = mock(BtcPegoutClientStorageAccessor.class); ScheduledExecutorService mockedExecutor = mock(ScheduledExecutorService.class); // Mock the executor to execute immediately @@ -227,8 +227,8 @@ void processBlock_ok() { return null; }).when(mockedExecutor).scheduleAtFixedRate(any(), anyLong(), anyLong(), any()); - BtcReleaseClientStorageSynchronizer storageSynchronizer = - new BtcReleaseClientStorageSynchronizer( + BtcPegoutClientStorageSynchronizer storageSynchronizer = + new BtcPegoutClientStorageSynchronizer( blockStore, mock(ReceiptStore.class), mock(NodeBlockProcessor.class), @@ -327,7 +327,7 @@ void accepts_transaction_with_two_release_requested() { when(blockStore.getBestBlock()).thenReturn(bestBlock); - BtcReleaseClientStorageAccessor storageAccessor = mock(BtcReleaseClientStorageAccessor.class); + BtcPegoutClientStorageAccessor storageAccessor = mock(BtcPegoutClientStorageAccessor.class); ScheduledExecutorService mockedExecutor = mock(ScheduledExecutorService.class); // Mock the executor to execute immediately @@ -336,8 +336,8 @@ void accepts_transaction_with_two_release_requested() { return null; }).when(mockedExecutor).scheduleAtFixedRate(any(), anyLong(), anyLong(), any()); - BtcReleaseClientStorageSynchronizer storageSynchronizer = - new BtcReleaseClientStorageSynchronizer( + BtcPegoutClientStorageSynchronizer storageSynchronizer = + new BtcPegoutClientStorageSynchronizer( blockStore, mock(ReceiptStore.class), mock(NodeBlockProcessor.class), diff --git a/src/test/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientTest.java b/src/test/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientTest.java similarity index 78% rename from src/test/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientTest.java rename to src/test/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientTest.java index c550a7330..c36a87e6d 100644 --- a/src/test/java/co/rsk/federate/btcreleaseclient/BtcReleaseClientTest.java +++ b/src/test/java/co/rsk/federate/btcreleaseclient/BtcPegoutClientTest.java @@ -44,16 +44,16 @@ import co.rsk.federate.signing.KeyId; import co.rsk.federate.signing.hsm.HSMUnsupportedVersionException; import co.rsk.federate.signing.hsm.SignerException; -import co.rsk.federate.signing.hsm.message.HSMReleaseCreationInformationException; -import co.rsk.federate.signing.hsm.message.ReleaseCreationInformation; -import co.rsk.federate.signing.hsm.message.ReleaseCreationInformationGetter; +import co.rsk.federate.signing.hsm.message.HSMPegoutCreationInformationException; +import co.rsk.federate.signing.hsm.message.PegoutCreationInformation; +import co.rsk.federate.signing.hsm.message.PegoutCreationInformationGetter; import co.rsk.federate.signing.hsm.message.SignerMessage; import co.rsk.federate.signing.hsm.message.SignerMessageBuilder; import co.rsk.federate.signing.hsm.message.SignerMessageBuilderException; import co.rsk.federate.signing.hsm.message.SignerMessageBuilderFactory; import co.rsk.federate.signing.hsm.message.SignerMessageBuilderV1; -import co.rsk.federate.signing.hsm.requirements.ReleaseRequirementsEnforcer; -import co.rsk.federate.signing.hsm.requirements.ReleaseRequirementsEnforcerException; +import co.rsk.federate.signing.hsm.requirements.PegoutSigningRequirementsEnforcer; +import co.rsk.federate.signing.hsm.requirements.PegoutSigningRequirementsEnforcerException; import co.rsk.federate.signing.utils.TestUtils; import co.rsk.net.NodeBlockProcessor; import co.rsk.peg.federation.*; @@ -76,6 +76,7 @@ import org.ethereum.core.Block; import org.ethereum.core.TransactionReceipt; import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import org.ethereum.db.BlockStore; import org.ethereum.db.ReceiptStore; import org.ethereum.db.TransactionInfo; @@ -88,7 +89,7 @@ import org.mockito.invocation.InvocationOnMock; import org.spongycastle.util.encoders.Hex; -class BtcReleaseClientTest { +class BtcPegoutClientTest { private NetworkParameters params; private BridgeConstants bridgeConstants; @@ -110,7 +111,7 @@ void if_start_not_called_rsk_blockchain_not_listened() { FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); Mockito.doReturn(Constants.regtest()).when(fedNodeSystemProperties).getNetworkConstants(); - new BtcReleaseClient( + new BtcPegoutClient( ethereum, mock(FederatorSupport.class), fedNodeSystemProperties, @@ -126,7 +127,7 @@ void when_start_called_rsk_blockchain_is_listened() { FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); Mockito.doReturn(Constants.regtest()).when(fedNodeSystemProperties).getNetworkConstants(); - BtcReleaseClient btcReleaseClient = new BtcReleaseClient( + BtcPegoutClient btcPegoutClient = new BtcPegoutClient( ethereum, mock(FederatorSupport.class), fedNodeSystemProperties, @@ -134,10 +135,10 @@ void when_start_called_rsk_blockchain_is_listened() { ); Federation fed1 = TestUtils.createFederation(params, 1); - btcReleaseClient.start(fed1); + btcPegoutClient.start(fed1); Federation fed2 = TestUtils.createFederation(params, 1); - btcReleaseClient.start(fed2); + btcPegoutClient.start(fed2); verify(ethereum, Mockito.times(1)).addListener(ArgumentMatchers.any(EthereumListener.class)); } @@ -148,7 +149,7 @@ void if_stop_called_with_just_one_federation_rsk_blockchain_is_still_listened() FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); Mockito.doReturn(Constants.regtest()).when(fedNodeSystemProperties).getNetworkConstants(); - BtcReleaseClient btcReleaseClient = new BtcReleaseClient( + BtcPegoutClient btcPegoutClient = new BtcPegoutClient( ethereum, mock(FederatorSupport.class), fedNodeSystemProperties, @@ -156,14 +157,14 @@ void if_stop_called_with_just_one_federation_rsk_blockchain_is_still_listened() ); Federation fed1 = TestUtils.createFederation(params, 1); - btcReleaseClient.start(fed1); + btcPegoutClient.start(fed1); Federation fed2 = TestUtils.createFederation(params, 1); - btcReleaseClient.start(fed2); + btcPegoutClient.start(fed2); Mockito.verify(ethereum, Mockito.times(1)).addListener(ArgumentMatchers.any(EthereumListener.class)); - btcReleaseClient.stop(fed1); + btcPegoutClient.stop(fed1); Mockito.verify(ethereum, never()).removeListener(ArgumentMatchers.any(EthereumListener.class)); } @@ -173,7 +174,7 @@ void if_stop_called_with_federations_rsk_blockchain_is_not_listened() { FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); Mockito.doReturn(Constants.regtest()).when(fedNodeSystemProperties).getNetworkConstants(); - BtcReleaseClient btcReleaseClient = new BtcReleaseClient( + BtcPegoutClient btcPegoutClient = new BtcPegoutClient( ethereum, mock(FederatorSupport.class), fedNodeSystemProperties, @@ -181,15 +182,15 @@ void if_stop_called_with_federations_rsk_blockchain_is_not_listened() { ); Federation fed1 = TestUtils.createFederation(params, 1); - btcReleaseClient.start(fed1); + btcPegoutClient.start(fed1); Federation fed2 = TestUtils.createFederation(params, 1); - btcReleaseClient.start(fed2); + btcPegoutClient.start(fed2); Mockito.verify(ethereum, Mockito.times(1)).addListener(ArgumentMatchers.any(EthereumListener.class)); - btcReleaseClient.stop(fed1); - btcReleaseClient.stop(fed2); + btcPegoutClient.stop(fed1); + btcPegoutClient.stop(fed2); Mockito.verify(ethereum, Mockito.times(1)).removeListener(ArgumentMatchers.any(EthereumListener.class)); } @@ -199,17 +200,17 @@ void processReleases_ok() throws Exception { Federation federation = TestUtils.createFederation(params, 1); // Create a tx from the Fed to a random btc address - BtcTransaction releaseTx = new BtcTransaction(params); + BtcTransaction pegoutBtcTx = new BtcTransaction(params); int amountOfInputs = 5; for (int i = 0; i < amountOfInputs; i++) { - TransactionInput releaseInput = TestUtils.createTransactionInput(params, releaseTx, federation); - releaseTx.addInput(releaseInput); + TransactionInput releaseInput = TestUtils.createTransactionInput(params, pegoutBtcTx, federation); + pegoutBtcTx.addInput(releaseInput); } BtcECKey fedKey = new BtcECKey(); ECPublicKey signerPublicKey = new ECPublicKey(fedKey.getPubKey()); - ECKey.ECDSASignature ethSig = new ECKey.ECDSASignature(BigInteger.ONE, BigInteger.TEN); + ECDSASignature ethSig = new ECDSASignature(BigInteger.ONE, BigInteger.TEN); ECDSASigner signer = mock(ECDSASigner.class); when(signer.getPublicKey(BTC_KEY_ID.getKeyId())).thenReturn(signerPublicKey); @@ -219,13 +220,13 @@ void processReleases_ok() throws Exception { FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); when(fedNodeSystemProperties.getNetworkConstants()).thenReturn(Constants.regtest()); - SignerMessageBuilder messageBuilder = new SignerMessageBuilderV1(releaseTx); + SignerMessageBuilder messageBuilder = new SignerMessageBuilderV1(pegoutBtcTx); SignerMessageBuilderFactory signerMessageBuilderFactory = mock(SignerMessageBuilderFactory.class); when(signerMessageBuilderFactory.buildFromConfig(ArgumentMatchers.anyInt(), ArgumentMatchers - .any(ReleaseCreationInformation.class))) + .any(PegoutCreationInformation.class))) .thenReturn(messageBuilder); - BtcReleaseClient client = new BtcReleaseClient( + BtcPegoutClient client = new BtcPegoutClient( mock(Ethereum.class), mock(FederatorSupport.class), fedNodeSystemProperties, @@ -235,37 +236,37 @@ void processReleases_ok() throws Exception { Keccak256 rskTxHash = Keccak256.ZERO_HASH; Block block = mock(Block.class); - ReleaseCreationInformation releaseCreationInformation = new ReleaseCreationInformation( + PegoutCreationInformation pegoutCreationInformation = new PegoutCreationInformation( block, mock(TransactionReceipt.class), rskTxHash, - releaseTx, + pegoutBtcTx, rskTxHash ); - ReleaseCreationInformationGetter releaseCreationInformationGetter = mock(ReleaseCreationInformationGetter.class); - when(releaseCreationInformationGetter.getTxInfoToSign( + PegoutCreationInformationGetter pegoutCreationInformationGetter = mock(PegoutCreationInformationGetter.class); + when(pegoutCreationInformationGetter.getPegoutCreationInformationToSign( anyInt(), any(), any(), any() - )).thenReturn(releaseCreationInformation); + )).thenReturn(pegoutCreationInformation); client.setup( signer, mock(ActivationConfig.class), signerMessageBuilderFactory, - releaseCreationInformationGetter, - mock(ReleaseRequirementsEnforcer.class), - mock(BtcReleaseClientStorageAccessor.class), - mock(BtcReleaseClientStorageSynchronizer.class) + pegoutCreationInformationGetter, + mock(PegoutSigningRequirementsEnforcer.class), + mock(BtcPegoutClientStorageAccessor.class), + mock(BtcPegoutClientStorageSynchronizer.class) ); client.start(federation); SortedMap releases = new TreeMap<>(); - releases.put(rskTxHash, releaseTx); + releases.put(rskTxHash, pegoutBtcTx); // Act - client.processReleases(releases.entrySet()); + client.processPegouts(releases.entrySet()); // Assert Mockito.verify(signer, Mockito.times(amountOfInputs)) @@ -304,7 +305,7 @@ void having_two_pegouts_signs_only_one() throws Exception { doReturn(stateForFederator).when(federatorSupport).getStateForFederator(); ECKey ecKey = new ECKey(); - ECKey.ECDSASignature ethSig = ecKey.doSign(new byte[]{}); + ECDSASignature ethSig = ECDSASignature.fromSignature(ecKey.doSign(new byte[]{})); BtcECKey fedKey = new BtcECKey(); ECPublicKey signerPublicKey = new ECPublicKey(fedKey.getPubKey()); @@ -344,31 +345,31 @@ void having_two_pegouts_signs_only_one() throws Exception { when(txInfo2.getBlockHash()).thenReturn(blockHash2.getBytes()); when(receiptStore.getInMainChain(hash2.getBytes(), blockStore)).thenReturn(Optional.of(txInfo2)); - ReleaseCreationInformationGetter releaseCreationInformationGetter = - new ReleaseCreationInformationGetter( + PegoutCreationInformationGetter pegoutCreationInformationGetter = + new PegoutCreationInformationGetter( receiptStore, blockStore ); - BtcReleaseClientStorageSynchronizer storageSynchronizer = mock(BtcReleaseClientStorageSynchronizer.class); + BtcPegoutClientStorageSynchronizer storageSynchronizer = mock(BtcPegoutClientStorageSynchronizer.class); when(storageSynchronizer.isSynced()).thenReturn(true); - BtcReleaseClient btcReleaseClient = new BtcReleaseClient( + BtcPegoutClient btcPegoutClient = new BtcPegoutClient( ethereum, federatorSupport, fedNodeSystemProperties, mock(NodeBlockProcessor.class) ); - btcReleaseClient.setup( + btcPegoutClient.setup( signer, mock(ActivationConfig.class), signerMessageBuilderFactory, - releaseCreationInformationGetter, - mock(ReleaseRequirementsEnforcer.class), - mock(BtcReleaseClientStorageAccessor.class), + pegoutCreationInformationGetter, + mock(PegoutSigningRequirementsEnforcer.class), + mock(BtcPegoutClientStorageAccessor.class), storageSynchronizer ); - btcReleaseClient.start(federation); + btcPegoutClient.start(federation); // Act ethereumListener.get().onBestBlock(null, Collections.emptyList()); @@ -381,7 +382,7 @@ void having_two_pegouts_signs_only_one() throws Exception { } @Test - void onBestBlock_return_when_node_is_syncing() throws BtcReleaseClientException { + void onBestBlock_return_when_node_is_syncing() throws BtcPegoutClientException { // Arrange Federation federation = TestUtils.createFederation(params, 1); @@ -402,22 +403,22 @@ void onBestBlock_return_when_node_is_syncing() throws BtcReleaseClientException NodeBlockProcessor nodeBlockProcessor = mock(NodeBlockProcessor.class); when(nodeBlockProcessor.hasBetterBlockToSync()).thenReturn(true); - BtcReleaseClient btcReleaseClient = new BtcReleaseClient( + BtcPegoutClient btcPegoutClient = new BtcPegoutClient( ethereum, federatorSupport, fedNodeSystemProperties, nodeBlockProcessor ); - btcReleaseClient.setup( + btcPegoutClient.setup( mock(ECDSASigner.class), mock(ActivationConfig.class), mock(SignerMessageBuilderFactory.class), - mock(ReleaseCreationInformationGetter.class), - mock(ReleaseRequirementsEnforcer.class), - mock(BtcReleaseClientStorageAccessor.class), - mock(BtcReleaseClientStorageSynchronizer.class) + mock(PegoutCreationInformationGetter.class), + mock(PegoutSigningRequirementsEnforcer.class), + mock(BtcPegoutClientStorageAccessor.class), + mock(BtcPegoutClientStorageSynchronizer.class) ); - btcReleaseClient.start(federation); + btcPegoutClient.start(federation); // Act ethereumListener.get().onBestBlock(null, null); @@ -427,7 +428,7 @@ void onBestBlock_return_when_node_is_syncing() throws BtcReleaseClientException } @Test - void onBestBlock_return_when_pegout_is_disabled() throws BtcReleaseClientException { + void onBestBlock_return_when_pegout_is_disabled() throws BtcPegoutClientException { // Arrange Federation federation = TestUtils.createFederation(params, 1); @@ -448,22 +449,22 @@ void onBestBlock_return_when_pegout_is_disabled() throws BtcReleaseClientExcepti NodeBlockProcessor nodeBlockProcessor = mock(NodeBlockProcessor.class); when(nodeBlockProcessor.hasBetterBlockToSync()).thenReturn(false); - BtcReleaseClient btcReleaseClient = new BtcReleaseClient( + BtcPegoutClient btcPegoutClient = new BtcPegoutClient( ethereum, federatorSupport, fedNodeSystemProperties, nodeBlockProcessor ); - btcReleaseClient.setup( + btcPegoutClient.setup( mock(ECDSASigner.class), mock(ActivationConfig.class), mock(SignerMessageBuilderFactory.class), - mock(ReleaseCreationInformationGetter.class), - mock(ReleaseRequirementsEnforcer.class), - mock(BtcReleaseClientStorageAccessor.class), - mock(BtcReleaseClientStorageSynchronizer.class) + mock(PegoutCreationInformationGetter.class), + mock(PegoutSigningRequirementsEnforcer.class), + mock(BtcPegoutClientStorageAccessor.class), + mock(BtcPegoutClientStorageSynchronizer.class) ); - btcReleaseClient.start(federation); + btcPegoutClient.start(federation); // Act ethereumListener.get().onBestBlock(null, null); @@ -494,13 +495,13 @@ void onBlock_return_when_node_is_syncing() { NodeBlockProcessor nodeBlockProcessor = mock(NodeBlockProcessor.class); when(nodeBlockProcessor.hasBetterBlockToSync()).thenReturn(true); - BtcReleaseClient btcReleaseClient = new BtcReleaseClient( + BtcPegoutClient btcPegoutClient = new BtcPegoutClient( ethereum, federatorSupport, fedNodeSystemProperties, nodeBlockProcessor ); - btcReleaseClient.start(federation); + btcPegoutClient.start(federation); List receipts = new ArrayList<>(); TransactionReceipt transactionReceipt = mock(TransactionReceipt.class); @@ -536,13 +537,13 @@ void onBlock_return_when_pegout_is_disabled() { NodeBlockProcessor nodeBlockProcessor = mock(NodeBlockProcessor.class); when(nodeBlockProcessor.hasBetterBlockToSync()).thenReturn(false); - BtcReleaseClient btcReleaseClient = new BtcReleaseClient( + BtcPegoutClient btcPegoutClient = new BtcPegoutClient( ethereum, federatorSupport, fedNodeSystemProperties, nodeBlockProcessor ); - btcReleaseClient.start(federation); + btcPegoutClient.start(federation); List receipts = new ArrayList<>(); TransactionReceipt transactionReceipt = mock(TransactionReceipt.class); @@ -557,23 +558,23 @@ void onBlock_return_when_pegout_is_disabled() { } @Test - void validateTxCanBeSigned_ok() throws Exception { + void validatePegoutBtcTxCanBeSigned_ok() throws Exception { // Arrange Federation federation = TestUtils.createFederation(params, 1); // Create a tx from the Fed to a random btc address - BtcTransaction releaseTx = new BtcTransaction(params); - TransactionInput releaseInput = TestUtils.createTransactionInput(params, releaseTx, federation); - releaseTx.addInput(releaseInput); + BtcTransaction pegoutBtcTx = new BtcTransaction(params); + TransactionInput pegoutBtcInput = TestUtils.createTransactionInput(params, pegoutBtcTx, federation); + pegoutBtcTx.addInput(pegoutBtcInput); BtcECKey fed1Key = federation.getBtcPublicKeys().get(0); ECPublicKey signerPublicKey = new ECPublicKey(fed1Key.getPubKey()); - test_validateTxCanBeSigned(federation, releaseTx, signerPublicKey); + test_validatePegoutBtcTxCanBeSigned(federation, pegoutBtcTx, signerPublicKey); } @Test - void validateTxCanBeSigned_fast_bridge_ok() throws Exception { + void validatePegoutBtcTxCanBeSigned_fast_bridge_ok() throws Exception { // Create a StandardMultisigFederation Federation federation = TestUtils.createFederation(params, 1); @@ -584,32 +585,32 @@ void validateTxCanBeSigned_fast_bridge_ok() throws Exception { ); // Create a tx from the Fed to a random btc address - BtcTransaction releaseTx = createReleaseTxAndAddInput(federation, fastBridgeRedeemScript); + BtcTransaction pegoutBtcTx = createPegoutBtcTxAndAddInput(federation, fastBridgeRedeemScript); BtcECKey fed1Key = federation.getBtcPublicKeys().get(0); ECPublicKey signerPublicKey = new ECPublicKey(fed1Key.getPubKey()); - test_validateTxCanBeSigned(federation, releaseTx, signerPublicKey); + test_validatePegoutBtcTxCanBeSigned(federation, pegoutBtcTx, signerPublicKey); } @Test - void validateTxCanBeSigned_erp_fed_ok() throws Exception { + void validatePegoutBtcTxCanBeSigned_erp_fed_ok() throws Exception { Federation federation = TestUtils.createFederation(params, 3); FederationArgs federationArgs = federation.getArgs(); ErpFederation nonStandardErpFederation = FederationFactory.buildNonStandardErpFederation(federationArgs, erpFedKeys, 5063, mock(ActivationConfig.ForBlock.class)); // Create a tx from the Fed to a random btc address - BtcTransaction releaseTx = createReleaseTxAndAddInput(federation); + BtcTransaction pegoutBtcTx = createPegoutBtcTxAndAddInput(federation); BtcECKey fed1Key = nonStandardErpFederation.getBtcPublicKeys().get(0); ECPublicKey signerPublicKey = new ECPublicKey(fed1Key.getPubKey()); - test_validateTxCanBeSigned(nonStandardErpFederation, releaseTx, signerPublicKey); + test_validatePegoutBtcTxCanBeSigned(nonStandardErpFederation, pegoutBtcTx, signerPublicKey); } @Test - void validateTxCanBeSigned_federatorAlreadySigned() throws Exception { + void validatePegoutBtcTxCanBeSigned_federatorAlreadySigned() throws Exception { // Arrange BtcECKey federator1PrivKey = new BtcECKey(); BtcECKey federator2PrivKey = new BtcECKey(); @@ -619,16 +620,16 @@ void validateTxCanBeSigned_federatorAlreadySigned() throws Exception { Federation federation = FederationFactory.buildStandardMultiSigFederation(federationArgs); // Create a tx from the Fed to a random btc address - BtcTransaction releaseTx = new BtcTransaction(params); - TransactionInput releaseInput = TestUtils.createTransactionInput(params, releaseTx, federation); - releaseTx.addInput(releaseInput); + BtcTransaction pegoutBtcTx = new BtcTransaction(params); + TransactionInput pegoutBtcInput = TestUtils.createTransactionInput(params, pegoutBtcTx, federation); + pegoutBtcTx.addInput(pegoutBtcInput); - Script inputScript = releaseInput.getScriptSig(); + Script inputScript = pegoutBtcInput.getScriptSig(); List chunks = inputScript.getChunks(); byte[] program = chunks.get(chunks.size() - 1).data; Script redeemScript = new Script(program); - Sha256Hash sighash = releaseTx.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false); + Sha256Hash sighash = pegoutBtcTx.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false); BtcECKey.ECDSASignature sig = federator1PrivKey.sign(sighash); TransactionSignature txSig = new TransactionSignature(sig, BtcTransaction.SigHash.ALL, false); @@ -636,7 +637,7 @@ void validateTxCanBeSigned_federatorAlreadySigned() throws Exception { int sigIndex = inputScript.getSigInsertionIndex(sighash, federator1PrivKey); inputScript = ScriptBuilder.updateScriptWithSignature(inputScript, txSigEncoded, sigIndex, 1, 1); - releaseInput.setScriptSig(inputScript); + pegoutBtcInput.setScriptSig(inputScript); FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); when(fedNodeSystemProperties.getNetworkConstants()).thenReturn(Constants.regtest()); @@ -645,7 +646,7 @@ void validateTxCanBeSigned_federatorAlreadySigned() throws Exception { ECDSASigner signer = mock(ECDSASigner.class); Mockito.doReturn(signerPublicKey).when(signer).getPublicKey(ArgumentMatchers.any(KeyId.class)); - BtcReleaseClient client = new BtcReleaseClient( + BtcPegoutClient client = new BtcPegoutClient( mock(Ethereum.class), mock(FederatorSupport.class), fedNodeSystemProperties, @@ -655,26 +656,26 @@ void validateTxCanBeSigned_federatorAlreadySigned() throws Exception { signer, mock(ActivationConfig.class), mock(SignerMessageBuilderFactory.class), - mock(ReleaseCreationInformationGetter.class), - mock(ReleaseRequirementsEnforcer.class), - mock(BtcReleaseClientStorageAccessor.class), - mock(BtcReleaseClientStorageSynchronizer.class) + mock(PegoutCreationInformationGetter.class), + mock(PegoutSigningRequirementsEnforcer.class), + mock(BtcPegoutClientStorageAccessor.class), + mock(BtcPegoutClientStorageSynchronizer.class) ); client.start(federation); // Act - assertThrows(FederatorAlreadySignedException.class, () -> client.validateTxCanBeSigned(releaseTx)); + assertThrows(FederatorAlreadySignedException.class, () -> client.validatePegoutBtcTxCanBeSigned(pegoutBtcTx)); } @Test - void validateTxCanBeSigned_federationCantSign() throws Exception { + void validatePegoutBtcTxCanBeSigned_federationCantSign() throws Exception { // Arrange Federation federation = TestUtils.createFederation(params, 1); // Create a tx from the Fed to a random btc address - BtcTransaction releaseTx = new BtcTransaction(params); - TransactionInput releaseInput = TestUtils.createTransactionInput(params, releaseTx, federation); - releaseTx.addInput(releaseInput); + BtcTransaction pegoutBtcTx = new BtcTransaction(params); + TransactionInput pegoutInput = TestUtils.createTransactionInput(params, pegoutBtcTx, federation); + pegoutBtcTx.addInput(pegoutInput); FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); when(fedNodeSystemProperties.getNetworkConstants()).thenReturn(Constants.regtest()); @@ -684,7 +685,7 @@ void validateTxCanBeSigned_federationCantSign() throws Exception { ECDSASigner signer = mock(ECDSASigner.class); Mockito.doReturn(signerPublicKey).when(signer).getPublicKey(ArgumentMatchers.any(KeyId.class)); - BtcReleaseClient client = new BtcReleaseClient( + BtcPegoutClient client = new BtcPegoutClient( mock(Ethereum.class), mock(FederatorSupport.class), fedNodeSystemProperties, @@ -694,14 +695,14 @@ void validateTxCanBeSigned_federationCantSign() throws Exception { signer, mock(ActivationConfig.class), mock(SignerMessageBuilderFactory.class), - mock(ReleaseCreationInformationGetter.class), - mock(ReleaseRequirementsEnforcer.class), - mock(BtcReleaseClientStorageAccessor.class), - mock(BtcReleaseClientStorageSynchronizer.class) + mock(PegoutCreationInformationGetter.class), + mock(PegoutSigningRequirementsEnforcer.class), + mock(BtcPegoutClientStorageAccessor.class), + mock(BtcPegoutClientStorageSynchronizer.class) ); // Act - assertThrows(FederationCantSignException.class, () -> client.validateTxCanBeSigned(releaseTx)); + assertThrows(FederationCantSignException.class, () -> client.validatePegoutBtcTxCanBeSigned(pegoutBtcTx)); } @Test @@ -715,19 +716,19 @@ void removeSignaturesFromTransaction() { Federation federation = FederationFactory.buildStandardMultiSigFederation(federationArgs); // Create a tx from the Fed to a random btc address - BtcTransaction releaseTx = new BtcTransaction(params); - TransactionInput releaseInput = TestUtils.createTransactionInput(params, releaseTx, federation); - releaseTx.addInput(releaseInput); + BtcTransaction pegoutBtcTx = new BtcTransaction(params); + TransactionInput pegoutBtcInput = TestUtils.createTransactionInput(params, pegoutBtcTx, federation); + pegoutBtcTx.addInput(pegoutBtcInput); - Sha256Hash unsignedTxHash = releaseTx.getHash(); + Sha256Hash unsignedTxHash = pegoutBtcTx.getHash(); // Sign the transaction - Script inputScript = releaseInput.getScriptSig(); + Script inputScript = pegoutBtcInput.getScriptSig(); List chunks = inputScript.getChunks(); byte[] program = chunks.get(chunks.size() - 1).data; Script redeemScript = new Script(program); - Sha256Hash sighash = releaseTx.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false); + Sha256Hash sighash = pegoutBtcTx.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false); BtcECKey.ECDSASignature sig = federator1PrivKey.sign(sighash); TransactionSignature txSig = new TransactionSignature(sig, BtcTransaction.SigHash.ALL, false); @@ -735,23 +736,23 @@ void removeSignaturesFromTransaction() { int sigIndex = inputScript.getSigInsertionIndex(sighash, federator1PrivKey); inputScript = ScriptBuilder.updateScriptWithSignature(inputScript, txSigEncoded, sigIndex, 1, 1); - releaseInput.setScriptSig(inputScript); + pegoutBtcInput.setScriptSig(inputScript); FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); when(fedNodeSystemProperties.getNetworkConstants()).thenReturn(Constants.regtest()); - BtcReleaseClient client = new BtcReleaseClient( + BtcPegoutClient client = new BtcPegoutClient( mock(Ethereum.class), mock(FederatorSupport.class), fedNodeSystemProperties, mock(NodeBlockProcessor.class) ); - Sha256Hash signedTxHash = releaseTx.getHash(); + Sha256Hash signedTxHash = pegoutBtcTx.getHash(); // Act - client.removeSignaturesFromTransaction(releaseTx, federation); - Sha256Hash removedSignaturesTxHash = releaseTx.getHash(); + client.removeSignaturesFromPegoutBtcTx(pegoutBtcTx, federation); + Sha256Hash removedSignaturesTxHash = pegoutBtcTx.getHash(); // Assert assertNotEquals(unsignedTxHash, signedTxHash); @@ -794,23 +795,23 @@ void extractStandardRedeemScript_erp_redeem_script() { @Test void sets_rsk_tx_hash_with_file_data() - throws BtcReleaseClientException, SignerException, - HSMReleaseCreationInformationException, ReleaseRequirementsEnforcerException, + throws BtcPegoutClientException, SignerException, + HSMPegoutCreationInformationException, PegoutSigningRequirementsEnforcerException, HSMUnsupportedVersionException, SignerMessageBuilderException { testUsageOfStorageWhenSigning(true); } @Test void sets_default_rsk_tx_hash_if_no_file_data() - throws BtcReleaseClientException, SignerException, - HSMReleaseCreationInformationException, ReleaseRequirementsEnforcerException, + throws BtcPegoutClientException, SignerException, + HSMPegoutCreationInformationException, PegoutSigningRequirementsEnforcerException, HSMUnsupportedVersionException, SignerMessageBuilderException { testUsageOfStorageWhenSigning(false); } - private void test_validateTxCanBeSigned( + private void test_validatePegoutBtcTxCanBeSigned( Federation federation, - BtcTransaction releaseTx, + BtcTransaction pegoutBtcTx, ECPublicKey signerPublicKey ) throws Exception { FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); @@ -819,7 +820,7 @@ private void test_validateTxCanBeSigned( ECDSASigner signer = mock(ECDSASigner.class); doReturn(signerPublicKey).when(signer).getPublicKey(any(KeyId.class)); - BtcReleaseClient client = new BtcReleaseClient( + BtcPegoutClient client = new BtcPegoutClient( mock(Ethereum.class), mock(FederatorSupport.class), fedNodeSystemProperties, @@ -829,15 +830,15 @@ private void test_validateTxCanBeSigned( signer, mock(ActivationConfig.class), mock(SignerMessageBuilderFactory.class), - mock(ReleaseCreationInformationGetter.class), - mock(ReleaseRequirementsEnforcer.class), - mock(BtcReleaseClientStorageAccessor.class), - mock(BtcReleaseClientStorageSynchronizer.class) + mock(PegoutCreationInformationGetter.class), + mock(PegoutSigningRequirementsEnforcer.class), + mock(BtcPegoutClientStorageAccessor.class), + mock(BtcPegoutClientStorageSynchronizer.class) ); client.start(federation); // Act - client.validateTxCanBeSigned(releaseTx); + client.validatePegoutBtcTxCanBeSigned(pegoutBtcTx); } private void test_extractStandardRedeemScript( @@ -847,7 +848,7 @@ private void test_extractStandardRedeemScript( FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); when(fedNodeSystemProperties.getNetworkConstants()).thenReturn(Constants.regtest()); - BtcReleaseClient client = new BtcReleaseClient( + BtcPegoutClient client = new BtcPegoutClient( mock(Ethereum.class), mock(FederatorSupport.class), fedNodeSystemProperties, @@ -861,7 +862,7 @@ private void test_extractStandardRedeemScript( } private void test_getRedeemScriptFromInput(boolean isFastBridgeRedeemScript) { - BtcReleaseClient client = createBtcClient(); + BtcPegoutClient client = createBtcClient(); BtcECKey ecKey1 = BtcECKey.fromPrivate(BigInteger.valueOf(100)); BtcECKey ecKey2 = BtcECKey.fromPrivate(BigInteger.valueOf(200)); @@ -893,26 +894,26 @@ private void test_getRedeemScriptFromInput(boolean isFastBridgeRedeemScript) { ); } - private BtcTransaction createReleaseTxAndAddInput(Federation federation, Script redeemScript) { - BtcTransaction releaseTx = new BtcTransaction(params); + private BtcTransaction createPegoutBtcTxAndAddInput(Federation federation, Script redeemScript) { + BtcTransaction pegoutBtcTx = new BtcTransaction(params); TransactionInput releaseInput = TestUtils.createTransactionInput( params, - releaseTx, + pegoutBtcTx, federation, redeemScript ); - releaseTx.addInput(releaseInput); + pegoutBtcTx.addInput(releaseInput); - return releaseTx; + return pegoutBtcTx; } - private BtcTransaction createReleaseTxAndAddInput(Federation federation) { - return createReleaseTxAndAddInput(federation, null); + private BtcTransaction createPegoutBtcTxAndAddInput(Federation federation) { + return createPegoutBtcTxAndAddInput(federation, null); } private void testUsageOfStorageWhenSigning(boolean shouldHaveDataInFile) - throws BtcReleaseClientException, SignerException, - HSMReleaseCreationInformationException, ReleaseRequirementsEnforcerException, + throws BtcPegoutClientException, SignerException, + HSMPegoutCreationInformationException, PegoutSigningRequirementsEnforcerException, HSMUnsupportedVersionException, SignerMessageBuilderException { FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); when(fedNodeSystemProperties.getNetworkConstants()).thenReturn(Constants.regtest()); @@ -952,23 +953,23 @@ private void testUsageOfStorageWhenSigning(boolean shouldHaveDataInFile) ECDSASigner signer = mock(ECDSASigner.class); when(signer.getVersionForKeyId(any())).thenReturn(2); when(signer.getPublicKey(any())).thenReturn(new ECPublicKey(key1.getPubKey())); - ECKey.ECDSASignature signature = new ECKey.ECDSASignature(BigInteger.ONE, BigInteger.TEN); + ECDSASignature signature = new ECDSASignature(BigInteger.ONE, BigInteger.TEN); when(signer.sign(any(), any())).thenReturn(signature); Block block = mock(Block.class); when(block.getNumber()).thenReturn(1L); - ReleaseCreationInformationGetter releaseCreationInformationGetter = mock(ReleaseCreationInformationGetter.class); - doReturn(new ReleaseCreationInformation( + PegoutCreationInformationGetter pegoutCreationInformationGetter = mock(PegoutCreationInformationGetter.class); + doReturn(new PegoutCreationInformation( block, mock(TransactionReceipt.class), rskTxHash, new BtcTransaction(bridgeConstants.getBtcParams()), otherRskTxHash - )).when(releaseCreationInformationGetter).getTxInfoToSign(anyInt(), any(), any(), any()); + )).when(pegoutCreationInformationGetter).getPegoutCreationInformationToSign(anyInt(), any(), any(), any()); - ReleaseRequirementsEnforcer releaseRequirementsEnforcer = mock(ReleaseRequirementsEnforcer.class); - doNothing().when(releaseRequirementsEnforcer).enforce(anyInt(), any()); + PegoutSigningRequirementsEnforcer pegoutSigningRequirementsEnforcer = mock(PegoutSigningRequirementsEnforcer.class); + doNothing().when(pegoutSigningRequirementsEnforcer).enforce(anyInt(), any()); SignerMessageBuilder signerMessageBuilder = mock(SignerMessageBuilder.class); when(signerMessageBuilder.buildMessageForIndex(anyInt())).thenReturn(mock(SignerMessage.class)); @@ -977,37 +978,37 @@ private void testUsageOfStorageWhenSigning(boolean shouldHaveDataInFile) SimpleEthereumImpl ethereumImpl = new SimpleEthereumImpl(); - BtcReleaseClient btcReleaseClient = new BtcReleaseClient( + BtcPegoutClient btcPegoutClient = new BtcPegoutClient( ethereumImpl, federatorSupport, fedNodeSystemProperties, nodeBlockProcessor ); - BtcReleaseClientStorageAccessor accessor = mock(BtcReleaseClientStorageAccessor.class); + BtcPegoutClientStorageAccessor accessor = mock(BtcPegoutClientStorageAccessor.class); when(accessor.hasBtcTxHash(releaseBtcTx.getHash())).thenReturn(shouldHaveDataInFile); when(accessor.getRskTxHash(releaseBtcTx.getHash())).thenReturn(shouldHaveDataInFile ? rskTxHash: null); - BtcReleaseClientStorageSynchronizer synchronizer = mock(BtcReleaseClientStorageSynchronizer.class); + BtcPegoutClientStorageSynchronizer synchronizer = mock(BtcPegoutClientStorageSynchronizer.class); when(synchronizer.isSynced()).thenReturn(true); - btcReleaseClient.setup( + btcPegoutClient.setup( signer, mock(ActivationConfig.class), signerMessageBuilderFactory, - releaseCreationInformationGetter, - releaseRequirementsEnforcer, + pegoutCreationInformationGetter, + pegoutSigningRequirementsEnforcer, accessor, synchronizer ); - btcReleaseClient.start(federation); + btcPegoutClient.start(federation); // Release "confirmed" ethereumImpl.addBestBlockWithReceipts(mock(Block.class), new ArrayList<>()); // Verify the rsk tx hash was updated - verify(releaseCreationInformationGetter, times(1)).getTxInfoToSign( + verify(pegoutCreationInformationGetter, times(1)).getPegoutCreationInformationToSign( anyInt(), eq(shouldHaveDataInFile ? rskTxHash: otherRskTxHash), any(), @@ -1018,12 +1019,12 @@ private void testUsageOfStorageWhenSigning(boolean shouldHaveDataInFile) verify(federatorSupport).addSignature(any(), eq(otherRskTxHash.getBytes())); } - private BtcReleaseClient createBtcClient() { + private BtcPegoutClient createBtcClient() { FedNodeSystemProperties fedNodeSystemProperties = mock(FedNodeSystemProperties.class); when(fedNodeSystemProperties.getNetworkConstants()).thenReturn(Constants.regtest()); when(fedNodeSystemProperties.isPegoutEnabled()).thenReturn(true); // Enabled by default - return new BtcReleaseClient( + return new BtcPegoutClient( mock(Ethereum.class), mock(FederatorSupport.class), fedNodeSystemProperties, diff --git a/src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageImplTest.java b/src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageImplTest.java similarity index 64% rename from src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageImplTest.java rename to src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageImplTest.java index cdce5d831..66df9961e 100644 --- a/src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageImplTest.java +++ b/src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageImplTest.java @@ -19,7 +19,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -class BtcReleaseClientFileStorageImplTest { +class BtcPegoutClientFileStorageImplTest { private static final String DIRECTORY_PATH = "src/test/java/co/rsk/federate/io" + File.separator + "peg"; private static final String FILE_PATH = DIRECTORY_PATH + File.separator + "btcReleaseClient.rlp"; @@ -40,92 +40,92 @@ void read_no_file() throws IOException { when(storageInfo.getPegDirectoryPath()).thenReturn(DIRECTORY_PATH); when(storageInfo.getFilePath()).thenReturn(FILE_PATH); - BtcReleaseClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); + BtcPegoutClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); - BtcReleaseClientFileReadResult result = storage.read(); + BtcPegoutClientFileReadResult result = storage.read(); assertTrue(result.getSuccess()); - assertTrue(result.getData().getReleaseHashesMap().isEmpty()); + assertTrue(result.getData().getPegoutHashesMap().isEmpty()); } @Test void read_empty_file() throws IOException { - BtcReleaseClientFileStorageInfo storageInfo = mock(BtcReleaseClientFileStorageInfo.class); + BtcPegoutClientFileStorageInfo storageInfo = mock(BtcPegoutClientFileStorageInfo.class); when(storageInfo.getPegDirectoryPath()).thenReturn(DIRECTORY_PATH); when(storageInfo.getFilePath()).thenReturn(FILE_PATH); createFile(storageInfo, new byte[]{}); - BtcReleaseClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); + BtcPegoutClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); - BtcReleaseClientFileReadResult result = storage.read(); + BtcPegoutClientFileReadResult result = storage.read(); assertTrue(result.getSuccess()); - assertTrue(result.getData().getReleaseHashesMap().isEmpty()); + assertTrue(result.getData().getPegoutHashesMap().isEmpty()); } @Test void read_trash_file() throws IOException { - BtcReleaseClientFileStorageInfo storageInfo = mock(BtcReleaseClientFileStorageInfo.class); + BtcPegoutClientFileStorageInfo storageInfo = mock(BtcPegoutClientFileStorageInfo.class); when(storageInfo.getPegDirectoryPath()).thenReturn(DIRECTORY_PATH); when(storageInfo.getFilePath()).thenReturn(FILE_PATH); createFile(storageInfo, new byte[]{ 6, 6, 6 }); - BtcReleaseClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); + BtcPegoutClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); - BtcReleaseClientFileReadResult result = storage.read(); + BtcPegoutClientFileReadResult result = storage.read(); assertFalse(result.getSuccess()); } @Test void write_null_data() { - BtcReleaseClientFileStorageInfo storageInfo = mock(BtcReleaseClientFileStorageInfo.class); + BtcPegoutClientFileStorageInfo storageInfo = mock(BtcPegoutClientFileStorageInfo.class); when(storageInfo.getPegDirectoryPath()).thenReturn(DIRECTORY_PATH); when(storageInfo.getFilePath()).thenReturn(FILE_PATH); - BtcReleaseClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); + BtcPegoutClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); assertThrows(IOException.class, () -> storage.write(null)); } @Test void write_empty_data() throws Exception { - BtcReleaseClientFileStorageInfo storageInfo = mock(BtcReleaseClientFileStorageInfo.class); + BtcPegoutClientFileStorageInfo storageInfo = mock(BtcPegoutClientFileStorageInfo.class); when(storageInfo.getPegDirectoryPath()).thenReturn(DIRECTORY_PATH); when(storageInfo.getFilePath()).thenReturn(FILE_PATH); - BtcReleaseClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); + BtcPegoutClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); - storage.write(new BtcReleaseClientFileData()); + storage.write(new BtcPegoutClientFileData()); - BtcReleaseClientFileReadResult result = storage.read(); + BtcPegoutClientFileReadResult result = storage.read(); assertTrue(result.getSuccess()); - assertEquals(0, result.getData().getReleaseHashesMap().size()); + assertEquals(0, result.getData().getPegoutHashesMap().size()); } @Test void write_and_read_ok() throws Exception { - BtcReleaseClientFileStorageInfo storageInfo = mock(BtcReleaseClientFileStorageInfo.class); + BtcPegoutClientFileStorageInfo storageInfo = mock(BtcPegoutClientFileStorageInfo.class); when(storageInfo.getPegDirectoryPath()).thenReturn(DIRECTORY_PATH); when(storageInfo.getFilePath()).thenReturn(FILE_PATH); - BtcReleaseClientFileData fileData = new BtcReleaseClientFileData(); - fileData.getReleaseHashesMap().putAll(getReleaseHashesData()); + BtcPegoutClientFileData fileData = new BtcPegoutClientFileData(); + fileData.getPegoutHashesMap().putAll(getReleaseHashesData()); fileData.setBestBlockHash(createHash(1)); - BtcReleaseClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); + BtcPegoutClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); storage.write(fileData); - BtcReleaseClientFileReadResult result = storage.read(); + BtcPegoutClientFileReadResult result = storage.read(); assertTrue(result.getSuccess()); - assertEquals(fileData.getReleaseHashesMap(), result.getData().getReleaseHashesMap()); + assertEquals(fileData.getPegoutHashesMap(), result.getData().getPegoutHashesMap()); assertEquals(fileData.getBestBlockHash(), result.getData().getBestBlockHash()); } @@ -135,7 +135,7 @@ void getInfo() { when(storageInfo.getPegDirectoryPath()).thenReturn(DIRECTORY_PATH); when(storageInfo.getFilePath()).thenReturn(FILE_PATH); - BtcReleaseClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); + BtcPegoutClientFileStorage storage = getBtcReleaseClientFileStorage(storageInfo); assertEquals(storageInfo, storage.getInfo()); } @@ -147,8 +147,8 @@ private Map getReleaseHashesData() { return data; } - private BtcReleaseClientFileStorage getBtcReleaseClientFileStorage(FileStorageInfo storageInfo) { - return new BtcReleaseClientFileStorageImpl(storageInfo); + private BtcPegoutClientFileStorage getBtcReleaseClientFileStorage(FileStorageInfo storageInfo) { + return new BtcPegoutClientFileStorageImpl(storageInfo); } private void clean() throws IOException { diff --git a/src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageInfoTest.java b/src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageInfoTest.java similarity index 84% rename from src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageInfoTest.java rename to src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageInfoTest.java index bffb2a544..9be95104d 100644 --- a/src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcReleaseClientFileStorageInfoTest.java +++ b/src/test/java/co/rsk/federate/io/btcreleaseclientstorage/BtcPegoutClientFileStorageInfoTest.java @@ -8,13 +8,13 @@ import java.io.File; import org.junit.jupiter.api.Test; -class BtcReleaseClientFileStorageInfoTest { +class BtcPegoutClientFileStorageInfoTest { @Test void test() { FedNodeSystemProperties fnsp = mock(FedNodeSystemProperties.class); when(fnsp.databaseDir()).thenReturn("test"); - BtcReleaseClientFileStorageInfo info = new BtcReleaseClientFileStorageInfo(fnsp); + BtcPegoutClientFileStorageInfo info = new BtcPegoutClientFileStorageInfo(fnsp); String directoryPath = fnsp.databaseDir() + File.separator + "peg"; String filePath = directoryPath + File.separator + "btcReleaseClient.rlp"; assertEquals(directoryPath, info.getPegDirectoryPath()); diff --git a/src/test/java/co/rsk/federate/signing/ECDSACompositeSignerTest.java b/src/test/java/co/rsk/federate/signing/ECDSACompositeSignerTest.java index 79117286d..fc9a26100 100644 --- a/src/test/java/co/rsk/federate/signing/ECDSACompositeSignerTest.java +++ b/src/test/java/co/rsk/federate/signing/ECDSACompositeSignerTest.java @@ -33,6 +33,7 @@ import java.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -82,10 +83,10 @@ void sign() throws Exception { when(signer1.canSignWith(new KeyId("a-key"))).thenReturn(false); when(signer2.canSignWith(new KeyId("a-key"))).thenReturn(true); - ECKey.ECDSASignature mockedSignature = mock(ECKey.ECDSASignature.class); + ECDSASignature mockedSignature = mock(ECDSASignature.class); when(signer2.sign(new KeyId("a-key"), new SignerMessageV1(Hex.decode("aabbccdd")))).thenReturn(mockedSignature); - ECKey.ECDSASignature result = signer.sign(new KeyId("a-key"), new SignerMessageV1(Hex.decode("aabbccdd"))); + ECDSASignature result = signer.sign(new KeyId("a-key"), new SignerMessageV1(Hex.decode("aabbccdd"))); verify(signer1, never()).sign(any(), any()); assertSame(mockedSignature, result); diff --git a/src/test/java/co/rsk/federate/signing/ECDSAHSMSignerTest.java b/src/test/java/co/rsk/federate/signing/ECDSAHSMSignerTest.java index 86f9fc763..048c04585 100644 --- a/src/test/java/co/rsk/federate/signing/ECDSAHSMSignerTest.java +++ b/src/test/java/co/rsk/federate/signing/ECDSAHSMSignerTest.java @@ -42,6 +42,7 @@ import co.rsk.federate.signing.hsm.message.SignerMessageV1; import org.bouncycastle.util.encoders.Hex; import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -171,12 +172,12 @@ void getPublicKeyClientError() throws HSMClientException { @Test void sign() throws HSMClientException, SignerException { HSMSignature signatureMock = mock(HSMSignature.class); - ECKey.ECDSASignature ethSignatureMock = mock(ECKey.ECDSASignature.class); + ECDSASignature ethSignatureMock = mock(ECDSASignature.class); when(signatureMock.toEthSignature()).thenReturn(ethSignatureMock); when(providerMock.getSigningClient()).thenReturn(clientMock); when(clientMock.sign("hsmKeyA", new SignerMessageV1( Hex.decode("aabbcc")))).thenReturn(signatureMock); - ECKey.ECDSASignature result = signer.sign(new KeyId("keyA"), new SignerMessageV1(Hex.decode("aabbcc"))); + ECDSASignature result = signer.sign(new KeyId("keyA"), new SignerMessageV1(Hex.decode("aabbcc"))); assertSame(ethSignatureMock, result); diff --git a/src/test/java/co/rsk/federate/signing/ECDSASignerFromFileKeyTest.java b/src/test/java/co/rsk/federate/signing/ECDSASignerFromFileKeyTest.java index 1475e0d69..be3718357 100644 --- a/src/test/java/co/rsk/federate/signing/ECDSASignerFromFileKeyTest.java +++ b/src/test/java/co/rsk/federate/signing/ECDSASignerFromFileKeyTest.java @@ -33,6 +33,7 @@ import org.bouncycastle.util.encoders.Hex; import org.ethereum.crypto.ECKey; import org.ethereum.crypto.Keccak256Helper; +import org.ethereum.crypto.signature.ECDSASignature; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; @@ -80,12 +81,12 @@ void sign() throws Exception { try (MockedConstruction keyFileHandlerMockedConstruction = mockConstruction(KeyFileHandler.class, keyFileHandlerMockInitializer)) { byte[] message = Keccak256Helper.keccak256("aabbccdd"); - ECKey.ECDSASignature result = signer.sign(new KeyId("an-id"), new SignerMessageV1(message)); - ECKey.ECDSASignature expectedSignature = ECKey.fromPrivate(Hex.decode("1122334455")).sign(message); + ECDSASignature result = signer.sign(new KeyId("an-id"), new SignerMessageV1(message)); + ECDSASignature expectedSignature = ECDSASignature.fromSignature(ECKey.fromPrivate(Hex.decode("1122334455")).sign(message)); assertEquals(1, keyFileHandlerMockedConstruction.constructed().size()); - assertEquals(expectedSignature.r, result.r); - assertEquals(expectedSignature.s, result.s); + assertEquals(expectedSignature.getR(), result.getR()); + assertEquals(expectedSignature.getS(), result.getS()); } } diff --git a/src/test/java/co/rsk/federate/signing/hsm/client/HSMSignatureTest.java b/src/test/java/co/rsk/federate/signing/hsm/client/HSMSignatureTest.java index 05e050fab..59662b0a6 100644 --- a/src/test/java/co/rsk/federate/signing/hsm/client/HSMSignatureTest.java +++ b/src/test/java/co/rsk/federate/signing/hsm/client/HSMSignatureTest.java @@ -22,50 +22,51 @@ import co.rsk.federate.signing.utils.TestUtils; import org.ethereum.crypto.ECKey; +import org.ethereum.crypto.signature.ECDSASignature; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class HSMSignatureTest { private ECKey key; - private ECKey.ECDSASignature signature; + private ECDSASignature signature; private byte[] hash; @BeforeEach void createSignature() { key = new ECKey(); hash = TestUtils.randomHash(); - signature = key.sign(hash); + signature = ECDSASignature.fromSignature(key.sign(hash)); } @Test void toEthWithV() { HSMSignature s = new HSMSignature( - signature.r.toByteArray(), - signature.s.toByteArray(), + signature.getR().toByteArray(), + signature.getS().toByteArray(), hash, key.getPubKey(), - signature.v + signature.getV() ); - ECKey.ECDSASignature output = s.toEthSignature(); + ECDSASignature output = s.toEthSignature(); - assertEquals(signature.r, output.r); - assertEquals(signature.s, output.s); - assertEquals(signature.v, output.v); + assertEquals(signature.getR(), output.getR()); + assertEquals(signature.getS(), output.getS()); + assertEquals(signature.getV(), output.getV()); } @Test void toEthWithoutV() { HSMSignature s = new HSMSignature( - signature.r.toByteArray(), - signature.s.toByteArray(), + signature.getR().toByteArray(), + signature.getS().toByteArray(), hash, key.getPubKey(), null ); - ECKey.ECDSASignature output = s.toEthSignature(); + ECDSASignature output = s.toEthSignature(); - assertEquals(signature.r, output.r); - assertEquals(signature.s, output.s); - assertEquals(signature.v, output.v); + assertEquals(signature.getR(), output.getR()); + assertEquals(signature.getS(), output.getS()); + assertEquals(signature.getV(), output.getV()); } } diff --git a/src/test/java/co/rsk/federate/signing/hsm/message/ReleaseCreationInformationGetterTest.java b/src/test/java/co/rsk/federate/signing/hsm/message/PegoutCreationInformationGetterTest.java similarity index 72% rename from src/test/java/co/rsk/federate/signing/hsm/message/ReleaseCreationInformationGetterTest.java rename to src/test/java/co/rsk/federate/signing/hsm/message/PegoutCreationInformationGetterTest.java index 1ae387391..5bff437d8 100644 --- a/src/test/java/co/rsk/federate/signing/hsm/message/ReleaseCreationInformationGetterTest.java +++ b/src/test/java/co/rsk/federate/signing/hsm/message/PegoutCreationInformationGetterTest.java @@ -27,10 +27,10 @@ import org.ethereum.vm.PrecompiledContracts; import org.junit.jupiter.api.Test; -class ReleaseCreationInformationGetterTest { +class PegoutCreationInformationGetterTest { @Test - void createGetTxInfoToSign_returnOK() throws HSMReleaseCreationInformationException { + void createGetTxInfoToSign_returnOK() throws HSMPegoutCreationInformationException { Keccak256 blockHash = TestUtils.createHash(3); Keccak256 rskTxHash = TestUtils.createHash(1); byte[] btcTxHash = TestUtils.createHash(2).getBytes(); @@ -70,7 +70,7 @@ void createGetTxInfoToSign_returnOK() throws HSMReleaseCreationInformationExcept ReceiptStore receiptStore = mock(ReceiptStore.class); when(receiptStore.getInMainChain(rskTxHash.getBytes(), blockStore)).thenReturn(Optional.of(transactionInfo)); - ReleaseCreationInformationGetter information = new ReleaseCreationInformationGetter( + PegoutCreationInformationGetter information = new PegoutCreationInformationGetter( receiptStore, blockStore ); @@ -84,26 +84,26 @@ void createGetTxInfoToSign_returnOK() throws HSMReleaseCreationInformationExcept createGetTxInfoToSign_returnOK(information, rskTxHash, btcTransaction, block, transactionReceipt, 4); } - private void createGetTxInfoToSign_returnOK(ReleaseCreationInformationGetter information, - Keccak256 rskTxHash, - BtcTransaction btcTransaction, - Block block, - TransactionReceipt transactionReceipt, - int hsmVersion) throws HSMReleaseCreationInformationException { - ReleaseCreationInformation releaseCreationInformation = information.getTxInfoToSign( + private void createGetTxInfoToSign_returnOK(PegoutCreationInformationGetter information, + Keccak256 pegoutCreationRskTxHash, + BtcTransaction pegoutBtcTx, + Block pegoutCreationRskBlock, + TransactionReceipt transactionReceipt, + int hsmVersion) throws HSMPegoutCreationInformationException { + PegoutCreationInformation pegoutCreationInformation = information.getPegoutCreationInformationToSign( hsmVersion, - rskTxHash, - btcTransaction + pegoutCreationRskTxHash, + pegoutBtcTx ); - assertEquals(releaseCreationInformation.getBlock(), block); - assertEquals(transactionReceipt, releaseCreationInformation.getTransactionReceipt()); - assertEquals(rskTxHash, releaseCreationInformation.getReleaseRskTxHash()); - assertEquals(btcTransaction, releaseCreationInformation.getBtcTransaction()); + assertEquals(pegoutCreationInformation.getPegoutCreationRskBlock(), pegoutCreationRskBlock); + assertEquals(transactionReceipt, pegoutCreationInformation.getTransactionReceipt()); + assertEquals(pegoutCreationRskTxHash, pegoutCreationInformation.getPegoutCreationRskTxHash()); + assertEquals(pegoutBtcTx, pegoutCreationInformation.getPegoutBtcTx()); } @Test - void createGetTxInfoToSign_returnOK_SecondBlock() throws HSMReleaseCreationInformationException { + void createGetTxInfoToSign_returnOK_SecondBlock() throws HSMPegoutCreationInformationException { // The event that is searched is not found in the first block but in the next block obtained. Keccak256 blockHash = TestUtils.createHash(3); Keccak256 rskTxHash = TestUtils.createHash(1); @@ -165,65 +165,65 @@ void createGetTxInfoToSign_returnOK_SecondBlock() throws HSMReleaseCreationInfor when(receiptStore.getInMainChain(rskTxHash.getBytes(), blockStore)).thenReturn(Optional.of(transactionInfo)); when(receiptStore.getInMainChain(rskTxHashInSecondBlock.getBytes(), blockStore)).thenReturn(Optional.of(transactionInfoInSecondBlock)); - ReleaseCreationInformationGetter information = new ReleaseCreationInformationGetter( + PegoutCreationInformationGetter information = new PegoutCreationInformationGetter( receiptStore, blockStore ); - ReleaseCreationInformation releaseCreationInformation = information.getTxInfoToSign(2, rskTxHash, btcTransaction); + PegoutCreationInformation pegoutCreationInformation = information.getPegoutCreationInformationToSign(2, rskTxHash, btcTransaction); - assertEquals(secondBlock, releaseCreationInformation.getBlock()); - assertEquals(transactionReceiptInSecondBlock, releaseCreationInformation.getTransactionReceipt()); - assertEquals(rskTxHash, releaseCreationInformation.getReleaseRskTxHash()); - assertEquals(btcTransaction, releaseCreationInformation.getBtcTransaction()); + assertEquals(secondBlock, pegoutCreationInformation.getPegoutCreationRskBlock()); + assertEquals(transactionReceiptInSecondBlock, pegoutCreationInformation.getTransactionReceipt()); + assertEquals(rskTxHash, pegoutCreationInformation.getPegoutCreationRskTxHash()); + assertEquals(btcTransaction, pegoutCreationInformation.getPegoutBtcTx()); } @Test void createGetTxInfoToSign_transactionHashNotFoundInBlock() { - Keccak256 blockHash = TestUtils.createHash(3); - Keccak256 rskTxHash = TestUtils.createHash(1); - byte[] btcTxHash = TestUtils.createHash(2).getBytes(); - BtcTransaction btcTransaction = mock(BtcTransaction.class); - when(btcTransaction.getHash()).thenReturn(Sha256Hash.wrap(btcTxHash)); + Keccak256 pegoutCreationBlockHash = TestUtils.createHash(3); + Keccak256 pegoutRskTxHash = TestUtils.createHash(1); + byte[] pegoutBtcTxHash = TestUtils.createHash(2).getBytes(); + BtcTransaction pegoutBtcTx = mock(BtcTransaction.class); + when(pegoutBtcTx.getHash()).thenReturn(Sha256Hash.wrap(pegoutBtcTxHash)); Transaction transaction = mock(Transaction.class); - when(transaction.getHash()).thenReturn(rskTxHash); + when(transaction.getHash()).thenReturn(pegoutRskTxHash); TransactionInfo transactionInfo = mock(TransactionInfo.class); - when(transactionInfo.getBlockHash()).thenReturn(blockHash.getBytes()); + when(transactionInfo.getBlockHash()).thenReturn(pegoutCreationBlockHash.getBytes()); Block block = mock(Block.class); - when(block.getHash()).thenReturn(blockHash); + when(block.getHash()).thenReturn(pegoutCreationBlockHash); when(block.getTransactionsList()).thenReturn(new ArrayList<>()); BlockStore blockStore = mock(BlockStore.class); - when(blockStore.getBlockByHash(blockHash.getBytes())).thenReturn(block); + when(blockStore.getBlockByHash(pegoutCreationBlockHash.getBytes())).thenReturn(block); ReceiptStore receiptStore = mock(ReceiptStore.class); - when(receiptStore.getInMainChain(rskTxHash.getBytes(), blockStore)).thenReturn(Optional.of(transactionInfo)); + when(receiptStore.getInMainChain(pegoutRskTxHash.getBytes(), blockStore)).thenReturn(Optional.of(transactionInfo)); - ReleaseCreationInformationGetter information = new ReleaseCreationInformationGetter( + PegoutCreationInformationGetter information = new PegoutCreationInformationGetter( receiptStore, blockStore ); - assertThrows(HSMReleaseCreationInformationException.class, () -> information.getTxInfoToSign( + assertThrows(HSMPegoutCreationInformationException.class, () -> information.getPegoutCreationInformationToSign( 2, - rskTxHash, - btcTransaction + pegoutRskTxHash, + pegoutBtcTx )); } @Test void createGetTxInfoToSignV2_noEventFound_noBlockFound() { - Keccak256 blockHash = TestUtils.createHash(3); - Keccak256 rskTxHash = TestUtils.createHash(1); + Keccak256 pegoutCreationBlockHash = TestUtils.createHash(3); + Keccak256 pegoutRskTxHash = TestUtils.createHash(1); byte[] btcTxHash = TestUtils.createHash(2).getBytes(); BtcTransaction btcTransaction = mock(BtcTransaction.class); when(btcTransaction.getHash()).thenReturn(Sha256Hash.wrap(btcTxHash)); Transaction transaction = mock(Transaction.class); - when(transaction.getHash()).thenReturn(rskTxHash); + when(transaction.getHash()).thenReturn(pegoutRskTxHash); when(transaction.getReceiveAddress()).thenReturn(PrecompiledContracts.BRIDGE_ADDR); TransactionReceipt transactionReceipt = new TransactionReceipt(); @@ -231,26 +231,26 @@ void createGetTxInfoToSignV2_noEventFound_noBlockFound() { TransactionInfo transactionInfo = mock(TransactionInfo.class); when(transactionInfo.getReceipt()).thenReturn(transactionReceipt); - when(transactionInfo.getBlockHash()).thenReturn(blockHash.getBytes()); + when(transactionInfo.getBlockHash()).thenReturn(pegoutCreationBlockHash.getBytes()); Block block = mock(Block.class); - when(block.getHash()).thenReturn(blockHash); + when(block.getHash()).thenReturn(pegoutCreationBlockHash); when(block.getTransactionsList()).thenReturn(Collections.singletonList(transaction)); BlockStore blockStore = mock(BlockStore.class); - when(blockStore.getBlockByHash(blockHash.getBytes())).thenReturn(block); + when(blockStore.getBlockByHash(pegoutCreationBlockHash.getBytes())).thenReturn(block); ReceiptStore receiptStore = mock(ReceiptStore.class); - when(receiptStore.getInMainChain(rskTxHash.getBytes(), blockStore)).thenReturn(Optional.of(transactionInfo)); + when(receiptStore.getInMainChain(pegoutRskTxHash.getBytes(), blockStore)).thenReturn(Optional.of(transactionInfo)); - ReleaseCreationInformationGetter information = new ReleaseCreationInformationGetter( + PegoutCreationInformationGetter information = new PegoutCreationInformationGetter( receiptStore, blockStore ); - assertThrows(HSMReleaseCreationInformationException.class, () -> information.getTxInfoToSign( + assertThrows(HSMPegoutCreationInformationException.class, () -> information.getPegoutCreationInformationToSign( 2, - rskTxHash, + pegoutRskTxHash, btcTransaction )); } @@ -287,12 +287,12 @@ void createGetTxInfoToSignV2_noEventFound_BestBlockFound() { ReceiptStore receiptStore = mock(ReceiptStore.class); when(receiptStore.getInMainChain(rskTxHash.getBytes(), blockStore)).thenReturn(Optional.of(transactionInfo)); - ReleaseCreationInformationGetter information = new ReleaseCreationInformationGetter( + PegoutCreationInformationGetter information = new PegoutCreationInformationGetter( receiptStore, blockStore ); - assertThrows(HSMReleaseCreationInformationException.class, () -> information.getTxInfoToSign( + assertThrows(HSMPegoutCreationInformationException.class, () -> information.getPegoutCreationInformationToSign( 2, rskTxHash, btcTransaction diff --git a/src/test/java/co/rsk/federate/signing/hsm/message/PowHSMSignerMessageBuilderTest.java b/src/test/java/co/rsk/federate/signing/hsm/message/PowHSMSignerMessageBuilderTest.java index fb3d71e21..45ed8e049 100644 --- a/src/test/java/co/rsk/federate/signing/hsm/message/PowHSMSignerMessageBuilderTest.java +++ b/src/test/java/co/rsk/federate/signing/hsm/message/PowHSMSignerMessageBuilderTest.java @@ -67,7 +67,7 @@ void createHSMVersion2Message() throws SignerMessageBuilderException { //Act PowHSMSignerMessageBuilder sigMessVersion2 = new PowHSMSignerMessageBuilder( receiptStore, - new ReleaseCreationInformation( + new PegoutCreationInformation( block, txReceipt, rskTxHash, @@ -112,7 +112,7 @@ void buildMessageForIndex_fails() { ReceiptStore receiptStore = mock(ReceiptStore.class); when(receiptStore.get(any(byte[].class), any(byte[].class))).thenReturn(Optional.empty()); - ReleaseCreationInformation releaseCreationInformation = new ReleaseCreationInformation( + PegoutCreationInformation pegoutCreationInformation = new PegoutCreationInformation( block, transactionReceipt, rskTx.getHash(), @@ -121,7 +121,7 @@ void buildMessageForIndex_fails() { ); PowHSMSignerMessageBuilder sigMessVersion2 = new PowHSMSignerMessageBuilder( receiptStore, - releaseCreationInformation + pegoutCreationInformation ); assertThrows(SignerMessageBuilderException.class, () -> sigMessVersion2.buildMessageForIndex(0)); } diff --git a/src/test/java/co/rsk/federate/signing/hsm/message/SignerMessageBuilderFactoryTest.java b/src/test/java/co/rsk/federate/signing/hsm/message/SignerMessageBuilderFactoryTest.java index 28ae57528..23fd08c98 100644 --- a/src/test/java/co/rsk/federate/signing/hsm/message/SignerMessageBuilderFactoryTest.java +++ b/src/test/java/co/rsk/federate/signing/hsm/message/SignerMessageBuilderFactoryTest.java @@ -31,7 +31,7 @@ public void createFactory() { void buildWithWrongVersion() { assertThrows(HSMUnsupportedVersionException.class, () -> factory.buildFromConfig( -5, - mock(ReleaseCreationInformation.class) + mock(PegoutCreationInformation.class) )); } @@ -40,7 +40,7 @@ void buildWithWrongVersion() { void buildFromHSMVersion1() throws HSMClientException { SignerMessageBuilder sigMessVersion1 = factory.buildFromConfig( 1, - mock(ReleaseCreationInformation.class) + mock(PegoutCreationInformation.class) ); assertTrue(sigMessVersion1 instanceof SignerMessageBuilderV1); } @@ -71,7 +71,7 @@ void test_buildFromConfig_hsm(int version) throws HSMUnsupportedVersionException ); SignerMessageBuilder messageBuilder = factory.buildFromConfig( version, - new ReleaseCreationInformation( + new PegoutCreationInformation( block, mock(TransactionReceipt.class), Keccak256.ZERO_HASH, diff --git a/src/test/java/co/rsk/federate/signing/hsm/requirements/ReleaseRequirementsEnforcerTest.java b/src/test/java/co/rsk/federate/signing/hsm/requirements/PegoutSigningRequirementsEnforcerTest.java similarity index 61% rename from src/test/java/co/rsk/federate/signing/hsm/requirements/ReleaseRequirementsEnforcerTest.java rename to src/test/java/co/rsk/federate/signing/hsm/requirements/PegoutSigningRequirementsEnforcerTest.java index 33c9cddf1..12c54e884 100644 --- a/src/test/java/co/rsk/federate/signing/hsm/requirements/ReleaseRequirementsEnforcerTest.java +++ b/src/test/java/co/rsk/federate/signing/hsm/requirements/PegoutSigningRequirementsEnforcerTest.java @@ -8,27 +8,27 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import co.rsk.federate.signing.hsm.message.ReleaseCreationInformation; +import co.rsk.federate.signing.hsm.message.PegoutCreationInformation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -class ReleaseRequirementsEnforcerTest { +class PegoutSigningRequirementsEnforcerTest { private AncestorBlockUpdater ancestorBlockUpdater; - private ReleaseRequirementsEnforcer enforcer; + private PegoutSigningRequirementsEnforcer enforcer; @BeforeEach void setup() { ancestorBlockUpdater = mock(AncestorBlockUpdater.class); - enforcer = new ReleaseRequirementsEnforcer(ancestorBlockUpdater); + enforcer = new PegoutSigningRequirementsEnforcer(ancestorBlockUpdater); } @Test void enforce_does_nothing_if_version_one() throws Exception { AncestorBlockUpdater ancestorBlockUpdater = mock(AncestorBlockUpdater.class); - ReleaseRequirementsEnforcer enforcer = new ReleaseRequirementsEnforcer(ancestorBlockUpdater); + PegoutSigningRequirementsEnforcer enforcer = new PegoutSigningRequirementsEnforcer(ancestorBlockUpdater); - enforcer.enforce(1, mock(ReleaseCreationInformation.class)); + enforcer.enforce(1, mock(PegoutCreationInformation.class)); verify(ancestorBlockUpdater, never()).ensureAncestorBlockInPosition(any()); } @@ -48,8 +48,8 @@ void enforce_version_four_ok() throws Exception { test_enforce_version(ancestorBlockUpdater, enforcer, 4); } - void test_enforce_version(AncestorBlockUpdater ancestorBlockUpdater, ReleaseRequirementsEnforcer enforcer, int version) throws Exception { - enforcer.enforce(version, mock(ReleaseCreationInformation.class)); + void test_enforce_version(AncestorBlockUpdater ancestorBlockUpdater, PegoutSigningRequirementsEnforcer enforcer, int version) throws Exception { + enforcer.enforce(version, mock(PegoutCreationInformation.class)); verify(ancestorBlockUpdater, times(1)).ensureAncestorBlockInPosition(any()); } @@ -58,15 +58,15 @@ void test_enforce_version(AncestorBlockUpdater ancestorBlockUpdater, ReleaseRequ void enforce_version_two_updater_fails() throws Exception { AncestorBlockUpdater ancestorBlockUpdater = mock(AncestorBlockUpdater.class); doThrow(new Exception()).when(ancestorBlockUpdater).ensureAncestorBlockInPosition(any()); - ReleaseRequirementsEnforcer enforcer = new ReleaseRequirementsEnforcer(ancestorBlockUpdater); + PegoutSigningRequirementsEnforcer enforcer = new PegoutSigningRequirementsEnforcer(ancestorBlockUpdater); - assertThrows(ReleaseRequirementsEnforcerException.class, () -> enforcer.enforce(2, mock(ReleaseCreationInformation.class))); + assertThrows(PegoutSigningRequirementsEnforcerException.class, () -> enforcer.enforce(2, mock(PegoutCreationInformation.class))); } @Test void enforce_invalid_version() { - ReleaseRequirementsEnforcer enforcer = new ReleaseRequirementsEnforcer(mock(AncestorBlockUpdater.class)); + PegoutSigningRequirementsEnforcer enforcer = new PegoutSigningRequirementsEnforcer(mock(AncestorBlockUpdater.class)); - assertThrows(ReleaseRequirementsEnforcerException.class, () -> enforcer.enforce(-5, mock(ReleaseCreationInformation.class))); + assertThrows(PegoutSigningRequirementsEnforcerException.class, () -> enforcer.enforce(-5, mock(PegoutCreationInformation.class))); } }