Skip to content

Commit

Permalink
Refactor ECDSASignerFactory to encapsulate logic in methods
Browse files Browse the repository at this point in the history
  • Loading branch information
marcos-iov committed Aug 22, 2024
1 parent 97d58c3 commit 6e12eca
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 45 deletions.
56 changes: 29 additions & 27 deletions src/main/java/co/rsk/federate/FedNodeRunner.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import co.rsk.NodeRunner;
import co.rsk.bitcoinj.core.BtcECKey;
import co.rsk.core.RskAddress;
import co.rsk.federate.signing.hsm.HSMVersion;
import co.rsk.peg.constants.BridgeConstants;
import co.rsk.federate.adapter.ThinConverter;
Expand Down Expand Up @@ -73,7 +74,7 @@
*/

public class FedNodeRunner implements NodeRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(FedNodeRunner.class);
private static final Logger logger = LoggerFactory.getLogger(FedNodeRunner.class);
private final BtcToRskClient btcToRskClientActive;
private final BtcToRskClient btcToRskClientRetiring;
private final BtcReleaseClient btcReleaseClient;
Expand Down Expand Up @@ -126,7 +127,7 @@ public FedNodeRunner(

@Override
public void run() throws Exception {
LOGGER.debug("[run] Starting RSK");
logger.debug("[run] Starting RSK");
signer = buildSigner();

SignerConfig btcSignerConfig = config.signerConfig(BTC.getId());
Expand All @@ -135,22 +136,23 @@ public void run() throws Exception {
}

if (!this.checkFederateRequirements()) {
LOGGER.error("[run] Error validating Fed-Node Requirements");
logger.error("[run] Error validating Fed-Node Requirements");
return;
}

LOGGER.info("[run] Signers: {}", signer.getVersionString());
logger.info("[run] Signers: {}", signer.getVersionString());
configureFederatorSupport();
fullNodeRunner.run();
startFederate();

signer.addListener(l -> {
LOGGER.error("[run] Signer informed unrecoverable state, shutting down", l);
logger.error("[run] Signer informed unrecoverable state, shutting down", l);
this.shutdown();
});

LOGGER.info("[run] Federated node started");
LOGGER.info("[run] RSK address: {}", Hex.toHexString(this.member.getRskPublicKey().getAddress()));
RskAddress pegnatoryRskAddress = new RskAddress(this.member.getRskPublicKey().getAddress());
logger.info("[run] Federated node started");
logger.info("[run] RSK address: {}", pegnatoryRskAddress);
}

private void startBookkeepingServices() throws SignerException, HSMClientException {
Expand All @@ -161,7 +163,7 @@ private void startBookkeepingServices() throws SignerException, HSMClientExcepti
hsmClientProtocolFactory.buildHSMClientProtocolFromConfig(powHsmConfig);

int hsmVersion = protocol.getVersion();
LOGGER.debug("[run] Using HSM version {}", hsmVersion);
logger.debug("[run] Using HSM version {}", hsmVersion);

if (HSMVersion.isPowHSM(hsmVersion)) {
hsmBookkeepingClient = buildBookKeepingClient(
Expand All @@ -175,7 +177,7 @@ private void configureFederatorSupport() throws SignerException {
BtcECKey btcPublicKey = signer.getPublicKey(BTC.getKeyId()).toBtcKey();
ECKey rskPublicKey = signer.getPublicKey(RSK.getKeyId()).toEthKey();
ECKey mstKey = signer.getPublicKey(MST.getKeyId()).toEthKey();
LOGGER.info(
logger.info(
"[configureFederatorSupport] BTC public key: {}. RSK public key: {}. MST public key: {}",
btcPublicKey,
rskPublicKey,
Expand All @@ -200,14 +202,14 @@ private ECDSASigner buildSigner() {
ECDSASigner createdSigner = buildSignerFromKey(keyId.getKeyId());
compositeSigner.addSigner(createdSigner);
} catch (SignerException e) {
LOGGER.error("[buildSigner] Error trying to build signer with key id {}. Detail: {}", keyId, e.getMessage());
logger.error("[buildSigner] Error trying to build signer with key id {}. Detail: {}", keyId, e.getMessage());
} catch (Exception e) {
LOGGER.error("[buildSigner] Error creating signer {}. Detail: {}", keyId, e.getMessage());
logger.error("[buildSigner] Error creating signer {}. Detail: {}", keyId, e.getMessage());
throw e;
}
});

LOGGER.debug("[buildSigner] Signers created");
logger.debug("[buildSigner] Signers created");

return compositeSigner;
}
Expand All @@ -218,7 +220,7 @@ private HSMBookkeepingClient buildBookKeepingClient(

HSMBookkeepingClient bookKeepingClient = hsmBookKeepingClientProvider.getHSMBookKeepingClient(protocol);
bookKeepingClient.setMaxChunkSizeToHsm(powHsmConfig.getMaxChunkSizeToHsm());
LOGGER.info("[buildBookKeepingClient] HSMBookkeeping client built for HSM version: {}", bookKeepingClient.getVersion());
logger.info("[buildBookKeepingClient] HSMBookkeeping client built for HSM version: {}", bookKeepingClient.getVersion());
return bookKeepingClient;
}

Expand All @@ -240,7 +242,7 @@ private HSMBookkeepingService buildBookKeepingService(
powHsmConfig.getInformerInterval(),
powHsmConfig.isStopBookkeepingScheduler()
);
LOGGER.info("[buildBookKeepingService] HSMBookkeeping Service built for HSM version: {}", bookKeepingClient.getVersion());
logger.info("[buildBookKeepingService] HSMBookkeeping Service built for HSM version: {}", bookKeepingClient.getVersion());
return service;
}

Expand Down Expand Up @@ -274,7 +276,7 @@ private boolean checkFederateRequirements() {
}

private void startFederate() throws Exception {
LOGGER.debug("[startFederate] Starting Federation Behaviour");
logger.debug("[startFederate] Starting Federation Behaviour");
if (config.isFederatorEnabled()) {
// Set up a federation watcher to trigger starts and stops of the
// btc to rsk client upon federation changes
Expand Down Expand Up @@ -308,8 +310,8 @@ private void startFederate() throws Exception {
btcLogMonitor.start();
rskLogMonitor.start();
if (hsmBookkeepingService != null) {
hsmBookkeepingService.addListener((e) -> {
LOGGER.error("[startFederate] HSM bookkeeping service informed unrecoverable state, shutting down", e);
hsmBookkeepingService.addListener(e -> {
logger.error("[startFederate] HSM bookkeeping service informed unrecoverable state, shutting down", e);
this.shutdown();
});
hsmBookkeepingService.start();
Expand Down Expand Up @@ -348,15 +350,15 @@ private void startFederate() throws Exception {
public void onActiveFederationChange(Optional<Federation> oldFederation, Federation newFederation) {
String oldFederationAddress = oldFederation.map(f -> f.getAddress().toString()).orElse("NONE");
String newFederationAddress = newFederation.getAddress().toString();
LOGGER.debug(String.format("[onActiveFederationChange] Active federation change: from %s to %s", oldFederationAddress, newFederationAddress));
logger.debug(String.format("[onActiveFederationChange] Active federation change: from %s to %s", oldFederationAddress, newFederationAddress));
triggerClientChange(btcToRskClientActive, Optional.of(newFederation));
}

@Override
public void onRetiringFederationChange(Optional<Federation> oldFederation, Optional<Federation> newFederation) {
String oldFederationAddress = oldFederation.map(f -> f.getAddress().toString()).orElse("NONE");
String newFederationAddress = newFederation.map(f -> f.getAddress().toString()).orElse("NONE");
LOGGER.debug(String.format("[onRetiringFederationChange] Retiring federation change: from %s to %s", oldFederationAddress, newFederationAddress));
logger.debug(String.format("[onRetiringFederationChange] Retiring federation change: from %s to %s", oldFederationAddress, newFederationAddress));
triggerClientChange(btcToRskClientRetiring, newFederation);
}
});
Expand All @@ -367,18 +369,18 @@ public void onRetiringFederationChange(Optional<Federation> oldFederation, Optio

@PreDestroy
public void tearDown() {
LOGGER.debug("[tearDown] FederateRunner tearDown starting...");
logger.debug("[tearDown] FederateRunner tearDown starting...");

this.stop();

LOGGER.debug("[tearDown] FederateRunner tearDown finished.");
logger.debug("[tearDown] FederateRunner tearDown finished.");
}

private void shutdown() {
try {
this.tearDown();
} catch(Exception e){
LOGGER.error("[shutdown] FederateRunner teardown failed", e);
logger.error("[shutdown] FederateRunner teardown failed", e);
}
System.exit(-1);
}
Expand All @@ -390,18 +392,18 @@ private void triggerClientChange(BtcToRskClient client, Optional<Federation> fed
// 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.info("[triggerClientChange] Joined to {} federation", federationAddress);
logger.debug("[triggerClientChange] Starting lock and release clients since I belong to federation {}", federationAddress);
logger.info("[triggerClientChange] Joined to {} federation", federationAddress);
client.start(federation.get());
btcReleaseClient.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");
logger.warn("[triggerClientChange] This federator node is not part of the new federation. Check your configuration for signers BTC, RSK and MST keys");
}
}

@Override
public void stop() {
LOGGER.info("[stop] Shutting down Federation node");
logger.info("[stop] Shutting down Federation node");
if (bitcoinWrapper != null) {
bitcoinWrapper.stop();
}
Expand All @@ -417,7 +419,7 @@ public void stop() {
}

fullNodeRunner.stop();
LOGGER.info("[stop] Federation node Shut down.");
logger.info("[stop] Federation node Shut down.");
}

private BitcoinWrapper createAndSetupBitcoinWrapper(
Expand Down
39 changes: 21 additions & 18 deletions src/main/java/co/rsk/federate/signing/ECDSASignerFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,27 +40,30 @@ public ECDSASigner buildFromConfig(SignerConfig config) throws SignerException {
switch (type) {
case KEYFILE:
return new ECDSASignerFromFileKey(
new KeyId(config.getId()),
config.getConfig().getString("path")
new KeyId(config.getId()),
config.getConfig().getString("path")
);
case HSM:
try {
PowHSMConfig powHSMConfig = new PowHSMConfig(config);
HSMClientProtocol hsmClientProtocol =
new HSMClientProtocolFactory().buildHSMClientProtocolFromConfig(powHSMConfig);
HSMSigningClientProvider hsmSigningClientProvider = new HSMSigningClientProvider(hsmClientProtocol, config.getId());
ECDSAHSMSigner signer = new ECDSAHSMSigner(hsmSigningClientProvider);
// Add the key mapping
String hsmKeyId = config.getConfig().getString("keyId");
signer.addKeyMapping(new KeyId(config.getId()), hsmKeyId);
return signer;
} catch (Exception e) {
String message = "Something went wrong while trying to build HSM Signer";
logger.debug("[buildFromConfig] {} - {}", message, e.getMessage());
throw new RuntimeException(e.getMessage());
}
return buildHSMFromConfig(config);
default:
throw new RuntimeException(String.format("Unsupported signer type: %s", type));
throw new IllegalArgumentException(String.format("Unsupported signer type: %s", type));
}
}

private ECDSAHSMSigner buildHSMFromConfig(SignerConfig config) throws SignerException {
PowHSMConfig powHSMConfig = new PowHSMConfig(config);
HSMClientProtocol hsmClientProtocol = new HSMClientProtocolFactory().buildHSMClientProtocolFromConfig(
powHSMConfig
);
HSMSigningClientProvider hsmSigningClientProvider = new HSMSigningClientProvider(
hsmClientProtocol,
config.getId()
);
ECDSAHSMSigner signer = new ECDSAHSMSigner(hsmSigningClientProvider);
// Add the key mapping
String hsmKeyId = config.getConfig().getString("keyId");
signer.addKeyMapping(new KeyId(config.getId()), hsmKeyId);

return signer;
}
}

0 comments on commit 6e12eca

Please sign in to comment.