Skip to content
This repository has been archived by the owner on Jun 7, 2023. It is now read-only.

Commit

Permalink
refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
vuapo-eth committed Dec 31, 2018
1 parent 42b34a0 commit e1f947c
Show file tree
Hide file tree
Showing 16 changed files with 85 additions and 76 deletions.
3 changes: 1 addition & 2 deletions src/main/java/org/iota/ict/Ict.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.rmi.RemoteException;
import java.util.LinkedList;
import java.util.List;

Expand Down Expand Up @@ -172,7 +171,7 @@ public boolean isRunning() {

public void newRound() {
Neighbor.newRound(this, round);
if(properties.spamEnabled) {
if (properties.spamEnabled) {
String spamHash = submit("spam transaction from node '" + properties.name + "'").hash;
LOGGER.info("submitted spam transaction: " + spamHash);
}
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/org/iota/ict/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ public static void main(String[] args) {
Properties properties = loadOrCreatedProperties(argMap);
properties.store(DEFAULT_PROPERTY_FILE_PATH);

if(properties.roundDuration < 30000 && properties.spamEnabled) {
logger.warn("Disabling spam because of low round duration.");
properties.spamEnabled = false;
}

logger.info("Starting new Ict '" + properties.name + "' (version: " + Constants.ICT_VERSION + ")");

Ict ict;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public void onIxiConnect(String ixiName) {
RemoteIxiModule ixiModule = (RemoteIxiModule) Naming.lookup("//localhost/" + ixiName);
ixiModulesByName.put(ixiName, ixiModule);
} catch (NotBoundException | MalformedURLException | RemoteException e) {
ErrorHandler.handleError(Ict.LOGGER, e, "Failed to accept connecting IXI module '"+ixiName+"'.");
ErrorHandler.handleError(Ict.LOGGER, e, "Failed to accept connecting IXI module '" + ixiName + "'.");
}
}

Expand Down
26 changes: 13 additions & 13 deletions src/main/java/org/iota/ict/model/RingTangle.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* This Tangle prunes transactions after reaching a certain size. It works similar to a ring memory (hence the name).
* The transactions are pruned in order of their timestamp, always keeping the N ({@link #transactionCapacity}) most recent ones.
* As an exception, the NULL transaction will never be pruned away.
* */
*/
public class RingTangle extends Tangle {

private final List<TransactionLog> transactionsOrderedByTimestamp = new ArrayList<>();
Expand All @@ -22,15 +22,15 @@ public RingTangle(Ict ict, long transactionCapacity) {
public TransactionLog createTransactionLogIfAbsent(Transaction transaction) {

TransactionLog log = super.createTransactionLogIfAbsent(transaction);
if(transactionsOrderedByTimestamp != null) {
if (transactionsOrderedByTimestamp != null) {
// == null only when calling the super constructor and adding NULL transaction
// do not add NULL transaction to transactionsOrderedByTimestamp to prevent it from being pruned
insertIntoSorted(transactionsOrderedByTimestamp, TimestampComparator.INSTANCE, log);
if (transactionsOrderedByTimestamp.size()+1 > transactionCapacity) { // +1 fpr NULL transaction
deleteTransaction(transactionsOrderedByTimestamp.get(0).transaction);
}
if (transactionsOrderedByTimestamp.size() + 1 > transactionCapacity) { // +1 fpr NULL transaction
deleteTransaction(transactionsOrderedByTimestamp.get(0).transaction);
}
assert size() <= transactionCapacity;
}
}
return log;
}

Expand All @@ -39,35 +39,35 @@ synchronized <T> void insertIntoSorted(List<T> list, Comparator<T> comparator, T
// TODO this can probably be rewritten much shorter

int lowerBound = 0;
int upperBound = list.size()-1;
int upperBound = list.size() - 1;

if(list.size() == 0 || comparator.compare(element, list.get(upperBound)) >= 0) {
if (list.size() == 0 || comparator.compare(element, list.get(upperBound)) >= 0) {
list.add(element);
return;
}

if(comparator.compare(element, list.get(lowerBound)) <= 0) {
if (comparator.compare(element, list.get(lowerBound)) <= 0) {
list.add(0, element);
return;
}

while (upperBound - lowerBound > 1) {
int referenceIndex = lowerBound + (upperBound - lowerBound)/2;
int referenceIndex = lowerBound + (upperBound - lowerBound) / 2;
T reference = list.get(referenceIndex);
if(comparator.compare(reference, element) <= 0) {
if (comparator.compare(reference, element) <= 0) {
lowerBound = referenceIndex;
} else {
upperBound = referenceIndex;
}
}
list.add(lowerBound+1, element);
list.add(lowerBound + 1, element);
}

@Override
public void deleteTransaction(Transaction transaction) {

TransactionLog log = transactionsByHash.remove(transaction.hash);
if(log != null) {
if (log != null) {
log.removeFromSetMap(transactionsByTag, transaction.tag);
log.removeFromSetMap(transactionsByAddress, transaction.address);
transactionsOrderedByTimestamp.remove(log);
Expand Down
14 changes: 7 additions & 7 deletions src/main/java/org/iota/ict/model/Tangle.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,25 +44,25 @@ public Transaction findTransactionByHash(String hash) {

public Set<Transaction> findTransactionsByAddress(String address) {
Set<Transaction> transactions = new HashSet<>();
if(transactionsByAddress.containsKey(address)) {
for(TransactionLog log : transactionsByAddress.get(address))
if (transactionsByAddress.containsKey(address)) {
for (TransactionLog log : transactionsByAddress.get(address))
transactions.add(log.transaction);
}
return transactions;
}

public Set<Transaction> findTransactionsByTag(String tag) {
Set<Transaction> transactions = new HashSet<>();
if(transactionsByTag.containsKey(tag)) {
for(TransactionLog log : transactionsByTag.get(tag))
if (transactionsByTag.containsKey(tag)) {
for (TransactionLog log : transactionsByTag.get(tag))
transactions.add(log.transaction);
}
return transactions;
}

public void deleteTransaction(Transaction transaction) {
TransactionLog log = transactionsByHash.remove(transaction.hash);
if(log != null) {
if (log != null) {
log.removeFromSetMap(transactionsByTag, transaction.tag);
log.removeFromSetMap(transactionsByAddress, transaction.address);
}
Expand Down Expand Up @@ -128,10 +128,10 @@ private <K> void insertIntoSetMap(Map<K, Set<TransactionLog>> map, K key) {
map.get(key).add(this);
}

protected <K> void removeFromSetMap(Map<K, Set<TransactionLog>> map, K key) {
protected <K> void removeFromSetMap(Map<K, Set<TransactionLog>> map, K key) {
if (map.containsKey(key)) {
map.get(key).remove(this);
if(map.get(key).size() == 0)
if (map.get(key).size() == 0)
map.remove(key);
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/org/iota/ict/network/Neighbor.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public void newRound() {

public void resolveHost() {
try {
if(!address.getAddress().equals(InetAddress.getByName(address.getHostName())))
if (!address.getAddress().equals(InetAddress.getByName(address.getHostName())))
address = new InetSocketAddress(address.getHostName(), address.getPort());
} catch (UnknownHostException e) {
ErrorHandler.handleWarning(logger, e, "Unknown Host for: " + address.getHostString());
Expand Down Expand Up @@ -79,7 +79,7 @@ public static void logHeader() {
}

public static void newRound(Ict ict, int round) {
if(round % 10 == 0)
if (round % 10 == 0)
Neighbor.logHeader();
// two separate FOR-loops to prevent delays between newRound() calls
for (Neighbor neighbor : ict.getNeighbors()) {
Expand All @@ -103,15 +103,15 @@ private static long calcReferenceForRelativeTolerance(List<Neighbor> allNeighbor

private static long calcUpperMedianOfPrevReceivedAll(List<Neighbor> neighbors) {
List<Long> values = new LinkedList<>();
for(Neighbor nb : neighbors)
for (Neighbor nb : neighbors)
values.add(nb.stats.prevReceivedAll);
return calcUpperMedian(values);
}

private static long calcUpperMedian(List<Long> values) {
assert values.size() > 0;
Collections.sort(values);
return values.get((int)Math.ceil((values.size()-1) / 2.0));
return values.get((int) Math.ceil((values.size() - 1) / 2.0));
}

private void newRound(long maxAllowedTransactionsForRound) {
Expand Down
14 changes: 7 additions & 7 deletions src/main/java/org/iota/ict/network/Receiver.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,18 @@ public void run() {
private void processIncoming(DatagramPacket packet) {

Neighbor sender = determineNeighborWhoSent(packet);
if(sender == null)
if (sender == null)
return;

sender.stats.receivedAll++;

if(sender.reachedLimitOfAllowedTransactions()) {
if (sender.reachedLimitOfAllowedTransactions()) {
sender.stats.ignored++;
return;
}

Transaction transaction = unpack(packet, sender);
if(transaction == null) {
if (transaction == null) {
sender.stats.receivedInvalid++;
return;
}
Expand All @@ -73,7 +73,7 @@ private void processIncoming(DatagramPacket packet) {
private Transaction unpack(DatagramPacket packet, Neighbor sender) {
try {
Transaction transaction = new Transaction(Trytes.fromBytes((packet.getData())));
if(Math.abs(transaction.issuanceTimestamp - System.currentTimeMillis()) > Constants.TIMESTAMP_DIFFERENCE_TOLERANCE_IN_MILLIS)
if (Math.abs(transaction.issuanceTimestamp - System.currentTimeMillis()) > Constants.TIMESTAMP_DIFFERENCE_TOLERANCE_IN_MILLIS)
throw new RuntimeException("issuance timestamp not in tolerated interval");
return transaction;
} catch (Throwable t) {
Expand Down Expand Up @@ -103,7 +103,7 @@ private void processRequest(Neighbor requester, Transaction transaction) {
sendRequested(requested, requester);
// unset requestHash because it's header information and does not actually belong to the transaction
transaction.requestHash = Trytes.NULL_HASH;
}
}

private void sendRequested(Transaction requested, Neighbor requester) {
Tangle.TransactionLog requestedLog = tangle.findTransactionLog(requested);
Expand All @@ -113,10 +113,10 @@ private void sendRequested(Transaction requested, Neighbor requester) {

private Neighbor determineNeighborWhoSent(DatagramPacket packet) {
for (Neighbor nb : ict.getNeighbors())
if(nb.sentPacket(packet))
if (nb.sentPacket(packet))
return nb;
for (Neighbor nb : ict.getNeighbors())
if(nb.sentPacketFromSameIP(packet))
if (nb.sentPacketFromSameIP(packet))
return nb;
Ict.LOGGER.warn("Received transaction from unknown address: " + packet.getAddress());
return null;
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/iota/ict/network/Sender.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public void run() {
}

private void manageRounds() {
if (roundStart + ict.getProperties().logRoundDuration < System.currentTimeMillis()) {
if (roundStart + ict.getProperties().roundDuration < System.currentTimeMillis()) {
ict.newRound();
roundStart = System.currentTimeMillis();
}
Expand All @@ -83,7 +83,7 @@ private void waitForNextTransaction() {
try {
synchronized (queue) {
// keep queue.isEmpty() within the synchronized block so notify is not called after the empty check and before queue.wait()
queue.wait(queue.isEmpty() ? properties.logRoundDuration : Math.max(1, queue.peek().sendingTime - System.currentTimeMillis()));
queue.wait(queue.isEmpty() ? properties.roundDuration : Math.max(1, queue.peek().sendingTime - System.currentTimeMillis()));
}
} catch (InterruptedException e) {
if (ict.isRunning())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ public void run() {
GossipEvent event = eventQueue.take();
for (GossipListener listener : listeners)
listener.on(event);
} catch(InterruptedException e) { Thread.currentThread().interrupt(); }
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

Expand Down
8 changes: 6 additions & 2 deletions src/main/java/org/iota/ict/network/event/GossipListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@ else if (e instanceof GossipSubmitEvent)
throw new IllegalArgumentException("Unknown event: " + e.getClass().getName());
}

public void onTransactionReceived(GossipReceiveEvent e) { ; }
public void onTransactionReceived(GossipReceiveEvent e) {
;
}

public void onTransactionSubmitted(GossipSubmitEvent e) { ; }
public void onTransactionSubmitted(GossipSubmitEvent e) {
;
}

}
4 changes: 2 additions & 2 deletions src/main/java/org/iota/ict/utils/ErrorHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public final class ErrorHandler {
private static List<ThrowableLog> logs = new LinkedList<>();

public static void handleWarning(Logger logger, Throwable throwable, String message) {
logger.warn(message + " ("+throwable.getMessage()+")");
logger.warn(message + " (" + throwable.getMessage() + ")");
logs.add(new ThrowableLog(throwable));
}

Expand All @@ -22,7 +22,7 @@ public static void handleError(Logger logger, Throwable throwable, String messag

public static void dump(File dir) {
dir.mkdirs();
File logFile = new File(dir, "error_"+System.currentTimeMillis()+".log");
File logFile = new File(dir, "error_" + System.currentTimeMillis() + ".log");
// TODO write to File
}

Expand Down
27 changes: 13 additions & 14 deletions src/main/java/org/iota/ict/utils/Properties.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public class Properties {
public String name = "ict";
public String host = "0.0.0.0";
public int port = 1337;
public long logRoundDuration = 60000;
public long roundDuration = 60000;
public List<InetSocketAddress> neighbors = new LinkedList<>();

public static Properties fromFile(String path) {
Expand All @@ -49,16 +49,16 @@ public Properties() {

}

Properties(java.util.Properties propObject) {
tangleCapacity = readLongProperty(propObject, Property.tangle_capacity, 10, Long.MAX_VALUE, DEFAULT_PROPERTIES.tangleCapacity);
maxTransactionsRelative = readLongProperty(propObject, Property.max_transactions_relative, 1, Long.MAX_VALUE, DEFAULT_PROPERTIES.maxTransactionsRelative);
maxTransactionsPerRound = readLongProperty(propObject, Property.max_transactions_per_round, 1, Long.MAX_VALUE, DEFAULT_PROPERTIES.maxTransactionsPerRound);
private Properties(java.util.Properties propObject) {
tangleCapacity = readLongProperty(propObject, Property.tangle_capacity, 10, Long.MAX_VALUE, DEFAULT_PROPERTIES.tangleCapacity);
maxTransactionsRelative = readLongProperty(propObject, Property.max_tx_abs, 1, Long.MAX_VALUE, DEFAULT_PROPERTIES.maxTransactionsRelative);
maxTransactionsPerRound = readLongProperty(propObject, Property.max_tx_rel, 1, Long.MAX_VALUE, DEFAULT_PROPERTIES.maxTransactionsPerRound);
minForwardDelay = readLongProperty(propObject, Property.min_forward_delay, 0, 10000, DEFAULT_PROPERTIES.minForwardDelay);
maxForwardDelay = readLongProperty(propObject, Property.max_forward_delay, 0, 10000, DEFAULT_PROPERTIES.maxForwardDelay);
host = propObject.getProperty(Property.host.name(), DEFAULT_PROPERTIES.host);
name = propObject.getProperty(Property.name.name(), DEFAULT_PROPERTIES.name);
port = (int) readLongProperty(propObject, Property.port, 1, 65535, DEFAULT_PROPERTIES.port);
logRoundDuration = readLongProperty(propObject, Property.log_round_duration, 100, Long.MAX_VALUE, DEFAULT_PROPERTIES.logRoundDuration);
roundDuration = readLongProperty(propObject, Property.round_duration, 100, Long.MAX_VALUE, DEFAULT_PROPERTIES.roundDuration);
neighbors = neighborsFromString(propObject.getProperty(Property.neighbors.name(), ""));
spamEnabled = propObject.getProperty(Property.spam_enabled.name(), DEFAULT_PROPERTIES.spamEnabled + "").toLowerCase().equals("true");
ixiEnabled = propObject.getProperty(Property.ixi_enabled.name(), DEFAULT_PROPERTIES.ixiEnabled + "").toLowerCase().equals("true");
Expand Down Expand Up @@ -139,14 +139,14 @@ public void store(String path) {
java.util.Properties toPropObject() {
java.util.Properties propObject = new java.util.Properties();
propObject.setProperty(Property.tangle_capacity.name(), tangleCapacity + "");
propObject.setProperty(Property.max_transactions_relative.name(), maxTransactionsRelative + "");
propObject.setProperty(Property.max_transactions_per_round.name(), maxTransactionsPerRound + "");
propObject.setProperty(Property.max_tx_abs.name(), maxTransactionsRelative + "");
propObject.setProperty(Property.max_tx_rel.name(), maxTransactionsPerRound + "");
propObject.setProperty(Property.min_forward_delay.name(), minForwardDelay + "");
propObject.setProperty(Property.max_forward_delay.name(), maxForwardDelay + "");
propObject.setProperty(Property.name.name(), name);
propObject.setProperty(Property.host.name(), host);
propObject.setProperty(Property.port.name(), port + "");
propObject.setProperty(Property.log_round_duration.name(), logRoundDuration + "");
propObject.setProperty(Property.round_duration.name(), roundDuration + "");
propObject.setProperty(Property.neighbors.name(), neighborsToString());
propObject.setProperty(Property.spam_enabled.name(), spamEnabled + "");
propObject.setProperty(Property.ixi_enabled.name(), ixiEnabled + "");
Expand All @@ -163,19 +163,18 @@ public Properties host(String host) {
return this;
}

private static enum Property {
max_transactions_relative,
max_transactions_per_round,
private enum Property {
max_tx_abs,
max_tx_rel,
tangle_capacity,
min_forward_delay,
max_forward_delay,
port,
host,
log_round_duration,
round_duration,
neighbors,
spam_enabled,
ixi_enabled,
ixis,
name;
}

Expand Down
Loading

0 comments on commit e1f947c

Please sign in to comment.