Code cleanup

This commit is contained in:
Christian Basler 2016-02-26 16:30:45 +01:00
parent 9ca28ead66
commit 57057298a1
4 changed files with 80 additions and 53 deletions

View File

@ -21,7 +21,6 @@ import ch.dissem.bitmessage.entity.payload.Pubkey;
import ch.dissem.bitmessage.entity.payload.V3Pubkey; import ch.dissem.bitmessage.entity.payload.V3Pubkey;
import ch.dissem.bitmessage.entity.payload.V4Pubkey; import ch.dissem.bitmessage.entity.payload.V4Pubkey;
import ch.dissem.bitmessage.entity.valueobject.PrivateKey; import ch.dissem.bitmessage.entity.valueobject.PrivateKey;
import ch.dissem.bitmessage.exception.ApplicationException;
import ch.dissem.bitmessage.factory.Factory; import ch.dissem.bitmessage.factory.Factory;
import ch.dissem.bitmessage.ports.AddressRepository; import ch.dissem.bitmessage.ports.AddressRepository;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -92,9 +91,12 @@ public class JdbcAddressRepository extends JdbcHelper implements AddressReposito
private List<BitmessageAddress> find(String where) { private List<BitmessageAddress> find(String where) {
List<BitmessageAddress> result = new LinkedList<>(); List<BitmessageAddress> result = new LinkedList<>();
try (Connection connection = config.getConnection()) { try (
Statement stmt = connection.createStatement(); Connection connection = config.getConnection();
ResultSet rs = stmt.executeQuery("SELECT address, alias, public_key, private_key, subscribed FROM Address WHERE " + where); Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT address, alias, public_key, private_key, subscribed " +
"FROM Address WHERE " + where)
) {
while (rs.next()) { while (rs.next()) {
BitmessageAddress address; BitmessageAddress address;
@ -126,9 +128,12 @@ public class JdbcAddressRepository extends JdbcHelper implements AddressReposito
} }
private boolean exists(BitmessageAddress address) { private boolean exists(BitmessageAddress address) {
try (Connection connection = config.getConnection()) { try (
Statement stmt = connection.createStatement(); Connection connection = config.getConnection();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM Address WHERE address='" + address.getAddress() + "'"); Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM Address " +
"WHERE address='" + address.getAddress() + "'")
) {
if (rs.next()) { if (rs.next()) {
return rs.getInt(1) > 0; return rs.getInt(1) > 0;
} }
@ -152,16 +157,18 @@ public class JdbcAddressRepository extends JdbcHelper implements AddressReposito
} }
private void update(BitmessageAddress address) throws IOException, SQLException { private void update(BitmessageAddress address) throws IOException, SQLException {
try (Connection connection = config.getConnection()) { StringBuilder statement = new StringBuilder("UPDATE Address SET alias=?");
StringBuilder statement = new StringBuilder("UPDATE Address SET alias=?"); if (address.getPubkey() != null) {
if (address.getPubkey() != null) { statement.append(", public_key=?");
statement.append(", public_key=?"); }
} if (address.getPrivateKey() != null) {
if (address.getPrivateKey() != null) { statement.append(", private_key=?");
statement.append(", private_key=?"); }
} statement.append(", subscribed=? WHERE address=?");
statement.append(", subscribed=? WHERE address=?"); try (
PreparedStatement ps = connection.prepareStatement(statement.toString()); Connection connection = config.getConnection();
PreparedStatement ps = connection.prepareStatement(statement.toString())
) {
int i = 0; int i = 0;
ps.setString(++i, address.getAlias()); ps.setString(++i, address.getAlias());
if (address.getPubkey() != null) { if (address.getPubkey() != null) {
@ -177,9 +184,12 @@ public class JdbcAddressRepository extends JdbcHelper implements AddressReposito
} }
private void insert(BitmessageAddress address) throws IOException, SQLException { private void insert(BitmessageAddress address) throws IOException, SQLException {
try (Connection connection = config.getConnection()) { try (
PreparedStatement ps = connection.prepareStatement( Connection connection = config.getConnection();
"INSERT INTO Address (address, version, alias, public_key, private_key, subscribed) VALUES (?, ?, ?, ?, ?, ?)"); PreparedStatement ps = connection.prepareStatement(
"INSERT INTO Address (address, version, alias, public_key, private_key, subscribed) " +
"VALUES (?, ?, ?, ?, ?, ?)")
) {
ps.setString(1, address.getAddress()); ps.setString(1, address.getAddress());
ps.setLong(2, address.getVersion()); ps.setLong(2, address.getVersion());
ps.setString(3, address.getAlias()); ps.setString(3, address.getAlias());
@ -202,8 +212,10 @@ public class JdbcAddressRepository extends JdbcHelper implements AddressReposito
@Override @Override
public void remove(BitmessageAddress address) { public void remove(BitmessageAddress address) {
try (Connection connection = config.getConnection()) { try (
Statement stmt = connection.createStatement(); Connection connection = config.getConnection();
Statement stmt = connection.createStatement()
) {
stmt.executeUpdate("DELETE FROM Address WHERE address = '" + address.getAddress() + "'"); stmt.executeUpdate("DELETE FROM Address WHERE address = '" + address.getAddress() + "'");
} catch (SQLException e) { } catch (SQLException e) {
LOG.error(e.getMessage(), e); LOG.error(e.getMessage(), e);

View File

@ -61,11 +61,12 @@ public class JdbcInventory extends JdbcHelper implements Inventory {
if (cache.get(stream) == null) { if (cache.get(stream) == null) {
result = new ConcurrentHashMap<>(); result = new ConcurrentHashMap<>();
cache.put(stream, result); cache.put(stream, result);
try (
try (Connection connection = config.getConnection()) { Connection connection = config.getConnection();
Statement stmt = connection.createStatement(); Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT hash, expires FROM Inventory WHERE expires > " ResultSet rs = stmt.executeQuery("SELECT hash, expires FROM Inventory " +
+ now(-5 * MINUTE) + " AND stream = " + stream); "WHERE expires > " + now(-5 * MINUTE) + " AND stream = " + stream)
) {
while (rs.next()) { while (rs.next()) {
result.put(new InventoryVector(rs.getBytes("hash")), rs.getLong("expires")); result.put(new InventoryVector(rs.getBytes("hash")), rs.getLong("expires"));
} }
@ -116,7 +117,7 @@ public class JdbcInventory extends JdbcHelper implements Inventory {
query.append(" AND version = ").append(version); query.append(" AND version = ").append(version);
} }
if (types.length > 0) { if (types.length > 0) {
query.append(" AND type IN (").append(join(types)).append(")"); query.append(" AND type IN (").append(join(types)).append(')');
} }
try ( try (
Connection connection = config.getConnection(); Connection connection = config.getConnection();

View File

@ -27,19 +27,23 @@ public class JdbcProofOfWorkRepository extends JdbcHelper implements ProofOfWork
@Override @Override
public Item getItem(byte[] initialHash) { public Item getItem(byte[] initialHash) {
try (Connection connection = config.getConnection()) { try (
PreparedStatement ps = connection.prepareStatement("SELECT data, version, nonce_trials_per_byte, extra_bytes FROM POW WHERE initial_hash=?"); Connection connection = config.getConnection();
PreparedStatement ps = connection.prepareStatement("SELECT data, version, nonce_trials_per_byte, " +
"extra_bytes FROM POW WHERE initial_hash=?")
) {
ps.setBytes(1, initialHash); ps.setBytes(1, initialHash);
ResultSet rs = ps.executeQuery(); try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) { if (rs.next()) {
Blob data = rs.getBlob("data"); Blob data = rs.getBlob("data");
return new Item( return new Item(
Factory.getObjectMessage(rs.getInt("version"), data.getBinaryStream(), (int) data.length()), Factory.getObjectMessage(rs.getInt("version"), data.getBinaryStream(), (int) data.length()),
rs.getLong("nonce_trials_per_byte"), rs.getLong("nonce_trials_per_byte"),
rs.getLong("extra_bytes") rs.getLong("extra_bytes")
); );
} else { } else {
throw new IllegalArgumentException("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 (SQLException e) { } catch (SQLException e) {
LOG.error(e.getMessage(), e); LOG.error(e.getMessage(), e);
@ -49,10 +53,12 @@ public class JdbcProofOfWorkRepository extends JdbcHelper implements ProofOfWork
@Override @Override
public List<byte[]> getItems() { public List<byte[]> getItems() {
try (Connection connection = config.getConnection()) { try (
Connection connection = config.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT initial_hash FROM POW")
) {
List<byte[]> result = new LinkedList<>(); List<byte[]> result = new LinkedList<>();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT initial_hash FROM POW");
while (rs.next()) { while (rs.next()) {
result.add(rs.getBytes("initial_hash")); result.add(rs.getBytes("initial_hash"));
} }
@ -65,8 +71,11 @@ public class JdbcProofOfWorkRepository extends JdbcHelper implements ProofOfWork
@Override @Override
public void putObject(ObjectMessage object, long nonceTrialsPerByte, long extraBytes) { public void putObject(ObjectMessage object, long nonceTrialsPerByte, long extraBytes) {
try (Connection connection = config.getConnection()) { try (
PreparedStatement ps = connection.prepareStatement("INSERT INTO POW (initial_hash, data, version, nonce_trials_per_byte, extra_bytes) VALUES (?, ?, ?, ?, ?)"); Connection connection = config.getConnection();
PreparedStatement ps = connection.prepareStatement("INSERT INTO POW (initial_hash, data, version, " +
"nonce_trials_per_byte, extra_bytes) VALUES (?, ?, ?, ?, ?)")
) {
ps.setBytes(1, security().getInitialHash(object)); ps.setBytes(1, security().getInitialHash(object));
writeBlob(ps, 2, object); writeBlob(ps, 2, object);
ps.setLong(3, object.getVersion()); ps.setLong(3, object.getVersion());
@ -81,8 +90,10 @@ public class JdbcProofOfWorkRepository extends JdbcHelper implements ProofOfWork
@Override @Override
public void removeObject(byte[] initialHash) { public void removeObject(byte[] initialHash) {
try (Connection connection = config.getConnection()) { try (
PreparedStatement ps = connection.prepareStatement("DELETE FROM POW WHERE initial_hash=?"); Connection connection = config.getConnection();
PreparedStatement ps = connection.prepareStatement("DELETE FROM POW WHERE initial_hash=?")
) {
ps.setBytes(1, initialHash); ps.setBytes(1, initialHash);
ps.executeUpdate(); ps.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {

View File

@ -23,8 +23,6 @@ import ch.dissem.bitmessage.factory.Factory;
import ch.dissem.bitmessage.utils.Base58; import ch.dissem.bitmessage.utils.Base58;
import org.ini4j.Ini; import org.ini4j.Ini;
import org.ini4j.Profile; import org.ini4j.Profile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*; import java.io.*;
import java.util.Arrays; import java.util.Arrays;
@ -39,6 +37,9 @@ import static ch.dissem.bitmessage.utils.Singleton.security;
* @author Christian Basler * @author Christian Basler
*/ */
public class WifImporter { public class WifImporter {
private static final byte WIF_FIRST_BYTE = (byte) 0x80;
private static final int WIF_SECRET_LENGTH = 37;
private final BitmessageContext ctx; private final BitmessageContext ctx;
private final List<BitmessageAddress> identities = new LinkedList<>(); private final List<BitmessageAddress> identities = new LinkedList<>();
@ -76,10 +77,12 @@ public class WifImporter {
private byte[] getSecret(String walletImportFormat) throws IOException { private byte[] getSecret(String walletImportFormat) throws IOException {
byte[] bytes = Base58.decode(walletImportFormat); byte[] bytes = Base58.decode(walletImportFormat);
if (bytes[0] != (byte) 0x80) if (bytes[0] != WIF_FIRST_BYTE)
throw new IOException("Unknown format: 0x80 expected as first byte, but secret " + walletImportFormat + " was " + bytes[0]); throw new IOException("Unknown format: 0x80 expected as first byte, but secret " + walletImportFormat +
if (bytes.length != 37) " was " + bytes[0]);
throw new IOException("Unknown format: 37 bytes expected, but secret " + walletImportFormat + " was " + bytes.length + " long"); if (bytes.length != WIF_SECRET_LENGTH)
throw new IOException("Unknown format: " + WIF_SECRET_LENGTH +
" bytes expected, but secret " + walletImportFormat + " was " + bytes.length + " long");
byte[] hash = security().doubleSha256(bytes, 33); byte[] hash = security().doubleSha256(bytes, 33);
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {