From f6add5b2ea8e9168b1ef467b9a8af8896504d6ae Mon Sep 17 00:00:00 2001 From: Christian Basler Date: Thu, 25 Feb 2016 16:36:43 +0100 Subject: [PATCH] Code cleanup --- .../dissem/bitmessage/BitmessageContext.java | 3 +- .../bitmessage/entity/payload/CryptoBox.java | 3 +- .../ch/dissem/bitmessage/utils/Base58.java | 3 +- .../bitmessage/BitmessageContextTest.java | 3 +- .../entity/BitmessageAddressTest.java | 56 ++++++++++--------- .../cryptography/bc/BouncyCryptography.java | 10 ++-- .../cryptography/sc/SpongyCryptography.java | 10 ++-- .../java/ch/dissem/bitmessage/SystemTest.java | 12 ++-- .../bitmessage/networking/Connection.java | 6 +- .../networking/DefaultNetworkHandler.java | 7 ++- .../repository/JdbcAddressRepository.java | 7 ++- .../repository/JdbcProofOfWorkRepository.java | 17 +++--- 12 files changed, 80 insertions(+), 57 deletions(-) diff --git a/core/src/main/java/ch/dissem/bitmessage/BitmessageContext.java b/core/src/main/java/ch/dissem/bitmessage/BitmessageContext.java index 9344b41..60b7267 100644 --- a/core/src/main/java/ch/dissem/bitmessage/BitmessageContext.java +++ b/core/src/main/java/ch/dissem/bitmessage/BitmessageContext.java @@ -416,7 +416,8 @@ public class BitmessageContext { customCommandHandler = new CustomCommandHandler() { @Override public MessagePayload handle(CustomMessage request) { - throw new RuntimeException("Received custom request, but no custom command handler configured."); + throw new IllegalStateException( + "Received custom request, but no custom command handler configured."); } }; } diff --git a/core/src/main/java/ch/dissem/bitmessage/entity/payload/CryptoBox.java b/core/src/main/java/ch/dissem/bitmessage/entity/payload/CryptoBox.java index 3d1c926..8887fea 100644 --- a/core/src/main/java/ch/dissem/bitmessage/entity/payload/CryptoBox.java +++ b/core/src/main/java/ch/dissem/bitmessage/entity/payload/CryptoBox.java @@ -17,6 +17,7 @@ package ch.dissem.bitmessage.entity.payload; import ch.dissem.bitmessage.entity.Streamable; +import ch.dissem.bitmessage.exception.ApplicationException; import ch.dissem.bitmessage.exception.DecryptionFailedException; import ch.dissem.bitmessage.utils.*; import org.slf4j.Logger; @@ -123,7 +124,7 @@ public class CryptoBox implements Streamable { writeWithoutMAC(macData); return security().mac(key_m, macData.toByteArray()); } catch (IOException e) { - throw new RuntimeException(e); + throw new ApplicationException(e); } } diff --git a/core/src/main/java/ch/dissem/bitmessage/utils/Base58.java b/core/src/main/java/ch/dissem/bitmessage/utils/Base58.java index 9f35fb7..167d862 100644 --- a/core/src/main/java/ch/dissem/bitmessage/utils/Base58.java +++ b/core/src/main/java/ch/dissem/bitmessage/utils/Base58.java @@ -18,6 +18,7 @@ package ch.dissem.bitmessage.utils; import ch.dissem.bitmessage.exception.AddressFormatException; +import ch.dissem.bitmessage.exception.ApplicationException; import java.io.UnsupportedEncodingException; @@ -83,7 +84,7 @@ public class Base58 { try { return new String(output, "US-ASCII"); } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); // Cannot happen. + throw new ApplicationException(e); // Cannot happen. } } diff --git a/core/src/test/java/ch/dissem/bitmessage/BitmessageContextTest.java b/core/src/test/java/ch/dissem/bitmessage/BitmessageContextTest.java index 828e794..890c2c3 100644 --- a/core/src/test/java/ch/dissem/bitmessage/BitmessageContextTest.java +++ b/core/src/test/java/ch/dissem/bitmessage/BitmessageContextTest.java @@ -194,7 +194,8 @@ public class BitmessageContextTest { .putObject(object(BROADCAST), eq(1000L), eq(1000L)); verify(ctx.internals().getProofOfWorkEngine()) .calculateNonce(any(byte[].class), any(byte[].class), any(ProofOfWorkEngine.Callback.class)); - verify(ctx.messages(), timeout(10000).atLeastOnce()).save(MessageMatchers.plaintext(Plaintext.Type.BROADCAST)); + verify(ctx.messages(), timeout(10000).atLeastOnce()) + .save(MessageMatchers.plaintext(Plaintext.Type.BROADCAST)); } @Test(expected = IllegalArgumentException.class) diff --git a/core/src/test/java/ch/dissem/bitmessage/entity/BitmessageAddressTest.java b/core/src/test/java/ch/dissem/bitmessage/entity/BitmessageAddressTest.java index e1fcc7f..495aea9 100644 --- a/core/src/test/java/ch/dissem/bitmessage/entity/BitmessageAddressTest.java +++ b/core/src/test/java/ch/dissem/bitmessage/entity/BitmessageAddressTest.java @@ -55,44 +55,56 @@ public class BitmessageAddressTest { } @Test - public void testCreateAddress() { + public void ensureIdentityCanBeCreated() { BitmessageAddress address = new BitmessageAddress(new PrivateKey(false, 1, 1000, 1000, DOES_ACK)); assertNotNull(address.getPubkey()); } @Test - public void testV2PubkeyImport() throws IOException { + public void ensureV2PubkeyCanBeImported() throws IOException { ObjectMessage object = TestUtils.loadObjectMessage(2, "V2Pubkey.payload"); Pubkey pubkey = (Pubkey) object.getPayload(); BitmessageAddress address = new BitmessageAddress("BM-opWQhvk9xtMFvQA2Kvetedpk8LkbraWHT"); - address.setPubkey(pubkey); + try { + address.setPubkey(pubkey); + } catch (Exception e) { + fail(e.getMessage()); + } } @Test - public void testV3PubkeyImport() throws IOException { + public void ensureV3PubkeyCanBeImported() throws IOException { BitmessageAddress address = new BitmessageAddress("BM-2D9Vc5rFxxR5vTi53T9gkLfemViHRMVLQZ"); assertArrayEquals(Bytes.fromHex("007402be6e76c3cb87caa946d0c003a3d4d8e1d5"), address.getRipe()); ObjectMessage object = TestUtils.loadObjectMessage(3, "V3Pubkey.payload"); Pubkey pubkey = (Pubkey) object.getPayload(); assertTrue(object.isSignatureValid(pubkey)); - address.setPubkey(pubkey); + try { + address.setPubkey(pubkey); + } catch (Exception e) { + fail(e.getMessage()); + } assertArrayEquals(Bytes.fromHex("007402be6e76c3cb87caa946d0c003a3d4d8e1d5"), pubkey.getRipe()); } @Test - public void testV4PubkeyImport() throws IOException, DecryptionFailedException { + public void ensureV4PubkeyCanBeImported() throws IOException, DecryptionFailedException { BitmessageAddress address = new BitmessageAddress("BM-2cXxfcSetKnbHJX2Y85rSkaVpsdNUZ5q9h"); ObjectMessage object = TestUtils.loadObjectMessage(4, "V4Pubkey.payload"); object.decrypt(address.getPublicDecryptionKey()); V4Pubkey pubkey = (V4Pubkey) object.getPayload(); assertTrue(object.isSignatureValid(pubkey)); - address.setPubkey(pubkey); + try { + address.setPubkey(pubkey); + } catch (Exception e) { + fail(e.getMessage()); + } } @Test - public void testV3AddressImport() throws IOException { + public void ensureV3IdentityCanBeImported() throws IOException { String address_string = "BM-2DAjcCFrqFrp88FUxExhJ9kPqHdunQmiyn"; assertEquals(3, new BitmessageAddress(address_string).getVersion()); assertEquals(1, new BitmessageAddress(address_string).getStream()); @@ -108,9 +120,17 @@ public class BitmessageAddressTest { } @Test - public void testGetSecret() throws IOException { - assertHexEquals("0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D", - getSecret("5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ")); + public void ensureV4IdentityCanBeImported() throws IOException { + assertEquals(4, new BitmessageAddress("BM-2cV5f9EpzaYARxtoruSpa6pDoucSf9ZNke").getVersion()); + byte[] privsigningkey = getSecret("5KMWqfCyJZGFgW6QrnPJ6L9Gatz25B51y7ErgqNr1nXUVbtZbdU"); + byte[] privencryptionkey = getSecret("5JXXWEuhHQEPk414SzEZk1PHDRi8kCuZd895J7EnKeQSahJPxGz"); + BitmessageAddress address = new BitmessageAddress(new PrivateKey(privsigningkey, privencryptionkey, + security().createPubkey(4, 1, privsigningkey, privencryptionkey, 320, 14000))); + assertEquals("BM-2cV5f9EpzaYARxtoruSpa6pDoucSf9ZNke", address.getAddress()); + } + + private void assertHexEquals(String hex, byte[] bytes) { + assertEquals(hex.toLowerCase(), Strings.hex(bytes).toString().toLowerCase()); } private byte[] getSecret(String walletImportFormat) throws IOException { @@ -126,18 +146,4 @@ public class BitmessageAddressTest { } return Arrays.copyOfRange(bytes, 1, 33); } - - @Test - public void testV4AddressImport() throws IOException { - assertEquals(4, new BitmessageAddress("BM-2cV5f9EpzaYARxtoruSpa6pDoucSf9ZNke").getVersion()); - byte[] privsigningkey = getSecret("5KMWqfCyJZGFgW6QrnPJ6L9Gatz25B51y7ErgqNr1nXUVbtZbdU"); - byte[] privencryptionkey = getSecret("5JXXWEuhHQEPk414SzEZk1PHDRi8kCuZd895J7EnKeQSahJPxGz"); - BitmessageAddress address = new BitmessageAddress(new PrivateKey(privsigningkey, privencryptionkey, - security().createPubkey(4, 1, privsigningkey, privencryptionkey, 320, 14000))); - assertEquals("BM-2cV5f9EpzaYARxtoruSpa6pDoucSf9ZNke", address.getAddress()); - } - - private void assertHexEquals(String hex, byte[] bytes) { - assertEquals(hex.toLowerCase(), Strings.hex(bytes).toString().toLowerCase()); - } } diff --git a/cryptography-bc/src/main/java/ch/dissem/bitmessage/cryptography/bc/BouncyCryptography.java b/cryptography-bc/src/main/java/ch/dissem/bitmessage/cryptography/bc/BouncyCryptography.java index 28be67a..41e2c37 100644 --- a/cryptography-bc/src/main/java/ch/dissem/bitmessage/cryptography/bc/BouncyCryptography.java +++ b/cryptography-bc/src/main/java/ch/dissem/bitmessage/cryptography/bc/BouncyCryptography.java @@ -18,6 +18,7 @@ package ch.dissem.bitmessage.cryptography.bc; import ch.dissem.bitmessage.entity.payload.Pubkey; import ch.dissem.bitmessage.entity.valueobject.PrivateKey; +import ch.dissem.bitmessage.exception.ApplicationException; import ch.dissem.bitmessage.ports.AbstractCryptography; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.crypto.BufferedBlockCipher; @@ -37,6 +38,7 @@ import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.math.ec.ECPoint; import java.math.BigInteger; +import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; @@ -109,8 +111,8 @@ public class BouncyCryptography extends AbstractCryptography { sig.initVerify(publicKey); sig.update(data); return sig.verify(signature); - } catch (Exception e) { - throw new RuntimeException(e); + } catch (GeneralSecurityException e) { + throw new ApplicationException(e); } } @@ -133,8 +135,8 @@ public class BouncyCryptography extends AbstractCryptography { sig.initSign(privKey); sig.update(data); return sig.sign(); - } catch (Exception e) { - throw new RuntimeException(e); + } catch (GeneralSecurityException e) { + throw new ApplicationException(e); } } diff --git a/cryptography-sc/src/main/java/ch/dissem/bitmessage/cryptography/sc/SpongyCryptography.java b/cryptography-sc/src/main/java/ch/dissem/bitmessage/cryptography/sc/SpongyCryptography.java index c9506fb..066ca10 100644 --- a/cryptography-sc/src/main/java/ch/dissem/bitmessage/cryptography/sc/SpongyCryptography.java +++ b/cryptography-sc/src/main/java/ch/dissem/bitmessage/cryptography/sc/SpongyCryptography.java @@ -18,6 +18,7 @@ package ch.dissem.bitmessage.cryptography.sc; import ch.dissem.bitmessage.entity.payload.Pubkey; import ch.dissem.bitmessage.entity.valueobject.PrivateKey; +import ch.dissem.bitmessage.exception.ApplicationException; import ch.dissem.bitmessage.ports.AbstractCryptography; import org.spongycastle.asn1.x9.X9ECParameters; import org.spongycastle.crypto.BufferedBlockCipher; @@ -37,6 +38,7 @@ import org.spongycastle.jce.spec.ECPublicKeySpec; import org.spongycastle.math.ec.ECPoint; import java.math.BigInteger; +import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; @@ -109,8 +111,8 @@ public class SpongyCryptography extends AbstractCryptography { sig.initVerify(publicKey); sig.update(data); return sig.verify(signature); - } catch (Exception e) { - throw new RuntimeException(e); + } catch (GeneralSecurityException e) { + throw new ApplicationException(e); } } @@ -133,8 +135,8 @@ public class SpongyCryptography extends AbstractCryptography { sig.initSign(privKey); sig.update(data); return sig.sign(); - } catch (Exception e) { - throw new RuntimeException(e); + } catch (GeneralSecurityException e) { + throw new ApplicationException(e); } } diff --git a/demo/src/test/java/ch/dissem/bitmessage/SystemTest.java b/demo/src/test/java/ch/dissem/bitmessage/SystemTest.java index a2e3da7..06b6628 100644 --- a/demo/src/test/java/ch/dissem/bitmessage/SystemTest.java +++ b/demo/src/test/java/ch/dissem/bitmessage/SystemTest.java @@ -19,6 +19,8 @@ import static org.junit.Assert.assertThat; * @author Christian Basler */ public class SystemTest { + private static int port = 6000; + private BitmessageContext alice; private TestListener aliceListener = new TestListener(); private BitmessageAddress aliceIdentity; @@ -29,6 +31,8 @@ public class SystemTest { @Before public void setUp() { + int alicePort = port++; + int bobPort = port++; TTL.msg(5 * MINUTE); TTL.getpubkey(5 * MINUTE); TTL.pubkey(5 * MINUTE); @@ -38,8 +42,8 @@ public class SystemTest { .inventory(new JdbcInventory(aliceDB)) .messageRepo(new JdbcMessageRepository(aliceDB)) .powRepo(new JdbcProofOfWorkRepository(aliceDB)) - .port(6001) - .nodeRegistry(new TestNodeRegistry(6002)) + .port(alicePort) + .nodeRegistry(new TestNodeRegistry(bobPort)) .networkHandler(new DefaultNetworkHandler()) .cryptography(new BouncyCryptography()) .listener(aliceListener) @@ -53,8 +57,8 @@ public class SystemTest { .inventory(new JdbcInventory(bobDB)) .messageRepo(new JdbcMessageRepository(bobDB)) .powRepo(new JdbcProofOfWorkRepository(bobDB)) - .port(6002) - .nodeRegistry(new TestNodeRegistry(6001)) + .port(bobPort) + .nodeRegistry(new TestNodeRegistry(alicePort)) .networkHandler(new DefaultNetworkHandler()) .cryptography(new BouncyCryptography()) .listener(bobListener) diff --git a/networking/src/main/java/ch/dissem/bitmessage/networking/Connection.java b/networking/src/main/java/ch/dissem/bitmessage/networking/Connection.java index f24736f..4f99144 100644 --- a/networking/src/main/java/ch/dissem/bitmessage/networking/Connection.java +++ b/networking/src/main/java/ch/dissem/bitmessage/networking/Connection.java @@ -21,6 +21,7 @@ import ch.dissem.bitmessage.InternalContext; import ch.dissem.bitmessage.entity.*; import ch.dissem.bitmessage.entity.valueobject.InventoryVector; import ch.dissem.bitmessage.entity.valueobject.NetworkAddress; +import ch.dissem.bitmessage.exception.ApplicationException; import ch.dissem.bitmessage.exception.InsufficientProofOfWorkException; import ch.dissem.bitmessage.exception.NodeException; import ch.dissem.bitmessage.factory.Factory; @@ -253,7 +254,7 @@ class Connection { case VERACK: case VERSION: default: - throw new RuntimeException("Unexpectedly received '" + messagePayload.getCommand() + "' command"); + throw new IllegalStateException("Unexpectedly received '" + messagePayload.getCommand() + "' command"); } } @@ -386,6 +387,8 @@ class Connection { case SYNC: activateConnection(); break; + default: + // NO OP } } else { LOG.info("Received unsupported version " + payload.getVersion() + ", disconnecting."); @@ -399,6 +402,7 @@ class Connection { break; case CLIENT: case SYNC: + default: // NO OP break; } diff --git a/networking/src/main/java/ch/dissem/bitmessage/networking/DefaultNetworkHandler.java b/networking/src/main/java/ch/dissem/bitmessage/networking/DefaultNetworkHandler.java index f69af2c..44dd437 100644 --- a/networking/src/main/java/ch/dissem/bitmessage/networking/DefaultNetworkHandler.java +++ b/networking/src/main/java/ch/dissem/bitmessage/networking/DefaultNetworkHandler.java @@ -23,6 +23,7 @@ import ch.dissem.bitmessage.entity.GetData; import ch.dissem.bitmessage.entity.NetworkMessage; import ch.dissem.bitmessage.entity.valueobject.InventoryVector; import ch.dissem.bitmessage.entity.valueobject.NetworkAddress; +import ch.dissem.bitmessage.exception.ApplicationException; import ch.dissem.bitmessage.exception.NodeException; import ch.dissem.bitmessage.factory.Factory; import ch.dissem.bitmessage.ports.NetworkHandler; @@ -85,7 +86,7 @@ public class DefaultNetworkHandler implements NetworkHandler, ContextHolder { pool.execute(connection.getWriter()); return reader; } catch (IOException e) { - throw new RuntimeException(e); + throw new ApplicationException(e); } } @@ -106,7 +107,7 @@ public class DefaultNetworkHandler implements NetworkHandler, ContextHolder { } } } catch (IOException e) { - throw new RuntimeException(e); + throw new ApplicationException(e); } } @@ -209,7 +210,7 @@ public class DefaultNetworkHandler implements NetworkHandler, ContextHolder { } }); } catch (IOException e) { - throw new RuntimeException(e); + throw new ApplicationException(e); } } diff --git a/repositories/src/main/java/ch/dissem/bitmessage/repository/JdbcAddressRepository.java b/repositories/src/main/java/ch/dissem/bitmessage/repository/JdbcAddressRepository.java index bf15a6a..6e58f09 100644 --- a/repositories/src/main/java/ch/dissem/bitmessage/repository/JdbcAddressRepository.java +++ b/repositories/src/main/java/ch/dissem/bitmessage/repository/JdbcAddressRepository.java @@ -21,12 +21,12 @@ import ch.dissem.bitmessage.entity.payload.Pubkey; import ch.dissem.bitmessage.entity.payload.V3Pubkey; import ch.dissem.bitmessage.entity.payload.V4Pubkey; import ch.dissem.bitmessage.entity.valueobject.PrivateKey; +import ch.dissem.bitmessage.exception.ApplicationException; import ch.dissem.bitmessage.factory.Factory; import ch.dissem.bitmessage.ports.AddressRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -129,8 +129,9 @@ public class JdbcAddressRepository extends JdbcHelper implements AddressReposito try (Connection connection = config.getConnection()) { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM Address WHERE address='" + address.getAddress() + "'"); - rs.next(); - return rs.getInt(1) > 0; + if (rs.next()) { + return rs.getInt(1) > 0; + } } catch (SQLException e) { LOG.error(e.getMessage(), e); } diff --git a/repositories/src/main/java/ch/dissem/bitmessage/repository/JdbcProofOfWorkRepository.java b/repositories/src/main/java/ch/dissem/bitmessage/repository/JdbcProofOfWorkRepository.java index 9268311..37628b5 100644 --- a/repositories/src/main/java/ch/dissem/bitmessage/repository/JdbcProofOfWorkRepository.java +++ b/repositories/src/main/java/ch/dissem/bitmessage/repository/JdbcProofOfWorkRepository.java @@ -1,12 +1,14 @@ package ch.dissem.bitmessage.repository; import ch.dissem.bitmessage.entity.ObjectMessage; +import ch.dissem.bitmessage.exception.ApplicationException; import ch.dissem.bitmessage.factory.Factory; import ch.dissem.bitmessage.ports.ProofOfWorkRepository; import ch.dissem.bitmessage.utils.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; import java.sql.*; import java.util.LinkedList; import java.util.List; @@ -37,11 +39,11 @@ public class JdbcProofOfWorkRepository extends JdbcHelper implements ProofOfWork rs.getLong("extra_bytes") ); } else { - throw new RuntimeException("Object requested that we don't have. Initial hash: " + Strings.hex(initialHash)); + throw new IllegalArgumentException("Object requested that we don't have. Initial hash: " + Strings.hex(initialHash)); } - } catch (Exception e) { + } catch (SQLException e) { LOG.error(e.getMessage(), e); - throw new RuntimeException(e); + throw new ApplicationException(e); } } @@ -57,7 +59,7 @@ public class JdbcProofOfWorkRepository extends JdbcHelper implements ProofOfWork return result; } catch (SQLException e) { LOG.error(e.getMessage(), e); - throw new RuntimeException(e); + throw new ApplicationException(e); } } @@ -71,12 +73,9 @@ public class JdbcProofOfWorkRepository extends JdbcHelper implements ProofOfWork ps.setLong(4, nonceTrialsPerByte); ps.setLong(5, extraBytes); ps.executeUpdate(); - } catch (SQLException e) { + } catch (IOException | SQLException e) { LOG.debug("Error storing object of type " + object.getPayload().getClass().getSimpleName(), e); - throw new RuntimeException(e); - } catch (Exception e) { - LOG.error(e.getMessage(), e); - throw new RuntimeException(e); + throw new ApplicationException(e); } }