repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
iri
iri-master/src/main/java/com/iota/iri/model/IntegerIndex.java
package com.iota.iri.model; import com.iota.iri.storage.Indexable; import com.iota.iri.utils.Serializer; /** An integer key that indexes {@link Persistable} objects in the database. */ public class IntegerIndex implements Indexable{ /**The internally stored index value*/ int value; /** * Constructor for storing index of persistable * @param value The index of the represented persistable */ public IntegerIndex(int value) { this.value = value; } public IntegerIndex() {} /**@return The index of the persistable */ public int getValue() { return value; } @Override public byte[] bytes() { return Serializer.serialize(value); } @Override public void read(byte[] bytes) { this.value = Serializer.getInteger(bytes); } /**Creates a new {@link #IntegerIndex(int)} with an incremented index value*/ @Override public Indexable incremented() { return new IntegerIndex(value + 1); } /**Creates a new {@link #IntegerIndex(int)} with a decremented index value*/ @Override public Indexable decremented() { return new IntegerIndex(value - 1); } @Override public int compareTo(Indexable o) { IntegerIndex i = new IntegerIndex(Serializer.getInteger(o.bytes())); return value - ((IntegerIndex) o).value; } @Override public int hashCode() { return value; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof IntegerIndex)) { return false; } return ((IntegerIndex) obj).value == value; } }
1,719
21.933333
81
java
iri
iri-master/src/main/java/com/iota/iri/model/LocalSnapshot.java
package com.iota.iri.model; import com.iota.iri.storage.Persistable; import javax.naming.OperationNotSupportedException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; /** * Contains the data of a local snapshot in its entirety. */ public class LocalSnapshot implements Persistable { // meta public Hash milestoneHash; public int milestoneIndex; public long milestoneTimestamp; public int numSolidEntryPoints; public int numSeenMilestones; public Map<Hash, Integer> solidEntryPoints; public Map<Hash, Integer> seenMilestones; // state public Map<Hash, Long> ledgerState; @Override public byte[] bytes() { ByteBuffer buf = ByteBuffer.allocate( 49 + // milestone hash bytes encoded 20 + // index (4), timestamp (8), num solid entry points (4) / seen milestones (4) = 20 (solidEntryPoints.size() * (Hash.SIZE_IN_BYTES + 4)) + // solid entry points (seenMilestones.size() * (Hash.SIZE_IN_BYTES + 4)) + // seen milestones (ledgerState.size() * (Hash.SIZE_IN_BYTES + 8))); // ledger state // milestone hash buf.put(milestoneHash.bytes()); // nums buf.putInt(milestoneIndex); buf.putLong(milestoneTimestamp); buf.putInt(numSolidEntryPoints); buf.putInt(numSeenMilestones); // maps for (Map.Entry<Hash, Integer> entry : solidEntryPoints.entrySet()) { buf.put(entry.getKey().bytes()); buf.putInt(entry.getValue()); } for (Map.Entry<Hash, Integer> entry : seenMilestones.entrySet()) { buf.put(entry.getKey().bytes()); buf.putInt(entry.getValue()); } for (Map.Entry<Hash, Long> entry : ledgerState.entrySet()) { buf.put(entry.getKey().bytes()); buf.putLong(entry.getValue()); } return buf.array(); } @Override public void read(byte[] bytes) { byte[] hashBuf = new byte[Hash.SIZE_IN_BYTES]; ByteBuffer buf = ByteBuffer.wrap(bytes); // milestone hash buf.get(hashBuf); milestoneHash = HashFactory.TRANSACTION.create(hashBuf, 0, Hash.SIZE_IN_BYTES); // nums milestoneIndex = buf.getInt(); milestoneTimestamp = buf.getLong(); numSolidEntryPoints = buf.getInt(); numSeenMilestones = buf.getInt(); // solid entry points solidEntryPoints = new HashMap<>(); for (int i = 0; i < numSolidEntryPoints; i++) { buf.get(hashBuf); solidEntryPoints.put(HashFactory.TRANSACTION.create(hashBuf, 0, Hash.SIZE_IN_BYTES), buf.getInt()); } // seen milestones seenMilestones = new HashMap<>(); for (int i = 0; i < numSeenMilestones; i++) { buf.get(hashBuf); seenMilestones.put(HashFactory.TRANSACTION.create(hashBuf, 0, Hash.SIZE_IN_BYTES), buf.getInt()); } // actual ledger state int ledgerStateEntriesCount = buf.remaining() / (Hash.SIZE_IN_BYTES + 8); ledgerState = new HashMap<>(); for (int i = 0; i < ledgerStateEntriesCount; i++) { buf.get(hashBuf); ledgerState.put(HashFactory.ADDRESS.create(hashBuf, 0, Hash.SIZE_IN_BYTES), buf.getLong()); } } @Override public byte[] metadata() { return new byte[0]; } @Override public void readMetadata(byte[] bytes) { // has no metadata } @Override public boolean canMerge() { return false; } @Override public Persistable mergeInto(Persistable source) throws OperationNotSupportedException { return null; } @Override public boolean exists() { return false; } }
3,848
29.547619
111
java
iri
iri-master/src/main/java/com/iota/iri/model/ObsoleteTagHash.java
package com.iota.iri.model; /** * The <tt>Obsolete Tag</tt> hash identifier of a transaction * * <p> * An Obsolete Tag is used for determining milestone indexes. * If a milestone is issued from the coordinator address, first * the signature is checked to confirm that the sender is indeed * the coordinator, and then it will check the Obsolete Tag hash * to determine the milestone's index. * </p> */ public class ObsoleteTagHash extends AbstractHash { /** * Constructor for a <tt>Obsolete Tag</tt> hash identifier using a source array and starting point * * @param tagBytes The trit or byte array source that the object will be generated from * @param offset The starting point in the array for the beginning of the Hash object * @param tagSizeInBytes The size of the Hash object that is to be created */ protected ObsoleteTagHash(byte[] tagBytes, int offset, int tagSizeInBytes) { super(tagBytes, offset, tagSizeInBytes); } }
1,010
36.444444
102
java
iri
iri-master/src/main/java/com/iota/iri/model/StateDiff.java
package com.iota.iri.model; import com.iota.iri.storage.Persistable; import com.iota.iri.utils.Serializer; import org.apache.commons.lang3.ArrayUtils; import javax.naming.OperationNotSupportedException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Creates a persistable State object, used to map addresses with values in the DB and snapshots. */ public class StateDiff implements Persistable { /** The map storing the address and balance of the current object */ public Map<Hash, Long> state; /** * Returns a byte array of the state map contained in the object. If no data is present in the state, * a new empty byte array is returned instead. */ @Override public byte[] bytes(){ int size = state.size(); if (size == 0) { return new byte[0]; } byte[] temp = new byte[size * (Hash.SIZE_IN_BYTES + Long.BYTES)]; int index = 0; for (Entry<Hash,Long> entry : state.entrySet()){ byte[] key = entry.getKey().bytes(); System.arraycopy(key, 0, temp, index, key.length); index += key.length; byte[] value = Serializer.serialize(entry.getValue()); System.arraycopy(value, 0, temp, index, value.length); index += value.length; } return temp; } /** * Iterates through the given byte array and populates the state map with the contained address * hashes and the associated balance. * * @param bytes The source data to be placed in the State */ public void read(byte[] bytes) { int i; state = new HashMap<>(); if(bytes != null) { for (i = 0; i < bytes.length; i += Hash.SIZE_IN_BYTES + Long.BYTES) { state.put(HashFactory.ADDRESS.create(bytes, i, Hash.SIZE_IN_BYTES), Serializer.getLong(Arrays.copyOfRange(bytes, i + Hash.SIZE_IN_BYTES, i + Hash.SIZE_IN_BYTES + Long.BYTES))); } } } @Override public byte[] metadata() { return new byte[0]; } @Override public void readMetadata(byte[] bytes) { } @Override public boolean canMerge() { return false; } @Override public Persistable mergeInto(Persistable source) throws OperationNotSupportedException { throw new OperationNotSupportedException("This object is not mergeable"); } @Override public boolean exists() { return !(this.state == null || this.state.isEmpty()); } }
2,598
28.534091
132
java
iri
iri-master/src/main/java/com/iota/iri/model/TagHash.java
package com.iota.iri.model; /** * Creates a <tt>Tag</tt> hash identifier * * <p> * Tags can be defined and used as a referencing hash for organizing and * finding transactions. A unique tag can be included in multiple transactions * and can then be used to identify these stored transactions in the database. * </p> */ public class TagHash extends AbstractHash { /** * Empty Constructor for a <tt>Tag</tt> hash identifier object. Creates a placeholder <tt>Tag</tt> hash identifier * object with no properties. */ public TagHash() { } /** * Constructor for a <tt>Tag</tt> hash identifier using a source array and starting point * * @param tagBytes The trit or byte array source that the object will be generated from * @param offset The starting point in the array for the beginning of the Hash object * @param tagSizeInBytes The size of the Hash object that is to be created */ protected TagHash(byte[] tagBytes, int offset, int tagSizeInBytes) { super(tagBytes, offset, tagSizeInBytes); } }
1,087
35.266667
118
java
iri
iri-master/src/main/java/com/iota/iri/model/TransactionHash.java
package com.iota.iri.model; import com.iota.iri.crypto.Sponge; import com.iota.iri.crypto.SpongeFactory; import com.iota.iri.utils.Converter; /** * Creates a <tt>Transaction</tt> Hash identifier. * * <p> * A transaction hash acts as a reference point for a transaction object. * </p> * * @see com.iota.iri.model.persistables.Transaction */ public class TransactionHash extends AbstractHash { public TransactionHash() { } protected TransactionHash(byte[] source, int offset, int sourceSize) { super(source, offset, sourceSize); } /** * Calculates a transaction hash identifier from an array of bytes. Uses the entire trits array * @param mode The mode we absorb the trits with * @param trits Array of trits we calculate the hash with * @return The {@link TransactionHash} */ public static TransactionHash calculate(SpongeFactory.Mode mode, byte[] trits) { return calculate(trits, 0, trits.length, SpongeFactory.create(mode)); } /** * Calculates a transaction hash identifier from an array of bytes * @param bytes The bytes that contain this transactionHash * @param tritsLength The length of trits the bytes represent * @param sponge The way we absorb the trits with * @return The {@link TransactionHash} */ public static TransactionHash calculate(byte[] bytes, int tritsLength, Sponge sponge) { byte[] trits = new byte[tritsLength]; Converter.getTrits(bytes, trits); return calculate(trits, 0, tritsLength, sponge); } /** * Calculates a transaction hash identifier from an array of bytes * @param tritsToCalculate array of trits we calculate the hash with * @param offset The position we start reading from inside the tritsToCalculate array * @param length The length of trits the bytes represent * @param sponge The way we absorb the trits with * @return The {@link TransactionHash} */ public static TransactionHash calculate(byte[] tritsToCalculate, int offset, int length, Sponge sponge) { byte[] hashTrits = new byte[SIZE_IN_TRITS]; sponge.reset(); sponge.absorb(tritsToCalculate, offset, length); sponge.squeeze(hashTrits, 0, SIZE_IN_TRITS); return (TransactionHash) HashFactory.TRANSACTION.create(hashTrits, 0, SIZE_IN_TRITS); } }
2,368
36.603175
109
java
iri
iri-master/src/main/java/com/iota/iri/model/persistables/Address.java
package com.iota.iri.model.persistables; import com.iota.iri.model.Hash; /** * This is a collection of {@link com.iota.iri.model.TransactionHash} identifiers indexed by their * {@link com.iota.iri.model.AddressHash} in the database. */ public class Address extends Hashes{ /** * Instantiates an empty <tt>Address</tt> hash identifier collection */ public Address(){} /** * Adds an <tt>Address</tt> hash identifier to the collection * @param hash The hash identifier that will be added to the collection */ public Address(Hash hash) { set.add(hash); } }
613
24.583333
98
java
iri
iri-master/src/main/java/com/iota/iri/model/persistables/Approvee.java
package com.iota.iri.model.persistables; import com.iota.iri.model.Hash; /** * This is a collection of {@link com.iota.iri.model.TransactionHash} identifiers indexed by a given * <tt>Aprovee</tt> {@link com.iota.iri.model.TransactionHash} in the database. * * <p> * An <tt>Approvee</tt> hash set is comprised of transaction hashes that reference * a specific transaction. Approvee's are transactions that directly approve a given * transaction. * </p> */ public class Approvee extends Hashes{ /** * Adds an <tt>Approvee</tt> identifier to the collection. * @param hash The hash identifier that will be added to the collection */ public Approvee(Hash hash) { set.add(hash); } /**Instantiates an empty <tt>Approvee</tt> hash identifier collection.*/ public Approvee() { } }
845
27.2
100
java
iri
iri-master/src/main/java/com/iota/iri/model/persistables/Bundle.java
package com.iota.iri.model.persistables; import com.iota.iri.model.Hash; /** * This is a collection of {@link com.iota.iri.model.TransactionHash} identifiers indexed by their * {@link com.iota.iri.model.BundleHash} in the database. */ public class Bundle extends Hashes{ /** * Adds a <tt>Bundle</tt> hash identifier to the collection. * @param hash The hash identifier that will be added to the collection. */ public Bundle(Hash hash) { set.add(hash); } /**Instantiates a collection of <tt>Bundle</tt> hash identifiers.*/ public Bundle() { } }
599
24
98
java
iri
iri-master/src/main/java/com/iota/iri/model/persistables/Hashes.java
package com.iota.iri.model.persistables; import com.iota.iri.model.Hash; import com.iota.iri.model.HashFactory; import com.iota.iri.storage.Persistable; import org.apache.commons.lang3.ArrayUtils; import java.util.LinkedHashSet; import java.util.Set; /** * Represents a persistable set of {@link Hash} to act as a container for hash identifiers. These are * used in our persistence layer to store the link of one key to a set of keys in the database. * * <p> * A <tt>Hash</tt> set contains the byte array representations of Hash objects. * These hashes serve as reference points for specific parts of a transaction set, * including the <tt>Address</tt>, <tt>Tag</tt>, <tt>Branch</tt> and <tt>Trunk</tt> * transaction components. * </p> */ public class Hashes implements Persistable { /**A set for storing hashes*/ public Set<Hash> set = new LinkedHashSet<>(); /**A delimeter for separating hashes within a byte stream*/ private static final byte delimiter = ",".getBytes()[0]; /**Returns the bytes of the contained hash set*/ @Override public byte[] bytes() { return set.parallelStream() .map(Hash::bytes) .reduce((a,b) -> ArrayUtils.addAll(ArrayUtils.add(a, delimiter), b)) .orElse(new byte[0]); } /** * Reads the given byte array. If the array is not null, the {@link Hash} objects will be added to * the collection. * * @param bytes the byte array that will be read */ @Override public void read(byte[] bytes) { if(bytes != null) { set = new LinkedHashSet<>(bytes.length / (1 + Hash.SIZE_IN_BYTES) + 1); for (int i = 0; i < bytes.length; i += 1 + Hash.SIZE_IN_BYTES) { set.add(HashFactory.TRANSACTION.create(bytes, i, Hash.SIZE_IN_BYTES)); } } } @Override public byte[] metadata() { return new byte[0]; } @Override public void readMetadata(byte[] bytes) { } @Override public boolean canMerge() { return true; } @Override public Persistable mergeInto(Persistable source){ if(source instanceof Hashes){ Set<Hash> setTwo = ((Hashes) source).set; set.addAll(setTwo); return this; } return null; } @Override public boolean exists() { return !set.isEmpty(); } }
2,441
27.068966
102
java
iri
iri-master/src/main/java/com/iota/iri/model/persistables/Milestone.java
package com.iota.iri.model.persistables; import com.iota.iri.model.Hash; import com.iota.iri.model.HashFactory; import com.iota.iri.model.IntegerIndex; import com.iota.iri.storage.Persistable; import com.iota.iri.utils.Serializer; import org.apache.commons.lang3.ArrayUtils; import javax.naming.OperationNotSupportedException; /** * This stores a hash identifier for a <tt>Milestone</tt> transaction, indexed by a unique <tt>IntegerIndex</tt> * generated from the serialized byte input. * * <p> * Milestones are issued by the coordinator to direct and verify the tangle. * The coordinator issues milestones to help confirm valid transactions. Milestones * are also verified by other nodes to ensure that they are not malicious in nature, * and do not confirm transactions that it should not (i.e. double spending). * </p> */ public class Milestone implements Persistable { /**Represents the integer index value of the milestone identifier*/ public IntegerIndex index; /**Represents the hash identifier of the milestone*/ public Hash hash; /**@return The milestone index and associated hash identifier*/ @Override public byte[] bytes() { return ArrayUtils.addAll(index.bytes(), hash.bytes()); } /** * Reads the input bytes and assigns an <tt>IntegerIndex</tt> to store a <tt>Milestone</tt> transaction * hash identifier * @param bytes The input bytes of the milestone transaction */ @Override public void read(byte[] bytes) { if(bytes != null) { index = new IntegerIndex(Serializer.getInteger(bytes)); hash = HashFactory.TRANSACTION.create(bytes, Integer.BYTES, Hash.SIZE_IN_BYTES); } } @Override public byte[] metadata() { return new byte[0]; } @Override public void readMetadata(byte[] bytes) { } @Override public boolean canMerge() { return false; } @Override public Persistable mergeInto(Persistable source) throws OperationNotSupportedException{ throw new OperationNotSupportedException("This object is not mergeable"); } @Override public boolean exists() { return !(hash == null || index == null); } }
2,252
29.863014
112
java
iri
iri-master/src/main/java/com/iota/iri/model/persistables/ObsoleteTag.java
package com.iota.iri.model.persistables; import com.iota.iri.model.Hash; /** * This is a collection of {@link com.iota.iri.model.TransactionHash} identifiers that are indexed by * {@link com.iota.iri.model.ObsoleteTagHash} in the database. * This is part of the bundle essence, and for normal transactions, a {@link Tag} collection should be * used instead. */ public class ObsoleteTag extends Tag { /** * Adds an <tt>Obsolete Tag</tt> hash identifier to the collection * @param hash The hash identifier that will be added to the collection */ public ObsoleteTag(Hash hash) { super(hash); } // used by the persistence layer to instantiate the object public ObsoleteTag() { } }
735
26.259259
102
java
iri
iri-master/src/main/java/com/iota/iri/model/persistables/SpentAddress.java
package com.iota.iri.model.persistables; import com.iota.iri.storage.Persistable; import javax.naming.OperationNotSupportedException; public class SpentAddress implements Persistable { private boolean exists = false; @Override public byte[] bytes() { return new byte[0]; } @Override public void read(byte[] bytes) { exists = bytes != null; } @Override public byte[] metadata() { return new byte[0]; } @Override public void readMetadata(byte[] bytes) { } @Override public boolean canMerge() { return false; } @Override public Persistable mergeInto(Persistable source) throws OperationNotSupportedException { throw new OperationNotSupportedException("This object is not mergeable"); } @Override public boolean exists() { return exists; } }
887
18.304348
93
java
iri
iri-master/src/main/java/com/iota/iri/model/persistables/Tag.java
package com.iota.iri.model.persistables; import com.iota.iri.model.Hash; /** * This is a collection of {@link com.iota.iri.model.TransactionHash} identifiers indexed by their * {@link com.iota.iri.model.TagHash} in the data base. */ public class Tag extends Hashes { /** * Adds a <tt>Tag</tt> hash identifier to the collection * @param hash The hash identifier that will be added to the collection */ public Tag(Hash hash) { set.add(hash); } /**Instantiates an empty <tt>Tag</tt> hash identifier collection*/ public Tag() { } }
583
23.333333
98
java
iri
iri-master/src/main/java/com/iota/iri/model/persistables/Transaction.java
package com.iota.iri.model.persistables; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import com.iota.iri.model.HashFactory; import com.iota.iri.storage.Persistable; import com.iota.iri.utils.Serializer; import com.iota.iri.utils.TransactionTruncator; import javax.naming.OperationNotSupportedException; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; /** * This is a collection of {@link com.iota.iri.model.Hash} identifiers indexed by a * {@link com.iota.iri.model.TransactionHash} in a database. This acts as the access * point for all other persistable set collections representing the contents of a * <tt>Transaction</tt>. * * <p> * A Transaction set contains all the information of a particular transaction. This includes * hash objects for the <tt>address</tt>, <tt>bundle</tt>, <tt>trunk</tt>, <tt>branch</tt>, * and <tt>obsolete tag</tt>, as well as data such as the <tt>value</tt> of the * transaction as well as the <tt>timestamps</tt> and more. * </p> */ public class Transaction implements Persistable { public static final int SIZE = 1604; /** * Bitmask used to access and store the solid flag. */ public static final int IS_SOLID_BITMASK = 0b01; /** * Bitmask used to access and store the milestone flag. */ public static final int IS_MILESTONE_BITMASK = 0b10; public byte[] bytes; public Hash address; public Hash bundle; public Hash trunk; public Hash branch; public Hash obsoleteTag; public long value; public long currentIndex; public long lastIndex; public long timestamp; public Hash tag; public long attachmentTimestamp; public long attachmentTimestampLowerBound; public long attachmentTimestampUpperBound; public int validity = 0; public AtomicInteger type = new AtomicInteger(TransactionViewModel.PREFILLED_SLOT); /** * The time when the transaction arrived. In milliseconds. */ public long arrivalTime = 0; //public boolean confirmed = false; /** * This flag indicates if the transaction metadata was parsed from a byte array. */ public AtomicBoolean parsed = new AtomicBoolean(false); /** * This flag indicates whether the transaction is considered solid or not */ public AtomicBoolean solid = new AtomicBoolean(false); /** * This flag indicates if the transaction is a coordinator issued milestone. */ public AtomicBoolean milestone = new AtomicBoolean(false); public AtomicLong height = new AtomicLong(0); public AtomicReference<String> sender = new AtomicReference<>(""); public AtomicInteger snapshot = new AtomicInteger(); /** * Returns a truncated representation of the bytes of the transaction. */ @Override public byte[] bytes() { return bytes == null ? null : TransactionTruncator.truncateTransaction(bytes); } /** * Assigns the Transaction set bytes to the given byte array provided the array is not null * * @param bytes the byte array that the transaction bytes will be assigned to */ @Override public void read(byte[] bytes) { if(bytes != null) { this.bytes = TransactionTruncator.expandTransaction(bytes); this.type.set(TransactionViewModel.FILLED_SLOT); } } /** * Returns a byte array containing all the relevant metadata for the transaction. */ @Override public byte[] metadata() { int allocateSize = Hash.SIZE_IN_BYTES * 6 + //address,bundle,trunk,branch,obsoleteTag,tag Long.BYTES * 9 + //value,currentIndex,lastIndex,timestamp,attachmentTimestampLowerBound,attachmentTimestampUpperBound,arrivalTime,height Integer.BYTES * 3 + //validity,type,snapshot 1 + //solid sender.get().getBytes().length; //sender ByteBuffer buffer = ByteBuffer.allocate(allocateSize); buffer.put(address.bytes()); buffer.put(bundle.bytes()); buffer.put(trunk.bytes()); buffer.put(branch.bytes()); buffer.put(obsoleteTag.bytes()); buffer.put(Serializer.serialize(value)); buffer.put(Serializer.serialize(currentIndex)); buffer.put(Serializer.serialize(lastIndex)); buffer.put(Serializer.serialize(timestamp)); buffer.put(tag.bytes()); buffer.put(Serializer.serialize(attachmentTimestamp)); buffer.put(Serializer.serialize(attachmentTimestampLowerBound)); buffer.put(Serializer.serialize(attachmentTimestampUpperBound)); buffer.put(Serializer.serialize(validity)); buffer.put(Serializer.serialize(type.get())); buffer.put(Serializer.serialize(arrivalTime)); buffer.put(Serializer.serialize(height.get())); //buffer.put((byte) (confirmed ? 1:0)); // encode booleans in 1 byte byte flags = 0; flags |= solid.get() ? IS_SOLID_BITMASK : 0; flags |= milestone.get() ? IS_MILESTONE_BITMASK : 0; buffer.put(flags); buffer.put(Serializer.serialize(snapshot.get())); buffer.put(sender.get().getBytes()); return buffer.array(); } /** * Reads the contents of a given array of bytes, assigning the array contents to the * appropriate classes. * * @param bytes The byte array containing the transaction information */ @Override public void readMetadata(byte[] bytes) { if(bytes == null) { return; } int i = 0; address = HashFactory.ADDRESS.create(bytes, i, Hash.SIZE_IN_BYTES); i += Hash.SIZE_IN_BYTES; bundle = HashFactory.BUNDLE.create(bytes, i, Hash.SIZE_IN_BYTES); i += Hash.SIZE_IN_BYTES; trunk = HashFactory.TRANSACTION.create(bytes, i, Hash.SIZE_IN_BYTES); i += Hash.SIZE_IN_BYTES; branch = HashFactory.TRANSACTION.create(bytes, i, Hash.SIZE_IN_BYTES); i += Hash.SIZE_IN_BYTES; obsoleteTag = HashFactory.OBSOLETETAG.create(bytes, i, Hash.SIZE_IN_BYTES); i += Hash.SIZE_IN_BYTES; value = Serializer.getLong(bytes, i); i += Long.BYTES; currentIndex = Serializer.getLong(bytes, i); i += Long.BYTES; lastIndex = Serializer.getLong(bytes, i); i += Long.BYTES; timestamp = Serializer.getLong(bytes, i); i += Long.BYTES; tag = HashFactory.TAG.create(bytes, i, Hash.SIZE_IN_BYTES); i += Hash.SIZE_IN_BYTES; attachmentTimestamp = Serializer.getLong(bytes, i); i += Long.BYTES; attachmentTimestampLowerBound = Serializer.getLong(bytes, i); i += Long.BYTES; attachmentTimestampUpperBound = Serializer.getLong(bytes, i); i += Long.BYTES; validity = Serializer.getInteger(bytes, i); i += Integer.BYTES; type.set(Serializer.getInteger(bytes, i)); i += Integer.BYTES; arrivalTime = Serializer.getLong(bytes, i); i += Long.BYTES; height.set(Serializer.getLong(bytes, i)); i += Long.BYTES; /* confirmed = bytes[i] == 1; i++; */ // decode the boolean byte by checking the bitmasks solid.set((bytes[i] & IS_SOLID_BITMASK) != 0); milestone.set((bytes[i] & IS_MILESTONE_BITMASK) != 0); i++; snapshot.set(Serializer.getInteger(bytes, i)); i += Integer.BYTES; byte[] senderBytes = new byte[bytes.length - i]; if (senderBytes.length != 0) { System.arraycopy(bytes, i, senderBytes, 0, senderBytes.length); } sender.set(new String(senderBytes)); parsed.set(true); } @Override public boolean canMerge() { return false; } @Override public Persistable mergeInto(Persistable source) throws OperationNotSupportedException { throw new OperationNotSupportedException("This object is not mergeable"); } @Override public boolean exists() { return !(bytes == null || bytes.length == 0); } }
8,352
33.804167
160
java
iri
iri-master/src/main/java/com/iota/iri/model/safe/ByteSafe.java
package com.iota.iri.model.safe; /** * Extends the HashSafeObject class to generate a null safe byte array with retrievable hash code index. This uses * Double-Checked Locking to ensure that the byte object is initialised correctly when referenced, and does not * return a null value. */ public class ByteSafe extends HashSafeObject { public ByteSafe(byte[] bytes) { super(bytes, "ByteSafe is attempted to be initialized with a null byte array"); } }
460
34.461538
114
java
iri
iri-master/src/main/java/com/iota/iri/model/safe/HashSafeObject.java
package com.iota.iri.model.safe; import java.util.Arrays; /** *Creates a null safe Hash object. */ public class HashSafeObject extends SafeObject { /**A hash code index to be assigned to each Hash object*/ private Integer hashcode; /** * Constructor for safe Hash object from a byte array * * @param obj the byte array that the object will be generated from * @param messageIfUnsafe error message for instantiation failure */ public HashSafeObject(byte[] obj, String messageIfUnsafe) { super(obj, messageIfUnsafe); this.hashcode = Arrays.hashCode(getData()); } /** * Returns the hash code from the contained data * * @return the hash code index of the current object */ public Integer getHashcode() { return hashcode; } }
771
21.057143
68
java
iri
iri-master/src/main/java/com/iota/iri/model/safe/SafeObject.java
package com.iota.iri.model.safe; import java.util.Objects; public class SafeObject { byte[] safeObj; /** * Creates an object which is verified during instantiation. * @param obj the array of bytes we check against * @param messageIfUnsafe The message we emit when it is not safe (inside an exception) */ SafeObject(byte[] obj, String messageIfUnsafe){ this.safeObj = obj; checkSafe(messageIfUnsafe); } /** * This data is checked against its "save" conditions. * @return the data this object guards */ public byte[] getData() { return safeObj; } /** * Ensures the object is not null, otherwise throws an explicit error message * @param messageIfUnsafe the error message */ protected void checkSafe(String messageIfUnsafe) { Objects.requireNonNull(safeObj, messageIfUnsafe); } }
826
21.972222
88
java
iri
iri-master/src/main/java/com/iota/iri/model/safe/TritSafe.java
package com.iota.iri.model.safe; /** * Creates a null safe byte array for storing trit values */ public class TritSafe extends SafeObject { public TritSafe(byte[] bytes) { super(bytes, "TritSafe is attempted to be initialized with a null byte array"); } }
263
23
81
java
iri
iri-master/src/main/java/com/iota/iri/network/FIFOCache.java
package com.iota.iri.network; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * The {@link FIFOCache} is a simple FIFO cache which removes entries at the front of the queue when the capacity is * reached. * * @param <K> the key type * @param <V> the value type */ public class FIFOCache<K, V> { private ReadWriteLock cacheLock = new ReentrantReadWriteLock(true); private final int capacity; private Map<K, V> map = new LinkedHashMap<>(); private AtomicLong cacheHits = new AtomicLong(); private AtomicLong cacheMisses = new AtomicLong(); /** * Creates a new {@link FIFOCache}. * * @param capacity the maximum capacity of the cache */ public FIFOCache(int capacity) { this.capacity = capacity; } /** * Gets the entry by the given key. * * @param key the key to use to retrieve the entry * @return the entry */ public V get(K key) { try { cacheLock.readLock().lock(); V v = this.map.get(key); if (v == null) { cacheMisses.incrementAndGet(); } else { cacheHits.incrementAndGet(); } return v; } finally { cacheLock.readLock().unlock(); } } /** * Adds the given entry by the given key. * * @param key the key to use for the entry * @param value the value of the entry * @return the added entry */ public V put(K key, V value) { try { cacheLock.writeLock().lock(); if (this.map.containsKey(key)) { return value; } if (this.map.size() >= this.capacity) { Iterator<K> it = this.map.keySet().iterator(); it.next(); it.remove(); } return this.map.put(key, value); } finally { cacheLock.writeLock().unlock(); } } /** * Gets the amount of cache hits. * * @return amount of cache hits */ public long getCacheHits() { return cacheHits.get(); } /** * Gets the amount of ache misses. * * @return amount of cache misses */ public long getCacheMisses() { return cacheMisses.get(); } /** * Resets the cache hits and misses stats back to 0. */ public void resetCacheStats() { cacheHits.set(0); cacheMisses.set(0); } }
2,681
24.542857
116
java
iri
iri-master/src/main/java/com/iota/iri/network/NeighborRouter.java
package com.iota.iri.network; import com.iota.iri.conf.BaseIotaConfig; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.network.neighbor.Neighbor; import com.iota.iri.network.pipeline.TransactionProcessingPipeline; import com.iota.iri.network.pipeline.TransactionProcessingPipelineImpl; import java.util.List; import java.util.Map; /** * A NeighborRouter takes care of managing connections to {@link Neighbor} instances, executing reads and writes from/to * neighbors and ensuring that wanted neighbors are connected. <br/> * A neighbor is identified by its identity which is made up of the IP address and the neighbor's own server socket port * for new incoming connections; for example: 153.59.34.101:15600. <br/> * The NeighborRouter and foreign neighbor will first exchange their server socket port via a handshaking packet, in * order to fully build up the identity between each other. If handshaking fails, the connection is dropped. */ public interface NeighborRouter { /** * Starts a dedicated thread for the {@link NeighborRouter} and then starts the routing mechanism. */ void start(); /** * <p> * Starts the routing mechanism which first initialises connections to neighbors from the configuration and then * continuously reads and writes messages from/to neighbors. * </p> * <p> * This method will also try to reconnect to wanted neighbors by the given * {@link BaseIotaConfig#getReconnectAttemptIntervalSeconds()} value. * </p> */ void route(); /** * Adds the given neighbor to the {@link NeighborRouter}. The {@link} Selector is woken up and an attempt to connect * to wanted neighbors is initiated. * * @param rawURI The URI of the neighbor * @return whether the neighbor was added or not */ NeighborMutOp addNeighbor(String rawURI); /** * Removes the given neighbor from the {@link NeighborRouter} by marking it for "disconnect". The neighbor is * disconnected as soon as the next selector loop is executed. * * @param uri The URI of the neighbor * @return whether the neighbor was removed or not */ NeighborMutOp removeNeighbor(String uri); /** * Returns the {@link TransactionProcessingPipelineImpl}. * * @return the {@link TransactionProcessingPipelineImpl} used by the {@link NeighborRouter} */ TransactionProcessingPipeline getTransactionProcessingPipeline(); /** * Gets all neighbors the {@link NeighborRouter} currently sees as either connected or attempts to build connections * to. * * @return The neighbors */ List<Neighbor> getNeighbors(); /** * Gets the currently connected neighbors. * * @return The connected neighbors. */ Map<String, Neighbor> getConnectedNeighbors(); /** * Gossips the given transaction to the given neighbor. * * @param neighbor The {@link Neighbor} to gossip the transaction to * @param tvm The transaction to gossip * @throws Exception thrown when loading a hash of transaction to request fails */ void gossipTransactionTo(Neighbor neighbor, TransactionViewModel tvm) throws Exception; /** * Gossips the given transaction to the given neighbor. * * @param neighbor The {@link Neighbor} to gossip the transaction to * @param tvm The transaction to gossip * @param useHashOfTVM Whether to use the hash of the given transaction as the requested transaction hash or not * @throws Exception thrown when loading a hash of transaction to request fails */ void gossipTransactionTo(Neighbor neighbor, TransactionViewModel tvm, boolean useHashOfTVM) throws Exception; /** * Shut downs the {@link NeighborRouter} and all currently open connections. */ void shutdown(); /** * Defines whether a neighbor got added/removed or not and the corresponding reason. */ enum NeighborMutOp { OK, SLOTS_FILLED, URI_INVALID, UNRESOLVED_DOMAIN, UNKNOWN_NEIGHBOR } }
4,134
36.252252
120
java
iri
iri-master/src/main/java/com/iota/iri/network/NeighborRouterImpl.java
package com.iota.iri.network; import com.iota.iri.conf.BaseIotaConfig; import com.iota.iri.conf.NetworkConfig; import com.iota.iri.conf.ProtocolConfig; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import com.iota.iri.network.neighbor.Neighbor; import com.iota.iri.network.neighbor.NeighborState; import com.iota.iri.network.neighbor.impl.NeighborImpl; import com.iota.iri.network.pipeline.TransactionProcessingPipeline; import com.iota.iri.network.pipeline.TransactionProcessingPipelineImpl; import com.iota.iri.network.protocol.Handshake; import com.iota.iri.network.protocol.Protocol; import com.iota.iri.utils.Converter; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.channels.*; import java.security.SecureRandom; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of the neighbor router interface. */ public class NeighborRouterImpl implements NeighborRouter { private static final Logger log = LoggerFactory.getLogger(NeighborRouterImpl.class); private static final String PROTOCOL_PREFIX = "tcp://"; private static final int MAX_PORT = 65535; private final AtomicBoolean shutdown = new AtomicBoolean(false); private static final SecureRandom rnd = new SecureRandom(); private final ExecutorService executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "Neighbor Router")); // external private NetworkConfig networkConfig; private ProtocolConfig protocolConfig; private TransactionRequester txRequester; private TransactionProcessingPipeline txPipeline; // internal private Selector selector; private ServerSocketChannel serverSocketChannel; /** * a mapping of host address + port (identity) to fully handshaked/connected neighbor */ private ConcurrentHashMap<String, Neighbor> connectedNeighbors = new ConcurrentHashMap<>(); /** * neighbors which we want to connect to. entries are added upon initialization of the NeighborRouter, when a * neighbor is added through addNeighbors and when a connection attempt failed. */ private Set<URI> reconnectPool = new CopyOnWriteArraySet<>(); /** * contains the IP addresses of neighbors which are allowed to connect to us. we use two sets as we allow multiple * connections from a single IP address. */ private Set<String> hostsWhitelist = new HashSet<>(); /** * contains the mapping of IP addresses to their domain names. this is used to map an initialized connection to the * domain which was defined in the configuration or added on addNeighbors, to ensure, that a reconnect attempt to * the given neighbor is done through the resolved IP address of the origin domain. */ private Map<String, String> ipToDomainMapping = new HashMap<>(); /** * contains the IP address + port as declared in the configuration file plus subsequent entries added by * addNeighbors. the identity of a neighbor is its IP address and its own server socket port. */ private Set<String> allowedNeighbors = new HashSet<>(); /** * used to silently drop connections. contains plain IP addresses */ private Set<String> hostsBlacklist = new CopyOnWriteArraySet<>(); /** * used to force the selection loop to reconnect to wanted neighbors */ private AtomicBoolean forceReconnectAttempt = new AtomicBoolean(false); /** * used to match against neighbor's coordinator address to cancel the connection in case it doesn't match this * node's own configured coordinator address */ private byte[] byteEncodedCooAddress; /** * Creates a {@link NeighborRouterImpl}. * * @param networkConfig Network related configuration parameters * @param protocolConfig Protocol related configuration parameters * @param txRequester {@link TransactionRequester} instance to load hashes of requested transactions when * gossiping * @param txPipeline {@link TransactionProcessingPipelineImpl} passed to newly created {@link Neighbor} * instances */ public NeighborRouterImpl(NetworkConfig networkConfig, ProtocolConfig protocolConfig, TransactionRequester txRequester, TransactionProcessingPipeline txPipeline) { this.txRequester = txRequester; this.txPipeline = txPipeline; this.networkConfig = networkConfig; this.protocolConfig = protocolConfig; // reduce the coordinator address to its byte encoded representation byte[] tritsEncodedCooAddress = new byte[protocolConfig.getCoordinator().toString().length() * Converter.NUMBER_OF_TRITS_IN_A_TRYTE]; Converter.trits(protocolConfig.getCoordinator().toString(), tritsEncodedCooAddress, 0); byteEncodedCooAddress = new byte[Handshake.BYTE_ENCODED_COO_ADDRESS_BYTES_LENGTH]; Converter.bytes(tritsEncodedCooAddress, byteEncodedCooAddress); } private void initNeighbors() { // parse URIs networkConfig.getNeighbors().stream() .distinct() .map(NeighborRouterImpl::parseURI) .filter(Optional::isPresent) .map(Optional::get) .forEach(uri -> reconnectPool.add(uri)); } @Override public void start() { executor.execute(this::route); } @Override public void route() { log.info("starting neighbor router"); // run selector loop try { selector = Selector.open(); serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); InetSocketAddress tcpBindAddr = new InetSocketAddress(networkConfig.getNeighboringSocketAddress(), networkConfig.getNeighboringSocketPort()); serverSocketChannel.socket().bind(tcpBindAddr); log.info("bound server TCP socket to {}", tcpBindAddr); // parse neighbors from configuration initNeighbors(); // init connections to the wanted neighbors, // this also ensures that the whitelists are updated with the corresponding // IP addresses and domain name mappings. connectToWantedNeighbors(); long lastReconnectAttempts = System.currentTimeMillis(); long reconnectAttemptTimeout = TimeUnit.SECONDS .toMillis(networkConfig.getReconnectAttemptIntervalSeconds()); while (!shutdown.get()) { selector.select(reconnectAttemptTimeout); if (shutdown.get()) { break; } // reinitialize connections to wanted neighbors long now = System.currentTimeMillis(); if (forceReconnectAttempt.get() || now - lastReconnectAttempts > reconnectAttemptTimeout) { lastReconnectAttempts = now; forceReconnectAttempt.set(false); connectToWantedNeighbors(); } Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { try { SelectionKey key = iterator.next(); if (key.isAcceptable()) { handleNewConnection(key); continue; } SocketChannel channel = (SocketChannel) key.channel(); Neighbor neighbor = (Neighbor) key.attachment(); String identity = neighbor.getHostAddressAndPort(); // check whether marked for disconnect if (neighbor.getState() == NeighborState.MARKED_FOR_DISCONNECT) { allowedNeighbors.remove(identity); closeNeighborConnection(channel, identity, selector); removeFromReconnectPool(neighbor); continue; } if (key.isConnectable()) { handleConnect(channel, key, identity, neighbor); continue; } if (key.isWritable() && !handleWrite(channel, key, identity, neighbor)) { continue; } if (key.isReadable()) { handleRead(channel, identity, neighbor); } } finally { iterator.remove(); } } } } catch (IOException e) { log.error("error occurred in the neighbor router", e); } finally { try { if (selector != null) { // close all connections for (SelectionKey keys : selector.keys()) { keys.channel().close(); } selector.close(); } if (serverSocketChannel != null) { serverSocketChannel.close(); } } catch (IOException e) { log.error("error occurred while trying to gracefully shutdown the neighbor router", e); } log.info("neighbor router stopped"); } } /** * Handles a new incoming connection and if it passes some initial conditions (via * {@link NeighborRouterImpl#okToConnect(String, SocketChannel)}), will start the handshaking process by placing a * handshake packet into the connection's send queue. * * @param key the selection key associated with the server socket channel * @return whether the new connection was accepted */ private boolean handleNewConnection(SelectionKey key) { try { // new connection from neighbor ServerSocketChannel srvSocket = (ServerSocketChannel) key.channel(); SocketChannel newConn = srvSocket.accept(); if (newConn == null) { return false; } InetSocketAddress remoteAddr = (InetSocketAddress) newConn.getRemoteAddress(); if (!okToConnect(remoteAddr.getAddress().getHostAddress(), newConn)) { return false; } configureSocket(newConn); Neighbor newNeighbor = new NeighborImpl<>(selector, newConn, remoteAddr.getAddress().getHostAddress(), Neighbor.UNKNOWN_REMOTE_SERVER_SOCKET_PORT, txPipeline); String domain = ipToDomainMapping.get(remoteAddr.getAddress().getHostAddress()); if (domain != null) { newNeighbor.setDomain(domain); } else { newNeighbor.setDomain(remoteAddr.getAddress().getHostAddress()); } newNeighbor.send(Handshake.createHandshakePacket((char) networkConfig.getNeighboringSocketPort(), byteEncodedCooAddress, (byte) protocolConfig.getMwm())); log.info("new connection from {}, performing handshake...", newNeighbor.getHostAddress()); newConn.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, newNeighbor); return true; } catch (IOException ex) { log.info("couldn't accept connection. reason: {}", ex.getMessage()); } return false; } /** * <p> * Finalizes the underlying connection sequence by calling the channel's finishConnect() method. * </p> * <p> * <strong> This method does not finalize the logical protocol level connection, rather, it kicks of that process by * placing a handshake packet into the neighbor's send queue if the connection was successfully established. * </strong> * </p> * <p> * Connections passed into this method are self-initialized and were not accepted by the server socket channel. * </p> * <p> * In case the connection sequence fails, the connection will be dropped. * </p> * * @param channel the associated channel for the given connection * @param key the associated selection key associated with the given connection * @param identity the identity of the connection/neighbor * @param neighbor the neighbor associated with this connection * @return whether the connection sequence finished successfully */ private boolean handleConnect(SocketChannel channel, SelectionKey key, String identity, Neighbor neighbor) { try { // the neighbor was faster than us to setup the connection if (connectedNeighbors.containsKey(identity)) { log.info("neighbor {} is already connected", identity); removeFromReconnectPool(neighbor); key.cancel(); return false; } if (channel.finishConnect()) { log.info("established connection to neighbor {}, now performing handshake...", identity); // remove connect interest key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); // add handshaking packet as the initial packet to send neighbor.send(Handshake.createHandshakePacket((char) networkConfig.getNeighboringSocketPort(), byteEncodedCooAddress, (byte) protocolConfig.getMwm())); return true; } } catch (IOException ex) { log.info("couldn't establish connection to neighbor {}, will attempt to reconnect later. reason: {}", identity, ex.getMessage()); closeNeighborConnection(channel, identity, selector); } return false; } /** * <p> * Handles the write readiness by the given channel by writing a message into its send buffer. * </p> * * <p> * If there was no message to send, then the channel is de-registered from write interests. If the channel would not * be de-registered from write interests, the channel's write readiness would constantly fire this method even if * there's nothing to send, causing high CPU usage. Re-registering the channel for write interest is implicitly done * via the caller who's interested to send a message through the neighbor's implementation. * </p> * <p> * In case the write fails with an IOException, the connection will be dropped. * </p> * * @param channel the associated channel for the given connection * @param key the associated selection key associated with the given connection * @param identity the identity of the connection/neighbor * @param neighbor the neighbor associated with this connection * @return whether the write operation was successful or not */ private boolean handleWrite(SocketChannel channel, SelectionKey key, String identity, Neighbor neighbor) { try { switch (neighbor.write()) { // something bad happened case -1: if (neighbor.getState() == NeighborState.HANDSHAKING) { log.info("closing connection to {} as handshake packet couldn't be written", identity); closeNeighborConnection(channel, null, selector); } else { closeNeighborConnection(channel, identity, selector); } return false; // bytes were either written or not written to the channel // we check whether we still have something else to send, if not we unregister write default: synchronized (key) { if (!neighbor.hasDataToSendTo()) { key.interestOps(SelectionKey.OP_READ); } } } return true; } catch (IOException ex) { log.warn("unable to write message to neighbor {}. reason: {}", identity, ex.getMessage()); closeNeighborConnection(channel, identity, selector); addToReconnectPool(neighbor); } return false; } /** * <p> * Handles the read readiness by the given channel by reading from the channel's receive buffer. * </p> * <p> * In case the read fails with an IOException, the connection will be dropped. * </p> * * @param channel the associated channel for the given connection * @param identity the identity of the connection/neighbor * @param neighbor the neighbor associated with this connection * @return whether the read operation was successful or not */ private boolean handleRead(SocketChannel channel, String identity, Neighbor neighbor) { try { switch (neighbor.getState()) { case READY_FOR_MESSAGES: if (neighbor.read() == -1) { closeNeighborConnection(channel, identity, selector); return false; } break; case HANDSHAKING: if (finalizeHandshake(identity, neighbor, channel) && availableNeighborSlotsFilled()) { // if all known neighbors or max neighbors are connected we are // no longer interested in any incoming connections // (as long as no neighbor dropped the connection) SelectionKey srvKey = serverSocketChannel.keyFor(selector); srvKey.interestOps(0); } default: // do nothing } return true; } catch (IOException ex) { log.warn("unable to read message from neighbor {}. reason: {}", identity, ex.getMessage()); closeNeighborConnection(channel, identity, selector); addToReconnectPool(neighbor); } return false; } /** * Adjusts the given socket's configuration. * * @param socketChannel the socket to configure * @throws IOException throw during adjusting the socket's configuration */ private void configureSocket(SocketChannel socketChannel) throws IOException { socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setSoLinger(true, 0); socketChannel.configureBlocking(false); } /** * Adds the given neighbor to the 'reconnect pool' of neighbors which this node will try to reconnect to. If the * domain of the neighbor was known when the connection was established, it will be used to re-establish the * connection to the neighbor, otherwise the neighbor's current known IP address is used.<br/> * The neighbor is only added to the 'reconnect pool' if the neighbor was ready to send/process messages. * * @param neighbor the neighbor to attempt to reconnect to * @return whether the neighbor got added to the reconnect pool or not */ private boolean addToReconnectPool(Neighbor neighbor) { if (neighbor.getState() != NeighborState.READY_FOR_MESSAGES) { return false; } // try to pull out the origin domain which was used to establish // the connection with this neighbor String domain = ipToDomainMapping.get(neighbor.getHostAddress()); URI reconnectURI; if (domain != null) { reconnectURI = URI .create(String.format("%s%s:%d", PROTOCOL_PREFIX, domain, neighbor.getRemoteServerSocketPort())); } else { reconnectURI = URI.create(String.format("%s%s", PROTOCOL_PREFIX, neighbor.getHostAddressAndPort())); } log.info("adding {} to the reconnect pool", reconnectURI); return reconnectPool.add(reconnectURI); } /** * Ensures that the neighbor is removed from the reconnect pool by using the neighbor's IP address and domain * identity. * * @param neighbor the neighbor to remove from the reconnect pool * @return whether the neighbor was removed from the reconnect pool or not */ private boolean removeFromReconnectPool(Neighbor neighbor) { URI raw = URI.create(String.format("%s%s", PROTOCOL_PREFIX, neighbor.getHostAddressAndPort())); boolean removedByURI = reconnectPool.remove(raw); String domain = neighbor.getDomain(); if (domain != null) { URI withDomain = URI .create(String.format("%s%s:%d", PROTOCOL_PREFIX, domain, neighbor.getRemoteServerSocketPort())); if (reconnectPool.remove(withDomain)) { return true; } } return removedByURI; } /** * Finalizes the handshaking to a {@link Neighbor} by reading the handshaking packet. <br/> * A faulty handshaking will drop the neighbor connection. <br/> * The connection will be dropped when: * <ul> * <li>the handshaking is faulty, meaning that a non handshaking packet was sent</li> * <li>{@link BaseIotaConfig#getMaxNeighbors()} has been reached</li> * <li>the neighbor has a different coordinator address set as we do</li> * <li>the neighbor uses a different minimum weight magnitude than we do</li> * <li>a non matching server socket port was communicated in the handshaking packet</li> * <li>the neighbor is already connected (checked by the identity)</li> * <li>the identity is not known (missing in {@link NeighborRouterImpl#allowedNeighbors})</li> * </ul> * * @param identity The identity of the neighbor * @param neighbor The {@link Neighbor} to finalize the handshaking with * @param channel The associated {@link SocketChannel} of the {@link Neighbor} * @return whether the handshaking was successful * @throws IOException thrown when reading the handshake packet fails */ private boolean finalizeHandshake(String identity, Neighbor neighbor, SocketChannel channel) throws IOException { Handshake handshake = neighbor.handshake(); switch (handshake.getState()) { case INIT: // not fully read handshake packet return false; case FAILED: // faulty handshaking log.warn("dropping connection to neighbor {} as handshaking was faulty", identity); closeNeighborConnection(channel, identity, selector); return false; default: // do nothing } // drop the connection if in the meantime the available neighbor slots were filled if (availableNeighborSlotsFilled()) { log.error("dropping handshaked connection to neighbor {} as all neighbor slots are filled", identity); closeNeighborConnection(channel, null, selector); return false; } // check whether same MWM is used if (handshake.getMWM() != protocolConfig.getMwm()) { log.error("dropping handshaked connection to neighbor {} as it uses a different MWM ({} instead of {})", identity, handshake.getMWM(), protocolConfig.getMwm()); closeNeighborConnection(channel, null, selector); return false; } // check whether the neighbor actually uses the same coordinator address if (!Arrays.equals(byteEncodedCooAddress, handshake.getByteEncodedCooAddress())) { log.error("dropping handshaked connection to neighbor {} as it uses a different coordinator address", identity); closeNeighborConnection(channel, null, selector); return false; } // check whether we support the supported protocol versions by the neighbor int supportedVersion = handshake.getNeighborSupportedVersion(Protocol.SUPPORTED_PROTOCOL_VERSIONS); if (supportedVersion <= 0) { log.error( "dropping handshaked connection to neighbor {} as its highest supported protocol version {} is not supported", identity, Math.abs(supportedVersion)); closeNeighborConnection(channel, null, selector); return false; } neighbor.setProtocolVersion(supportedVersion); // after a successful handshake, the neighbor's server socket port is initialized // and thereby the identity of the neighbor is now fully distinguishable // check whether the remote server socket port from the origin URI // actually corresponds to the port advertised in the handshake packet int originPort = neighbor.getRemoteServerSocketPort(); int handshakePort = handshake.getServerSocketPort(); if (originPort != Neighbor.UNKNOWN_REMOTE_SERVER_SOCKET_PORT && originPort != handshakePort) { log.warn("dropping handshaked connection from {} as neighbor advertised " + "wrong server socket port (wanted {}, got {})", identity, originPort, handshakePort); closeNeighborConnection(channel, null, selector); return false; } neighbor.setRemoteServerSocketPort(handshakePort); // check if neighbor is already connected String newIdentity = neighbor.getHostAddressAndPort(); if (connectedNeighbors.containsKey(newIdentity)) { log.info("dropping handshaked connection from {} as neighbor is already connected", newIdentity); // pass just host address to not actually delete the already existing connection/neighbor closeNeighborConnection(channel, null, selector); return false; } // check if the given host + server socket port combination is actually defined in the config/wanted if (!networkConfig.isAutoTetheringEnabled() && !allowedNeighbors.contains(newIdentity)) { log.info("dropping handshaked connection as neighbor from {} is not allowed to connect", newIdentity); closeNeighborConnection(channel, null, selector); return false; } log.info("neighbor connection to {} is ready for messages [latency {} ms, protocol version {}]", newIdentity, System.currentTimeMillis() - handshake.getSentTimestamp(), supportedVersion); // the neighbor is now ready to process actual protocol messages neighbor.setState(NeighborState.READY_FOR_MESSAGES); // we finally add the neighbor to the connected neighbors map // if the handshake was successful and we got the remote port connectedNeighbors.put(neighbor.getHostAddressAndPort(), neighbor); // prevent reconnect attempts from the 'reconnect pool' // by constructing the source URI which was used for this neighbor removeFromReconnectPool(neighbor); return true; } /** * Initializes connections to wanted neighbors which are neighbors added by * {@link NeighborRouter#addNeighbor(String)} or defined in the configuration.<br/> * * A connection attempt is only made if the domain name of the neighbor could be resolved to its IP address. * Reconnect attempts will continuously try to resolve the domain name until the neighbor is explicitly removed via * {@link NeighborRouter#removeNeighbor(String)}. */ private void connectToWantedNeighbors() { if (reconnectPool.isEmpty()) { return; } log.info("establishing connections to {} wanted neighbors {}", reconnectPool.size(), reconnectPool.toArray()); reconnectPool.forEach(neighborURI -> { InetSocketAddress inetAddr = new InetSocketAddress(neighborURI.getHost(), neighborURI.getPort()); try { // if in the meantime the neighbor connected to us, we don't need to reinitialize a connection. if (!inetAddr.isUnresolved()) { String ipAddress = inetAddr.getAddress().getHostAddress(); String identity = String.format("%s:%d", ipAddress, inetAddr.getPort()); if (connectedNeighbors.containsKey(identity)) { log.info("skipping connecting to {} as neighbor is already connected", identity); reconnectPool.remove(neighborURI); return; } } initNeighborConnection(neighborURI, inetAddr); } catch (IOException e) { log.warn("unable to build socket for neighbor {}. reason: {}", neighborURI, e.getMessage()); } }); } /** * Initializes a new {@link SocketChannel} to the given neighbor. <br/> * The IP address of the neighbor is removed from the blacklist, added to the whitelist and registered as an allowed * neighbor by its identity. * * @param neighborURI The {@link URI} of the neighbor to connect to * @param addr The {@link InetSocketAddress} extracted from the {@link URI} * @throws IOException if initializing the {@link SocketChannel} fails */ private void initNeighborConnection(URI neighborURI, InetSocketAddress addr) throws IOException { if (addr.isUnresolved()) { log.warn("unable to resolve neighbor {} to IP address, will attempt to reconnect later", neighborURI); return; } String ipAddress = addr.getAddress().getHostAddress(); // we are overriding a blacklist entry as we are explicitly trying to create a connection hostsBlacklist.remove(ipAddress); // allow connections from the given remote IP address to us. // this comes into place if our own initialized connection fails // but afterwards the added neighbor builds a connection to us. hostsWhitelist.add(ipAddress); // map the ip address to the domain ipToDomainMapping.put(ipAddress, addr.getHostString()); // make the identity of the newly added neighbor clear, so that it gets rejected during handshaking // finalisation, in case the communicated server socket port is wrong. allowedNeighbors.add(String.format("%s:%d", addr.getAddress().getHostAddress(), addr.getPort())); // init new TCP socket channel SocketChannel tcpChannel = SocketChannel.open(); configureSocket(tcpChannel); tcpChannel.connect(addr); Neighbor neighbor = new NeighborImpl<>(selector, tcpChannel, addr.getAddress().getHostAddress(), addr.getPort(), txPipeline); neighbor.setDomain(addr.getHostString()); tcpChannel.register(selector, SelectionKey.OP_CONNECT, neighbor); } /** * Checks whether the given host is allowed to connect given its IP address. <br/> * The connection is allowed when: * <ul> * <li>the IP address is not in the {@link NeighborRouterImpl#hostsBlacklist}</li> * <li>{@link BaseIotaConfig#getMaxNeighbors()} has not been reached</li> * <li>is whitelisted in {@link NeighborRouterImpl#hostsWhitelist} (if {@link BaseIotaConfig#isAutoTetheringEnabled()} * is false)</li> * </ul> * The IP address is blacklisted to mute it from subsequent connection attempts. The blacklisting is removed if the * IP address is added through {@link NeighborRouter#addNeighbor(String)}. * * @param ipAddress The IP address * @param newNeighborConn The {@link SocketChannel} to close if the connection is not allowed * @return true if allowed, false if not * @throws IOException if anything goes wrong closing the {@link SocketChannel} */ private boolean okToConnect(String ipAddress, SocketChannel newNeighborConn) throws IOException { if (hostsBlacklist.contains(ipAddress)) { // silently drop connection newNeighborConn.close(); return false; } if (availableNeighborSlotsFilled()) { log.info("dropping new connection from {} as all neighbor slots are filled", ipAddress); newNeighborConn.close(); return false; } boolean whitelisted = hostsWhitelist.contains(ipAddress); if (!whitelisted) { if (!networkConfig.isAutoTetheringEnabled()) { log.info("blacklisting/dropping new connection as neighbor from {} is not defined in the config", ipAddress); hostsBlacklist.add(ipAddress); newNeighborConn.close(); return false; } log.info("new auto-tethering connection from {}", ipAddress); } return true; } /** * Closes the connection to the neighbor, re-registers the {@link ServerSocketChannel} for * {@link SelectionKey#OP_CONNECT} in case neighbor slots will be available again and finally removes the neighbor * from the connected neighbors map. * * @param channel {@link SocketChannel} to close * @param identity The identity of the neighbor, null must be passed if the neighbor should not be marked as not * connected. * @param selector The used {@link Selector} */ private void closeNeighborConnection(SelectableChannel channel, String identity, Selector selector) { try { channel.close(); } catch (IOException e) { log.error("error while closing connection: {}", e.getMessage()); } if (identity == null) { return; } if (connectedNeighbors.remove(identity) != null) { log.info("removed neighbor {} from connected neighbors", identity); // re-register the server socket for incoming connections as we will have a new slot open if (availableNeighborSlotsFilled()) { serverSocketChannel.keyFor(selector).interestOps(SelectionKey.OP_ACCEPT); } } } private boolean availableNeighborSlotsFilled() { // while this check is not thread-safe, initiated connections will be dropped // when their handshaking was done but already all neighbor slots are filled return connectedNeighbors.size() >= networkConfig.getMaxNeighbors(); } @Override public NeighborMutOp addNeighbor(String rawURI) { if (availableNeighborSlotsFilled()) { return NeighborMutOp.SLOTS_FILLED; } Optional<URI> optUri = parseURI(rawURI); if (!optUri.isPresent()) { return NeighborMutOp.URI_INVALID; } URI neighborURI = optUri.get(); // add to wanted neighbors reconnectPool.add(neighborURI); // wake up the selector and let it build connections to wanted neighbors forceReconnectAttempt.set(true); selector.wakeup(); return NeighborMutOp.OK; } @Override public NeighborMutOp removeNeighbor(String uri) { Optional<URI> optUri = parseURI(uri); if (!optUri.isPresent()) { return NeighborMutOp.URI_INVALID; } URI neighborURI = optUri.get(); InetSocketAddress inetAddr = new InetSocketAddress(neighborURI.getHost(), neighborURI.getPort()); if (inetAddr.isUnresolved()) { log.warn("unable to remove neighbor {} as IP address couldn't be resolved", uri); return NeighborMutOp.UNRESOLVED_DOMAIN; } // remove the neighbor from connection attempts boolean isSeen = reconnectPool.remove(neighborURI); URI rawURI = URI.create(String.format("%s%s:%d", PROTOCOL_PREFIX, inetAddr.getAddress().getHostAddress(), neighborURI.getPort())); reconnectPool.remove(rawURI); String identity = String.format("%s:%d", inetAddr.getAddress().getHostAddress(), inetAddr.getPort()); Neighbor neighbor = connectedNeighbors.get(identity); if (neighbor == null) { if (isSeen) { return NeighborMutOp.OK; } return NeighborMutOp.UNKNOWN_NEIGHBOR; } // the neighbor will be disconnected inside the selector loop neighbor.setState(NeighborState.MARKED_FOR_DISCONNECT); return NeighborMutOp.OK; } /** * Parses the given string to an URI. The URI must use "tcp://" as the protocol. * * @param uri The URI string to parse * @return the parsed URI, if parsed correctly */ private static Optional<URI> parseURI(final String uri) { if (uri.isEmpty()) { return Optional.empty(); } URI neighborURI; try { neighborURI = new URI(uri); } catch (URISyntaxException e) { log.error("URI {} raised URI Syntax Exception. reason: {}", uri, e.getMessage()); return Optional.empty(); } if (!isURIValid(neighborURI)) { return Optional.empty(); } return Optional.of(neighborURI); } /** * Checks whether the given URI is valid. The URI is valid if * - it is not null * - it uses TCP as the protocol and * - the port is in the range 0 and {@value MAX_PORT} * * @param uri The URI to check * @return true if the URI is valid, false if not */ private static boolean isURIValid(final URI uri) { if (uri == null) { return false; } if (!uri.getScheme().equals("tcp")) { log.error("'{}' is not a valid URI schema, only TCP ({}) is supported", uri, PROTOCOL_PREFIX); return false; } if (uri.getPort() < 0 || uri.getPort() > MAX_PORT) { log.error("'{} is not in the valid port range of {} and {}", uri.getPort(), 0, MAX_PORT); return false; } return true; } @Override public TransactionProcessingPipeline getTransactionProcessingPipeline() { return txPipeline; } @Override public List<Neighbor> getNeighbors() { List<Neighbor> neighbors = new ArrayList<>(connectedNeighbors.values()); reconnectPool.forEach(uri -> { // try to resolve the address of the neighbor which is not connected InetSocketAddress inetAddr = new InetSocketAddress(uri.getHost(), uri.getPort()); String hostAddress = ""; if(!inetAddr.isUnresolved()){ hostAddress = inetAddr.getAddress().getHostAddress(); } Neighbor neighbor = new NeighborImpl<>(null, null, hostAddress, uri.getPort(), null); // enforce the domain to be set, if the uri contains the IP address, the host address will not be empty // hence using the getNeighbors() HTTP API call will return a meaningful answer. neighbor.setDomain(uri.getHost()); neighbors.add(neighbor); }); return neighbors; } @Override public Map<String, Neighbor> getConnectedNeighbors() { return Collections.unmodifiableMap(connectedNeighbors); } @Override public void gossipTransactionTo(Neighbor neighbor, TransactionViewModel tvm) throws Exception { gossipTransactionTo(neighbor, tvm, false); } @Override public void gossipTransactionTo(Neighbor neighbor, TransactionViewModel tvm, boolean useHashOfTVM) throws Exception { byte[] requestedHash = null; if (!useHashOfTVM) { Hash hash = txRequester.transactionToRequest(); if (hash != null) { requestedHash = hash.bytes(); } } if (requestedHash == null) { requestedHash = tvm.getHash().bytes(); } ByteBuffer packet = Protocol.createTransactionGossipPacket(tvm, requestedHash); neighbor.send(packet); // tx might actually not be sent, we are merely putting it into the send queue // TODO: find a way to increment once we actually sent the txs into the channel neighbor.getMetrics().incrSentTransactionsCount(); } @Override public void shutdown() { shutdown.set(true); executor.shutdownNow(); } }
40,891
43.496192
130
java
iri
iri-master/src/main/java/com/iota/iri/network/NetworkInjectionConfiguration.java
package com.iota.iri.network; import com.iota.iri.conf.IotaConfig; import com.iota.iri.controllers.TipsViewModel; import com.iota.iri.network.impl.TipsRequesterImpl; import com.iota.iri.network.pipeline.TransactionProcessingPipeline; import com.iota.iri.network.pipeline.TransactionProcessingPipelineImpl; import com.iota.iri.service.milestone.InSyncService; import com.iota.iri.service.milestone.MilestoneService; import com.iota.iri.service.milestone.MilestoneSolidifier; import com.iota.iri.service.snapshot.SnapshotProvider; import com.iota.iri.service.validation.TransactionSolidifier; import com.iota.iri.service.validation.TransactionValidator; import com.iota.iri.storage.Tangle; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; /** * Guice module for network package. Configuration class for dependency injection. */ public class NetworkInjectionConfiguration extends AbstractModule { private final IotaConfig configuration; /** * Creates the guice injection module. * @param configuration The iota configuration used for conditional bean creation and constructing beans with * configuration parameters. */ public NetworkInjectionConfiguration(IotaConfig configuration) { this.configuration = configuration; } @Singleton @Provides TransactionRequester provideTransactionRequester(Tangle tangle, SnapshotProvider snapshotProvider) { return new TransactionRequester(tangle, snapshotProvider); } @Singleton @Provides TipsRequester provideTipsRequester(NeighborRouter neighborRouter, Tangle tangle, MilestoneSolidifier milestoneSolidifier, TransactionRequester txRequester) { return new TipsRequesterImpl(neighborRouter, tangle, milestoneSolidifier, txRequester); } @Singleton @Provides TransactionProcessingPipeline provideTransactionProcessingPipeline(NeighborRouter neighborRouter, TransactionValidator txValidator, Tangle tangle, SnapshotProvider snapshotProvider, TipsViewModel tipsViewModel, TransactionRequester transactionRequester, TransactionSolidifier transactionSolidifier, MilestoneService milestoneService, MilestoneSolidifier milestoneSolidifier, InSyncService inSyncService) { return new TransactionProcessingPipelineImpl(neighborRouter, configuration, txValidator, tangle, snapshotProvider, tipsViewModel, milestoneSolidifier, transactionRequester, transactionSolidifier, milestoneService, inSyncService); } @Singleton @Provides NeighborRouter provideNeighborRouter(TransactionRequester transactionRequester, TransactionProcessingPipeline transactionProcessingPipeline) { return new NeighborRouterImpl(configuration, configuration, transactionRequester, transactionProcessingPipeline); } }
2,928
42.716418
161
java
iri
iri-master/src/main/java/com/iota/iri/network/TipsRequester.java
package com.iota.iri.network; /** * The {@link TipsRequester} requests tips from all neighbors in a given interval. */ public interface TipsRequester { /** * Issues random tip requests to all connected neighbors. */ void requestTips(); /** * Starts the background worker that automatically calls {@link #requestTips()} periodically to request * tips from neighbors. */ void start(); /** * Stops the background worker that requests tips from the neighbors. */ void shutdown(); }
544
20.8
107
java
iri
iri-master/src/main/java/com/iota/iri/network/TransactionCacheDigester.java
package com.iota.iri.network; import net.openhft.hashing.LongHashFunction; /** * Helper class for computing hashes for the transaction cache. */ public class TransactionCacheDigester { private static final LongHashFunction TX_CACHE_DIGEST_HASH_FUNC = LongHashFunction.xx(); /** * Computes the digest of the given transaction data. * * @param txBytes The raw byte encoded transaction data * @return The the digest of the transaction data */ public static long getDigest(byte[] txBytes) { return TX_CACHE_DIGEST_HASH_FUNC.hashBytes(txBytes); } }
600
25.130435
92
java
iri
iri-master/src/main/java/com/iota/iri/network/TransactionRequester.java
package com.iota.iri.network; import java.util.*; import com.google.common.annotations.VisibleForTesting; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import com.iota.iri.service.snapshot.Snapshot; import com.iota.iri.service.snapshot.SnapshotProvider; import com.iota.iri.storage.Tangle; public class TransactionRequester { private final Set<Hash> transactionsToRequest = new LinkedHashSet<>(); private final Set<Hash> recentlyRequestedTransactions = Collections.synchronizedSet(new HashSet<>()); public static final int MAX_TX_REQ_QUEUE_SIZE = 10000; private final Object syncObj = new Object(); private final Tangle tangle; private final SnapshotProvider snapshotProvider; /** * Create {@link TransactionRequester} for receiving transactions from the tangle. * * @param tangle used to request transaction * @param snapshotProvider that allows to retrieve the {@link Snapshot} instances that are relevant for the node */ public TransactionRequester(Tangle tangle, SnapshotProvider snapshotProvider) { this.tangle = tangle; this.snapshotProvider = snapshotProvider; } public Hash[] getRequestedTransactions() { synchronized (syncObj) { return transactionsToRequest.stream().toArray(Hash[]::new); } } public int numberOfTransactionsToRequest() { return transactionsToRequest.size(); } public boolean clearTransactionRequest(Hash hash) { synchronized (syncObj) { return transactionsToRequest.remove(hash); } } /** * Adds the given transaction hash to the request queue. * * @param hash the hash of the transaction to add to the request queue */ public void requestTransaction(Hash hash) { if (!snapshotProvider.getInitialSnapshot().hasSolidEntryPoint(hash)) { synchronized (syncObj) { if (transactionsToRequestIsFull()) { popEldestTransactionToRequest(); } transactionsToRequest.add(hash); } } } /** * Puts the given transaction's trunk and branch transactions into the request queue if: * <ul> * <li>the approver transaction is not solid</li> * <li>trunk/branch is not a solid entry point</li> * <li>trunk/branch is not persisted in the database</li> * </ul> * * @param approver the approver transaction */ public void requestTrunkAndBranch(TransactionViewModel approver) throws Exception { // don't request anything if the approver is already solid if(approver.isSolid()){ return; } Hash trunkHash = approver.getTrunkTransactionHash(); Hash branchHash = approver.getBranchTransactionHash(); if(!snapshotProvider.getInitialSnapshot().hasSolidEntryPoint(trunkHash) && !TransactionViewModel.exists(tangle, trunkHash)){ requestTransaction(trunkHash); } if(!snapshotProvider.getInitialSnapshot().hasSolidEntryPoint(branchHash) && !TransactionViewModel.exists(tangle, branchHash)){ requestTransaction(branchHash); } } /** * This method removes the oldest transaction in the transactionsToRequest Set. * <p> * It used when the queue capacity is reached, and new transactions would be dropped as a result. */ @VisibleForTesting void popEldestTransactionToRequest() { Iterator<Hash> iterator = transactionsToRequest.iterator(); if (iterator.hasNext()) { iterator.next(); iterator.remove(); } } /** * This method allows to check if a transaction was requested by the TransactionRequester. * <p> * It can for example be used to determine if a transaction that was received by the node was actively requested * while i.e. solidifying transactions or if a transaction arrived due to the gossip protocol. * * @param transactionHash hash of the transaction to check * @return true if the transaction is in the set of transactions to be requested and false otherwise */ public boolean isTransactionRequested(Hash transactionHash) { return transactionsToRequest.contains(transactionHash); } /** * Checks whether the given transaction was recently requested on a neighbor. * * @param transactionHash hash of the transaction to check * @return true if the transaction was recently requested on a neighbor */ public boolean wasTransactionRecentlyRequested(Hash transactionHash) { return recentlyRequestedTransactions.contains(transactionHash); } /** * Gets the amount of recently requested transactions. * @return the amount of recently requested transactions */ public int numberOfRecentlyRequestedTransactions() { return recentlyRequestedTransactions.size(); } /** * Clears the recently requested transactions set. */ public void clearRecentlyRequestedTransactions(){ recentlyRequestedTransactions.clear(); } /** * Removes the given transaction hash from the recently requested transactions set. * * @param transactionHash hash of the transaction to remove * @return true if the transaction was recently requested and removed from the set */ public boolean removeRecentlyRequestedTransaction(Hash transactionHash) { return recentlyRequestedTransactions.remove(transactionHash); } private boolean transactionsToRequestIsFull() { return transactionsToRequest.size() >= TransactionRequester.MAX_TX_REQ_QUEUE_SIZE; } public Hash transactionToRequest() throws Exception { // determine the first hash in our set that needs to be processed Hash hash = null; synchronized (syncObj) { // repeat while we have transactions that shall be requested if (transactionsToRequest.size() != 0) { // get the first item in our set for further examination Iterator<Hash> iterator = transactionsToRequest.iterator(); hash = iterator.next(); iterator.remove(); recentlyRequestedTransactions.add(hash); } } // return our result return hash; } }
6,479
35.404494
116
java
iri
iri-master/src/main/java/com/iota/iri/network/impl/TipsRequesterImpl.java
package com.iota.iri.network.impl; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.network.NeighborRouter; import com.iota.iri.network.TipsRequester; import com.iota.iri.network.TransactionRequester; import com.iota.iri.network.neighbor.Neighbor; import com.iota.iri.network.pipeline.TransactionProcessingPipeline; import com.iota.iri.service.milestone.MilestoneSolidifier; import com.iota.iri.storage.Tangle; import com.iota.iri.utils.thread.DedicatedScheduledExecutorService; import com.iota.iri.utils.thread.SilentScheduledExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; /** * The {@link TipsRequesterImpl} requests tips from all neighbors in a given interval. */ public class TipsRequesterImpl implements TipsRequester { private static final Logger log = LoggerFactory.getLogger(TipsRequesterImpl.class); private static final int REQUESTER_THREAD_INTERVAL = 5000; private final SilentScheduledExecutorService executorService = new DedicatedScheduledExecutorService( "Tips Requester", log); private final NeighborRouter neighborRouter; private final Tangle tangle; private final TransactionRequester txRequester; private final MilestoneSolidifier milestoneSolidifier; private long lastIterationTime = 0; /** * Creates a tips requester. * * @param neighborRouter the {@link NeighborRouter} to use * @param tangle the {@link Tangle} database to load the latest milestone from * @param milestoneSolidifier the {@link MilestoneSolidifier} to gets the latest milestone hash from * @param txRequester the {@link TransactionRequester} to get the currently number of requested * transactions from */ public TipsRequesterImpl(NeighborRouter neighborRouter, Tangle tangle, MilestoneSolidifier milestoneSolidifier, TransactionRequester txRequester) { this.neighborRouter = neighborRouter; this.tangle = tangle; this.milestoneSolidifier = milestoneSolidifier; this.txRequester = txRequester; } /** * Starts a dedicated thread for the {@link TipsRequesterImpl} and then starts requesting of tips. */ public void start() { executorService.silentScheduleWithFixedDelay(this::requestTips, 0, REQUESTER_THREAD_INTERVAL, TimeUnit.MILLISECONDS); } /** * Starts the loop to indefinitely request tips from neighbors. */ public void requestTips() { try { final TransactionViewModel msTVM = TransactionViewModel.fromHash(tangle, milestoneSolidifier.getLatestMilestoneHash()); if (msTVM.getBytes().length > 0) { for (Neighbor neighbor : neighborRouter.getConnectedNeighbors().values()) { if(Thread.currentThread().isInterrupted()){ return; } try { neighborRouter.gossipTransactionTo(neighbor, msTVM, true); } catch (Exception e) { log.error("error while sending tip request to neighbor {}. reason: {}", neighbor.getHostAddressAndPort(), e.getMessage()); } } } long now = System.currentTimeMillis(); if ((now - lastIterationTime) > 10_000L) { lastIterationTime = now; TransactionProcessingPipeline txPipeline = neighborRouter.getTransactionProcessingPipeline(); log.info( "toProcess = {} , toBroadcast = {} , toRequest = {} , toReply = {} / totalTransactions = {}", txPipeline.getReceivedStageQueue().size(), txPipeline.getBroadcastStageQueue().size(), txRequester.numberOfTransactionsToRequest() + txRequester.numberOfRecentlyRequestedTransactions(), txPipeline.getReplyStageQueue().size(), TransactionViewModel.getNumberOfStoredTransactions(tangle)); } } catch (final Exception e) { log.error("Tips Requester Thread Exception:", e); } } /** * Shut downs the {@link TipsRequesterImpl}. */ public void shutdown() { executorService.shutdownNow(); } }
4,488
41.349057
146
java
iri
iri-master/src/main/java/com/iota/iri/network/neighbor/Neighbor.java
package com.iota.iri.network.neighbor; import com.iota.iri.network.protocol.Handshake; import com.iota.iri.network.protocol.Heartbeat; import java.io.IOException; import java.nio.ByteBuffer; /** * A {@link Neighbor} is a peer to/from which messages are sent/read from. */ public interface Neighbor { /** * Defines not knowing yet what server socket port a neighbor is using. */ int UNKNOWN_REMOTE_SERVER_SOCKET_PORT = -1; /** * Instructs the {@link Neighbor} to read from its source channel. * * @return the amount of bytes read * @throws IOException thrown when reading from the source channel fails */ int read() throws IOException; /** * Instructs the {@link Neighbor} to write to its destination channel. * * @return the amount of bytes written * @throws IOException thrown when writing to the destination channel fails */ int write() throws IOException; /** * Instructs the {@link Neighbor} to read from its source channel a {@link Handshake} packet. * * @return the {@link Handshake} object defining the state of the handshaking * @throws IOException thrown when reading from the source channels fails */ Handshake handshake() throws IOException; /** * Instructs the {@link Neighbor} to read from its source channel a {@link Heartbeat} packet. * @return The {@link Heartbeat} object * @throws IOException thrown when reading from the source channels fails */ Heartbeat heartbeat() throws IOException; /** * Instructs the {@link Neighbor} to send the given {@link ByteBuffer} to its destination channel. * * @param buf the {@link ByteBuffer} containing the message to send */ void send(ByteBuffer buf); /** * Gets the host address. * * @return the host address of the neighbor (always the IP address, never a domain name) */ String getHostAddress(); /** * Sets the domain name. * * @param domain the domain to set */ void setDomain(String domain); /** * Gets the domain name or if not available, the IP address. * * @return the domain name or IP address */ String getDomain(); /** * Gets the server socket port. * * @return the server socket port */ int getRemoteServerSocketPort(); /** * Sets the server socket port. * * @param port the port number to set */ void setRemoteServerSocketPort(int port); /** * Gets the host and port which also defines the identity of the {@link Neighbor}. * * @return the host and port */ String getHostAddressAndPort(); /** * Gets the current state of the {@link Neighbor}. * * @return the state */ NeighborState getState(); /** * Sets the state of the {@link Neighbor}. * * @param state */ void setState(NeighborState state); /** * Gets the metrics of the {@link Neighbor}. * * @return the metrics */ NeighborMetrics getMetrics(); /** * Sets the protocol version to use to communicate with this {@link Neighbor}. * * @param version the protocol version to use */ void setProtocolVersion(int version); /** * The protocol version used to communicate with the {@link Neighbor}. * * @return the protocol version */ int getProtocolVersion(); /** * Checks if we have data (transactions) to send to the neighbor * * @return {@code true} if we have data to send, else returns {@code false} */ boolean hasDataToSendTo(); }
3,700
25.06338
102
java
iri
iri-master/src/main/java/com/iota/iri/network/neighbor/NeighborMetrics.java
package com.iota.iri.network.neighbor; /** * Defines the metrics of a {@link Neighbor}. */ public interface NeighborMetrics { /** * Returns the number of all transactions. * * @return the number of all transactions */ long getAllTransactionsCount(); /** * Increments the all transactions count. * * @return the number of all transactions */ long incrAllTransactionsCount(); /** * Gets the number of invalid transctions. * * @return the number of invalid transactions */ long getInvalidTransactionsCount(); /** * Increments the invalid transaction count. * * @return the number of invalid transactions */ long incrInvalidTransactionsCount(); /** * Gets the number of stale transactions. * * @return the number of stale transactions */ long getStaleTransactionsCount(); /** * Increments the number of stale transactions. * * @return the number of stale transactions */ long incrStaleTransactionsCount(); /** * Gets the number of new transactions. * * @return the number of new transactions */ long getNewTransactionsCount(); /** * Increments the new transactions count. * * @return the number of new transactions */ long incrNewTransactionsCount(); /** * Gets the number of random transactions. * * @return the number of random transactions */ long getRandomTransactionRequestsCount(); /** * Increments the random transactions count. * * @return the number of random transactions */ long incrRandomTransactionRequestsCount(); /** * Gets the number of send transactions. * * @return the number of send transactions */ long getSentTransactionsCount(); /** * Increments the send transactions count. * * @return the number of send transactions */ long incrSentTransactionsCount(); /** * Gets the number of packets dropped from the neighbor's send queue. * * @return the number of packets dropped from the neighbor's send queue */ long getDroppedSendPacketsCount(); /** * Increments the number of packets dropped from the neighbor's send queue. * * @return the number of packets dropped from the neighbor's send queue */ long incrDroppedSendPacketsCount(); }
2,473
22.339623
79
java
iri
iri-master/src/main/java/com/iota/iri/network/neighbor/NeighborState.java
package com.iota.iri.network.neighbor; /** * Defines the different states a {@link Neighbor} can be in. */ public enum NeighborState { HANDSHAKING, READY_FOR_MESSAGES, MARKED_FOR_DISCONNECT, }
208
18
61
java
iri
iri-master/src/main/java/com/iota/iri/network/neighbor/impl/NeighborImpl.java
package com.iota.iri.network.neighbor.impl; import com.iota.iri.network.neighbor.Neighbor; import com.iota.iri.network.neighbor.NeighborMetrics; import com.iota.iri.network.neighbor.NeighborState; import com.iota.iri.network.pipeline.TransactionProcessingPipeline; import com.iota.iri.network.protocol.*; import com.iota.iri.network.protocol.message.MessageReader; import com.iota.iri.network.protocol.message.MessageReaderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * {@link NeighborImpl} is an implementation of {@link Neighbor} using a {@link ByteChannel} as the source and * destination of data. * * @param <T> */ public class NeighborImpl<T extends SelectableChannel & ByteChannel> implements Neighbor { private static final Logger log = LoggerFactory.getLogger(NeighborImpl.class); /** * The current state whether the neighbor is parsing a header or reading a message. */ private enum ReadState { PARSE_HEADER, HANDLE_MESSAGE } // next stage in the processing of incoming data private TransactionProcessingPipeline txPipeline; // data to be written out to the neighbor private BlockingQueue<ByteBuffer> sendQueue = new ArrayBlockingQueue<>(100); private ByteBuffer currentToWrite; private NeighborState state = NeighborState.HANDSHAKING; private ReadState readState = ReadState.PARSE_HEADER; // ident private String domain; private String hostAddress; private int remoteServerSocketPort; private int protocolVersion; // we need the reference to the channel in order to register it for // write interests once messages to send are available. private T channel; private Selector selector; private NeighborMetrics metrics = new NeighborMetricsImpl(); private MessageReader msgReader; private Handshake handshake = new Handshake(); private Heartbeat heartbeat = new Heartbeat(); /** * Creates a new {@link NeighborImpl} using the given channel. * * @param selector the {@link Selector} which is associated with passed in channel * @param channel the channel to use to read and write bytes from/to. * @param hostAddress the host address (IP address) of the neighbor * @param remoteServerSocketPort the server socket port of the neighbor * @param txPipeline the transaction processing pipeline to submit newly received transactions to */ public NeighborImpl(Selector selector, T channel, String hostAddress, int remoteServerSocketPort, TransactionProcessingPipeline txPipeline) { this.hostAddress = hostAddress; this.remoteServerSocketPort = remoteServerSocketPort; this.selector = selector; this.channel = channel; this.txPipeline = txPipeline; this.msgReader = MessageReaderFactory.create(ProtocolMessage.HEADER, ProtocolMessage.HEADER.getMaxLength()); } @Override public Handshake handshake() throws IOException { if (read() == -1) { handshake.setState(Handshake.State.FAILED); } return handshake; } @Override public Heartbeat heartbeat() throws IOException { read(); return heartbeat; } @Override public int read() throws IOException { int bytesRead = msgReader.readMessage(channel); if (!msgReader.ready()) { return bytesRead; } ByteBuffer msg = msgReader.getMessage(); msg.flip(); switch (readState) { case PARSE_HEADER: if (!parseHeader(msg)) { return -1; } // execute another read as we likely already have the message in the network buffer return read(); case HANDLE_MESSAGE: handleMessage(msg); break; default: // do nothing } return bytesRead; } /** * Parses the header in the given {@link ByteBuffer} and sets up the message reader to read the bytes for a message * of the advertised type/size. * * @param msg the {@link ByteBuffer} containing the header * @return whether the parsing was successful or not */ private boolean parseHeader(ByteBuffer msg) { ProtocolHeader protocolHeader; try { protocolHeader = Protocol.parseHeader(msg); } catch (UnknownMessageTypeException e) { log.error("unknown message type received from {}, closing connection", getHostAddressAndPort()); return false; } catch (InvalidProtocolMessageLengthException e) { log.error("{} is trying to send a message with an invalid length for the given message type, " + "closing connection", getHostAddressAndPort()); return false; } // if we are handshaking, then we must have a handshaking packet as the initial packet if (state == NeighborState.HANDSHAKING && protocolHeader.getMessageType() != ProtocolMessage.HANDSHAKE) { log.error("neighbor {}'s initial packet is not a handshaking packet, closing connection", getHostAddressAndPort()); return false; } // we got the header, now we want to read/handle the message readState = ReadState.HANDLE_MESSAGE; msgReader = MessageReaderFactory.create(protocolHeader.getMessageType(), protocolHeader.getMessageLength()); return true; } /** * Relays the message to the component in charge of handling this message. * * @param msg the {@link ByteBuffer} containing the message (without header) */ private void handleMessage(ByteBuffer msg) { switch (msgReader.getMessageType()) { case HANDSHAKE: handshake = Handshake.fromByteBuffer(msg); break; case TRANSACTION_GOSSIP: txPipeline.process(this, msg); break; case HEARTBEAT: heartbeat = Heartbeat.fromByteBuffer(msg); break; default: // do nothing } // reset readState = ReadState.PARSE_HEADER; msgReader = MessageReaderFactory.create(ProtocolMessage.HEADER, ProtocolMessage.HEADER.getMaxLength()); } @Override public int write() throws IOException { // previous message wasn't fully sent yet if (currentToWrite != null) { return writeMsg(); } currentToWrite = sendQueue.poll(); if (currentToWrite == null) { return 0; } return writeMsg(); } private int writeMsg() throws IOException { int written = channel.write(currentToWrite); if (!currentToWrite.hasRemaining()) { currentToWrite = null; } return written; } @Override public void send(ByteBuffer buf) { // first fill sendQueue to signal other threads that we have something ready to write if (!sendQueue.offer(buf)) { metrics.incrDroppedSendPacketsCount(); } // re-register write interest SelectionKey key = channel.keyFor(selector); if (key != null) { synchronized (key) { if (key.isValid() && (key.interestOps() & SelectionKey.OP_WRITE) == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); selector.wakeup(); } } } } @Override public String getHostAddressAndPort() { if (remoteServerSocketPort == Neighbor.UNKNOWN_REMOTE_SERVER_SOCKET_PORT) { return hostAddress; } return String.format("%s:%d", hostAddress, remoteServerSocketPort); } @Override public String getHostAddress() { return hostAddress; } @Override public void setDomain(String domain) { this.domain = domain; } @Override public String getDomain() { return domain; } @Override public int getRemoteServerSocketPort() { return remoteServerSocketPort; } @Override public void setRemoteServerSocketPort(int port) { remoteServerSocketPort = port; } @Override public NeighborState getState() { return state; } @Override public void setState(NeighborState state) { if (this.state == NeighborState.MARKED_FOR_DISCONNECT) { return; } this.state = state; } @Override public NeighborMetrics getMetrics() { return metrics; } @Override public void setProtocolVersion(int protocolVersion) { this.protocolVersion = protocolVersion; } @Override public int getProtocolVersion() { return protocolVersion; } @Override public boolean hasDataToSendTo() { return currentToWrite != null || !sendQueue.isEmpty(); } }
9,277
31.554386
119
java
iri
iri-master/src/main/java/com/iota/iri/network/neighbor/impl/NeighborMetricsImpl.java
package com.iota.iri.network.neighbor.impl; import com.iota.iri.network.neighbor.NeighborMetrics; import java.util.concurrent.atomic.AtomicLong; /** * Implements {@link NeighborMetrics} using {@link AtomicLong}s. */ public class NeighborMetricsImpl implements NeighborMetrics { private AtomicLong allTxsCount = new AtomicLong(); private AtomicLong invalidTxsCount = new AtomicLong(); private AtomicLong staleTxsCount = new AtomicLong(); private AtomicLong randomTxsCount = new AtomicLong(); private AtomicLong sentTxsCount = new AtomicLong(); private AtomicLong newTxsCount = new AtomicLong(); private AtomicLong droppedSendPacketsCount = new AtomicLong(); @Override public long getAllTransactionsCount() { return allTxsCount.get(); } @Override public long incrAllTransactionsCount() { return allTxsCount.incrementAndGet(); } @Override public long getInvalidTransactionsCount() { return invalidTxsCount.get(); } @Override public long incrInvalidTransactionsCount() { return invalidTxsCount.incrementAndGet(); } @Override public long getStaleTransactionsCount() { return staleTxsCount.get(); } @Override public long incrStaleTransactionsCount() { return staleTxsCount.incrementAndGet(); } @Override public long getNewTransactionsCount() { return newTxsCount.get(); } @Override public long incrNewTransactionsCount() { return newTxsCount.incrementAndGet(); } @Override public long getRandomTransactionRequestsCount() { return randomTxsCount.get(); } @Override public long incrRandomTransactionRequestsCount() { return randomTxsCount.incrementAndGet(); } @Override public long getSentTransactionsCount() { return sentTxsCount.get(); } @Override public long incrSentTransactionsCount() { return sentTxsCount.incrementAndGet(); } @Override public long getDroppedSendPacketsCount() { return droppedSendPacketsCount.get(); } @Override public long incrDroppedSendPacketsCount() { return droppedSendPacketsCount.incrementAndGet(); } }
2,254
24.055556
66
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/BroadcastPayload.java
package com.iota.iri.network.pipeline; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.network.neighbor.Neighbor; /** * Defines a payload which gets submitted to the {@link BroadcastStage}. */ public class BroadcastPayload extends Payload { private Neighbor originNeighbor; private TransactionViewModel tvm; /** * Creates a new {@link BroadcastPayload} with the given neighbor and transaction. * * @param originNeighbor The neighbor from which the transaction originated from * @param tvm The transaction */ public BroadcastPayload(Neighbor originNeighbor, TransactionViewModel tvm) { this.originNeighbor = originNeighbor; this.tvm = tvm; } /** * Gets the origin neighbor. * * @return the origin neighbor */ public Neighbor getOriginNeighbor() { return originNeighbor; } /** * Gets the transaction * * @return the transaction */ public TransactionViewModel getTransactionViewModel() { return tvm; } @Override public String toString() { return "BroadcastPayload{" + "originNeighbor=" + originNeighbor.getHostAddressAndPort() + ", tvm=" + tvm.getHash() + '}'; } }
1,288
25.306122
106
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/BroadcastStage.java
package com.iota.iri.network.pipeline; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.network.NeighborRouter; import com.iota.iri.network.neighbor.Neighbor; import com.iota.iri.service.milestone.InSyncService; import com.iota.iri.service.validation.TransactionSolidifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * The {@link BroadcastStage} takes care of broadcasting newly received transactions to all neighbors except the * neighbor from which the transaction originated from. */ public class BroadcastStage implements Stage { private static final Logger log = LoggerFactory.getLogger(BroadcastStage.class); private NeighborRouter neighborRouter; private TransactionSolidifier transactionSolidifier; /** * Service used to determine if we send back tx to the original neighbour */ private InSyncService inSyncService; /** * Creates a new {@link BroadcastStage}. * * @param neighborRouter The {@link NeighborRouter} instance to use to broadcast */ public BroadcastStage(NeighborRouter neighborRouter, TransactionSolidifier transactionSolidifier, InSyncService inSyncService) { this.neighborRouter = neighborRouter; this.transactionSolidifier = transactionSolidifier; this.inSyncService = inSyncService; } /** * Extracts the transaction and then broadcasts it to all neighbors. If the transaction originated from a neighbor, * it is not sent to that given neighbor. * * @param ctx the broadcast stage {@link ProcessingContext} * @return the same ctx as passed in */ @Override public ProcessingContext process(ProcessingContext ctx) { BroadcastPayload payload = (BroadcastPayload) ctx.getPayload(); Neighbor originNeighbor = payload.getOriginNeighbor(); TransactionViewModel tvm = payload.getTransactionViewModel(); // racy Map<String, Neighbor> currentlyConnectedNeighbors = neighborRouter.getConnectedNeighbors(); for (Neighbor neighbor : currentlyConnectedNeighbors.values()) { // don't send back to origin neighbor, unless we are not in sync yet // Required after PR: #1745 which removes ping pong behaviour if (neighbor.equals(originNeighbor) && inSyncService.isInSync()) { continue; } try { neighborRouter.gossipTransactionTo(neighbor, tvm); } catch (Exception e) { log.error(e.getMessage()); } } // Check the transaction solidifier to see if there are solid transactions that need to be broadcast. // If so, forward them to the BroadcastStageQueue to be processed. TransactionViewModel transactionToBroadcast; if((transactionToBroadcast = transactionSolidifier.getNextTxInBroadcastQueue()) != null){ ctx.setNextStage(TransactionProcessingPipeline.Stage.BROADCAST); ctx.setPayload(new BroadcastPayload(payload.getOriginNeighbor(), transactionToBroadcast)); return ctx; } ctx.setNextStage(TransactionProcessingPipeline.Stage.FINISH); return ctx; } }
3,268
37.916667
132
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/HashingPayload.java
package com.iota.iri.network.pipeline; import com.iota.iri.crypto.batched.HashRequest; import com.iota.iri.model.Hash; import com.iota.iri.network.neighbor.Neighbor; /** * Defines a payload which gets submitted to the {@link HashingStage}. */ public class HashingPayload extends ValidationPayload { private HashRequest hashRequest; /** * Creates a new {@link HashingPayload}. * * @param neighbor The neighbor from which the transaction originated from * @param txTrits The transaction trits * @param txDigest The transaction bytes digest * @param hashOfRequestedTx The hash of the requested transaction */ public HashingPayload(Neighbor neighbor, byte[] txTrits, Long txDigest, Hash hashOfRequestedTx) { super(neighbor, txTrits, null, txDigest, hashOfRequestedTx); } /** * Gets the {@link HashRequest}. * * @return the {@link HashRequest} */ public HashRequest getHashRequest() { return hashRequest; } /** * Sets the {@link HashRequest}. * * @param hashRequest the {@link HashRequest} to set */ public void setHashRequest(HashRequest hashRequest) { this.hashRequest = hashRequest; } }
1,262
27.704545
101
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/HashingStage.java
package com.iota.iri.network.pipeline; import com.iota.iri.crypto.batched.BatchedHasher; import com.iota.iri.crypto.batched.HashRequest; /** * The {@link HashingStage} batches up transaction trits and then hashes them using a {@link BatchedHasher} in one go. */ public class HashingStage implements Stage { private BatchedHasher batchedHasher; /** * Creates a new {@link HashingStage}. * * @param batchedHasher The {@link BatchedHasher} to use */ public HashingStage(BatchedHasher batchedHasher) { this.batchedHasher = batchedHasher; } /** * Extracts the {@link HashRequest} from the context and submits it to the {@link BatchedHasher}. The * {@link com.iota.iri.crypto.batched.HashRequest}'s callback must be setup to submit the result to the * {@link ValidationStage}. * * @param ctx the hashing stage {@link ProcessingContext} * @return the same ctx as passed in */ @Override public ProcessingContext process(ProcessingContext ctx) { HashingPayload payload = (HashingPayload) ctx.getPayload(); batchedHasher.submitHashingRequest(payload.getHashRequest()); return ctx; } }
1,202
31.513514
118
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/MilestonePayload.java
package com.iota.iri.network.pipeline; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.network.neighbor.Neighbor; /** * A payload object for processing milestone candidates */ public class MilestonePayload extends Payload { /** * Origin neighbor for transaction */ private Neighbor originNeighbor; /** * {@link TransactionViewModel} of potential milestone object */ private TransactionViewModel milestoneTransaction; /** * Index of potential milestone object */ private int milestoneIndex; /** * Constructor for a {@link MilestonePayload} object that will be processed by the {@link MilestoneStage}. * * @param originNeighbor Neighbor that milestone candidate originated from * @param milestoneTransaction {@link TransactionViewModel} of the milestone candidate * @param milestoneIndex Index of the milestone candidate */ public MilestonePayload(Neighbor originNeighbor, TransactionViewModel milestoneTransaction, int milestoneIndex){ this.originNeighbor = originNeighbor; this.milestoneTransaction = milestoneTransaction; this.milestoneIndex = milestoneIndex; } @Override public Neighbor getOriginNeighbor() { return originNeighbor; } /** * @return {@link #milestoneTransaction} */ public TransactionViewModel getMilestoneTransaction(){ return this.milestoneTransaction; } /** * @return {@link #milestoneIndex} */ public int getMilestoneIndex(){ return this.milestoneIndex; } }
1,631
27.631579
116
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/MilestoneStage.java
package com.iota.iri.network.pipeline; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.service.milestone.MilestoneSolidifier; import com.iota.iri.service.snapshot.SnapshotProvider; import com.iota.iri.service.validation.TransactionSolidifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Stage for processing {@link MilestonePayload} objects */ public class MilestoneStage implements Stage { private static final Logger log = LoggerFactory.getLogger(MilestoneStage.class); private MilestoneSolidifier milestoneSolidifier; private SnapshotProvider snapshotProvider; private TransactionSolidifier transactionSolidifier; /** * Constructor for {@link MilestoneStage}. This stage will process {@link MilestonePayload} candidate objects using * the {@link MilestoneSolidifier} to determine the latest milestone, the latest solid milestone, and place unsolid * milestone candidates into a queue for solidification. The stage will always try to solidify the oldest milestone * candidate in the queue. * * @param milestoneSolidifier Solidification service for processing milestone objects * @param snapshotProvider Snapshot provider service for latest snapshot references * @param transactionSolidifier A service for solidifying transactions * @param milestoneSolidifier Tracks the latest milestone object */ public MilestoneStage(MilestoneSolidifier milestoneSolidifier, SnapshotProvider snapshotProvider, TransactionSolidifier transactionSolidifier) { this.milestoneSolidifier = milestoneSolidifier; this.snapshotProvider = snapshotProvider; this.transactionSolidifier = transactionSolidifier; } /** * Process {@link MilestonePayload} objects. While processing the {@link MilestoneStage} will determine the latest * milestone and log it. If the milestone object passes a validity check, it is added to the seenMilestones queue in * the {@link MilestoneSolidifier}, whereas if it is invalid, the transaction is ignored. The milestone is then * checked for solidity using the {@link TransactionSolidifier}. If the transaction is solid it is passed forward to * the {@link TransactionSolidifier} propagation queue. * * @param ctx the context to process * @return Either an abort or solidify stage ctx */ @Override public ProcessingContext process(ProcessingContext ctx) { try { MilestonePayload payload = (MilestonePayload) ctx.getPayload(); //If the milestone index is below the latest snapshot initial index, then abort the process //Exempts index 0, as milestone objects don't require both transactions to hold the index if (payload.getMilestoneIndex() < snapshotProvider.getLatestSnapshot().getInitialIndex() && payload.getMilestoneIndex() != 0) { return abort(ctx); } TransactionViewModel milestone = payload.getMilestoneTransaction(); int newMilestoneIndex = payload.getMilestoneIndex(); boolean isTail = milestone.getCurrentIndex() == 0; if (isTail) { milestoneSolidifier.addMilestoneCandidate(milestone.getHash(), newMilestoneIndex); } if (milestone.isSolid()) { transactionSolidifier.addToPropagationQueue(milestone.getHash()); } return solidify(ctx, payload, milestone); } catch (Exception e) { log.error("Error processing milestone: ", e); return abort(ctx); } } private ProcessingContext solidify(ProcessingContext ctx, Payload payload, TransactionViewModel tvm) { SolidifyPayload solidifyPayload = new SolidifyPayload(payload.getOriginNeighbor(), tvm); ctx.setNextStage(TransactionProcessingPipeline.Stage.SOLIDIFY); ctx.setPayload(solidifyPayload); return ctx; } private ProcessingContext abort(ProcessingContext ctx) { ctx.setNextStage(TransactionProcessingPipeline.Stage.ABORT); return ctx; } }
4,208
43.305263
120
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/MultiStagePayload.java
package com.iota.iri.network.pipeline; import com.iota.iri.network.neighbor.Neighbor; /** * A payload which contains processing contexts for two stages. */ public class MultiStagePayload extends Payload { private ProcessingContext left; private ProcessingContext right; /** * Creates a new {@link MultiStagePayload} with the given left and right assigned contexts. * * @param left the left assigned context * @param right the right assigned context */ public MultiStagePayload(ProcessingContext left, ProcessingContext right) { this.left = left; this.right = right; } /** * Returns the left assigned context. * * @return the left assigned context */ public ProcessingContext getLeft() { return left; } /** * Returns the right assigned context. * * @return the right assigned context */ public ProcessingContext getRight() { return right; } @Override public Neighbor getOriginNeighbor() { return left.getPayload().getOriginNeighbor(); } @Override public String toString() { return "MultiStagePayload{" + "left=" + left.getPayload().toString() + ", right=" + right.getPayload().toString() + '}'; } }
1,308
23.698113
95
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/Payload.java
package com.iota.iri.network.pipeline; import com.iota.iri.network.neighbor.Neighbor; /** * Defines a payload which is given to a {@link ProcessingContext} for processing within a {@link Stage}. */ public abstract class Payload { /** * Gets the origin neighbor from which a given transaction originated from. * Can be null if the transaction did not originate from a neighbor. * * @return the origin neighbor */ public abstract Neighbor getOriginNeighbor(); }
498
26.722222
105
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/PreProcessPayload.java
package com.iota.iri.network.pipeline; import com.iota.iri.network.neighbor.Neighbor; import java.nio.ByteBuffer; /** * Defines the payload which gets submitted to the {@link PreProcessStage}. */ public class PreProcessPayload extends Payload { private Neighbor neighbor; private ByteBuffer data; /** * Creates a new {@link PreProcessPayload}. * * @param neighbor The origin neighbor * @param data The gossip transaction data */ public PreProcessPayload(Neighbor neighbor, ByteBuffer data) { this.neighbor = neighbor; this.data = data; } /** * {@inheritDoc} */ public Neighbor getOriginNeighbor() { return neighbor; } /** * Sets the {@link Neighbor} * * @param neighbor the {@link Neighbor} */ public void setNeighbor(Neighbor neighbor) { this.neighbor = neighbor; } /** * Gets the transaction gossip data. * * @return the transaction gossip data */ public ByteBuffer getData() { return data; } @Override public String toString() { return "PreProcessPayload{" + "neighbor=" + neighbor.getHostAddressAndPort() + '}'; } }
1,229
20.964286
91
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/PreProcessStage.java
package com.iota.iri.network.pipeline; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import com.iota.iri.model.HashFactory; import com.iota.iri.network.FIFOCache; import com.iota.iri.network.TransactionCacheDigester; import com.iota.iri.network.protocol.Protocol; import com.iota.iri.network.protocol.ProtocolMessage; import com.iota.iri.utils.Converter; import com.iota.iri.utils.TransactionTruncator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; /** * The {@link PreProcessStage} expands truncated transaction gossip payloads, computes the digest of the payload and * converts the transaction to its trits representation. */ public class PreProcessStage implements Stage { private static final Logger log = LoggerFactory.getLogger(PreProcessStage.class); private FIFOCache<Long, Hash> recentlySeenBytesCache; /** * Creates a new {@link PreProcessStage}. * * @param recentlySeenBytesCache The cache to use for checking whether a transaction is known */ public PreProcessStage(FIFOCache<Long, Hash> recentlySeenBytesCache) { this.recentlySeenBytesCache = recentlySeenBytesCache; } /** * Extracts the transaction gossip payload, expands it, computes the digest and then creates a new * {@link ProcessingContext} to the appropriate stage. If the transaction is not known, the transaction payload is * also converted to its trits representation. * * @param ctx the pre process stage {@link ProcessingContext} * @return a {@link ProcessingContext} which either redirects to the {@link ReplyStage} or {@link HashingStage} * depending on whether the transaction is known */ @Override public ProcessingContext process(ProcessingContext ctx) { PreProcessPayload payload = (PreProcessPayload) ctx.getPayload(); ByteBuffer packetData = payload.getData(); byte[] data = packetData.array(); // expand received tx data byte[] txDataBytes = TransactionTruncator.expandTransaction(data, ProtocolMessage.TRANSACTION_GOSSIP.getMaxLength()); // copy requested tx hash byte[] reqHashBytes = Protocol.extractRequestedTxHash(data); // increment all txs count payload.getOriginNeighbor().getMetrics().incrAllTransactionsCount(); // compute digest of tx bytes data long txDigest = TransactionCacheDigester.getDigest(txDataBytes); Hash receivedTxHash = recentlySeenBytesCache.get(txDigest); Hash requestedHash = HashFactory.TRANSACTION.create(reqHashBytes, 0, Protocol.GOSSIP_REQUESTED_TX_HASH_BYTES_LENGTH); // log cache hit/miss ratio every 50k get()s if (log.isDebugEnabled()) { long hits = recentlySeenBytesCache.getCacheHits(); long misses = recentlySeenBytesCache.getCacheMisses(); if ((hits + misses) % 50000L == 0) { log.debug("recently seen bytes cache hit/miss ratio: {}/{}", hits, misses); recentlySeenBytesCache.resetCacheStats(); } } // received tx is known, therefore we can submit to the reply stage directly. if (receivedTxHash != null) { // reply with a random tip by setting the request hash to the null hash requestedHash = requestedHash.equals(receivedTxHash) ? Hash.NULL_HASH : requestedHash; ctx.setNextStage(TransactionProcessingPipeline.Stage.REPLY); ctx.setPayload(new ReplyPayload(payload.getOriginNeighbor(), requestedHash)); return ctx; } // convert tx byte data into trits representation once byte[] txTrits = new byte[TransactionViewModel.TRINARY_SIZE]; Converter.getTrits(txDataBytes, txTrits); // submit to hashing stage. ctx.setNextStage(TransactionProcessingPipeline.Stage.HASHING); HashingPayload hashingStagePayload = new HashingPayload(payload.getOriginNeighbor(), txTrits, txDigest, requestedHash); ctx.setPayload(hashingStagePayload); return ctx; } }
4,164
42.385417
125
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/ProcessingContext.java
package com.iota.iri.network.pipeline; /** * A {@link ProcessingContext} defines a context within the {@link TransactionProcessingPipelineImpl} of processing a * transaction. It holds the information to which stage to be submitted next and the associated payload. */ public class ProcessingContext { private TransactionProcessingPipelineImpl.Stage nextStage; private Payload payload; /** * Creates a new {@link ProcessingContext}. * * @param payload The payload */ public ProcessingContext(Payload payload) { this.payload = payload; } /** * Creates a new {@link ProcessingContext}. * * @param nextStage The next stage * @param payload The payload for the next stage */ public ProcessingContext(TransactionProcessingPipelineImpl.Stage nextStage, Payload payload) { this.nextStage = nextStage; this.payload = payload; } /** * Gets the payload. * * @return the payload */ public Payload getPayload() { return payload; } /** * Sets the payload. * * @param payload the payload to set */ public void setPayload(Payload payload) { this.payload = payload; } /** * Gets the next stage. * * @return the next stage to submit this {@link ProcessingContext} to */ public TransactionProcessingPipelineImpl.Stage getNextStage() { return nextStage; } /** * Sets the next stage. * * @param nextStage the stage to set as the next stage */ public void setNextStage(TransactionProcessingPipelineImpl.Stage nextStage) { this.nextStage = nextStage; } }
1,711
24.176471
117
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/ReceivedPayload.java
package com.iota.iri.network.pipeline; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.network.neighbor.Neighbor; /** * Defines a payload which gets submitted to the {@link ReceivedStage}. */ public class ReceivedPayload extends Payload { private Neighbor neighbor; private TransactionViewModel tvm; /** * Creates a new {@link ReceivedPayload}. * * @param neighbor the {@link Neighbor} from which the transaction originated from (can be null) * @param tvm the transaction */ public ReceivedPayload(Neighbor neighbor, TransactionViewModel tvm) { this.neighbor = neighbor; this.tvm = tvm; } /** * {@inheritDoc} */ public Neighbor getOriginNeighbor() { return neighbor; } /** * Gets the transaction. * * @return the transaction */ public TransactionViewModel getTransactionViewModel() { return tvm; } @Override public String toString() { return "ReceivedPayload{" + "neighbor=" + neighbor.getHostAddressAndPort() + ", tvm=" + tvm.getHash() + '}'; } }
1,141
23.826087
116
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/ReceivedStage.java
package com.iota.iri.network.pipeline; import com.iota.iri.model.Hash; import com.iota.iri.service.milestone.MilestoneService; import com.iota.iri.service.validation.TransactionSolidifier; import com.iota.iri.service.validation.TransactionValidator; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.network.TransactionRequester; import com.iota.iri.network.neighbor.Neighbor; import com.iota.iri.service.snapshot.SnapshotProvider; import com.iota.iri.storage.Tangle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link ReceivedStage} stores the given transaction in the database, updates the arrival time and sender and then * submits to the {@link BroadcastStage}. */ public class ReceivedStage implements Stage { private static final Logger log = LoggerFactory.getLogger(ReceivedStage.class); private Tangle tangle; private TransactionRequester transactionRequester; private TransactionSolidifier txSolidifier; private SnapshotProvider snapshotProvider; private MilestoneService milestoneService; private Hash cooAddress; /** * Creates a new {@link ReceivedStage}. * * @param tangle The {@link Tangle} database used to store/update the transaction * @param txSolidifier The {@link TransactionSolidifier} used to store/update the transaction * @param snapshotProvider The {@link SnapshotProvider} used to store/update the transaction */ public ReceivedStage(Tangle tangle, TransactionSolidifier txSolidifier, SnapshotProvider snapshotProvider, TransactionRequester transactionRequester, MilestoneService milestoneService, Hash cooAddress) { this.txSolidifier = txSolidifier; this.tangle = tangle; this.snapshotProvider = snapshotProvider; this.transactionRequester = transactionRequester; this.milestoneService = milestoneService; this.cooAddress = cooAddress; } /** * Stores the given transaction in the database, updates it status * ({@link TransactionSolidifier#updateStatus(TransactionViewModel)}) and updates the sender. * * @param ctx the received stage {@link ProcessingContext} * @return a {@link ProcessingContext} which redirects to the {@link BroadcastStage} */ @Override public ProcessingContext process(ProcessingContext ctx) { ReceivedPayload payload = (ReceivedPayload) ctx.getPayload(); Neighbor originNeighbor = payload.getOriginNeighbor(); TransactionViewModel tvm = payload.getTransactionViewModel(); boolean stored; try { stored = tvm.store(tangle, snapshotProvider.getInitialSnapshot()); } catch (Exception e) { log.error("error persisting newly received tx", e); if (originNeighbor != null) { originNeighbor.getMetrics().incrInvalidTransactionsCount(); } ctx.setNextStage(TransactionProcessingPipeline.Stage.ABORT); return ctx; } if (stored) { tvm.setArrivalTime(System.currentTimeMillis()); try { txSolidifier.updateStatus(tvm); // free up the recently requested transaction set if(transactionRequester.removeRecentlyRequestedTransaction(tvm.getHash())){ // as the transaction came from the request queue, we can add its branch and trunk to the request // queue already, as we only have transactions in the request queue which are needed for solidifying // milestones. this speeds up solidification significantly transactionRequester.requestTrunkAndBranch(tvm); } // neighbor might be null because tx came from a broadcastTransaction command if (originNeighbor != null) { tvm.updateSender(originNeighbor.getHostAddressAndPort()); } tvm.update(tangle, snapshotProvider.getInitialSnapshot(), "arrivalTime|sender"); } catch (Exception e) { log.error("error updating newly received tx", e); } if (originNeighbor != null) { originNeighbor.getMetrics().incrNewTransactionsCount(); } }else{ transactionRequester.removeRecentlyRequestedTransaction(tvm.getHash()); } try{ if(tvm.getAddressHash().equals(cooAddress)) { int milestoneIndex = milestoneService.getMilestoneIndex(tvm); MilestonePayload milestonePayload = new MilestonePayload(payload.getOriginNeighbor(), tvm, milestoneIndex); ctx.setNextStage(TransactionProcessingPipeline.Stage.MILESTONE); ctx.setPayload(milestonePayload); return ctx; } } catch(Exception e){ log.error("Error checking apparent milestone transaction", e); } // broadcast the newly saved tx to the other neighbors ctx.setNextStage(TransactionProcessingPipeline.Stage.SOLIDIFY); ctx.setPayload(new SolidifyPayload(originNeighbor, tvm)); return ctx; } }
5,303
43.571429
120
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/ReplyPayload.java
package com.iota.iri.network.pipeline; import com.iota.iri.model.Hash; import com.iota.iri.network.neighbor.Neighbor; /** * Defines a payload which gets submitted to the {@link ReplyStage}. */ public class ReplyPayload extends Payload { private Neighbor neighbor; private Hash hashOfRequestedTx; /** * Creates a new {@link ReplyStage}. * * @param neighbor the neighbor from which the request came from * @param hashOfRequestedTx the hash of the requested transaction */ public ReplyPayload(Neighbor neighbor, Hash hashOfRequestedTx) { this.neighbor = neighbor; this.hashOfRequestedTx = hashOfRequestedTx; } /** * {@inheritDoc} */ public Neighbor getOriginNeighbor() { return neighbor; } /** * Sets the {@link Neighbor}. * * @param neighbor the neighbor to set */ public void setNeighbor(Neighbor neighbor) { this.neighbor = neighbor; } /** * Gets the hash of the requested transaction. * * @return the hash of the requested transaction */ public Hash getHashOfRequestedTx() { return hashOfRequestedTx; } @Override public String toString() { return "ReplyPayload{" + "neighbor=" + neighbor.getHostAddressAndPort() + ", hashOfRequestedTx=" + hashOfRequestedTx.toString() + '}'; } }
1,409
24.178571
104
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/ReplyStage.java
package com.iota.iri.network.pipeline; import com.iota.iri.conf.NodeConfig; import com.iota.iri.controllers.TipsViewModel; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import com.iota.iri.model.HashFactory; import com.iota.iri.network.FIFOCache; import com.iota.iri.network.NeighborRouter; import com.iota.iri.network.TransactionCacheDigester; import com.iota.iri.network.neighbor.Neighbor; import com.iota.iri.network.protocol.Protocol; import com.iota.iri.service.milestone.MilestoneSolidifier; import com.iota.iri.service.snapshot.SnapshotProvider; import com.iota.iri.storage.Tangle; import java.security.SecureRandom; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link ReplyStage} replies to the neighbor which supplied the given hash of the requested transaction. If a * {@link Hash#NULL_HASH} is supplied, then a random tip is replied back to the neighbor. A neighbor indicates to * receive a random tip, when the requested transaction hash is the same as the transaction hash of the transaction in * the gossip payload. */ public class ReplyStage implements Stage { private static final Logger log = LoggerFactory.getLogger(ReplyStage.class); private NeighborRouter neighborRouter; private Tangle tangle; private NodeConfig config; private TipsViewModel tipsViewModel; private MilestoneSolidifier milestoneSolidifier; private SnapshotProvider snapshotProvider; private FIFOCache<Long, Hash> recentlySeenBytesCache; private SecureRandom rnd = new SecureRandom(); /** * Creates a new {@link ReplyStage}. * * @param neighborRouter the {@link NeighborRouter} to use to send the requested transaction * @param config the {@link NodeConfig} * @param tangle the {@link Tangle} database to load the request transaction from * @param tipsViewModel the {@link TipsViewModel} to load the random tips from * @param milestoneSolidifier the {@link MilestoneSolidifier} to load the latest milestone from * @param snapshotProvider the {@link SnapshotProvider} to check the latest solid milestone from * @param recentlySeenBytesCache the {@link FIFOCache} to use to cache the replied transaction * @param rnd the {@link SecureRandom} used to get random values to randomize chances for not * replying at all or not requesting a not stored requested transaction from neighbors */ public ReplyStage(NeighborRouter neighborRouter, NodeConfig config, Tangle tangle, TipsViewModel tipsViewModel, MilestoneSolidifier milestoneSolidifier, SnapshotProvider snapshotProvider, FIFOCache<Long, Hash> recentlySeenBytesCache, SecureRandom rnd) { this.neighborRouter = neighborRouter; this.config = config; this.tangle = tangle; this.tipsViewModel = tipsViewModel; this.milestoneSolidifier = milestoneSolidifier; this.snapshotProvider = snapshotProvider; this.recentlySeenBytesCache = recentlySeenBytesCache; this.rnd = rnd; } /** * Creates a new {@link ReplyStage}. * * @param neighborRouter the {@link NeighborRouter} to use to send the requested transaction * @param config the {@link NodeConfig} * @param tangle the {@link Tangle} database to load the request transaction from * @param tipsViewModel the {@link TipsViewModel} to load the random tips from * @param milestoneSolidifier the {@link MilestoneSolidifier} to load the latest milestone from * @param snapshotProvider the {@link SnapshotProvider} to check the latest solid milestone from * @param recentlySeenBytesCache the {@link FIFOCache} to use to cache the replied transaction */ public ReplyStage(NeighborRouter neighborRouter, NodeConfig config, Tangle tangle, TipsViewModel tipsViewModel, MilestoneSolidifier milestoneSolidifier, SnapshotProvider snapshotProvider, FIFOCache<Long, Hash> recentlySeenBytesCache) { this.neighborRouter = neighborRouter; this.config = config; this.tangle = tangle; this.tipsViewModel = tipsViewModel; this.milestoneSolidifier = milestoneSolidifier; this.snapshotProvider = snapshotProvider; this.recentlySeenBytesCache = recentlySeenBytesCache; } /** * Loads the requested transaction from the database and replies it back to the neighbor who requested it. If the * {@link Hash#NULL_HASH} is supplied, then a random tip is replied with. * * @param ctx the reply stage {@link ProcessingContext} * @return the same {@link ProcessingContext} as passed in */ @Override public ProcessingContext process(ProcessingContext ctx) { ReplyPayload payload = (ReplyPayload) ctx.getPayload(); Neighbor neighbor = payload.getOriginNeighbor(); Hash hashOfRequestedTx = payload.getHashOfRequestedTx(); TransactionViewModel tvm = null; if (hashOfRequestedTx.equals(Hash.NULL_HASH)) { try { // don't reply to random tip requests if we are synchronized with a max delta of one // to the newest milestone if (snapshotProvider.getLatestSnapshot().getIndex() >= milestoneSolidifier.getLatestMilestoneIndex() - 1) { ctx.setNextStage(TransactionProcessingPipeline.Stage.FINISH); return ctx; } // retrieve random tx neighbor.getMetrics().incrRandomTransactionRequestsCount(); Hash transactionPointer = getRandomTipPointer(); tvm = TransactionViewModel.fromHash(tangle, transactionPointer); } catch (Exception e) { log.error("error loading random tip for reply", e); ctx.setNextStage(TransactionProcessingPipeline.Stage.ABORT); return ctx; } } else { try { // retrieve requested tx tvm = TransactionViewModel.fromHash(tangle, HashFactory.TRANSACTION.create(hashOfRequestedTx.bytes(), 0, Protocol.GOSSIP_REQUESTED_TX_HASH_BYTES_LENGTH)); } catch (Exception e) { log.error("error while searching for explicitly asked for tx", e); ctx.setNextStage(TransactionProcessingPipeline.Stage.ABORT); return ctx; } } if (tvm != null && tvm.getType() == TransactionViewModel.FILLED_SLOT) { try { // send the requested tx data to the requester neighborRouter.gossipTransactionTo(neighbor, tvm); // cache the replied with tx long txDigest = TransactionCacheDigester.getDigest(tvm.getBytes()); recentlySeenBytesCache.put(txDigest, tvm.getHash()); } catch (Exception e) { log.error("error adding reply tx to neighbor's send queue", e); } ctx.setNextStage(TransactionProcessingPipeline.Stage.ABORT); return ctx; } ctx.setNextStage(TransactionProcessingPipeline.Stage.FINISH); return ctx; } private Hash getRandomTipPointer() { Hash tip = rnd.nextDouble() < config.getpSendMilestone() ? milestoneSolidifier.getLatestMilestoneHash() : tipsViewModel.getRandomSolidTipHash(); return tip == null ? Hash.NULL_HASH : tip; } }
7,678
47.295597
120
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/SolidifyPayload.java
package com.iota.iri.network.pipeline; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.network.neighbor.Neighbor; /** * Defines a payload which gets submitted to the {@link SolidifyStage}. */ public class SolidifyPayload extends Payload { private Neighbor originNeighbor; private TransactionViewModel tvm; /** * Constructor for solidification payload. * * @param originNeighbor The originating point of a received transaction * @param tvm The transaction that needs to be solidified */ public SolidifyPayload(Neighbor originNeighbor, TransactionViewModel tvm){ this.originNeighbor = originNeighbor; this.tvm = tvm; } /** * {@inheritDoc} */ @Override public Neighbor getOriginNeighbor(){ return originNeighbor; } /** * Fetches the transaction from the payload. * @return The transaction stored in the payload. */ public TransactionViewModel getTransaction(){ return tvm; } }
1,062
26.25641
79
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/SolidifyStage.java
package com.iota.iri.network.pipeline; import com.iota.iri.controllers.TipsViewModel; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import com.iota.iri.service.validation.TransactionSolidifier; import com.iota.iri.storage.Tangle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.iota.iri.controllers.TransactionViewModel.fromHash; /** * The {@link SolidifyStage} is used to process newly received transaction for solidity. Once a transaction has been * passed from the {@link ReceivedStage} it will be placed into this stage to have the {@link TransactionSolidifier} * check the solidity of the transaction. If the transaction is found to be solid, it will be passed forward to the * {@link BroadcastStage}. If it is found to be unsolid, it is put through the solidity check so that missing reference * transactions get requested. If the transaction is unsolid, a random solid tip is broadcast instead to keep the * requests transmitting to neighbors. */ public class SolidifyStage implements Stage { private static final Logger log = LoggerFactory.getLogger(SolidifyStage.class); private TransactionSolidifier txSolidifier; private TipsViewModel tipsViewModel; private Tangle tangle; /** * Constructor for the {@link SolidifyStage}. * * @param txSolidifier Transaction validator implementation for determining the validity of a transaction * @param tipsViewModel Used for broadcasting random solid tips if the subject transaction is unsolid * @param tangle A reference to the nodes DB */ public SolidifyStage(TransactionSolidifier txSolidifier, TipsViewModel tipsViewModel, Tangle tangle){ this.txSolidifier = txSolidifier; this.tipsViewModel = tipsViewModel; this.tangle = tangle; } /** * Processes the payload of the {@link ProcessingContext} as a {@link SolidifyPayload}. First the transaction will * be checked for solidity and validity. If the transaction is already solid or can be set solid quickly by the * transaction validator, the transaction is passed to the {@link BroadcastStage}. If not, a random solid tip is * pulled form the {@link TipsViewModel} to be broadcast instead. * * @param ctx The context to process * @return The output context, in most cases a {@link BroadcastPayload}. */ @Override public ProcessingContext process(ProcessingContext ctx){ try { SolidifyPayload payload = (SolidifyPayload) ctx.getPayload(); TransactionViewModel tvm = payload.getTransaction(); if (tvm.isSolid() || txSolidifier.quickSetSolid(tvm)) { // If the transaction is in the solidifier broadcast queue, remove it as it will be broadcast now txSolidifier.clearFromBroadcastQueue(tvm); ctx.setNextStage(TransactionProcessingPipeline.Stage.BROADCAST); ctx.setPayload(new BroadcastPayload(payload.getOriginNeighbor(), payload.getTransaction())); return ctx; } return broadcastTip(ctx, payload); }catch (Exception e){ log.error("Failed to process transaction for solidification", e); ctx.setNextStage(TransactionProcessingPipeline.Stage.ABORT); return ctx; } } private ProcessingContext broadcastTip(ProcessingContext ctx, SolidifyPayload payload) throws Exception{ Hash tipHash = tipsViewModel.getRandomSolidTipHash(); if (tipHash == null) { ctx.setNextStage(TransactionProcessingPipeline.Stage.FINISH); return ctx; } TransactionViewModel tip = fromHash(tangle, tipHash); ctx.setNextStage(TransactionProcessingPipeline.Stage.BROADCAST); ctx.setPayload(new BroadcastPayload(payload.getOriginNeighbor(), tip)); return ctx; } }
3,976
43.685393
119
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/Stage.java
package com.iota.iri.network.pipeline; /** * Defines a stage in the {@link TransactionProcessingPipelineImpl} which processes a {@link ProcessingContext} and its * payload and then mutates the given context with the information for the next stage. */ public interface Stage { /** * Processes the given context and adjusts it with the payloads needed for the next stage (if any). * * @param ctx the context to process * @return the mutated context (usually the same context as the passed in context) */ ProcessingContext process(ProcessingContext ctx); }
593
33.941176
119
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/TransactionProcessingPipeline.java
package com.iota.iri.network.pipeline; import com.iota.iri.network.neighbor.Neighbor; import java.nio.ByteBuffer; import java.util.concurrent.BlockingQueue; /** * A pipeline using stages to process incoming transaction data from neighbors and API calls. */ public interface TransactionProcessingPipeline { /** * Defines the different stages of the {@link TransactionProcessingPipelineImpl}. */ enum Stage { PRE_PROCESS, HASHING, VALIDATION, REPLY, RECEIVED, BROADCAST, MULTIPLE, ABORT, FINISH, SOLIDIFY, MILESTONE } /** * Kicks of the pipeline by assembling the pipeline and starting all threads. */ void start(); /** * Gets the received stage queue. * * @return the received stage queue */ BlockingQueue<ProcessingContext> getReceivedStageQueue(); /** * Gets the broadcast stage queue. * * @return the broadcast stage queue. */ BlockingQueue<ProcessingContext> getBroadcastStageQueue(); /** * Gets the reply stage queue. * * @return the reply stage queue */ BlockingQueue<ProcessingContext> getReplyStageQueue(); /** * Gets the validation stage queue. * * @return the validation stage queue */ BlockingQueue<ProcessingContext> getValidationStageQueue(); /** * Submits the given data from the given neighbor into the pre processing stage of the pipeline. * * @param neighbor the {@link Neighbor} from which the data originated from * @param data the data to process */ void process(Neighbor neighbor, ByteBuffer data); /** * Submits the given transactions trits into the hashing stage of the pipeline. * * @param txTrits the transaction trits */ void process(byte[] txTrits); /** * Shut downs the pipeline by shutting down all stages. */ void shutdown(); /** * Sets the pre process stage. This method should only be used for injecting mocked objects. * * @param preProcessStage the {@link PreProcessStage} to use */ void setPreProcessStage(PreProcessStage preProcessStage); /** * Sets the validation stage. This method should only be used for injecting mocked objects. * * @param receivedStage the {@link ReceivedStage} to use */ void setReceivedStage(ReceivedStage receivedStage); /** * Sets the validation stage. This method should only be used for injecting mocked objects. * * @param validationStage the {@link ValidationStage} to use */ void setValidationStage(ValidationStage validationStage); /** * Sets the reply stage. This method should only be used for injecting mocked objects. * * @param replyStage the {@link ReplyStage} to use */ void setReplyStage(ReplyStage replyStage); /** * Sets the broadcast stage. This method should only be used for injecting mocked objects. * * @param broadcastStage the {@link BroadcastStage} to use */ void setBroadcastStage(BroadcastStage broadcastStage); /** * Sets the hashing stage. This method should only be used for injecting mocked objects. * * @param hashingStage the {@link HashingStage} to use */ void setHashingStage(HashingStage hashingStage); /** * Sets the solidify stage. This method should only be used for injecting mocked objects. * * @param solidifyStage the {@link SolidifyStage} to use */ void setSolidifyStage(SolidifyStage solidifyStage); /** * Sets the milestone stage. This method should only be used for injecting mocked objects. * * @param milestoneStage the {@link MilestoneStage} to use */ void setMilestoneStage(MilestoneStage milestoneStage); }
3,808
28.757813
114
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/TransactionProcessingPipelineImpl.java
package com.iota.iri.network.pipeline; import com.iota.iri.conf.NodeConfig; import com.iota.iri.controllers.TipsViewModel; import com.iota.iri.crypto.batched.BatchedHasher; import com.iota.iri.crypto.batched.BatchedHasherFactory; import com.iota.iri.crypto.batched.HashRequest; import com.iota.iri.model.Hash; import com.iota.iri.model.persistables.Transaction; import com.iota.iri.network.FIFOCache; import com.iota.iri.network.NeighborRouter; import com.iota.iri.network.TransactionCacheDigester; import com.iota.iri.network.TransactionRequester; import com.iota.iri.network.neighbor.Neighbor; import com.iota.iri.service.milestone.InSyncService; import com.iota.iri.service.milestone.MilestoneService; import com.iota.iri.service.milestone.MilestoneSolidifier; import com.iota.iri.service.snapshot.SnapshotProvider; import com.iota.iri.service.validation.TransactionSolidifier; import com.iota.iri.service.validation.TransactionValidator; import com.iota.iri.storage.Tangle; import com.iota.iri.utils.Converter; import com.iota.iri.utils.IotaUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; /** * The {@link TransactionProcessingPipelineImpl} processes transactions which either came from {@link Neighbor} instances or * were submitted via {@link com.iota.iri.service.API#broadcastTransactionsStatement(List)}.<br/> * The pipeline splits the processing of transactions into different stages which run concurrently: * <ul> * <li><strong>PreProcess</strong>: expands transaction payloads, computes the digest of transactions received by * {@link Neighbor} instances and converts the transaction payload to its trits representation.<br/> * Submits to the hashing stage if the transaction payload is not known or to the reply stage if already known.</li> * <li><strong>Hashing</strong>: hashes transaction trits using a {@link BatchedHasher} and then submits it further to * the validation stage.</li> * <li><strong>Validation</strong>: validates the newly received transaction payload and adds it to the known bytes * cache.<br/> * If the transaction originated from a {@link com.iota.iri.service.API#broadcastTransactionsStatement(List)}, then the * transaction is submitted to the received stage, otherwise it is both submitted to the reply and received stage.</li> * <li><strong>Reply</strong>: replies to the given neighbor with the requested transaction or a random tip.</li> * <li><strong>Received</strong>: stores the newly received and validated transaction and then submits it to the * broadcast stage.</li> * <li><strong>Broadcast</strong>: broadcasts the given transaction to all connected {@link Neighbor} instances except * the neighbor from which the transaction originated from.</li> * </ul> */ public class TransactionProcessingPipelineImpl implements TransactionProcessingPipeline { private static final Logger log = LoggerFactory.getLogger(TransactionProcessingPipelineImpl.class); private ExecutorService stagesThreadPool = Executors.newFixedThreadPool(NUMBER_OF_THREADS); /** * List of stages that will be ignored when determining thread count */ private static final List IGNORED_STAGES = IotaUtils.createImmutableList(Stage.MULTIPLE, Stage.ABORT, Stage.FINISH); private static final int NUMBER_OF_THREADS = Stage.values().length - IGNORED_STAGES.size(); // stages of the protocol protocol private PreProcessStage preProcessStage; private ReceivedStage receivedStage; private ValidationStage validationStage; private ReplyStage replyStage; private BroadcastStage broadcastStage; private BatchedHasher batchedHasher; private HashingStage hashingStage; private SolidifyStage solidifyStage; private MilestoneStage milestoneStage; private BlockingQueue<ProcessingContext> milestoneStageQueue = new LinkedBlockingQueue<>(); private BlockingQueue<ProcessingContext> preProcessStageQueue = new LinkedBlockingQueue<>(); private BlockingQueue<ProcessingContext> validationStageQueue = new LinkedBlockingQueue<>(); private BlockingQueue<ProcessingContext> receivedStageQueue = new LinkedBlockingQueue<>(); private BlockingQueue<ProcessingContext> replyStageQueue = new LinkedBlockingQueue<>(); private BlockingQueue<ProcessingContext> broadcastStageQueue = new LinkedBlockingQueue<>(); private BlockingQueue<ProcessingContext> solidifyStageQueue = new LinkedBlockingQueue<>(); /** * Creates a {@link TransactionProcessingPipeline}. * * @param neighborRouter The {@link NeighborRouter} to use for broadcasting transactions * @param config The config to set cache sizes and other options * @param txValidator The transaction validator to validate incoming transactions with * @param tangle The {@link Tangle} database to use to store and load transactions. * @param snapshotProvider The {@link SnapshotProvider} to use to store transactions with. * @param tipsViewModel The {@link TipsViewModel} to load tips from in the reply stage * @param inSyncService The {@link InSyncService} to check if we are in sync */ public TransactionProcessingPipelineImpl(NeighborRouter neighborRouter, NodeConfig config, TransactionValidator txValidator, Tangle tangle, SnapshotProvider snapshotProvider, TipsViewModel tipsViewModel, MilestoneSolidifier milestoneSolidifier, TransactionRequester transactionRequester, TransactionSolidifier txSolidifier, MilestoneService milestoneService, InSyncService inSyncService) { FIFOCache<Long, Hash> recentlySeenBytesCache = new FIFOCache<>(config.getCacheSizeBytes()); this.preProcessStage = new PreProcessStage(recentlySeenBytesCache); this.replyStage = new ReplyStage(neighborRouter, config, tangle, tipsViewModel, milestoneSolidifier, snapshotProvider, recentlySeenBytesCache); this.broadcastStage = new BroadcastStage(neighborRouter, txSolidifier, inSyncService); this.validationStage = new ValidationStage(txValidator, recentlySeenBytesCache); this.receivedStage = new ReceivedStage(tangle, txSolidifier, snapshotProvider, transactionRequester, milestoneService, config.getCoordinator()); this.batchedHasher = BatchedHasherFactory.create(BatchedHasherFactory.Type.BCTCURL81, 20); this.hashingStage = new HashingStage(batchedHasher); this.solidifyStage = new SolidifyStage(txSolidifier, tipsViewModel, tangle); this.milestoneStage = new MilestoneStage(milestoneSolidifier, snapshotProvider, txSolidifier); } @Override public void start() { stagesThreadPool.submit(batchedHasher); addStage("pre-process", preProcessStageQueue, preProcessStage); addStage("validation", validationStageQueue, validationStage); addStage("reply", replyStageQueue, replyStage); addStage("received", receivedStageQueue, receivedStage); addStage("broadcast", broadcastStageQueue, broadcastStage); addStage("solidify", solidifyStageQueue, solidifyStage); addStage("milestone", milestoneStageQueue, milestoneStage); } /** * Adds the given stage to the processing pipeline. * * @param name the name of the stage * @param queue the queue from which contexts are taken to process within the stage * @param stage the stage with the processing logic */ private void addStage(String name, BlockingQueue<ProcessingContext> queue, com.iota.iri.network.pipeline.Stage stage) { stagesThreadPool.submit(new Thread(() -> { try { while (!Thread.currentThread().isInterrupted()) { ProcessingContext ctx = stage.process(queue.take()); switch (ctx.getNextStage()) { case REPLY: replyStageQueue.put(ctx); break; case HASHING: hashAndValidate(ctx); break; case RECEIVED: receivedStageQueue.put(ctx); break; case MULTIPLE: MultiStagePayload payload = (MultiStagePayload) ctx.getPayload(); replyStageQueue.put(payload.getLeft()); receivedStageQueue.put(payload.getRight()); break; case BROADCAST: broadcastStageQueue.put(ctx); break; case SOLIDIFY: solidifyStageQueue.put(ctx); break; case MILESTONE: milestoneStageQueue.put(ctx); break; case ABORT: break; case FINISH: break; default: // do nothing } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { log.info("{}-stage shutdown", name); } }, String.format("%s-stage", name))); } @Override public BlockingQueue<ProcessingContext> getReceivedStageQueue() { return receivedStageQueue; } @Override public BlockingQueue<ProcessingContext> getBroadcastStageQueue() { return broadcastStageQueue; } @Override public BlockingQueue<ProcessingContext> getReplyStageQueue() { return replyStageQueue; } @Override public BlockingQueue<ProcessingContext> getValidationStageQueue() { return validationStageQueue; } @Override public void process(Neighbor neighbor, ByteBuffer data) { try { preProcessStageQueue.put(new ProcessingContext(new PreProcessPayload(neighbor, data))); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void process(byte[] txTrits) { byte[] txBytes = new byte[Transaction.SIZE]; Converter.bytes(txTrits, txBytes); long txDigest = TransactionCacheDigester.getDigest(txBytes); HashingPayload payload = new HashingPayload(null, txTrits, txDigest, null); hashAndValidate(new ProcessingContext(payload)); } /** * Sets up the given hashing stage {@link ProcessingContext} so that up on success, it will submit further to the * validation stage. * * @param ctx the hashing stage {@link ProcessingContext} */ private void hashAndValidate(ProcessingContext ctx) { // the hashing already runs in its own thread, // the callback will submit the data to the validation stage HashingPayload hashingStagePayload = (HashingPayload) ctx.getPayload(); hashingStagePayload.setHashRequest(new HashRequest(hashingStagePayload.getTxTrits(), hashTrits -> { try { hashingStagePayload.setHashTrits(hashTrits); // the validation stage takes care of submitting a payload to the reply stage. ctx.setNextStage(TransactionProcessingPipeline.Stage.VALIDATION); validationStageQueue.put(ctx); } catch (InterruptedException e) { log.error("unable to put processing context into hashing stage. reason: {}", e.getMessage()); } })); hashingStage.process(ctx); } @Override public void shutdown() { stagesThreadPool.shutdownNow(); } @Override public void setPreProcessStage(PreProcessStage preProcessStage) { this.preProcessStage = preProcessStage; } @Override public void setReceivedStage(ReceivedStage receivedStage) { this.receivedStage = receivedStage; } @Override public void setValidationStage(ValidationStage validationStage) { this.validationStage = validationStage; } @Override public void setReplyStage(ReplyStage replyStage) { this.replyStage = replyStage; } @Override public void setBroadcastStage(BroadcastStage broadcastStage) { this.broadcastStage = broadcastStage; } @Override public void setHashingStage(HashingStage hashingStage) { this.hashingStage = hashingStage; } @Override public void setSolidifyStage(SolidifyStage solidifyStage){ this.solidifyStage = solidifyStage; } @Override public void setMilestoneStage(MilestoneStage milestoneStage){ this.milestoneStage = milestoneStage; } }
13,134
44.607639
124
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/ValidationPayload.java
package com.iota.iri.network.pipeline; import com.iota.iri.model.Hash; import com.iota.iri.network.neighbor.Neighbor; import java.util.Arrays; /** * Defines a payload whic gets submitted to the {@link ValidationStage}. */ public class ValidationPayload extends Payload { private Neighbor neighbor; private byte[] txTrits; private byte[] hashTrits; private Long txBytesDigest; private Hash hashOfRequestedTx; /** * Creates a new {@link ValidationStage}. * * @param neighbor the {@link Neighbor} from which the transaction originated from (can be null) * @param txTrits the trits representation of the transaction * @param hashTrits the hash of the transaction in trits representation * @param txBytesDigest the digest of the tansaction payload * @param hashOfRequestedTx the hash of the requested transaction */ public ValidationPayload(Neighbor neighbor, byte[] txTrits, byte[] hashTrits, Long txBytesDigest, Hash hashOfRequestedTx) { this.neighbor = neighbor; this.txBytesDigest = txBytesDigest; this.txTrits = txTrits; this.hashTrits = hashTrits; this.hashOfRequestedTx = hashOfRequestedTx; } /** * {@inheritDoc} */ public Neighbor getOriginNeighbor() { return neighbor; } /** * Gets the transaction trits. * * @return the transaction trits */ public byte[] getTxTrits() { return txTrits; } /** * Gets the transaction payload digest. * * @return the transaction payload digest */ public Long getTxBytesDigest() { return txBytesDigest; } /** * Gets the hash of the requested transaction. * * @return the hash of the requested transaction. */ public Hash getHashOfRequestedTx() { return hashOfRequestedTx; } /** * Gets the hash of the transaction. * * @return the hash of the transaction. */ public byte[] getHashTrits() { return hashTrits; } /** * Sets the transaction hash trits. * * @param hashTrits the hash trits to set */ public void setHashTrits(byte[] hashTrits) { this.hashTrits = hashTrits; } @Override public String toString() { return "ValidationPayload{" + "neighbor=" + neighbor.getHostAddressAndPort() + ", hashTrits=" + Arrays.toString(hashTrits) + ", txBytesDigest=" + txBytesDigest + ", hashOfRequestedTx=" + hashOfRequestedTx.toString() + '}'; } }
2,623
26.333333
109
java
iri
iri-master/src/main/java/com/iota/iri/network/pipeline/ValidationStage.java
package com.iota.iri.network.pipeline; import com.iota.iri.service.validation.TransactionValidator; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import com.iota.iri.model.HashFactory; import com.iota.iri.model.TransactionHash; import com.iota.iri.network.FIFOCache; import com.iota.iri.network.neighbor.Neighbor; import static com.iota.iri.model.Hash.SIZE_IN_TRITS; /** * The {@link ValidationStage} validates the given transaction, caches it as recently seen and then either submits * further to the {@link ReceivedStage} or/and {@link ReplyStage} depending on whether the transaction originated from a * neighbor or not. */ public class ValidationStage implements Stage { private TransactionValidator txValidator; private FIFOCache<Long, Hash> recentlySeenBytesCache; /** * Creates a new {@link ValidationStage}. * * @param txValidator the {@link TransactionValidator} to use to validate the transaction * @param recentlySeenBytesCache the {@link FIFOCache} to cache the validate transaction as recently seen */ public ValidationStage(TransactionValidator txValidator, FIFOCache<Long, Hash> recentlySeenBytesCache) { this.txValidator = txValidator; this.recentlySeenBytesCache = recentlySeenBytesCache; } /** * Validates the transaction and caches it as 'recently seen'. * * @param ctx the reply stage {@link ProcessingContext} * @return a {@link ProcessingContext} either directing to only the {@link ReceivedStage} or both * {@link ReceivedStage} and {@link ReplyStage}, depending on whether the transaction came from a neighbor * or not */ @Override public ProcessingContext process(ProcessingContext ctx) { ValidationPayload payload = (ValidationPayload) ctx.getPayload(); byte[] hashTrits = payload.getHashTrits(); byte[] txTrits = payload.getTxTrits(); Neighbor originNeighbor = payload.getOriginNeighbor(); Long txBytesDigest = payload.getTxBytesDigest(); Hash hashOfRequestedTx = payload.getHashOfRequestedTx(); // construct transaction hash and model TransactionHash txHash = (TransactionHash) HashFactory.TRANSACTION.create(hashTrits, 0, SIZE_IN_TRITS); TransactionViewModel tvm = new TransactionViewModel(txTrits, txHash); try { txValidator.runValidation(tvm, txValidator.getMinWeightMagnitude()); } catch (TransactionValidator.StaleTimestampException ex) { if (originNeighbor != null) { originNeighbor.getMetrics().incrStaleTransactionsCount(); } ctx.setNextStage(TransactionProcessingPipeline.Stage.ABORT); return ctx; } catch (Exception ex) { if (originNeighbor != null) { originNeighbor.getMetrics().incrInvalidTransactionsCount(); } ctx.setNextStage(TransactionProcessingPipeline.Stage.ABORT); return ctx; } // cache the tx hash under the tx payload digest if (txBytesDigest != null && txBytesDigest != 0) { recentlySeenBytesCache.put(txBytesDigest, txHash); } ReceivedPayload receivedStagePayload = new ReceivedPayload(originNeighbor, tvm); // go directly to receive stage if the transaction didn't originate from a neighbor if (hashOfRequestedTx == null || originNeighbor == null) { ctx.setNextStage(TransactionProcessingPipeline.Stage.RECEIVED); ctx.setPayload(receivedStagePayload); return ctx; } // diverge flow to received and reply stage ctx.setNextStage(TransactionProcessingPipeline.Stage.MULTIPLE); hashOfRequestedTx = hashOfRequestedTx.equals(txHash) ? Hash.NULL_HASH : hashOfRequestedTx; ReplyPayload replyStagePayload = new ReplyPayload(originNeighbor, hashOfRequestedTx); ProcessingContext replyCtx = new ProcessingContext(TransactionProcessingPipeline.Stage.REPLY, replyStagePayload); ProcessingContext receivedCtx = new ProcessingContext(TransactionProcessingPipeline.Stage.RECEIVED, receivedStagePayload); ctx.setPayload(new MultiStagePayload(replyCtx, receivedCtx)); return ctx; } }
4,362
43.520408
120
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/Handshake.java
package com.iota.iri.network.protocol; import com.iota.iri.network.neighbor.Neighbor; import java.nio.ByteBuffer; /** * Defines information exchanged up on a new connection with a {@link Neighbor}. */ public class Handshake { /** * The amount of bytes used for the coo address sent in a handshake packet. */ public final static int BYTE_ENCODED_COO_ADDRESS_BYTES_LENGTH = 49; /** * The amount of bytes in the handshake payload is * <i>source port length + timestamp size + coo address size in bytes + mwm byte + supported version bytes */ public static final short PAYLOAD_LENGTH_BYTES = (short) (Character.BYTES + Long.BYTES + BYTE_ENCODED_COO_ADDRESS_BYTES_LENGTH + Byte.BYTES + Protocol.SUPPORTED_PROTOCOL_VERSIONS.length); /** * The state of the handshaking. */ public enum State { INIT, FAILED, OK, } private int serverSocketPort; private long sentTimestamp; private byte[] byteEncodedCooAddress; private int mwm; private State state = State.INIT; private byte[] supportedVersions; /** * Creates a new handshake packet. * * @param ownSourcePort the node's own server socket port number * @return a {@link ByteBuffer} containing the handshake packet */ public static ByteBuffer createHandshakePacket(char ownSourcePort, byte[] ownByteEncodedCooAddress, byte ownUsedMWM) { ByteBuffer buf = ByteBuffer.allocate(ProtocolMessage.HEADER.getMaxLength() + PAYLOAD_LENGTH_BYTES); Protocol.addProtocolHeader(buf, ProtocolMessage.HANDSHAKE, PAYLOAD_LENGTH_BYTES); buf.putChar(ownSourcePort); buf.putLong(System.currentTimeMillis()); buf.put(ownByteEncodedCooAddress); buf.put(ownUsedMWM); buf.put(Protocol.SUPPORTED_PROTOCOL_VERSIONS); //update PAYLOAD_LENGTH_BYTES if changed buf.flip(); return buf; } /** * Parses the given message into a {@link Handshake} object. * * @param msg the buffer containing the handshake info * @return the {@link Handshake} object */ public static Handshake fromByteBuffer(ByteBuffer msg) { Handshake handshake = new Handshake(); handshake.setServerSocketPort((int) msg.getChar()); handshake.setSentTimestamp(msg.getLong()); byte[] byteEncodedCooAddress = new byte[BYTE_ENCODED_COO_ADDRESS_BYTES_LENGTH]; msg.get(byteEncodedCooAddress); handshake.setByteEncodedCooAddress(byteEncodedCooAddress); handshake.setMWM(msg.get()); handshake.setState(Handshake.State.OK); // extract supported versions byte[] supportedVersions = new byte[msg.remaining()]; msg.get(supportedVersions); handshake.setSupportedVersions(supportedVersions); return handshake; } /** * Gets the state of the handshaking. * * @return the state */ public State getState() { return state; } /** * Sets the state of the handshaking. * * @param state the state to set */ public void setState(State state) { this.state = state; } /** * Sets the server socket port number. * * @param serverSocketPort the number to set */ public void setServerSocketPort(int serverSocketPort) { this.serverSocketPort = serverSocketPort; } /** * Gets the server socket port number. * * @return the server socket port number. */ public int getServerSocketPort() { return serverSocketPort; } /** * Sets the sent timestamp. * * @param sentTimestamp the timestamp */ public void setSentTimestamp(long sentTimestamp) { this.sentTimestamp = sentTimestamp; } /** * Gets the sent timestamp. * * @return the sent timestamp */ public long getSentTimestamp() { return sentTimestamp; } /** * Gets the byte encoded coordinator address. * * @return the byte encoded coordinator address */ public byte[] getByteEncodedCooAddress() { return byteEncodedCooAddress; } /** * Sets the byte encoded coordinator address. * * @param byteEncodedCooAddress the byte encoded coordinator to set */ public void setByteEncodedCooAddress(byte[] byteEncodedCooAddress) { this.byteEncodedCooAddress = byteEncodedCooAddress; } /** * Gets the MWM. * * @return the mwm */ public int getMWM() { return mwm; } /** * Sets the mwm. * * @param mwm the mwm to set */ public void setMWM(int mwm) { this.mwm = mwm; } /** * Gets the supported versions. * * @return the supported versions */ public byte[] getSupportedVersions() { return supportedVersions; } /** * Sets the supported versions. * * @param supportedVersions the supported versions to set */ public void setSupportedVersions(byte[] supportedVersions) { this.supportedVersions = supportedVersions; } /** * Returns the highest supported protocol version by the neighbor or a negative number indicating the highest * protocol version the neighbor would have supported but which our node doesn't. * * @param ownSupportedVersions the versions our own node supports * @return a positive integer defining the highest supported protocol version and a negative integer indicating the * highest supported version by the given neighbor but which is not supported by us */ public int getNeighborSupportedVersion(byte[] ownSupportedVersions) { int highestSupportedVersion = 0; for (int i = 0; i < ownSupportedVersions.length; i++) { // max check up to advertised versions by the neighbor if (i > supportedVersions.length - 1) { break; } // get versions matched by both byte supported = (byte) (supportedVersions[i] & ownSupportedVersions[i]); // none supported if (supported == 0) { continue; } // iterate through all bits and find highest (more to the left is higher) int highest = 0; for (int j = 0; j < 8; j++) { if (((supported >> j) & 1) == 1) { highest = j + 1; } } highestSupportedVersion = highest + (i * 8); } // if the highest version is still 0, it means that we don't support // any protocol version the neighbor supports if (highestSupportedVersion == 0) { // grab last byte denoting the highest versions. // a node will only hold version bytes if at least one version in that // byte is supported, therefore it's safe to assume, that the last byte contains // the highest supported version of a given node. byte lastVersionsByte = supportedVersions[supportedVersions.length - 1]; // find highest version int highest = 0; for (int j = 0; j < 8; j++) { if (((lastVersionsByte >> j) & 1) == 1) { highest = j + 1; } } int highestSupportedVersionByNeighbor = highest + ((supportedVersions.length - 1) * 8); // negate to indicate that we don't actually support it return -highestSupportedVersionByNeighbor; } return highestSupportedVersion; } }
7,727
30.542857
119
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/Heartbeat.java
package com.iota.iri.network.protocol; import java.nio.ByteBuffer; /** * Defines the information contained in a heartbeat */ public class Heartbeat { private int firstSolidMilestoneIndex; private int lastSolidMilestoneIndex; /** * Parses the given message into a {@link Heartbeat} object. * * @param msg the buffer containing the handshake info * @return the {@link Heartbeat} object */ public static Heartbeat fromByteBuffer(ByteBuffer msg) { Heartbeat heartbeat = new Heartbeat(); heartbeat.setFirstSolidMilestoneIndex(msg.getInt()); heartbeat.setLastSolidMilestoneIndex(msg.getInt()); return heartbeat; } /** * Gets the first solid milestone index of the node * * @return The first solid milestone index */ public int getFirstSolidMilestoneIndex() { return firstSolidMilestoneIndex; } /** * Sets the first solid milestone index of the node * * @param firstSolidMilestoneIndex The first solid milestone index */ public void setFirstSolidMilestoneIndex(int firstSolidMilestoneIndex) { this.firstSolidMilestoneIndex = firstSolidMilestoneIndex; } /** * Gets the last solid milestone index of the node * * @return The last solid milestone index */ public int getLastSolidMilestoneIndex() { return lastSolidMilestoneIndex; } /** * Sets the last solid milestone index * * @param lastSolidMilestoneIndex The last solid milestone index */ public void setLastSolidMilestoneIndex(int lastSolidMilestoneIndex) { this.lastSolidMilestoneIndex = lastSolidMilestoneIndex; } }
1,714
26.66129
75
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/InvalidProtocolMessageLengthException.java
package com.iota.iri.network.protocol; /** * Thrown when a packet advertises a message length which is invalid for the given {@link ProtocolMessage} type. */ public class InvalidProtocolMessageLengthException extends Exception { /** * Constructs a new exception for invlaid protocol message lengths. * * @param msg the message for this exception */ public InvalidProtocolMessageLengthException(String msg) { super(msg); } }
469
26.647059
112
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/Protocol.java
package com.iota.iri.network.protocol; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.utils.TransactionTruncator; import java.nio.ByteBuffer; /** * The IRI protocol uses a 4 bytes header denoting the version, type and length of a packet. */ public class Protocol { /** * The protocol version used by this node. */ public final static byte PROTOCOL_VERSION = 1; /** * <p> * The supported protocol versions by this node. Bitmasks are used to denote what protocol version this node * supports in its implementation. The LSB acts as a starting point. Up to 32 bytes are supported in the handshake * packet, limiting the amount of supported denoted protocol versions to 256. * </p> * <p> * Examples: * </p> * <ul> * <li>[00000001] denotes that this node supports protocol version 1.</li> * <li>[00000111] denotes that this node supports protocol versions 1, 2 and 3.</li> * <li>[01101110] denotes that this node supports protocol versions 2, 3, 4, 6 and 7.</li> * <li>[01101110, 01010001] denotes that this node supports protocol versions 2, 3, 4, 6, 7, 9, 13 and 15.</li> * <li>[01101110, 01010001, 00010001] denotes that this node supports protocol versions 2, 3, 4, 6, 7, 9, 13, 15, * 17 and 21.</li> * </ul> */ public final static byte[] SUPPORTED_PROTOCOL_VERSIONS = { /* supports protocol version(s): 1 */ (byte) 0b00000001, }; /** * The amount of bytes dedicated for the message type in the packet header. */ public final static byte HEADER_TLV_TYPE_BYTES_LENGTH = 1; /** * The amount of bytes dedicated for the message length denotation in the packet header. */ public final static byte HEADER_TLV_LENGTH_BYTES_LENGTH = 2; /** * The amount of bytes making up the protocol packet header. */ public final static byte PROTOCOL_HEADER_BYTES_LENGTH = HEADER_TLV_LENGTH_BYTES_LENGTH + HEADER_TLV_TYPE_BYTES_LENGTH; /** * The amount of bytes used for the requested transaction hash. */ public final static int GOSSIP_REQUESTED_TX_HASH_BYTES_LENGTH = 49; /** * The amount of bytes to store first and last solid milestone index */ public final static byte PROTOCOL_HEARTBEAT_BYTES_LENGTH = 8; /** * Parses the given buffer into a {@link ProtocolHeader}. * * @param buf the buffer to parse * @return the parsed {@link ProtocolHeader} * @throws UnknownMessageTypeException thrown when the advertised message type is unknown * @throws InvalidProtocolMessageLengthException thrown when the advertised message length is invalid */ public static ProtocolHeader parseHeader(ByteBuffer buf) throws UnknownMessageTypeException, InvalidProtocolMessageLengthException { // extract type of message byte type = buf.get(); ProtocolMessage protoMsg = ProtocolMessage.fromTypeID(type); if (protoMsg == null) { throw new UnknownMessageTypeException(String.format("got unknown message type in protocol: %d", type)); } // extract length of message short advertisedMsgLength = buf.getShort(); if ((advertisedMsgLength > protoMsg.getMaxLength()) || (!protoMsg.supportsDynamicLength() && advertisedMsgLength < protoMsg.getMaxLength())) { throw new InvalidProtocolMessageLengthException(String.format( "advertised length: %d bytes; max length: %d bytes", advertisedMsgLength, protoMsg.getMaxLength())); } return new ProtocolHeader(protoMsg, advertisedMsgLength); } /** * Creates a new transaction gossip packet. * * @param tvm The transaction to add into the packet * @param requestedHash The hash of the requested transaction * @return a {@link ByteBuffer} containing the transaction gossip packet. */ public static ByteBuffer createTransactionGossipPacket(TransactionViewModel tvm, byte[] requestedHash) { byte[] truncatedTx = TransactionTruncator.truncateTransaction(tvm.getBytes()); final short payloadLengthBytes = (short) (truncatedTx.length + GOSSIP_REQUESTED_TX_HASH_BYTES_LENGTH); ByteBuffer buf = ByteBuffer.allocate(ProtocolMessage.HEADER.getMaxLength() + payloadLengthBytes); addProtocolHeader(buf, ProtocolMessage.TRANSACTION_GOSSIP, payloadLengthBytes); buf.put(truncatedTx); buf.put(requestedHash, 0, GOSSIP_REQUESTED_TX_HASH_BYTES_LENGTH); buf.flip(); return buf; } /** * Creates a new heartbeat packet. * * @param heartbeat The heartbeat to add to the packet * @return a {@link ByteBuffer} containing the transaction gossip packet. */ public static ByteBuffer createHeartbeatPacket(Heartbeat heartbeat) { final short payloadLengthBytes = Protocol.PROTOCOL_HEARTBEAT_BYTES_LENGTH; ByteBuffer buf = ByteBuffer.allocate(ProtocolMessage.HEADER.getMaxLength() + payloadLengthBytes); addProtocolHeader(buf, ProtocolMessage.HEARTBEAT, payloadLengthBytes); buf.putInt(heartbeat.getFirstSolidMilestoneIndex()); buf.putInt(heartbeat.getLastSolidMilestoneIndex()); buf.flip(); return buf; } /** * Adds the protocol header to the given {@link ByteBuffer}. * * @param buf the {@link ByteBuffer} to write into. * @param protoMsg the message type which will be sent */ public static void addProtocolHeader(ByteBuffer buf, ProtocolMessage protoMsg) { addProtocolHeader(buf, protoMsg, protoMsg.getMaxLength()); } /** * Adds the protocol header to the given {@link ByteBuffer}. * * @param buf the {@link ByteBuffer} to write into. * @param protoMsg the message type which will be sent * @param payloadLengthBytes the message length */ public static void addProtocolHeader(ByteBuffer buf, ProtocolMessage protoMsg, short payloadLengthBytes) { buf.put(protoMsg.getTypeID()); buf.putShort(payloadLengthBytes); } /** * Copies the requested transaction hash from the given source data byte array into the given destination byte * array. * * @param source the transaction gossip packet data */ public static byte[] extractRequestedTxHash(byte[] source) { byte[] reqHashBytes = new byte[Protocol.GOSSIP_REQUESTED_TX_HASH_BYTES_LENGTH]; System.arraycopy(source, source.length - Protocol.GOSSIP_REQUESTED_TX_HASH_BYTES_LENGTH, reqHashBytes, 0, Protocol.GOSSIP_REQUESTED_TX_HASH_BYTES_LENGTH); return reqHashBytes; } }
6,807
41.024691
120
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/ProtocolHeader.java
package com.iota.iri.network.protocol; /** * The {@link ProtocolHeader} denotes the protocol version used by the node and the TLV of the packet. */ public class ProtocolHeader { private ProtocolMessage protoMsg; private short messageLength; /** * Creates a new protocol header. * * @param protoMsg the message type * @param messageLength the message length */ public ProtocolHeader(ProtocolMessage protoMsg, short messageLength) { this.protoMsg = protoMsg; this.messageLength = messageLength; } /** * Gets the denoted message type. * * @return the denoted message type */ public ProtocolMessage getMessageType() { return protoMsg; } /** * Gets the denoted message length. * * @return the denoted message length */ public short getMessageLength() { return messageLength; } }
929
22.25
102
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/ProtocolMessage.java
package com.iota.iri.network.protocol; import com.iota.iri.utils.TransactionTruncator; /** * Defines the different message types supported by the protocol and their characteristics. */ public enum ProtocolMessage { /** * The message header sent in each message denoting the TLV fields. */ HEADER((byte) 0, (short) Protocol.PROTOCOL_HEADER_BYTES_LENGTH, false), /** * The initial handshake packet sent over the wire up on a new neighbor connection. * Made up of: * - own server socket port (2 bytes) * - time at which the packet was sent (8 bytes) * - own used byte encoded coordinator address (49 bytes) * - own used MWM (1 byte) * - supported protocol versions. we need up to 32 bytes to represent 256 possible protocol * versions. only up to N bytes are used to communicate the highest supported version. */ HANDSHAKE((byte) 1, (short) 92, true), /** * The transaction payload + requested transaction hash gossipping packet. In reality most of this packets won't * take up their full 1604 bytes as the signature message fragment of the tx is truncated. */ TRANSACTION_GOSSIP((byte) 2, (short) (Protocol.GOSSIP_REQUESTED_TX_HASH_BYTES_LENGTH + TransactionTruncator.NON_SIG_TX_PART_BYTES_LENGTH + TransactionTruncator.SIG_DATA_MAX_BYTES_LENGTH), true), HEARTBEAT((byte) 3, Protocol.PROTOCOL_HEARTBEAT_BYTES_LENGTH, true); private static final ProtocolMessage[] lookup = new ProtocolMessage[256]; private byte typeID; private short maxLength; private boolean supportsDynamicLength; ProtocolMessage(byte typeID, short maxLength, boolean supportsDynamicLength) { this.typeID = typeID; this.maxLength = maxLength; this.supportsDynamicLength = supportsDynamicLength; } static { lookup[0] = HEADER; lookup[1] = HANDSHAKE; lookup[2] = TRANSACTION_GOSSIP; lookup[3] = HEARTBEAT; } /** * Gets the {@link ProtocolMessage} corresponding to the given type id. * * @param typeID the type id of the message * @return the {@link ProtocolMessage} corresponding to the given type id or null */ public static ProtocolMessage fromTypeID(byte typeID) { if (typeID >= lookup.length) { return null; } return lookup[typeID]; } /** * Gets the type id of the message. * * @return the type id of the message */ public byte getTypeID() { return typeID; } /** * Gets the maximum length of the message. * * @return the maximum length of the message */ public short getMaxLength() { return maxLength; } /** * Whether this message type supports dynamic length. * * @return whether this message type supports dynamic length */ public boolean supportsDynamicLength() { return supportsDynamicLength; } }
2,980
31.053763
140
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/UnknownMessageTypeException.java
package com.iota.iri.network.protocol; /** * Thrown when an unknown {@link ProtocolMessage} type is advertised in a packet. */ public class UnknownMessageTypeException extends Exception { /** * Creates a new exception for when an unknown message type is advertised. * @param msg the message for this exception */ public UnknownMessageTypeException(String msg) { super(msg); } }
417
25.125
81
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/message/MessageReader.java
package com.iota.iri.network.protocol.message; import com.iota.iri.network.protocol.ProtocolMessage; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; /** * A {@link MessageReader} reads up to N defined bytes from a {@link ReadableByteChannel}. */ public interface MessageReader { /** * Checks whether the underlying {@link ByteBuffer} is ready. * * @return whether the {@link MessageReader}'s {@link ByteBuffer} is ready */ boolean ready(); /** * Reads bytes from the given channel into the {@link ByteBuffer}. * * @param channel the channel to read from * @return how many bytes have been read into the buffer. * @throws IOException thrown when reading from the channel fails */ int readMessage(ReadableByteChannel channel) throws IOException; /** * Gets the {@link ByteBuffer} holding the message. * * @return the {@link ByteBuffer} holding the message. */ ByteBuffer getMessage(); /** * Gets the message type this {@link MessageReader} is expecting. * * @return the message type this {@link MessageReader} is expecting */ ProtocolMessage getMessageType(); }
1,250
26.8
90
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/message/MessageReaderFactory.java
package com.iota.iri.network.protocol.message; import com.iota.iri.network.protocol.ProtocolMessage; import com.iota.iri.network.protocol.UnknownMessageTypeException; import com.iota.iri.network.protocol.message.impl.MessageReaderImpl; /** * {@link MessageReaderFactory} provides methods to easily construct a {@link MessageReader}. */ public class MessageReaderFactory { /** * Creates a new {@link MessageReader} for the given message type. * * @param protoMsg the message type * @return a {@link MessageReader} for the given message type * @throws UnknownMessageTypeException when the message type is not known */ public static MessageReader create(ProtocolMessage protoMsg) throws UnknownMessageTypeException { switch (protoMsg) { case HEADER: case HANDSHAKE: case TRANSACTION_GOSSIP: case HEARTBEAT: return create(protoMsg, protoMsg.getMaxLength()); // there might be message types in the future which need a separate message reader implementation default: throw new UnknownMessageTypeException("can't construct MessageReaderImpl for unknown message type"); } } /** * Creates a new {@link MessageReader} with an explicit length to read. * * @param protoMsg the message type * @param messageLength the max bytes to read * @return a {@link MessageReader} for the given message type */ public static MessageReader create(ProtocolMessage protoMsg, short messageLength) { return new MessageReaderImpl(protoMsg, messageLength); } }
1,654
36.613636
116
java
iri
iri-master/src/main/java/com/iota/iri/network/protocol/message/impl/MessageReaderImpl.java
package com.iota.iri.network.protocol.message.impl; import com.iota.iri.network.protocol.ProtocolMessage; import com.iota.iri.network.protocol.message.MessageReader; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; /** * A {@link MessageReaderImpl} is a {@link MessageReader}. */ public class MessageReaderImpl implements MessageReader { private ByteBuffer msgBuf; private ProtocolMessage protoMsg; /** * Creates a new {@link MessageReaderImpl}. * @param protoMsg the message type * @param msgLength the message length */ public MessageReaderImpl(ProtocolMessage protoMsg, short msgLength) { this.protoMsg = protoMsg; this.msgBuf = ByteBuffer.allocate(msgLength); } @Override public boolean ready() { return !msgBuf.hasRemaining(); } @Override public int readMessage(ReadableByteChannel channel) throws IOException { return channel.read(msgBuf); } @Override public ByteBuffer getMessage() { return msgBuf; } @Override public ProtocolMessage getMessageType() { return protoMsg; } }
1,181
23.625
76
java
iri
iri-master/src/main/java/com/iota/iri/service/API.java
package com.iota.iri.service; import com.iota.iri.BundleValidator; import com.iota.iri.IRI; import com.iota.iri.IXI; import com.iota.iri.service.validation.TransactionValidator; import com.iota.iri.service.validation.TransactionSolidifier; import com.iota.iri.conf.APIConfig; import com.iota.iri.conf.IotaConfig; import com.iota.iri.controllers.AddressViewModel; import com.iota.iri.controllers.BundleViewModel; import com.iota.iri.controllers.MilestoneViewModel; import com.iota.iri.controllers.TagViewModel; import com.iota.iri.controllers.TipsViewModel; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.crypto.PearlDiver; import com.iota.iri.crypto.Sponge; import com.iota.iri.crypto.SpongeFactory; import com.iota.iri.model.Hash; import com.iota.iri.model.HashFactory; import com.iota.iri.model.persistables.Transaction; import com.iota.iri.network.NeighborRouter; import com.iota.iri.network.TransactionRequester; import com.iota.iri.network.pipeline.TransactionProcessingPipeline; import com.iota.iri.service.dto.AbstractResponse; import com.iota.iri.service.dto.AccessLimitedResponse; import com.iota.iri.service.dto.AddedNeighborsResponse; import com.iota.iri.service.dto.AttachToTangleResponse; import com.iota.iri.service.dto.CheckConsistency; import com.iota.iri.service.dto.ErrorResponse; import com.iota.iri.service.dto.ExceptionResponse; import com.iota.iri.service.dto.FindTransactionsResponse; import com.iota.iri.service.dto.GetBalancesResponse; import com.iota.iri.service.dto.GetInclusionStatesResponse; import com.iota.iri.service.dto.GetNeighborsResponse; import com.iota.iri.service.dto.GetNodeAPIConfigurationResponse; import com.iota.iri.service.dto.GetNodeInfoResponse; import com.iota.iri.service.dto.GetTipsResponse; import com.iota.iri.service.dto.GetTransactionsToApproveResponse; import com.iota.iri.service.dto.GetTrytesResponse; import com.iota.iri.service.dto.RemoveNeighborsResponse; import com.iota.iri.service.dto.WereAddressesSpentFrom; import com.iota.iri.service.ledger.LedgerService; import com.iota.iri.service.milestone.MilestoneSolidifier; import com.iota.iri.service.restserver.RestConnector; import com.iota.iri.service.snapshot.SnapshotProvider; import com.iota.iri.service.spentaddresses.SpentAddressesService; import com.iota.iri.service.tipselection.TipSelector; import com.iota.iri.service.tipselection.impl.TipSelectionCancelledException; import com.iota.iri.service.tipselection.impl.WalkValidatorImpl; import com.iota.iri.storage.Tangle; import com.iota.iri.utils.Converter; import com.iota.iri.utils.IotaUtils; import com.iota.iri.utils.comparators.TryteIndexComparator; import org.apache.commons.lang3.StringUtils; import org.iota.mddoclet.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import org.apache.commons.lang3.StringUtils; import org.iota.mddoclet.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * The API makes it possible to interact with the node by requesting information or actions to be taken. * You can interact with it by passing a JSON object which at least contains a <tt>command</tt>. * Upon successful execution of the command, the API returns your requested information in an {@link AbstractResponse}. * </p> * <p> * If the request is invalid, an {@link ErrorResponse} is returned. * This, for example, happens when the command does not exist or there is no command section at all. * If there is an error in the given data during the execution of a command, an {@link ErrorResponse} is also sent. * </p> * <p> * If an Exception is thrown during the execution of a command, an {@link ExceptionResponse} is returned. * </p> */ @SuppressWarnings("unchecked") public class API { private static final Logger log = LoggerFactory.getLogger(API.class); //region [CONSTANTS] /////////////////////////////////////////////////////////////////////////////// public static final String REFERENCE_TRANSACTION_NOT_FOUND = "reference transaction not found"; public static final String REFERENCE_TRANSACTION_TOO_OLD = "reference transaction is too old"; public static final String INVALID_SUBTANGLE = "This operation cannot be executed: " + "The subtangle has not been updated yet."; private static final String OVER_MAX_ERROR_MESSAGE = "Could not complete request"; private static final String INVALID_PARAMS = "Invalid parameters"; private static final char ZERO_LENGTH_ALLOWED = 'Y'; private static final char ZERO_LENGTH_NOT_ALLOWED = 'N'; private static final int HASH_SIZE = 81; private static final int TRYTES_SIZE = 2673; private static final long MAX_TIMESTAMP_VALUE = (long) (Math.pow(3, 27) - 1) / 2; // max positive 27-trits value //endregion //////////////////////////////////////////////////////////////////////////////////////////////////////// private static int counterGetTxToApprove = 0; private static long ellapsedTime_getTxToApprove = 0L; private static int counter_PoW = 0; private static long ellapsedTime_PoW = 0L; //region [CONSTRUCTOR_FIELDS] /////////////////////////////////////////////////////////////////////////////// private final IotaConfig configuration; private final IXI ixi; private final TransactionRequester transactionRequester; private final SpentAddressesService spentAddressesService; private final Tangle tangle; private final BundleValidator bundleValidator; private final SnapshotProvider snapshotProvider; private final LedgerService ledgerService; private final NeighborRouter neighborRouter; private final TransactionProcessingPipeline txPipeline; private final TipSelector tipsSelector; private final TipsViewModel tipsViewModel; private final TransactionValidator transactionValidator; private final TransactionSolidifier transactionSolidifier; private final MilestoneSolidifier milestoneSolidifier; private final int maxFindTxs; private final int maxRequestList; private final int maxGetTrytes; private final String[] features; //endregion //////////////////////////////////////////////////////////////////////////////////////////////////////// private final Gson gson = new GsonBuilder().create(); private volatile PearlDiver pearlDiver = new PearlDiver(); private final AtomicInteger counter = new AtomicInteger(0); private Pattern trytesPattern = Pattern.compile("[9A-Z]*"); //Package Private For Testing final Map<ApiCommand, Function<Map<String, Object>, AbstractResponse>> commandRoute; private RestConnector connector; private final ExecutorService tipSelExecService = Executors.newSingleThreadExecutor(r -> new Thread(r, "tip-selection")); /** * Starts loading the IOTA API, parameters do not have to be initialized. * * @param configuration Holds IRI configuration parameters. * @param ixi If a command is not in the standard API, * we try to process it as a Nashorn JavaScript module through {@link IXI} * @param transactionRequester Service where transactions get requested * @param spentAddressesService Service to check if addresses are spent * @param tangle The transaction storage * @param bundleValidator Validates bundles * @param snapshotProvider Manager of our currently taken snapshots * @param ledgerService contains all the relevant business logic for modifying and calculating the ledger state. * @param neighborRouter Handles and manages neighbors * @param tipsSelector Handles logic for selecting tips based on other transactions * @param tipsViewModel Contains the current tips of this node * @param transactionValidator Validates transactions * @param milestoneSolidifier Service that tracks the latest milestone * @param txPipeline Network service for routing transaction requests and broadcasts * @param transactionSolidifier Holds transaction pipeline, including broadcast transactions * */ public API(IotaConfig configuration, IXI ixi, TransactionRequester transactionRequester, SpentAddressesService spentAddressesService, Tangle tangle, BundleValidator bundleValidator, SnapshotProvider snapshotProvider, LedgerService ledgerService, NeighborRouter neighborRouter, TipSelector tipsSelector, TipsViewModel tipsViewModel, TransactionValidator transactionValidator, MilestoneSolidifier milestoneSolidifier, TransactionProcessingPipeline txPipeline, TransactionSolidifier transactionSolidifier) { this.configuration = configuration; this.ixi = ixi; this.transactionRequester = transactionRequester; this.spentAddressesService = spentAddressesService; this.tangle = tangle; this.bundleValidator = bundleValidator; this.snapshotProvider = snapshotProvider; this.ledgerService = ledgerService; this.neighborRouter = neighborRouter; this.txPipeline = txPipeline; this.tipsSelector = tipsSelector; this.tipsViewModel = tipsViewModel; this.transactionValidator = transactionValidator; this.transactionSolidifier = transactionSolidifier; this.milestoneSolidifier = milestoneSolidifier; maxFindTxs = configuration.getMaxFindTransactions(); maxRequestList = configuration.getMaxRequestsList(); maxGetTrytes = configuration.getMaxGetTrytes(); features = Feature.calculateFeatureNames(configuration); commandRoute = new HashMap<>(); commandRoute.put(ApiCommand.ADD_NEIGHBORS, addNeighbors()); commandRoute.put(ApiCommand.ATTACH_TO_TANGLE, attachToTangle()); commandRoute.put(ApiCommand.BROADCAST_TRANSACTIONs, broadcastTransactions()); commandRoute.put(ApiCommand.FIND_TRANSACTIONS, findTransactions()); commandRoute.put(ApiCommand.GET_BALANCES, getBalances()); commandRoute.put(ApiCommand.GET_INCLUSION_STATES, getInclusionStates()); commandRoute.put(ApiCommand.GET_NEIGHBORS, getNeighbors()); commandRoute.put(ApiCommand.GET_NODE_INFO, getNodeInfo()); commandRoute.put(ApiCommand.GET_NODE_API_CONFIG, getNodeAPIConfiguration()); commandRoute.put(ApiCommand.GET_TRANSACTIONS_TO_APPROVE, getTransactionsToApprove()); commandRoute.put(ApiCommand.GET_TRYTES, getTrytes()); commandRoute.put(ApiCommand.INTERRUPT_ATTACHING_TO_TANGLE, interruptAttachingToTangle()); commandRoute.put(ApiCommand.REMOVE_NEIGHBORS, removeNeighbors()); commandRoute.put(ApiCommand.STORE_TRANSACTIONS, storeTransactions()); commandRoute.put(ApiCommand.GET_MISSING_TRANSACTIONS, getMissingTransactions()); commandRoute.put(ApiCommand.CHECK_CONSISTENCY, checkConsistency()); commandRoute.put(ApiCommand.WERE_ADDRESSES_SPENT_FROM, wereAddressesSpentFrom()); } /** * Initializes the API for usage. * Will initialize and start the supplied {@link RestConnector} * * @param connector THe connector we use to handle API requests */ public void init(RestConnector connector){ this.connector = connector; connector.init(this::process); connector.start(); } /** * Handles an API request body. * Its returned {@link AbstractResponse} is created using the following logic * <ul> * <li> * {@link ExceptionResponse} if the body cannot be parsed. * </li> * <li> * {@link ErrorResponse} if the body does not contain a '<tt>command</tt>' section. * </li> * <li> * {@link AccessLimitedResponse} if the command is not allowed on this node. * </li> * <li> * {@link ErrorResponse} if the command contains invalid parameters. * </li> * <li> * {@link ExceptionResponse} if we encountered an unexpected exception during command processing. * </li> * <li> * {@link AbstractResponse} when the command is successfully processed. * The response class depends on the command executed. * </li> * </ul> * * @param requestString The JSON encoded data of the request. * This String is attempted to be converted into a {@code Map<String, Object>}. * @param netAddress The address from the sender of this API request. * @return The result of this request. * @throws UnsupportedEncodingException If the requestString cannot be parsed into a Map. * Currently caught and turned into a {@link ExceptionResponse}. */ private AbstractResponse process(final String requestString, InetAddress netAddress){ try { // Request JSON data into map Map<String, Object> request; try { request = gson.fromJson(requestString, Map.class); } catch (JsonSyntaxException jsonSyntaxException) { return ErrorResponse.create("Invalid JSON syntax: " + jsonSyntaxException.getMessage()); } if (request == null) { return ErrorResponse.create("Invalid request payload: '" + requestString + "'"); } // Did the requester ask for a command? final String command = (String) request.get("command"); if (command == null) { return ErrorResponse.create("COMMAND parameter has not been specified in the request."); } // Is this command allowed to be run from this request address? // We check the remote limit API configuration. if (configuration.getRemoteLimitApi().contains(command) && !configuration.getRemoteTrustedApiHosts().contains(netAddress)) { return AccessLimitedResponse.create("COMMAND " + command + " is not available on this node"); } log.debug("# {} -> Requesting command '{}'", counter.incrementAndGet(), command); ApiCommand apiCommand = ApiCommand.findByName(command); if (apiCommand != null) { return commandRoute.get(apiCommand).apply(request); } else { AbstractResponse response = ixi.processCommand(command, request); if (response == null) { return ErrorResponse.create("Command [" + command + "] is unknown"); } else { return response; } } } catch (ValidationException e) { log.error("API Validation failed: " + e.getLocalizedMessage()); return ExceptionResponse.create(e.getLocalizedMessage()); } catch (IllegalStateException e) { log.error("API Exception: " + e.getLocalizedMessage()); return ExceptionResponse.create(e.getLocalizedMessage()); } catch (RuntimeException e) { log.error("Unexpected API Exception: " + e.getLocalizedMessage()); return ExceptionResponse.create(e.getLocalizedMessage()); } } /** * Check if a list of addresses was ever spent from, in the current epoch, or in previous epochs. * If an address has a pending transaction, it is also marked as spend. * * @param addresses List of addresses to check if they were ever spent from. * @return {@link com.iota.iri.service.dto.WereAddressesSpentFrom} **/ @Document(name="wereAddressesSpentFrom") private AbstractResponse wereAddressesSpentFromStatement(List<String> addresses) throws Exception { final List<Hash> addressesHash = addresses.stream() .map(HashFactory.ADDRESS::create) .collect(Collectors.toList()); final boolean[] states = new boolean[addressesHash.size()]; int index = 0; for (Hash address : addressesHash) { states[index++] = spentAddressesService.wasAddressSpentFrom(address); } return WereAddressesSpentFrom.create(states); } /** * Walks back from the hash until a tail transaction has been found or transaction aprovee is not found. * A tail transaction is the first transaction in a bundle, thus with <code>index = 0</code> * * @param hash The transaction hash where we start the search from. If this is a tail, its hash is returned. * @return The transaction hash of the tail * @throws Exception When a model could not be loaded. */ private Hash findTail(Hash hash) throws Exception { TransactionViewModel tx = TransactionViewModel.fromHash(tangle, hash); final Hash bundleHash = tx.getBundleHash(); long index = tx.getCurrentIndex(); boolean foundApprovee = false; // As long as the index is bigger than 0 and we are still traversing the same bundle // If the hash we asked about is already a tail, this loop never starts while (index-- > 0 && tx.getBundleHash().equals(bundleHash)) { Set<Hash> approvees = tx.getApprovers(tangle).getHashes(); for (Hash approvee : approvees) { TransactionViewModel nextTx = TransactionViewModel.fromHash(tangle, approvee); if (nextTx.getBundleHash().equals(bundleHash)) { tx = nextTx; foundApprovee = true; break; } } if (!foundApprovee) { break; } } if (tx.getCurrentIndex() == 0) { return tx.getHash(); } return null; } /** * * Check the consistency of the transactions. * A consistent transaction is one where the following statements are true: * <ul> * <li>Valid bundle</li> * <li>The transaction is not missing a reference transaction</li> * <li>Tails of tails are valid</li> * </ul> * <p> * If a transaction does not exist, or it is not a tail, an {@link ErrorResponse} is returned. * * @param transactionsList Transactions you want to check the consistency for * @return {@link CheckConsistency} **/ @Document(name="checkConsistency") private AbstractResponse checkConsistencyStatement(List<String> transactionsList) throws Exception { final List<Hash> transactions = transactionsList.stream().map(HashFactory.TRANSACTION::create).collect(Collectors.toList()); boolean state = true; String info = ""; // Check if the transactions themselves are valid for (Hash transaction : transactions) { TransactionViewModel txVM = TransactionViewModel.fromHash(tangle, transaction); if (txVM.getType() == TransactionViewModel.PREFILLED_SLOT) { return ErrorResponse.create("Invalid transaction, missing: " + transaction); } if (txVM.getCurrentIndex() != 0) { return ErrorResponse.create("Invalid transaction, not a tail: " + transaction); } if (!txVM.isSolid()) { state = false; info = "tails are not solid (missing a referenced tx): " + transaction; break; } else { if (bundleValidator .validate(tangle, true, snapshotProvider.getInitialSnapshot(), txVM.getHash()) .isEmpty()) { state = false; info = "tails are not consistent (bundle is invalid): " + transaction; break; } } } // Transactions are valid, lets check ledger consistency if (state) { snapshotProvider.getLatestSnapshot().lockRead(); try { WalkValidatorImpl walkValidator = new WalkValidatorImpl(tangle, snapshotProvider, ledgerService, configuration); for (Hash transaction : transactions) { if (!walkValidator.isValid(transaction)) { state = false; info = "tails are not consistent (would lead to inconsistent ledger state or below max depth)"; break; } } } finally { snapshotProvider.getLatestSnapshot().unlockRead(); } } return CheckConsistency.create(state, info); } /** * Checks whether the node is synchronized by comparing the latest known milestone index against the current * latest solid milestone index. We allow for max. one milestone delta as a headroom, as a milestone is * only applied in a set interval to the current ledger state. * * @return true if the node is synced, false if not */ private boolean isNodeSynchronized() { return (snapshotProvider.getLatestSnapshot().getIndex() != snapshotProvider.getInitialSnapshot().getIndex()) && snapshotProvider.getLatestSnapshot().getIndex() >= milestoneSolidifier.getLatestMilestoneIndex() -1; } /** * Returns an IRI node's neighbors, as well as their activity. * <b>Note:</b> The activity counters are reset after restarting IRI. * * @return {@link com.iota.iri.service.dto.GetNeighborsResponse} **/ @Document(name="getNeighbors") private AbstractResponse getNeighborsStatement() { return GetNeighborsResponse.create(neighborRouter.getNeighbors()); } /** * Temporarily add a list of neighbors to your node. * The added neighbors will not be available after restart. * Add the neighbors to your config file * or supply them in the <tt>-n</tt> command line option if you want to add them permanently. * <p> * The URI (Unique Resource Identification) for adding neighbors is: * <b>tcp://IPADDRESS:PORT</b> * * @param uris list of neighbors to add * @return {@link com.iota.iri.service.dto.AddedNeighborsResponse} **/ @Document(name="addNeighbors") private AbstractResponse addNeighborsStatement(List<String> uris) { int numberOfAddedNeighbors = 0; for (final String uriStr : uris) { switch (neighborRouter.addNeighbor(uriStr)) { case OK: log.info("Added neighbor: {}", uriStr); numberOfAddedNeighbors++; break; case URI_INVALID: log.info("Can't add neighbor {}: URI is invalid", uriStr); break; case SLOTS_FILLED: log.info("Can't add neighbor {}: no more slots available for new neighbors", uriStr); break; default: // do nothing } } return AddedNeighborsResponse.create(numberOfAddedNeighbors); } /** * Temporarily removes a list of neighbors from your node. * The added neighbors will be added again after relaunching IRI. * Remove the neighbors from your config file or make sure you don't supply them in the -n command line option if you want to keep them removed after restart. * * The URI (Unique Resource Identification) for removing neighbors is: * <b>udp://IPADDRESS:PORT</b> * * Returns an {@link com.iota.iri.service.dto.ErrorResponse} if the URI scheme is wrong * * @param uris The URIs of the neighbors we want to remove. * @return {@link com.iota.iri.service.dto.RemoveNeighborsResponse} **/ @Document(name="removeNeighbors") private AbstractResponse removeNeighborsStatement(List<String> uris) { int numberOfRemovedNeighbors = 0; for (final String uriString : uris) { log.info("Removing neighbor: " + uriString); switch(neighborRouter.removeNeighbor(uriString)){ case OK: log.info("Removed neighbor: {}", uriString); numberOfRemovedNeighbors++; break; case URI_INVALID: log.info("Can't remove neighbor {}: URI is invalid", uriString); break; case UNRESOLVED_DOMAIN: log.info("Can't remove neighbor {}: domain couldn't be resolved to its IP address", uriString); break; case UNKNOWN_NEIGHBOR: log.info("Can't remove neighbor {}: neighbor is unknown", uriString); break; default: // do nothing } } return RemoveNeighborsResponse.create(numberOfRemovedNeighbors); } /** * Returns raw transaction data (trytes) of a specific transaction. * These trytes can then be converted into the actual transaction object. * See utility and {@link Transaction} functions in an IOTA library for more details. * * @param hashes The transaction hashes you want to get trytes from. * @return {@link com.iota.iri.service.dto.GetTrytesResponse} **/ @Document(name="getTrytes") private synchronized AbstractResponse getTrytesStatement(List<String> hashes) throws Exception { final List<String> elements = new LinkedList<>(); for (final String hash : hashes) { final TransactionViewModel transactionViewModel = TransactionViewModel.fromHash(tangle, HashFactory.TRANSACTION.create(hash)); if (transactionViewModel != null) { elements.add(Converter.trytes(transactionViewModel.trits())); } else { elements.add(null); } } if (elements.size() > maxGetTrytes){ return ErrorResponse.create(OVER_MAX_ERROR_MESSAGE); } return GetTrytesResponse.create(elements); } /** * Can be 0 or more, and is set to 0 every 100 requests. * Each increase indicates another 2 tips send. * * @return The current amount of times this node has returned transactions to approve */ public static int getCounterGetTxToApprove() { return counterGetTxToApprove; } /** * Increases the amount of tips send for transactions to approve by one */ private static void incCounterGetTxToApprove() { counterGetTxToApprove++; } /** * Can be 0 or more, and is set to 0 every 100 requests. * * @return The current amount of time spent on sending transactions to approve in milliseconds */ private static long getEllapsedTimeGetTxToApprove() { return ellapsedTime_getTxToApprove; } /** * Increases the current amount of time spent on sending transactions to approve * * @param ellapsedTime the time to add, in milliseconds */ private static void incEllapsedTimeGetTxToApprove(long ellapsedTime) { ellapsedTime_getTxToApprove += ellapsedTime; } /** * Tip selection which returns <tt>trunkTransaction</tt> and <tt>branchTransaction</tt>. * The input value <tt>depth</tt> determines how many milestones to go back for finding the transactions to approve. * The higher your <tt>depth</tt> value, the more work you have to do as you are confirming more transactions. * If the <tt>depth</tt> is too large (usually above 15, it depends on the node's configuration) an error will be returned. * The <tt>reference</tt> is an optional hash of a transaction you want to approve. * If it can't be found at the specified <tt>depth</tt> then an error will be returned. * * @param depth Number of bundles to go back to determine the transactions for approval. * @param reference Hash of transaction to start random-walk from, used to make sure the tips returned reference a given transaction in their past. * @return {@link com.iota.iri.service.dto.GetTransactionsToApproveResponse} **/ @Document(name="getTransactionsToApprove") private synchronized AbstractResponse getTransactionsToApproveStatement(int depth, Optional<Hash> reference) { if (depth < 0 || depth > configuration.getMaxDepth()) { return ErrorResponse.create("Invalid depth input"); } try { List<Hash> tips = getTransactionToApproveTips(depth, reference); return GetTransactionsToApproveResponse.create(tips.get(0), tips.get(1)); } catch (Exception e) { log.info("Tip selection failed: " + e.getLocalizedMessage()); return ErrorResponse.create(e.getLocalizedMessage()); } } /** * Gets tips which can be used by new transactions to approve. * If debug is enabled, statistics on tip selection will be gathered. * * @param depth The milestone depth for finding the transactions to approve. * @param reference An optional transaction hash to be referenced by tips. * @return The tips which can be approved. * @throws Exception if the subtangle is out of date or if we fail to retrieve transaction tips. * @see TipSelector */ List<Hash> getTransactionToApproveTips(int depth, Optional<Hash> reference) throws Exception { if (!isNodeSynchronized()) { throw new IllegalStateException(INVALID_SUBTANGLE); } Future<List<Hash>> tipSelection = null; List<Hash> tips; try { tipSelection = tipSelExecService.submit(() -> tipsSelector.getTransactionsToApprove(depth, reference)); tips = tipSelection.get(configuration.getTipSelectionTimeoutSec(), TimeUnit.SECONDS); } catch (TimeoutException ex) { // interrupt the tip-selection thread so that it aborts tipSelection.cancel(true); throw new TipSelectionCancelledException(String.format("tip-selection exceeded timeout of %d seconds", configuration.getTipSelectionTimeoutSec())); } if (log.isDebugEnabled()) { gatherStatisticsOnTipSelection(); } return tips; } /** * <p> * Handles statistics on tip selection. * Increases the tip selection by one use. * </p> * <p> * If the {@link #getCounterGetTxToApprove()} is a power of 100, a log is send and counters are reset. * </p> */ private void gatherStatisticsOnTipSelection() { API.incCounterGetTxToApprove(); if ((getCounterGetTxToApprove() % 100) == 0) { String sb = "Last 100 getTxToApprove consumed " + API.getEllapsedTimeGetTxToApprove() / 1000000000L + " seconds processing time."; log.debug(sb); counterGetTxToApprove = 0; ellapsedTime_getTxToApprove = 0L; } } /** * Stores transactions in the local storage. * The trytes to be used for this call should be valid, attached transaction trytes. * These trytes are returned by <tt>attachToTangle</tt>, or by doing proof of work somewhere else. * * @param trytes Transaction data to be stored. * @return {@link com.iota.iri.service.dto.AbstractResponse.Emptyness} * @throws Exception When storing or updating a transaction fails. **/ @Document(name="storeTransactions") public AbstractResponse storeTransactionsStatement(List<String> trytes) throws Exception { final List<TransactionViewModel> elements = convertTrytes(trytes); for (final TransactionViewModel transactionViewModel : elements) { //store transactions if(transactionViewModel.store(tangle, snapshotProvider.getInitialSnapshot())) { transactionViewModel.setArrivalTime(System.currentTimeMillis()); transactionSolidifier.updateStatus(transactionViewModel); transactionViewModel.updateSender("local"); transactionViewModel.update(tangle, snapshotProvider.getInitialSnapshot(), "sender"); } } return AbstractResponse.createEmptyResponse(); } /** * Interrupts and completely aborts the <tt>attachToTangle</tt> process. * * @return {@link com.iota.iri.service.dto.AbstractResponse.Emptyness} **/ @Document(name="interruptAttachingToTangle") private AbstractResponse interruptAttachingToTangleStatement(){ pearlDiver.cancel(); return AbstractResponse.createEmptyResponse(); } /** * Returns information about this node. * * @return {@link com.iota.iri.service.dto.GetNodeInfoResponse} * @throws Exception When we cant find the first milestone in the database **/ @Document(name="getNodeInfo") private AbstractResponse getNodeInfoStatement() throws Exception{ String name = configuration.isTestnet() ? IRI.TESTNET_NAME : IRI.MAINNET_NAME; MilestoneViewModel milestone = MilestoneViewModel.first(tangle); return GetNodeInfoResponse.create( name, IotaUtils.getIriVersion(), Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().freeMemory(), System.getProperty("java.version"), Runtime.getRuntime().maxMemory(), Runtime.getRuntime().totalMemory(), milestoneSolidifier.getLatestMilestoneHash(), milestoneSolidifier.getLatestMilestoneIndex(), snapshotProvider.getLatestSnapshot().getHash(), snapshotProvider.getLatestSnapshot().getIndex(), milestone != null ? milestone.index() : -1, snapshotProvider.getLatestSnapshot().getInitialIndex(), neighborRouter.getConnectedNeighbors().size(), txPipeline.getBroadcastStageQueue().size(), System.currentTimeMillis(), tipsViewModel.size(), transactionRequester.numberOfTransactionsToRequest(), features, configuration.getCoordinator().toString(), tangle.getPersistanceSize()); } /** * Returns information about this node configuration. * * @return {@link GetNodeAPIConfigurationResponse} */ private AbstractResponse getNodeAPIConfigurationStatement() { return GetNodeAPIConfigurationResponse.create(configuration); } /** * <p> * Get the inclusion states of a set of transactions. * This endpoint determines if a transaction is confirmed by the network (referenced by a valid milestone). * </p> * <p> * This API call returns a list of boolean values in the same order as the submitted transactions. * Boolean values will be <tt>true</tt> for confirmed transactions, otherwise <tt>false</tt>. * </p> * * @param transactions List of transactions you want to get the inclusion state for. * @return {@link com.iota.iri.service.dto.GetInclusionStatesResponse} * @throws Exception When a transaction cannot be loaded from hash **/ @Document(name="getInclusionStates") private AbstractResponse getInclusionStatesStatement(final List<String> transactions ) throws Exception { final List<Hash> trans = transactions.stream() .map(HashFactory.TRANSACTION::create) .collect(Collectors.toList()); boolean[] inclusionStates = new boolean[trans.size()]; for(int i = 0; i < trans.size(); i++){ inclusionStates[i] = TransactionViewModel.fromHash(tangle, trans.get(i)).snapshotIndex() > 0; } return GetInclusionStatesResponse.create(inclusionStates); } /** * Traverses down the tips until all transactions we wish to validate have been found or transaction data is missing. * * @param nonAnalyzedTransactions Tips we will analyze. * @param analyzedTips The hashes of tips we have analyzed. * Hashes specified here won't be analyzed again. * @param transactions All transactions we are validating. * @param inclusionStates The state of each transaction. * 1 means confirmed, -1 means unconfirmed, 0 is unknown confirmation. * Should be of equal length as <tt>transactions</tt>. * @param count The amount of transactions on the same index level as <tt>nonAnalyzedTransactions</tt>. * @param index The snapshot index of the tips in <tt>nonAnalyzedTransactions</tt>. * @return <tt>true</tt> if all <tt>transactions</tt> are directly or indirectly references by * <tt>nonAnalyzedTransactions</tt>. * If at some point we are missing transaction data <tt>false</tt> is returned immediately. * @throws Exception If a {@link TransactionViewModel} cannot be loaded. */ private boolean exhaustiveSearchWithinIndex( Queue<Hash> nonAnalyzedTransactions, Set<Hash> analyzedTips, List<Hash> transactions, byte[] inclusionStates, int count, int index) throws Exception { Hash pointer; MAIN_LOOP: // While we have nonAnalyzedTransactions in the Queue while ((pointer = nonAnalyzedTransactions.poll()) != null) { // Only analyze tips we haven't analyzed yet if (analyzedTips.add(pointer)) { // Check if the transactions have indeed this index. Otherwise ignore. // Starts off with the tips in nonAnalyzedTransactions, but transaction trunk & branch gets added. final TransactionViewModel transactionViewModel = TransactionViewModel.fromHash(tangle, pointer); if (transactionViewModel.snapshotIndex() == index) { // Do we have the complete transaction? if (transactionViewModel.getType() == TransactionViewModel.PREFILLED_SLOT) { // Incomplete transaction data, stop search. return false; } else { // check all transactions we wish to verify confirmation for for (int i = 0; i < inclusionStates.length; i++) { if (inclusionStates[i] < 1 && pointer.equals(transactions.get(i))) { // A tip, or its branch/trunk points to this transaction. // That means this transaction is confirmed by this tip. inclusionStates[i] = 1; // Only stop search when we have found all transactions we were looking for if (--count <= 0) { break MAIN_LOOP; } } } // Add trunk and branch to the queue for the transaction confirmation check nonAnalyzedTransactions.offer(transactionViewModel.getTrunkTransactionHash()); nonAnalyzedTransactions.offer(transactionViewModel.getBranchTransactionHash()); } } } } return true; } /** * <p> * Find transactions that contain the given values in their transaction fields. * All input values are lists, for which a list of return values (transaction hashes), in the same order, is returned for all individual elements. * The input fields can either be <tt>bundles</tt>, <tt>addresses</tt>, <tt>tags</tt> or <tt>approvees</tt>. * </p> * * <b>Using multiple transaction fields returns transactions hashes at the intersection of those values.</b> * * @param request The map with input fields * Must contain at least one of 'bundles', 'addresses', 'tags' or 'approvees'. * @return {@link com.iota.iri.service.dto.FindTransactionsResponse}. * @throws Exception If a model cannot be loaded, no valid input fields were supplied * or the total transactions to find exceeds {@link APIConfig#getMaxFindTransactions()}. **/ @Document(name="findTransactions") private synchronized AbstractResponse findTransactionsStatement(final Map<String, Object> request) throws Exception { final Set<Hash> foundTransactions = new HashSet<>(); boolean containsKey = false; final Set<Hash> bundlesTransactions = new HashSet<>(); if (request.containsKey("bundles")) { final Set<String> bundles = getParameterAsSet(request, "bundles", HASH_SIZE); for (final String bundle : bundles) { bundlesTransactions.addAll( BundleViewModel.load(tangle, HashFactory.BUNDLE.create(bundle)) .getHashes()); } foundTransactions.addAll(bundlesTransactions); containsKey = true; } final Set<Hash> addressesTransactions = new HashSet<>(); if (request.containsKey("addresses")) { final Set<String> addresses = getParameterAsSet(request, "addresses", HASH_SIZE); for (final String address : addresses) { addressesTransactions.addAll( AddressViewModel.load(tangle, HashFactory.ADDRESS.create(address)) .getHashes()); } foundTransactions.addAll(addressesTransactions); containsKey = true; } final Set<Hash> tagsTransactions = new HashSet<>(); if (request.containsKey("tags")) { final Set<String> tags = getParameterAsSet(request, "tags", 0); for (String tag : tags) { tag = padTag(tag); tagsTransactions.addAll( TagViewModel.load(tangle, HashFactory.TAG.create(tag)) .getHashes()); } if (tagsTransactions.isEmpty()) { for (String tag : tags) { tag = padTag(tag); tagsTransactions.addAll( TagViewModel.loadObsolete(tangle, HashFactory.OBSOLETETAG.create(tag)) .getHashes()); } } foundTransactions.addAll(tagsTransactions); containsKey = true; } final Set<Hash> approveeTransactions = new HashSet<>(); if (request.containsKey("approvees")) { final Set<String> approvees = getParameterAsSet(request, "approvees", HASH_SIZE); for (final String approvee : approvees) { approveeTransactions.addAll( TransactionViewModel.fromHash(tangle, HashFactory.TRANSACTION.create(approvee)) .getApprovers(tangle) .getHashes()); } foundTransactions.addAll(approveeTransactions); containsKey = true; } if (!containsKey) { throw new ValidationException(INVALID_PARAMS); } //Using multiple of these input fields returns the intersection of the values. if (request.containsKey("bundles")) { foundTransactions.retainAll(bundlesTransactions); } if (request.containsKey("addresses")) { foundTransactions.retainAll(addressesTransactions); } if (request.containsKey("tags")) { foundTransactions.retainAll(tagsTransactions); } if (request.containsKey("approvees")) { foundTransactions.retainAll(approveeTransactions); } if (foundTransactions.size() > maxFindTxs){ return ErrorResponse.create(OVER_MAX_ERROR_MESSAGE); } final List<String> elements = foundTransactions.stream() .map(Hash::toString) .collect(Collectors.toCollection(LinkedList::new)); return FindTransactionsResponse.create(elements); } /** * Adds '9' until the String is of {@link #HASH_SIZE} length. * * @param tag The String to fill. * @return The updated * @throws ValidationException If the <tt>tag</tt> is a {@link Hash#NULL_HASH}. */ private String padTag(String tag) throws ValidationException { while (tag.length() < HASH_SIZE) { tag += Converter.TRYTE_ALPHABET.charAt(0); } if (tag.equals(Hash.NULL_HASH.toString())) { throw new ValidationException("Invalid tag input"); } return tag; } /** * Runs {@link #getParameterAsList(Map, String, int)} and transforms it into a {@link Set}. * * @param request All request parameters. * @param paramName The name of the parameter we want to turn into a list of Strings. * @param size the length each String must have. * @return the list of valid Tryte Strings. * @throws ValidationException If the requested parameter does not exist or * the string is not exactly trytes of <tt>size</tt> length or * the amount of Strings in the list exceeds {@link APIConfig#getMaxRequestsList} */ private Set<String> getParameterAsSet( Map<String, Object> request, String paramName, int size) throws ValidationException { HashSet<String> result = getParameterAsList(request, paramName, size) .stream() .collect(Collectors.toCollection(HashSet::new)); if (result.contains(Hash.NULL_HASH.toString())) { throw new ValidationException("Invalid " + paramName + " input"); } return result; } /** * Broadcast a list of transactions to all neighbors. * The trytes to be used for this call should be valid, attached transaction trytes. * These trytes are returned by <tt>attachToTangle</tt>, or by doing proof of work somewhere else. * * @param trytes the list of transaction trytes to broadcast * @return {@link com.iota.iri.service.dto.AbstractResponse.Emptyness} **/ @Document(name="broadcastTransactions") public AbstractResponse broadcastTransactionsStatement(List<String> trytes) { for (final String tryte : trytes) { byte[] txTrits = Converter.allocateTritsForTrytes(TRYTES_SIZE); Converter.trits(tryte, txTrits, 0); txPipeline.process(txTrits); } return AbstractResponse.createEmptyResponse(); } /** * <p> * Calculates the confirmed balance, as viewed by the specified <tt>tips</tt>. * If the <tt>tips</tt> parameter is missing, the returned balance is correct as of the latest confirmed milestone. * In addition to the balances, it also returns the referencing <tt>tips</tt> (or milestone), * as well as the index with which the confirmed balance was determined. * The balances are returned as a list in the same order as the addresses were provided as input. * </p> * * @param addresses Address for which to get the balance (do not include the checksum) * @param tips The optional tips to find the balance through. * @return {@link com.iota.iri.service.dto.GetBalancesResponse} * @throws Exception When the database has encountered an error **/ @Document(name="getBalances") private AbstractResponse getBalancesStatement(List<String> addresses, List<String> tips) throws Exception { final List<Hash> addressList = addresses.stream() .map(address -> (HashFactory.ADDRESS.create(address))) .collect(Collectors.toCollection(LinkedList::new)); List<Hash> hashes; final Map<Hash, Long> balances = new HashMap<>(); snapshotProvider.getLatestSnapshot().lockRead(); final int index = snapshotProvider.getLatestSnapshot().getIndex(); if (tips == null || tips.isEmpty()) { hashes = Collections.singletonList(snapshotProvider.getLatestSnapshot().getHash()); } else { hashes = tips.stream() .map(tip -> (HashFactory.TRANSACTION.create(tip))) .collect(Collectors.toCollection(LinkedList::new)); } try { // Get the balance for each address at the last snapshot for (final Hash address : addressList) { Long value = snapshotProvider.getLatestSnapshot().getBalance(address); if (value == null) { value = 0L; } balances.put(address, value); } final Set<Hash> visitedHashes = new HashSet<>(); final Map<Hash, Long> diff = new HashMap<>(); // Calculate the difference created by the non-verified transactions which tips approve. // This difference is put in a map with address -> value changed for (Hash tip : hashes) { if (!TransactionViewModel.exists(tangle, tip)) { return ErrorResponse.create("Tip not found: " + tip.toString()); } if (!ledgerService.isBalanceDiffConsistent(visitedHashes, diff, tip)) { return ErrorResponse.create("Tips are not consistent"); } } // Update the found balance according to 'diffs' balance changes diff.forEach((key, value) -> balances.computeIfPresent(key, (hash, aLong) -> value + aLong)); } finally { snapshotProvider.getLatestSnapshot().unlockRead(); } final List<String> elements = addressList.stream() .map(address -> balances.get(address).toString()) .collect(Collectors.toCollection(LinkedList::new)); return GetBalancesResponse.create(elements, hashes.stream() .map(h -> h.toString()) .collect(Collectors.toList()), index); } /** * Can be 0 or more, and is set to 0 every 100 requests. * Each increase indicates another 2 tips sent. * * @return The current amount of times this node has done proof of work. * Doesn't distinguish between remote and local proof of work. */ public static int getCounterPoW() { return counter_PoW; } /** * Increases the amount of times this node has done proof of work by one. */ public static void incCounterPoW() { API.counter_PoW++; } /** * Can be 0 or more, and is set to 0 every 100 requests. * * @return The current amount of time spent on doing proof of work in milliseconds. * Doesn't distinguish between remote and local proof of work. */ public static long getEllapsedTimePoW() { return ellapsedTime_PoW; } /** * Increases the current amount of time spent on doing proof of work. * * @param ellapsedTime the time to add, in milliseconds. */ public static void incEllapsedTimePoW(long ellapsedTime) { ellapsedTime_PoW += ellapsedTime; } /** * <p> * Prepares the specified transactions (trytes) for attachment to the Tangle by doing Proof of Work. * You need to supply <tt>branchTransaction</tt> as well as <tt>trunkTransaction</tt>. * These are the tips which you're going to validate and reference with this transaction. * These are obtainable by the <tt>getTransactionsToApprove</tt> API call. * </p> * <p> * The returned value is a different set of tryte values which you can input into * <tt>broadcastTransactions</tt> and <tt>storeTransactions</tt>. * The last 243 trytes of the return value consist of the following: * <ul> * <li><code>trunkTransaction</code></li> * <li><code>branchTransaction</code></li> * <li><code>nonce</code></li> * </ul> * </p> * These are valid trytes which are then accepted by the network. * @param trunkTransaction A reference to an external transaction (tip) used as trunk. * The transaction with index 0 will have this tip in its trunk. * All other transactions reference the previous transaction in the bundle (Their index-1). * * @param branchTransaction A reference to an external transaction (tip) used as branch. * Each Transaction in the bundle will have this tip as their branch, except the last. * The last one will have the branch in its trunk. * @param minWeightMagnitude The amount of work we should do to confirm this transaction. * Each 0-trit on the end of the transaction represents 1 magnitude. * A 9-tryte represents 3 magnitudes, since a 9 is represented by 3 0-trits. * Transactions with a different minWeightMagnitude are compatible. * @param trytes The list of trytes to prepare for network attachment, by doing proof of work. * @return The list of transactions in trytes, ready to be broadcast to the network. **/ @Document(name="attachToTangle", returnParam="trytes") public synchronized List<String> attachToTangleStatement(Hash trunkTransaction, Hash branchTransaction, int minWeightMagnitude, List<String> trytes) { final List<TransactionViewModel> transactionViewModels = new LinkedList<>(); Hash prevTransaction = null; pearlDiver = new PearlDiver(); byte[] transactionTrits = Converter.allocateTritsForTrytes(TRYTES_SIZE); trytes.sort(new TryteIndexComparator().reversed()); for (final String tryte : trytes) { long startTime = System.nanoTime(); long timestamp = System.currentTimeMillis(); try { Converter.trits(tryte, transactionTrits, 0); //branch and trunk System.arraycopy((prevTransaction == null ? trunkTransaction : prevTransaction).trits(), 0, transactionTrits, TransactionViewModel.TRUNK_TRANSACTION_TRINARY_OFFSET, TransactionViewModel.TRUNK_TRANSACTION_TRINARY_SIZE); System.arraycopy((prevTransaction == null ? branchTransaction : trunkTransaction).trits(), 0, transactionTrits, TransactionViewModel.BRANCH_TRANSACTION_TRINARY_OFFSET, TransactionViewModel.BRANCH_TRANSACTION_TRINARY_SIZE); //attachment fields: tag and timestamps //tag - copy the obsolete tag to the attachment tag field only if tag isn't set. if (IntStream.range(TransactionViewModel.TAG_TRINARY_OFFSET, TransactionViewModel.TAG_TRINARY_OFFSET + TransactionViewModel.TAG_TRINARY_SIZE) .allMatch(idx -> transactionTrits[idx] == ((byte) 0))) { System.arraycopy(transactionTrits, TransactionViewModel.OBSOLETE_TAG_TRINARY_OFFSET, transactionTrits, TransactionViewModel.TAG_TRINARY_OFFSET, TransactionViewModel.TAG_TRINARY_SIZE); } Converter.copyTrits(timestamp, transactionTrits, TransactionViewModel.ATTACHMENT_TIMESTAMP_TRINARY_OFFSET, TransactionViewModel.ATTACHMENT_TIMESTAMP_TRINARY_SIZE); Converter.copyTrits(0, transactionTrits, TransactionViewModel.ATTACHMENT_TIMESTAMP_LOWER_BOUND_TRINARY_OFFSET, TransactionViewModel.ATTACHMENT_TIMESTAMP_LOWER_BOUND_TRINARY_SIZE); Converter.copyTrits(MAX_TIMESTAMP_VALUE, transactionTrits, TransactionViewModel.ATTACHMENT_TIMESTAMP_UPPER_BOUND_TRINARY_OFFSET, TransactionViewModel.ATTACHMENT_TIMESTAMP_UPPER_BOUND_TRINARY_SIZE); if (!pearlDiver.search(transactionTrits, minWeightMagnitude, configuration.getPowThreads())) { transactionViewModels.clear(); break; } //validate PoW - throws exception if invalid final TransactionViewModel transactionViewModel = transactionValidator.validateTrits( transactionTrits, transactionValidator.getMinWeightMagnitude()); transactionViewModels.add(transactionViewModel); prevTransaction = transactionViewModel.getHash(); } finally { API.incEllapsedTimePoW(System.nanoTime() - startTime); API.incCounterPoW(); if ((API.getCounterPoW() % 100) == 0) { String sb = "Last 100 PoW consumed " + API.getEllapsedTimePoW() / 1000000000L + " seconds processing time."; log.info(sb); counter_PoW = 0; ellapsedTime_PoW = 0L; } } } final List<String> elements = new LinkedList<>(); for (int i = transactionViewModels.size(); i-- > 0; ) { elements.add(Converter.trytes(transactionViewModels.get(i).trits())); } return elements; } /** * Transforms an object parameter into an int. * * @param request A map of all request parameters * @param paramName The parameter we want to get as an int. * @return The integer value of this parameter * @throws ValidationException If the requested parameter does not exist or cannot be transformed into an int. */ private int getParameterAsInt(Map<String, Object> request, String paramName) throws ValidationException { validateParamExists(request, paramName); int result; try { result = ((Double) request.get(paramName)).intValue(); } catch (ClassCastException e) { throw new ValidationException("Invalid " + paramName + " input"); } return result; } /** * Transforms an object parameter into a String. * * @param request A map of all request parameters * @param paramName The parameter we want to get as a String. * @param size The expected length of this String * @return The String value of this parameter * @throws ValidationException If the requested parameter does not exist or * the string is not exactly trytes of <tt>size</tt> length */ private String getParameterAsStringAndValidate(Map<String, Object> request, String paramName, int size) throws ValidationException { validateParamExists(request, paramName); String result = (String) request.get(paramName); validateTrytes(paramName, size, result); return result; } /** * Checks if a string is non 0 length, and contains exactly <tt>size</tt> amount of trytes. * Trytes are Strings containing only A-Z and the number 9. * * @param paramName The name of the parameter this String came from. * @param size The amount of trytes it should contain. * @param result The String we validate. * @throws ValidationException If the string is not exactly trytes of <tt>size</tt> length */ private void validateTrytes(String paramName, int size, String result) throws ValidationException { if (!validTrytes(result, size, ZERO_LENGTH_NOT_ALLOWED)) { throw new ValidationException("Invalid " + paramName + " input"); } } /** * Checks if a parameter exists in the map * * @param request All request parameters * @param paramName The name of the parameter we are looking for * @throws ValidationException if <tt>request</tt> does not contain <tt>paramName</tt> */ private void validateParamExists(Map<String, Object> request, String paramName) throws ValidationException { if (!request.containsKey(paramName)) { throw new ValidationException(INVALID_PARAMS); } } /** * Translates the parameter into a {@link List}. * We then validate if the amount of elements does not exceed the maximum allowed. * Afterwards we verify if each element is valid according to {@link #validateTrytes(String, int, String)}. * * @param request All request parameters * @param paramName The name of the parameter we want to turn into a list of Strings * @param size the length each String must have * @return the list of valid Tryte Strings. * @throws ValidationException If the requested parameter does not exist or * the string is not exactly trytes of <tt>size</tt> length or * the amount of Strings in the list exceeds {@link APIConfig#getMaxRequestsList} */ private List<String> getParameterAsList(Map<String, Object> request, String paramName, int size) throws ValidationException { validateParamExists(request, paramName); final List<String> paramList = (List<String>) request.get(paramName); if (paramList.size() > maxRequestList) { throw new ValidationException(OVER_MAX_ERROR_MESSAGE); } if (size > 0) { //validate for (final String param : paramList) { validateTrytes(paramName, size, param); } } return paramList; } /** * Checks if a string is of a certain length, and contains exactly <tt>size</tt> amount of trytes. * Trytes are Strings containing only A-Z and the number 9. * * @param trytes The String we validate. * @param length The amount of trytes it should contain. * @param zeroAllowed If set to '{@value #ZERO_LENGTH_ALLOWED}', an empty string is also valid. * @return <tt>true</tt> if the string is valid, otherwise <tt>false</tt> */ private boolean validTrytes(String trytes, int length, char zeroAllowed) { if (trytes.length() == 0 && zeroAllowed == ZERO_LENGTH_ALLOWED) { return true; } if (trytes.length() != length) { return false; } Matcher matcher = trytesPattern.matcher(trytes); return matcher.matches(); } /** * If a server is running, stops the server from accepting new incoming requests. * Does not remove the instance, so the server may be restarted without having to recreate it. */ public void shutDown() { tipSelExecService.shutdownNow(); if (connector != null) { connector.stop(); } } /** * <b>Only available on testnet.</b> * Creates, attaches, stores, and broadcasts a transaction with this message * * @param address The address to add the message to * @param message The message to store **/ private synchronized AbstractResponse storeMessageStatement(String address, String message) throws Exception { final List<Hash> txToApprove = getTransactionToApproveTips(3, Optional.empty()); final int txMessageSize = TransactionViewModel.SIGNATURE_MESSAGE_FRAGMENT_TRINARY_SIZE / 3; final int txCount = (message.length() + txMessageSize - 1) / txMessageSize; final byte[] timestampTrits = new byte[TransactionViewModel.TIMESTAMP_TRINARY_SIZE]; Converter.copyTrits(System.currentTimeMillis(), timestampTrits, 0, timestampTrits.length); final String timestampTrytes = StringUtils.rightPad( Converter.trytes(timestampTrits), timestampTrits.length / 3, '9'); final byte[] lastIndexTrits = new byte[TransactionViewModel.LAST_INDEX_TRINARY_SIZE]; byte[] currentIndexTrits = new byte[TransactionViewModel.CURRENT_INDEX_TRINARY_SIZE]; Converter.copyTrits(txCount - 1, lastIndexTrits, 0, lastIndexTrits.length); final String lastIndexTrytes = Converter.trytes(lastIndexTrits); List<String> transactions = new ArrayList<>(); for (int i = 0; i < txCount; i++) { String tx; if (i != txCount - 1) { tx = message.substring(i * txMessageSize, (i + 1) * txMessageSize); } else { tx = message.substring(i * txMessageSize); } Converter.copyTrits(i, currentIndexTrits, 0, currentIndexTrits.length); tx = StringUtils.rightPad(tx, txMessageSize, '9'); tx += address.substring(0, 81); // value tx += StringUtils.repeat('9', 27); // obsolete tag tx += StringUtils.repeat('9', 27); // timestamp tx += timestampTrytes; // current index tx += StringUtils.rightPad(Converter.trytes(currentIndexTrits), currentIndexTrits.length / 3, '9'); // last index tx += StringUtils.rightPad(lastIndexTrytes, lastIndexTrits.length / 3, '9'); transactions.add(tx); } // let's calculate the bundle essence :S int startIdx = TransactionViewModel.ESSENCE_TRINARY_OFFSET / 3; Sponge sponge = SpongeFactory.create(SpongeFactory.Mode.KERL); for (String tx : transactions) { String essence = tx.substring(startIdx); byte[] essenceTrits = new byte[essence.length() * Converter.NUMBER_OF_TRITS_IN_A_TRYTE]; Converter.trits(essence, essenceTrits, 0); sponge.absorb(essenceTrits, 0, essenceTrits.length); } byte[] essenceTrits = new byte[243]; sponge.squeeze(essenceTrits, 0, essenceTrits.length); final String bundleHash = Converter.trytes(essenceTrits, 0, essenceTrits.length); transactions = transactions.stream() .map(tx -> StringUtils.rightPad(tx + bundleHash, TRYTES_SIZE, '9')) .collect(Collectors.toList()); // do pow List<String> powResult = attachToTangleStatement(txToApprove.get(0), txToApprove.get(1), 9, transactions); storeTransactionsStatement(powResult); broadcastTransactionsStatement(powResult); return AbstractResponse.createEmptyResponse(); } // // FUNCTIONAL COMMAND ROUTES // private Function<Map<String, Object>, AbstractResponse> addNeighbors() { return request -> { List<String> uris = getParameterAsList(request,"uris",0); log.debug("Invoking 'addNeighbors' with {}", uris); return addNeighborsStatement(uris); }; } private Function<Map<String, Object>, AbstractResponse> attachToTangle() { return request -> { final Hash trunkTransaction = HashFactory.TRANSACTION.create(getParameterAsStringAndValidate(request,"trunkTransaction", HASH_SIZE)); final Hash branchTransaction = HashFactory.TRANSACTION.create(getParameterAsStringAndValidate(request,"branchTransaction", HASH_SIZE)); final int minWeightMagnitude = getParameterAsInt(request,"minWeightMagnitude"); final List<String> trytes = getParameterAsList(request,"trytes", TRYTES_SIZE); List<String> elements = attachToTangleStatement(trunkTransaction, branchTransaction, minWeightMagnitude, trytes); return AttachToTangleResponse.create(elements); }; } private Function<Map<String, Object>, AbstractResponse> broadcastTransactions() { return request -> { final List<String> trytes = getParameterAsList(request,"trytes", TRYTES_SIZE); broadcastTransactionsStatement(trytes); return AbstractResponse.createEmptyResponse(); }; } private Function<Map<String, Object>, AbstractResponse> findTransactions() { return request -> { try { return findTransactionsStatement(request); } catch (Exception e) { throw new IllegalStateException(e); } }; } private Function<Map<String, Object>, AbstractResponse> getBalances() { return request -> { final List<String> addresses = getParameterAsList(request,"addresses", HASH_SIZE); final List<String> tips = request.containsKey("tips") ? getParameterAsList(request,"tips", HASH_SIZE): null; try { return getBalancesStatement(addresses, tips); } catch (Exception e) { throw new IllegalStateException(e); } }; } private Function<Map<String, Object>, AbstractResponse> getInclusionStates() { return request -> { if (!isNodeSynchronized()) { return ErrorResponse.create(INVALID_SUBTANGLE); } final List<String> transactions = getParameterAsList(request, "transactions", HASH_SIZE); try { return getInclusionStatesStatement(transactions); } catch (Exception e) { throw new IllegalStateException(e); } }; } private Function<Map<String, Object>, AbstractResponse> getNeighbors() { return request -> getNeighborsStatement(); } private Function<Map<String, Object>, AbstractResponse> getNodeInfo() { return request -> { try { return getNodeInfoStatement(); } catch (Exception e) { throw new IllegalStateException(e); } }; } private Function<Map<String, Object>, AbstractResponse> getNodeAPIConfiguration() { return request -> getNodeAPIConfigurationStatement(); } private Function<Map<String, Object>, AbstractResponse> getTransactionsToApprove() { return request -> { Optional<Hash> reference = request.containsKey("reference") ? Optional.of(HashFactory.TRANSACTION.create(getParameterAsStringAndValidate(request,"reference", HASH_SIZE))) : Optional.empty(); int depth = getParameterAsInt(request, "depth"); return getTransactionsToApproveStatement(depth, reference); }; } private Function<Map<String, Object>, AbstractResponse> getTrytes() { return request -> { final List<String> hashes = getParameterAsList(request,"hashes", HASH_SIZE); try { return getTrytesStatement(hashes); } catch (Exception e) { throw new IllegalStateException(e); } }; } private Function<Map<String, Object>, AbstractResponse> interruptAttachingToTangle() { return request -> interruptAttachingToTangleStatement(); } private Function<Map<String, Object>, AbstractResponse> removeNeighbors() { return request -> { List<String> uris = getParameterAsList(request,"uris",0); log.debug("Invoking 'removeNeighbors' with {}", uris); return removeNeighborsStatement(uris); }; } private Function<Map<String, Object>, AbstractResponse> storeTransactions() { return request -> { try { final List<String> trytes = getParameterAsList(request,"trytes", TRYTES_SIZE); storeTransactionsStatement(trytes); } catch (Exception e) { //transaction not valid return ErrorResponse.create("Error: " + e.getMessage()); } return AbstractResponse.createEmptyResponse(); }; } private Function<Map<String, Object>, AbstractResponse> getMissingTransactions() { return request -> { synchronized (transactionRequester) { List<String> missingTx = Arrays.stream(transactionRequester.getRequestedTransactions()) .map(Hash::toString) .collect(Collectors.toList()); return GetTipsResponse.create(missingTx); } }; } private Function<Map<String, Object>, AbstractResponse> checkConsistency() { return request -> { if (!isNodeSynchronized()) { return ErrorResponse.create(INVALID_SUBTANGLE); } final List<String> transactions = getParameterAsList(request,"tails", HASH_SIZE); try { return checkConsistencyStatement(transactions); } catch (Exception e) { throw new IllegalStateException(e); } }; } private Function<Map<String, Object>, AbstractResponse> wereAddressesSpentFrom() { return request -> { final List<String> addresses = getParameterAsList(request,"addresses", HASH_SIZE); try { return wereAddressesSpentFromStatement(addresses); } catch (Exception e) { throw new IllegalStateException(e); } }; } private List<TransactionViewModel> convertTrytes(List<String> trytes) { final List<TransactionViewModel> elements = new LinkedList<>(); byte[] txTrits = Converter.allocateTritsForTrytes(TRYTES_SIZE); for (final String trytesPart : trytes) { //validate all trytes Converter.trits(trytesPart, txTrits, 0); final TransactionViewModel transactionViewModel = transactionValidator.validateTrits(txTrits, transactionValidator.getMinWeightMagnitude()); elements.add(transactionViewModel); } return elements; } }
75,106
44.16356
163
java
iri
iri-master/src/main/java/com/iota/iri/service/ApiCommand.java
package com.iota.iri.service; /** * * ApiCommand is a list of all public API endpoints officially supported by IRI * */ public enum ApiCommand { /** * Add a temporary neighbor to this node */ ADD_NEIGHBORS("addNeighbors"), /** * Prepare transactions for tangle attachment by doing proof of work */ ATTACH_TO_TANGLE("attachToTangle"), /** * Broadcast transactions to the tangle */ BROADCAST_TRANSACTIONs("broadcastTransactions"), /** * Check the consistency of a transaction */ CHECK_CONSISTENCY("checkConsistency"), /** * Find transactions by bundle, address, tag and approve */ FIND_TRANSACTIONS("findTransactions"), /** * Get the balance of an address */ GET_BALANCES("getBalances"), /** * Get the acceptance of a transaction on the tangle */ GET_INCLUSION_STATES("getInclusionStates"), /** * Get the neighbors on this node, including temporary added */ GET_NEIGHBORS("getNeighbors"), /** * Get information about this node */ GET_NODE_INFO("getNodeInfo"), /** * Get information about the API configuration */ GET_NODE_API_CONFIG("getNodeAPIConfiguration"), /** * Get all the transactions this node is currently requesting */ GET_MISSING_TRANSACTIONS("getMissingTransactions"), /** * Get 2 transactions to approve for proof of work */ GET_TRANSACTIONS_TO_APPROVE("getTransactionsToApprove"), /** * Get trytes of a transaction by its hash */ GET_TRYTES("getTrytes"), /** * Stop attaching to the tangle */ INTERRUPT_ATTACHING_TO_TANGLE("interruptAttachingToTangle"), /** * Temporary remove a neighbor from this node */ REMOVE_NEIGHBORS("removeNeighbors"), /** * Store a transaction on this node, without broadcasting */ STORE_TRANSACTIONS("storeTransactions"), /** * Check if an address has been spent from */ WERE_ADDRESSES_SPENT_FROM("wereAddressesSpentFrom"); private String name; private ApiCommand(String name) { this.name = name; } @Override public String toString() { return name; } /** * Looks up the {@link ApiCommand} based on its name * * @param name the name of the API we are looking for * @return The ApiCommand if it exists, otherwise <code>null</code> */ public static ApiCommand findByName(String name) { for (ApiCommand c : values()) { if (c.toString().equals(name)) { return c; } } return null; } }
2,804
22.181818
79
java
iri
iri-master/src/main/java/com/iota/iri/service/CallableRequest.java
package com.iota.iri.service; import java.util.Map; public interface CallableRequest<V> { V call(Map<String, Object> request); }
135
16
40
java
iri
iri-master/src/main/java/com/iota/iri/service/Feature.java
package com.iota.iri.service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.iota.iri.conf.IotaConfig; /** * * Features describe the capability of the node. * They do not have to have a name specifically linked to a class/action. * Features are based on enabled/disabled functionality due to, for example, config values * */ public enum Feature { /** * This node allows doing proof of work for you. */ PROOF_OF_WORK("RemotePOW"), /** * This node has enabled snapshot pruning * It will most likely just contain "recent" transactions, as defined in the nodes config */ SNAPSHOT_PRUNING("snapshotPruning"), /** * This node automatically tries to get the new IP from neighbors with dynamic IPs * */ DNS_REFRESHER("dnsRefresher"), /** * This node is connected to the testnet instead of the mainnet tangle */ TESTNET("testnet"), /** * This node has the zero message queue enabled for fetching/reading "activities" on the node */ ZMQ("zeroMessageQueue"), /** * This node supports the api call "wereAddressesSpentFrom" */ WERE_ADDRESSES_SPENT_FROM("WereAddressesSpentFrom"); private String name; Feature(String name) { this.name = name; } @Override public String toString() { return name; } /** * Calculates all features for this Iota node * @param instance the instance of this node * @return An array of features */ public static Feature[] calculateFeatures(IotaConfig configuration) { List<Feature> features = new ArrayList<>(); if (configuration.getLocalSnapshotsPruningEnabled()) { features.add(SNAPSHOT_PRUNING); } if (configuration.isDnsRefresherEnabled()) { features.add(DNS_REFRESHER); } if (configuration.isTestnet()) { features.add(TESTNET); } if (configuration.isZmqEnabled()) { features.add(ZMQ); } List<Feature> apiFeatures = new ArrayList<Feature>(Arrays.asList(new Feature[] { PROOF_OF_WORK, WERE_ADDRESSES_SPENT_FROM })); for (String disabled : configuration.getRemoteLimitApi()) { switch (disabled) { case "attachToTangle": apiFeatures.remove(PROOF_OF_WORK); break; case "wereAddressesSpentFrom": apiFeatures.remove(WERE_ADDRESSES_SPENT_FROM); break; default: break; } } features.addAll(apiFeatures); return features.toArray(new Feature[]{}); } /** * Calculates all features for this Iota node * @param instance the instance of this node * @return An array of the features in readable name format */ public static String[] calculateFeatureNames(IotaConfig configuration) { Feature[] features = calculateFeatures(configuration); String[] featureNames = Arrays.stream(features) .map(feature -> feature.toString()) .toArray(String[]::new); return featureNames; } }
3,241
26.243697
97
java
iri
iri-master/src/main/java/com/iota/iri/service/ValidationException.java
package com.iota.iri.service; public class ValidationException extends RuntimeException { /** * Initializes a new instance of the ValidationException. */ public ValidationException() { super("Invalid parameters are passed"); } /** * Initializes a new instance of the ValidationException with the specified detail message. * @param msg message shown in exception details. */ public ValidationException(String msg) { super(msg); } }
499
24
95
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/AbstractResponse.java
package com.iota.iri.service.dto; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * * Every response that the IRI API gives is a child of this class. * * Duration for every response is recorded automatically during the processing of a request. * **/ public abstract class AbstractResponse { /** * Number of milliseconds it took to complete the request */ private Integer duration; /** * Builds a string representation of this object using multiple lines * * @return Returns a string representation of this object. */ @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this, false); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj, false); } /** * * @return {@link #duration} */ public Integer getDuration() { return duration; } /** * * @param duration {@link #duration} */ public void setDuration(Integer duration) { this.duration = duration; } /** * If a response doesn't need to send data back, an {@link Emptyness} is used. * This has all the fields and functions of an AbstractResponse, and nothing more. * * @return Returns a plain AbstractResponse without extra fields */ public static AbstractResponse createEmptyResponse() { return new Emptyness(); } /** * An 'empty' Response class. * Will only contain values which are included in {@link AbstractResponse} itself. * This is used when an API command does not need to return data. */ private static class Emptyness extends AbstractResponse {} }
2,032
25.402597
93
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/AccessLimitedResponse.java
package com.iota.iri.service.dto; /** * * This class represents the API error for accessing a command when it is not allowed by this node. * */ public class AccessLimitedResponse extends AbstractResponse { /** * The error identifies what caused this Response. * It is a readable message identifying the command that is limited. */ private String error; /** * Creates a new {@link AccessLimitedResponse} * * @param error {@link #error} * @return an {@link AccessLimitedResponse} filled with the error message */ public static AbstractResponse create(String error) { AccessLimitedResponse res = new AccessLimitedResponse(); res.error = error; return res; } /** * * @return {@link #error} */ public String getError() { return error; } }
865
23.055556
99
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/AddedNeighborsResponse.java
package com.iota.iri.service.dto; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code addNeighbors} API call. * See {@link API#addNeighborsStatement} for how this response is created. * */ public class AddedNeighborsResponse extends AbstractResponse { /** * The amount of temporally added neighbors to this node. * Can be 0 or more. */ private int addedNeighbors; /** * Creates a new {@link AddedNeighborsResponse} * * @param numberOfAddedNeighbors {@link #addedNeighbors} * @return an {@link AddedNeighborsResponse} filled with the number of added neighbors */ public static AbstractResponse create(int numberOfAddedNeighbors) { AddedNeighborsResponse res = new AddedNeighborsResponse(); res.addedNeighbors = numberOfAddedNeighbors; return res; } /** * * @return {link #addedNeighbors} */ public int getAddedNeighbors() { return addedNeighbors; } }
995
23.9
90
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/AttachToTangleResponse.java
package com.iota.iri.service.dto; import java.util.List; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code attachToTangle} API call. * * @see {@link API#attachToTangleStatement} for how this response is created. */ public class AttachToTangleResponse extends AbstractResponse { /** * List of the attached transaction trytes. * The last 243 trytes of the return value consist of the: * <code>trunkTransaction</code> + <code>branchTransaction</code> + <code>nonce</code>. */ private List<String> trytes; /** * Creates a new {@link AttachToTangleResponse} * @param elements {@link #trytes} * @return an {@link AttachToTangleResponse} filled with the trytes */ public static AbstractResponse create(List<String> elements) { AttachToTangleResponse res = new AttachToTangleResponse(); res.trytes = elements; return res; } /** * * @return {@link #trytes} */ public List<String> getTrytes() { return trytes; } }
1,036
24.292683
91
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/CheckConsistency.java
package com.iota.iri.service.dto; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code checkConsistency} API call. * See {@link API#checkConsistencyStatement} for how this response is created. * */ public class CheckConsistency extends AbstractResponse { /** * States of the specified transactions in the same order as the values in the `tails` parameter. * A `true` value means that the transaction is consistent. */ private boolean state; /** * If state is {@code false}, this contains information about why the transaction is inconsistent. */ private String info; /** * Creates a new {@link CheckConsistency} * @param state {@link #state} * @param info {@link #info} * @return a {@link CheckConsistency} filled with the state and info */ public static AbstractResponse create(boolean state, String info) { CheckConsistency res = new CheckConsistency(); res.state = state; res.info = info; return res; } /** * * @return {@link #state} */ public boolean getState() { return state; } /** * * @return {@link #info} */ public String getInfo() { return info; } }
1,313
23.792453
102
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/ErrorResponse.java
package com.iota.iri.service.dto; import com.iota.iri.service.API; /** * This class represents the response the API returns when an error has occurred. * This can be returned for various reasons, see {@link API#process} for the cases. **/ public class ErrorResponse extends AbstractResponse { /** * The error string is a readable message identifying what caused this Error response. */ private String error; /** * Creates a new {@link ErrorResponse} * * @param error {@link #error} * @return an {@link ErrorResponse} filled with the error message */ public static AbstractResponse create(String error) { ErrorResponse res = new ErrorResponse(); res.error = error; return res; } /** * * @return {@link #error} */ public String getError() { return error; } }
829
22.055556
90
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/ExceptionResponse.java
package com.iota.iri.service.dto; import com.iota.iri.service.API; /** * * This class represents the response the API returns when an exception has occurred. * This can be returned for various reasons, see {@link API#process} for the cases. * **/ public class ExceptionResponse extends AbstractResponse { /** * Contains a readable message as to why an exception has been thrown. * This is either due to invalid payload of an API request, or the message of an uncaught exception. */ private String exception; /** * * Creates a new {@link ExceptionResponse} * * @param exception {@link #exception} * @return an {@link ExceptionResponse} filled with the exception */ public static AbstractResponse create(String exception) { ExceptionResponse res = new ExceptionResponse(); res.exception = exception; return res; } /** * * @return {@link #exception} */ public String getException() { return exception; } }
996
23.925
104
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/FindTransactionsResponse.java
package com.iota.iri.service.dto; import java.util.List; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code findTransactions} API call. * See {@link API#findTransactionsStatement} for how this response is created. * */ public class FindTransactionsResponse extends AbstractResponse { /** * The transaction hashes which are returned depend on your input. * For each specified input value, the command will return the following: * <ul> * <li><code>bundles</code>: returns an array of transaction hashes that contain the given bundle hash.</li> * <li><code>addresses</code>: returns an array of transaction hashes that contain the given address in the `address` field.</li> * <li><code>tags</code>: returns an array of transaction hashes that contain the given value in the `tag` field.</li> * <li><code>approvees</code>: returns an array of transaction hashes that contain the given transactions in their `branchTransaction` or `trunkTransaction` fields.</li> * </ul> */ private String [] hashes; /** * Creates a new {@link FindTransactionsResponse} * * @param elements {@link #hashes} * @return an {@link FindTransactionsResponse} filled with the hashes */ public static AbstractResponse create(List<String> elements) { FindTransactionsResponse res = new FindTransactionsResponse(); res.hashes = elements.toArray(new String[] {}); return res; } /** * * @return {@link #hashes} */ public String[] getHashes() { return hashes; } }
1,571
31.75
172
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/GetBalancesResponse.java
package com.iota.iri.service.dto; import java.util.List; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code getBalances} API call. * See {@link API#getBalancesStatement} for how this response is created. * */ public class GetBalancesResponse extends AbstractResponse { /** * Array of balances in the same order as the `addresses` parameters were passed to the endpoint */ private List<String> balances; /** * The referencing tips. * If no `tips` parameter was passed to the endpoint, * this field contains the hash of the latest milestone that confirmed the balance */ private List<String> references; /** * The milestone index with which the confirmed balance was determined */ private int milestoneIndex; /** * Creates a new {@link GetBalancesResponse} * * @param elements {@link #balances} * @param references {@link #references} * @param milestoneIndex {@link #milestoneIndex} * @return an {@link GetBalancesResponse} filled with the balances, references used and index used */ public static AbstractResponse create(List<String> elements, List<String> references, int milestoneIndex) { GetBalancesResponse res = new GetBalancesResponse(); res.balances = elements; res.references = references; res.milestoneIndex = milestoneIndex; return res; } /** * * @return {@link #references} */ public List<String> getReferences() { return references; } /** * * @return {@link #milestoneIndex} */ public int getMilestoneIndex() { return milestoneIndex; } /** * * @return {@link #balances} */ public List<String> getBalances() { return balances; } }
1,774
23.652778
108
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/GetInclusionStatesResponse.java
package com.iota.iri.service.dto; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code getInclusionStates} API call. * See {@link API#getInclusionStatesStatement} for how this response is created. * */ public class GetInclusionStatesResponse extends AbstractResponse { /** * A list of booleans indicating if the transaction is confirmed or not, according to the tips supplied. * Order of booleans is equal to order of the supplied transactions. */ private boolean [] states; /** * Creates a new {@link GetInclusionStatesResponse} * * @param inclusionStates {@link #states} * @return an {@link GetInclusionStatesResponse} filled with the error message */ public static AbstractResponse create(boolean[] inclusionStates) { GetInclusionStatesResponse res = new GetInclusionStatesResponse(); res.states = inclusionStates; return res; } /** * * @return {@link #states} */ public boolean[] getStates() { return states; } }
1,059
25.5
108
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/GetNeighborsResponse.java
package com.iota.iri.service.dto; import com.iota.iri.network.neighbor.NeighborMetrics; import com.iota.iri.network.neighbor.NeighborState; import java.util.Collection; /** * Contains information about the result of a successful {@code getNeighbors} API call. * See {@link GetNeighborsResponse#create(Collection)} for how this response is created. * */ public class GetNeighborsResponse extends AbstractResponse { /** * The neighbors you are connected with, as well as their activity counters. * * @see Neighbor */ private Neighbor[] neighbors; /** * @return {@link #neighbors} * @see Neighbor */ public Neighbor[] getNeighbors() { return neighbors; } /** * Creates a new {@link GetNeighborsResponse} * * @param elements {@link com.iota.iri.network.neighbor.Neighbor} * @return an {@link GetNeighborsResponse} filled all neighbors and their activity. */ public static AbstractResponse create(final Collection<com.iota.iri.network.neighbor.Neighbor> elements) { GetNeighborsResponse res = new GetNeighborsResponse(); res.neighbors = new Neighbor[elements.size()]; int i = 0; for (com.iota.iri.network.neighbor.Neighbor neighbor : elements) { res.neighbors[i++] = GetNeighborsResponse.Neighbor.createFrom(neighbor); } return res; } /** * A plain DTO of an iota neighbor. */ @SuppressWarnings("unused") public static class Neighbor { /** * The address of your neighbor. */ private String address; /** * The origin domain or IP address of the given neighbor. */ private String domain; /** * Number of all transactions sent (invalid, valid, already-seen) */ private long numberOfAllTransactions; /** * Random tip requests which were sent. */ private long numberOfRandomTransactionRequests; /** * New transactions which were transmitted. */ private long numberOfNewTransactions; /** * Invalid transactions your neighbor has sent you. * These are transactions with invalid signatures or overall schema. */ private long numberOfInvalidTransactions; /** * Stale transactions your neighbor has sent you. * These are transactions with a timestamp older than your latest snapshot. */ private long numberOfStaleTransactions; /** * Amount of transactions send to your neighbor. */ private long numberOfSentTransactions; /** * Amount of packets dropped from the neighbor's send queue as it was full. */ private long numberOfDroppedSentPackets; /** * The transport protocol used to the neighbor. */ private String connectionType; /** * Whether the node is currently connected. */ public boolean connected; /** * Creates a new Neighbor DTO from a Neighbor network instance. * * @param neighbor the neighbor currently connected to this node * @return a new instance of {@link Neighbor} */ public static Neighbor createFrom(com.iota.iri.network.neighbor.Neighbor neighbor) { Neighbor ne = new Neighbor(); NeighborMetrics metrics = neighbor.getMetrics(); int port = neighbor.getRemoteServerSocketPort(); String hostAddr = neighbor.getHostAddress(); ne.address = hostAddr == null || hostAddr.isEmpty() ? "" : neighbor.getHostAddressAndPort(); ne.domain = neighbor.getDomain(); ne.numberOfAllTransactions = metrics.getAllTransactionsCount(); ne.numberOfInvalidTransactions = metrics.getInvalidTransactionsCount(); ne.numberOfStaleTransactions = metrics.getStaleTransactionsCount(); ne.numberOfNewTransactions = metrics.getNewTransactionsCount(); ne.numberOfSentTransactions = metrics.getSentTransactionsCount(); ne.numberOfDroppedSentPackets = metrics.getDroppedSendPacketsCount(); ne.numberOfRandomTransactionRequests = metrics.getRandomTransactionRequestsCount(); ne.connectionType = "tcp"; ne.connected = neighbor.getState() == NeighborState.READY_FOR_MESSAGES; return ne; } /** * * {@link #address} */ public String getAddress() { return address; } /** * {@link #domain} */ public String getDomain() { return domain; } /** * * {@link #numberOfAllTransactions} */ public long getNumberOfAllTransactions() { return numberOfAllTransactions; } /** * * {@link #numberOfNewTransactions} */ public long getNumberOfNewTransactions() { return numberOfNewTransactions; } /** * * {@link #numberOfInvalidTransactions} */ public long getNumberOfInvalidTransactions() { return numberOfInvalidTransactions; } /** * * {@link #numberOfStaleTransactions} */ public long getNumberOfStaleTransactions() { return numberOfStaleTransactions; } /** * * {@link #numberOfSentTransactions} */ public long getNumberOfSentTransactions() { return numberOfSentTransactions; } /** * * {@link #numberOfRandomTransactionRequests} */ public long getNumberOfRandomTransactionRequests() { return numberOfRandomTransactionRequests; } /** * {@link #numberOfDroppedSentPackets} */ public long getNumberOfDroppedSentPackets() { return numberOfDroppedSentPackets; } /** * {@link #connected} */ public boolean isConnected(){ return connected; } /** * * {@link #connectionType} */ public String getConnectionType() { return connectionType; } } }
6,424
28.072398
110
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/GetNodeAPIConfigurationResponse.java
package com.iota.iri.service.dto; import com.iota.iri.conf.IotaConfig; /** * Contains information about the result of a successful {@link com.iota.iri.service.API#getNodeAPIConfigurationStatement()} API call. * See {@link com.iota.iri.service.API#getNodeAPIConfigurationStatement()} for how this response is created. */ public class GetNodeAPIConfigurationResponse extends AbstractResponse { private int maxFindTransactions; private int maxRequestsList; private int maxGetTrytes; private int maxBodyLength; private boolean testNet; private int milestoneStartIndex; /** * Use factory method {@link GetNodeAPIConfigurationResponse#create(IotaConfig) to create response.} */ private GetNodeAPIConfigurationResponse() { } /** * Creates a new {@link GetNodeAPIConfigurationResponse} with configuration options that should be returned. * <b>Make sure that you do not return secret informations (e.g. passwords, secrets...).</b> * * @param configuration {@link IotaConfig} used to create response. * @return an {@link GetNodeAPIConfigurationResponse} filled with actual config options. */ public static AbstractResponse create(IotaConfig configuration) { if(configuration == null) { throw new IllegalStateException("configuration must not be null!"); } final GetNodeAPIConfigurationResponse res = new GetNodeAPIConfigurationResponse(); res.maxFindTransactions = configuration.getMaxFindTransactions(); res.maxRequestsList = configuration.getMaxRequestsList(); res.maxGetTrytes = configuration.getMaxGetTrytes(); res.maxBodyLength = configuration.getMaxBodyLength(); res.testNet = configuration.isTestnet(); res.milestoneStartIndex = configuration.getMilestoneStartIndex(); return res; } /** {@link IotaConfig#getMaxFindTransactions()} */ public int getMaxFindTransactions() { return maxFindTransactions; } /** {@link IotaConfig#getMaxRequestsList()} */ public int getMaxRequestsList() { return maxRequestsList; } /** {@link IotaConfig#getMaxGetTrytes()} */ public int getMaxGetTrytes() { return maxGetTrytes; } /** {@link IotaConfig#getMaxBodyLength()} */ public int getMaxBodyLength() { return maxBodyLength; } /** {@link IotaConfig#isTestnet()} */ public boolean isTestNet() { return testNet; } /** {@link IotaConfig#getMilestoneStartIndex()} */ public int getMilestoneStartIndex() { return milestoneStartIndex; } }
2,627
33.12987
134
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/GetNodeInfoResponse.java
package com.iota.iri.service.dto; import com.iota.iri.model.Hash; import com.iota.iri.service.API; import com.iota.iri.service.Feature; /** * * Contains information about the result of a successful {@code getNodeInfo} API call. * See {@link API#getNodeInfoStatement} for how this response is created. * */ public class GetNodeInfoResponse extends AbstractResponse { /** * Name of the IOTA software you're currently using. (IRI stands for IOTA Reference Implementation) */ private String appName; /** * The version of the IOTA software this node is running. */ private String appVersion; /** * Available cores for JRE on this node. */ private int jreAvailableProcessors; /** * The amount of free memory in the Java Virtual Machine. */ private long jreFreeMemory; /** * The JRE version this node runs on */ private String jreVersion; /** * The maximum amount of memory that the Java virtual machine will attempt to use. */ private long jreMaxMemory; /** * The total amount of memory in the Java virtual machine. */ private long jreTotalMemory; /** * The hash of the latest transaction that was signed off by the coordinator. */ private String latestMilestone; /** * Index of the {@link #latestMilestone} */ private int latestMilestoneIndex; /** * The hash of the latest transaction which is solid and is used for sending transactions. * For a milestone to become solid, your local node must approve the subtangle of coordinator-approved transactions, * and have a consistent view of all referenced transactions. */ private String latestSolidSubtangleMilestone; /** * Index of the {@link #latestSolidSubtangleMilestone} */ private int latestSolidSubtangleMilestoneIndex; /** * The index of the milestone from which the node started synchronizing when it first joined the network. * The Coordinator encodes this index in each milestone transaction. */ private int milestoneStartIndex; /** * The index of the milestone used in the latest snapshot. * This is the most recent milestone in the entire snapshot */ private int lastSnapshottedMilestoneIndex; /** * Number of neighbors this node is directly connected with. */ private int neighbors; /** * The amount of transaction packets which are currently waiting to be broadcast. */ private int packetsQueueSize; /** * The difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC */ private long time; /** * Number of tips in the network. */ private int tips; /** * When a node receives a transaction from one of its neighbors, * this transaction is referencing two other transactions t1 and t2 (trunk and branch transaction). * If either t1 or t2 (or both) is not in the node's local database, * then the transaction hash of t1 (or t2 or both) is added to the queue of the "transactions to request". * At some point, the node will process this queue and ask for details about transactions in the * "transaction to request" queue from one of its neighbors. * This number represents the amount of "transaction to request" */ private int transactionsToRequest; /** * Every node can have features enabled or disabled. * This list will contain all the names of the features of a node as specified in {@link Feature}. */ private String[] features; /** * The address of the Coordinator being followed by this node. */ private String coordinatorAddress; /** * The db size in bytes, as estimated by all total persistence providers */ private long dbSizeInBytes; /** * Creates a new {@link GetNodeInfoResponse} * * @param appName {@link #appName} * @param appVersion {@link #appVersion} * @param jreAvailableProcessors {@link #jreAvailableProcessors} * @param jreFreeMemory {@link #jreFreeMemory} * @param jreVersion {@link #jreVersion} * @param maxMemory {@link #jreMaxMemory} * @param totalMemory {@link #jreTotalMemory} * @param latestMilestone {@link #latestMilestone} * @param latestMilestoneIndex {@link #latestMilestoneIndex} * @param latestSolidSubtangleMilestone {@link #latestSolidSubtangleMilestone} * @param latestSolidSubtangleMilestoneIndex {@link #latestSolidSubtangleMilestoneIndex} * @param milestoneStartIndex {@link #milestoneStartIndex} * @param lastSnapshottedMilestoneIndex {@link #lastSnapshottedMilestoneIndex} * @param neighbors {@link #neighbors} * @param packetsQueueSize {@link #packetsQueueSize} * @param currentTimeMillis {@link #time} * @param tips {@link #tips} * @param numberOfTransactionsToRequest {@link #transactionsToRequest} * @param features {@link #features} * @param coordinatorAddress {@link #coordinatorAddress} * @param dbSizeInBytes {@link #dbSizeInBytes} * @return a {@link GetNodeInfoResponse} filled with all the provided parameters */ public static AbstractResponse create(String appName, String appVersion, int jreAvailableProcessors, long jreFreeMemory, String jreVersion, long maxMemory, long totalMemory, Hash latestMilestone, int latestMilestoneIndex, Hash latestSolidSubtangleMilestone, int latestSolidSubtangleMilestoneIndex, int milestoneStartIndex, int lastSnapshottedMilestoneIndex, int neighbors, int packetsQueueSize, long currentTimeMillis, int tips, int numberOfTransactionsToRequest, String[] features, String coordinatorAddress, long dbSizeInBytes) { final GetNodeInfoResponse res = new GetNodeInfoResponse(); res.appName = appName; res.appVersion = appVersion; res.jreAvailableProcessors = jreAvailableProcessors; res.jreFreeMemory = jreFreeMemory; res.jreVersion = jreVersion; res.jreMaxMemory = maxMemory; res.jreTotalMemory = totalMemory; res.latestMilestone = latestMilestone.toString(); res.latestMilestoneIndex = latestMilestoneIndex; res.latestSolidSubtangleMilestone = latestSolidSubtangleMilestone.toString(); res.latestSolidSubtangleMilestoneIndex = latestSolidSubtangleMilestoneIndex; res.milestoneStartIndex = milestoneStartIndex; res.lastSnapshottedMilestoneIndex = lastSnapshottedMilestoneIndex; res.neighbors = neighbors; res.packetsQueueSize = packetsQueueSize; res.time = currentTimeMillis; res.tips = tips; res.transactionsToRequest = numberOfTransactionsToRequest; res.features = features; res.coordinatorAddress = coordinatorAddress; res.dbSizeInBytes = dbSizeInBytes; return res; } /** * * @return {@link #appName} */ public String getAppName() { return appName; } /** * * @return {@link #appVersion} */ public String getAppVersion() { return appVersion; } /** * * @return {@link #jreAvailableProcessors} */ public int getJreAvailableProcessors() { return jreAvailableProcessors; } /** * * @return {@link #jreFreeMemory} */ public long getJreFreeMemory() { return jreFreeMemory; } /** * * @return {@link #jreMaxMemory} */ public long getJreMaxMemory() { return jreMaxMemory; } /** * * @return {@link #jreTotalMemory} */ public long getJreTotalMemory() { return jreTotalMemory; } /** * * @return {@link #jreVersion} */ public String getJreVersion() { return jreVersion; } /** * * @return {@link #latestMilestone} */ public String getLatestMilestone() { return latestMilestone; } /** * * @return {@link #latestMilestoneIndex} */ public int getLatestMilestoneIndex() { return latestMilestoneIndex; } /** * * @return {@link #latestSolidSubtangleMilestone} */ public String getLatestSolidSubtangleMilestone() { return latestSolidSubtangleMilestone; } /** * * @return {@link #latestSolidSubtangleMilestoneIndex} */ public int getLatestSolidSubtangleMilestoneIndex() { return latestSolidSubtangleMilestoneIndex; } /** * * @return {@link #milestoneStartIndex} */ public int getMilestoneStartIndex() { return milestoneStartIndex; } /** * * @return {@link #lastSnapshottedMilestoneIndex} */ public int getLastSnapshottedMilestoneIndex() { return lastSnapshottedMilestoneIndex; } /** * * @return {@link #neighbors} */ public int getNeighbors() { return neighbors; } /** * * @return {@link #packetsQueueSize} */ public int getPacketsQueueSize() { return packetsQueueSize; } /** * * @return {@link #time} */ public long getTime() { return time; } /** * * @return {@link #tips} */ public int getTips() { return tips; } /** * * @return {@link #transactionsToRequest} */ public int getTransactionsToRequest() { return transactionsToRequest; } /** * * @return {@link #features} */ public String[] getFeatures() { return features; } /** * * @return {@link #coordinatorAddress} */ public String getCoordinatorAddress() { return coordinatorAddress; } }
9,499
25.988636
121
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/GetTipsResponse.java
package com.iota.iri.service.dto; import java.util.List; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code getTips} API call. * See {@link API#getTipsStatement} for how this response is created. * */ public class GetTipsResponse extends AbstractResponse { /** * The current tips as seen by this node. */ private String[] hashes; /** * Creates a new {@link GetTipsResponse} * * @param elements {@link #hashes} * @return a {@link GetTipsResponse} filled with the provided tips */ public static AbstractResponse create(List<String> elements) { GetTipsResponse res = new GetTipsResponse(); res.hashes = elements.toArray(new String[] {}); return res; } /** * * @return {@link #hashes} */ public String[] getHashes() { return hashes; } }
857
19.926829
82
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/GetTransactionsToApproveResponse.java
package com.iota.iri.service.dto; import com.iota.iri.model.Hash; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code getTransactionsToApprove} API call. * See {@link API#getTransactionsToApproveStatement} for how this response is created. * */ public class GetTransactionsToApproveResponse extends AbstractResponse { /** * The trunk transaction tip to reference in your transaction or bundle */ private String trunkTransaction; /** * The branch transaction tip to reference in your transaction or bundle */ private String branchTransaction; /** * Creates a new {@link GetTransactionsToApproveResponse} * * @param trunkTransactionToApprove {@link #trunkTransaction} * @param branchTransactionToApprove {@link #branchTransaction} * @return a {@link GetTransactionsToApproveResponse} filled with the provided tips */ public static AbstractResponse create(Hash trunkTransactionToApprove, Hash branchTransactionToApprove) { GetTransactionsToApproveResponse res = new GetTransactionsToApproveResponse(); res.trunkTransaction = trunkTransactionToApprove.toString(); res.branchTransaction = branchTransactionToApprove.toString(); return res; } /** * * @return {@link #branchTransaction} */ public String getBranchTransaction() { return branchTransaction; } /** * * @return {@link #trunkTransaction} */ public String getTrunkTransaction() { return trunkTransaction; } }
1,560
27.907407
105
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/GetTrytesResponse.java
package com.iota.iri.service.dto; import java.util.List; import com.iota.iri.model.persistables.Transaction; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code getTrytes} API call. * See {@link API#getTrytesStatement} for how this response is created. * */ public class GetTrytesResponse extends AbstractResponse { /** * The raw transaction data (trytes) of the specified transactions. * These trytes can then be easily converted into the actual transaction object. * See library functions as to how to transform back to a {@link Transaction}. */ private String[] trytes; /** * Creates a new {@link GetTrytesResponse} * * @param elements {@link #trytes} * @return a {@link GetTrytesResponse} filled with the provided tips */ public static GetTrytesResponse create(List<String> elements) { GetTrytesResponse res = new GetTrytesResponse(); res.trytes = elements.toArray(new String[] {}); return res; } /** * * @return {@link #trytes} */ public String [] getTrytes() { return trytes; } }
1,143
25.604651
85
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/IXIResponse.java
package com.iota.iri.service.dto; import com.iota.iri.IXI; /** * <p> * When a command is not recognized by the default API, we try to process it as an IXI module. * IXI stands for Iota eXtension Interface. See {@link IXI} for more information. * </p> * <p> * The response will contain the reply that the IXI module gave. * This could be empty, depending on the module. * </p> * * An example module can be found here: <a href="https://github.com/iotaledger/Snapshot.ixi">Snapshot.ixi</a> * */ public class IXIResponse extends AbstractResponse { private Object ixi; public static IXIResponse create(Object myixi) { IXIResponse ixiResponse = new IXIResponse(); ixiResponse.ixi = myixi; return ixiResponse; } public Object getResponse() { return ixi; } }
838
26.064516
109
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/RemoveNeighborsResponse.java
package com.iota.iri.service.dto; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code removeNeighbors} API call. * See {@link API#removeNeighborsStatement} for how this response is created. * */ public class RemoveNeighborsResponse extends AbstractResponse { /** * The amount of temporarily removed neighbors from this node. * Can be 0 or more. */ private int removedNeighbors; /** * Creates a new {@link RemoveNeighborsResponse} * * @param numberOfRemovedNeighbors {@link #removedNeighbors} * @return an {@link RemoveNeighborsResponse} filled with the number of removed neighbors */ public static AbstractResponse create(int numberOfRemovedNeighbors) { RemoveNeighborsResponse res = new RemoveNeighborsResponse(); res.removedNeighbors = numberOfRemovedNeighbors; return res; } /** * * @return {@link #removedNeighbors} */ public int getRemovedNeighbors() { return removedNeighbors; } }
1,034
24.875
93
java
iri
iri-master/src/main/java/com/iota/iri/service/dto/WereAddressesSpentFrom.java
package com.iota.iri.service.dto; import com.iota.iri.service.API; /** * * Contains information about the result of a successful {@code wereAddressesSpentFrom} API call. * See {@link API#wereAddressesSpentFromStatement} for how this response is created. * */ public class WereAddressesSpentFrom extends AbstractResponse { /** * States of the specified addresses in Boolean * Order of booleans is equal to order of the supplied addresses. */ private boolean[] states; /** * Creates a new {@link WereAddressesSpentFrom} * * @param inclusionStates {@link #states} * @return a {@link WereAddressesSpentFrom} filled with the address states */ public static AbstractResponse create(boolean[] inclusionStates) { WereAddressesSpentFrom res = new WereAddressesSpentFrom(); res.states = inclusionStates; return res; } /** * * @return {@link #states} */ public boolean[] getStates() { return states; } }
1,026
24.675
97
java
iri
iri-master/src/main/java/com/iota/iri/service/ledger/LedgerException.java
package com.iota.iri.service.ledger; /** * Wraps exceptions that are specific to the ledger logic. * * It allows us to distinct between the different kinds of errors that can happen during the execution of the code. */ public class LedgerException extends Exception { /** * Constructor of the exception which allows us to provide a specific error message and the cause of the error. * * @param message reason why this error occurred * @param cause wrapped exception that caused this error */ public LedgerException(String message, Throwable cause) { super(message, cause); } /** * Constructor of the exception which allows us to provide a specific error message without having an underlying * cause. * * @param message reason why this error occurred */ public LedgerException(String message) { super(message); } /** * Constructor of the exception which allows us to wrap the underlying cause of the error without providing a * specific reason. * * @param cause wrapped exception that caused this error */ public LedgerException(Throwable cause) { super(cause); } }
1,207
29.974359
116
java
iri
iri-master/src/main/java/com/iota/iri/service/ledger/LedgerService.java
package com.iota.iri.service.ledger; import com.iota.iri.controllers.MilestoneViewModel; import com.iota.iri.model.Hash; import com.iota.iri.storage.Tangle; import java.util.List; import java.util.Map; import java.util.Set; /** * <p> * Represents the service that contains all the relevant business logic for modifying and calculating the ledger * state. * </p> * This class is stateless and does not hold any domain specific models. */ public interface LedgerService { /** * <p> * Restores the ledger state after a restart of IRI, which allows us to fast forward to the point where we * stopped before the restart. * </p> * <p> * It looks for the last solid milestone that was applied to the ledger in the database and then replays all * milestones leading up to this point by applying them to the latest snapshot. We do not check every single * milestone again but assume that the data in the database is correct. If the database would have any * inconsistencies and the application fails, the latest solid milestone tracker will check and apply the milestones * one by one and repair the corresponding inconsistencies. * </p> * * @throws LedgerException if anything unexpected happens while trying to restore the ledger state */ void restoreLedgerState() throws LedgerException; /** * <p> * Applies the given milestone to the ledger state. * </p> * <p> * It first marks the transactions that were confirmed by this milestones as confirmed by setting their * corresponding {@code snapshotIndex} value. Then it generates the {@link com.iota.iri.model.StateDiff} that * reflects the accumulated balance changes of all these transactions and applies it to the latest Snapshot. * </p> * * @param milestone the milestone that shall be applied * @return {@code true} if the milestone could be applied to the ledger and {@code false} otherwise * @throws LedgerException if anything goes wrong while modifying the ledger state */ boolean applyMilestoneToLedger(MilestoneViewModel milestone) throws LedgerException; /** * <p> * Checks the consistency of the combined balance changes of the given tips. * </p> * <p> * It simply calculates the balance changes of the tips and then combines them to verify that they are leading to a * consistent ledger state (which means that they are not containing any double-spends or spends of non-existent * IOTA). * </p> * * @param hashes a list of hashes that reference the chosen tips * @return {@code true} if the tips are consistent and {@code false} otherwise * @throws LedgerException if anything unexpected happens while checking the consistency of the tips */ boolean tipsConsistent(List<Hash> hashes) throws LedgerException; /** * <p> * Checks if the balance changes of the transactions that are referenced by the given tip are consistent. * </p> * <p> * It first calculates the balance changes, then adds them to the given {@code diff} and finally checks their * consistency. If we are only interested in the changes that are referenced by the given {@code tip} we need to * pass in an empty map for the {@code diff} parameter. * </p> * <p> * The {@code diff} as well as the {@code approvedHashes} parameters are modified, so they will contain the new * balance changes and the approved transactions after this method terminates. * </p> * * @param approvedHashes a set of transaction hashes that shall be considered to be approved already (and that * consequently shall be excluded from the calculation) * @param diff a map of balances associated to their address that shall be used as a basis for the balance * @param tip the tip that will have its approvees checked * @return {@code true} if the balance changes are consistent and {@code false} otherwise * @throws LedgerException if anything unexpected happens while determining the consistency */ boolean isBalanceDiffConsistent(Set<Hash> approvedHashes, Map<Hash, Long> diff, Hash tip) throws LedgerException; /** * <p> * Generates the accumulated balance changes of the transactions that are directly or indirectly referenced by the * given transaction relative to the referenced milestone. Also persists the spent addresses that were found in the * process. * </p> * <p> * It simply iterates over all approvees that have not been confirmed yet and that have not been processed already * (by being part of the {@code visitedNonMilestoneSubtangleHashes} set) and collects their balance changes. * </p> * * @param visitedTransactions a set of transaction hashes that shall be considered to be visited already * @param startTransaction the transaction that marks the start of the dag traversal and that has its approvees * examined * @param enforceExtraRules enforce {@link com.iota.iri.BundleValidator#validateBundleTransactionsApproval(List)} * and {@link com.iota.iri.BundleValidator#validateBundleTailApproval(Tangle, List)}. * Enforcing them may break backwards compatibility. * @return a map of the balance changes (addresses associated to their balance) or {@code null} if the balance could * not be generated due to inconsistencies * @throws LedgerException if anything unexpected happens while generating the balance changes */ Map<Hash, Long> generateBalanceDiff(Set<Hash> visitedTransactions, Hash startTransaction, int milestoneIndex, boolean enforceExtraRules) throws LedgerException; }
5,886
49.75
120
java
iri
iri-master/src/main/java/com/iota/iri/service/ledger/impl/LedgerServiceImpl.java
package com.iota.iri.service.ledger.impl; import com.iota.iri.BundleValidator; import com.iota.iri.controllers.MilestoneViewModel; import com.iota.iri.controllers.StateDiffViewModel; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import com.iota.iri.service.ledger.LedgerException; import com.iota.iri.service.ledger.LedgerService; import com.iota.iri.service.milestone.MilestoneService; import com.iota.iri.service.snapshot.Snapshot; import com.iota.iri.service.snapshot.SnapshotException; import com.iota.iri.service.snapshot.SnapshotProvider; import com.iota.iri.service.snapshot.SnapshotService; import com.iota.iri.service.snapshot.impl.SnapshotStateDiffImpl; import com.iota.iri.service.spentaddresses.SpentAddressesService; import com.iota.iri.storage.Tangle; import com.iota.iri.utils.dag.DAGHelper; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * Creates a service instance that allows us to perform ledger state specific operations. * </p> * <p> * This class is stateless and does not hold any domain specific models. * </p> */ public class LedgerServiceImpl implements LedgerService { private static final Logger log = LoggerFactory.getLogger(LedgerServiceImpl.class); /** * Holds the tangle object which acts as a database interface. */ private final Tangle tangle; /** * Holds the snapshot provider which gives us access to the relevant snapshots. */ private final SnapshotProvider snapshotProvider; /** * Holds a reference to the service instance containing the business logic of the snapshot package. */ private final SnapshotService snapshotService; /** * Holds a reference to the service instance containing the business logic of the milestone package. */ private final MilestoneService milestoneService; private final SpentAddressesService spentAddressesService; private final BundleValidator bundleValidator; /** * @param tangle Tangle object which acts as a database interface * @param snapshotProvider snapshot provider which gives us access to the relevant snapshots * @param snapshotService service instance of the snapshot package that gives us access to packages' business logic * @param milestoneService contains the important business logic when dealing with milestones */ public LedgerServiceImpl(Tangle tangle, SnapshotProvider snapshotProvider, SnapshotService snapshotService, MilestoneService milestoneService, SpentAddressesService spentAddressesService, BundleValidator bundleValidator) { this.tangle = tangle; this.snapshotProvider = snapshotProvider; this.snapshotService = snapshotService; this.milestoneService = milestoneService; this.spentAddressesService = spentAddressesService; this.bundleValidator = bundleValidator; } @Override public void restoreLedgerState() throws LedgerException { try { Optional<MilestoneViewModel> milestone = milestoneService.findLatestProcessedSolidMilestoneInDatabase(); if (milestone.isPresent()) { snapshotService.replayMilestones(snapshotProvider.getLatestSnapshot(), milestone.get().index()); } } catch (Exception e) { throw new LedgerException("unexpected error while restoring the ledger state", e); } } @Override public boolean applyMilestoneToLedger(MilestoneViewModel milestone) throws LedgerException { log.debug("applying milestone {}", milestone.index()); if(generateStateDiff(milestone)) { try { snapshotService.replayMilestones(snapshotProvider.getLatestSnapshot(), milestone.index()); } catch (SnapshotException e) { throw new LedgerException("failed to apply the balance changes to the ledger state", e); } return true; } return false; } @Override public boolean tipsConsistent(List<Hash> tips) throws LedgerException { Set<Hash> visitedHashes = new HashSet<>(); Map<Hash, Long> diff = new HashMap<>(); for (Hash tip : tips) { if (!isBalanceDiffConsistent(visitedHashes, diff, tip)) { return false; } } return true; } @Override public boolean isBalanceDiffConsistent(Set<Hash> approvedHashes, Map<Hash, Long> diff, Hash tip) throws LedgerException { try { if (!TransactionViewModel.fromHash(tangle, tip).isSolid()) { return false; } } catch (Exception e) { throw new LedgerException("failed to check the consistency of the balance changes", e); } if (approvedHashes.contains(tip)) { return true; } Set<Hash> visitedHashes = new HashSet<>(approvedHashes); Map<Hash, Long> currentState = generateBalanceDiff(visitedHashes, tip, snapshotProvider.getLatestSnapshot().getIndex(), true); if (currentState == null) { return false; } diff.forEach((key, value) -> { if (currentState.computeIfPresent(key, ((hash, aLong) -> value + aLong)) == null) { currentState.putIfAbsent(key, value); } }); boolean isConsistent = snapshotProvider.getLatestSnapshot().patchedState(new SnapshotStateDiffImpl( currentState)).isConsistent(); if (isConsistent) { diff.putAll(currentState); approvedHashes.addAll(visitedHashes); } return isConsistent; } @Override public Map<Hash, Long> generateBalanceDiff(Set<Hash> visitedTransactions, Hash startTransaction, int milestoneIndex, boolean enforceExtraRules) throws LedgerException { Map<Hash, Long> state = new HashMap<>(); Snapshot initialSnapshot = snapshotProvider.getInitialSnapshot(); Map<Hash, Integer> solidEntryPoints = initialSnapshot.getSolidEntryPoints(); solidEntryPoints.keySet().forEach(solidEntryPointHash -> { visitedTransactions.add(solidEntryPointHash); }); final Queue<Hash> nonAnalyzedTransactions = new LinkedList<>(Collections.singleton(startTransaction)); Hash transactionPointer; while ((transactionPointer = nonAnalyzedTransactions.poll()) != null) { try { final TransactionViewModel transactionViewModel = TransactionViewModel.fromHash(tangle, transactionPointer); if (transactionViewModel.getCurrentIndex() == 0 && visitedTransactions.add(transactionPointer)) { if (transactionViewModel.getType() == TransactionViewModel.PREFILLED_SLOT) { return null; } if (!milestoneService.isTransactionConfirmed(transactionViewModel, milestoneIndex)) { final List<TransactionViewModel> bundleTransactions = bundleValidator.validate(tangle, enforceExtraRules, snapshotProvider.getInitialSnapshot(), transactionViewModel.getHash()); if (bundleTransactions.isEmpty()) { return null; } // ISSUE 1008: generateBalanceDiff should be refactored so we don't have those hidden // concerns spentAddressesService.persistValidatedSpentAddressesAsync(bundleTransactions); if (BundleValidator.isInconsistent(bundleTransactions)) { log.error("Encountered an inconsistent bundle with tail {} and bundle hash {}", bundleTransactions.get(0).getHash(), bundleTransactions.get(0).getBundleHash()); return null; } for (final TransactionViewModel bundleTransactionViewModel : bundleTransactions) { if (bundleTransactionViewModel.value() != 0) { final Hash address = bundleTransactionViewModel.getAddressHash(); final Long value = state.get(address); state.put(address, value == null ? bundleTransactionViewModel.value() : Math.addExact(value, bundleTransactionViewModel.value())); } } nonAnalyzedTransactions.addAll(DAGHelper.get(tangle).findTails(transactionViewModel)); } } } catch (Exception e) { throw new LedgerException("unexpected error while generating the balance diff", e); } } return state; } /** * <p> * Generates the {@link com.iota.iri.model.StateDiff} that belongs to the given milestone in the database and marks * all transactions that have been approved by the milestone accordingly by setting their {@code snapshotIndex} * value. * </p> * <p> * It first checks if the {@code snapshotIndex} of the transaction belonging to the milestone was correctly set * already (to determine if this milestone was processed already) and proceeds to generate the {@link * com.iota.iri.model.StateDiff} if that is not the case. To do so, it calculates the balance changes, checks if * they are consistent and only then writes them to the database. * </p> * <p> * If inconsistencies in the {@code snapshotIndex} are found it issues a reset of the corresponding milestone to * recover from this problem. * </p> * * @param milestone the milestone that shall have its {@link com.iota.iri.model.StateDiff} generated * @return {@code true} if the {@link com.iota.iri.model.StateDiff} could be generated and {@code false} otherwise * @throws LedgerException if anything unexpected happens while generating the {@link com.iota.iri.model.StateDiff} */ private boolean generateStateDiff(MilestoneViewModel milestone) throws LedgerException { try { TransactionViewModel transactionViewModel = TransactionViewModel.fromHash(tangle, milestone.getHash()); if (!transactionViewModel.isSolid()) { return false; } final int transactionSnapshotIndex = transactionViewModel.snapshotIndex(); boolean successfullyProcessed = transactionSnapshotIndex == milestone.index(); if (!successfullyProcessed) { // if the snapshotIndex of our transaction was set already, we have processed our milestones in // the wrong order (i.e. while rescanning the db) if (transactionSnapshotIndex != 0) { milestoneService.resetCorruptedMilestone(milestone.index()); } snapshotProvider.getLatestSnapshot().lockRead(); try { Hash tail = transactionViewModel.getHash(); Map<Hash, Long> balanceChanges = generateBalanceDiff(new HashSet<>(), tail, snapshotProvider.getLatestSnapshot().getIndex(), false); successfullyProcessed = balanceChanges != null; if (successfullyProcessed) { successfullyProcessed = snapshotProvider.getLatestSnapshot().patchedState( new SnapshotStateDiffImpl(balanceChanges)).isConsistent(); if (successfullyProcessed) { milestoneService.updateMilestoneIndexOfMilestoneTransactions(milestone.getHash(), milestone.index()); if (!balanceChanges.isEmpty()) { new StateDiffViewModel(balanceChanges, milestone.getHash()).store(tangle); } } } } finally { snapshotProvider.getLatestSnapshot().unlockRead(); } } return successfullyProcessed; } catch (Exception e) { throw new LedgerException("unexpected error while generating the StateDiff for " + milestone, e); } } }
12,627
43
120
java
iri
iri-master/src/main/java/com/iota/iri/service/milestone/InSyncService.java
package com.iota.iri.service.milestone; /** * * Service for checking our node status * */ public interface InSyncService { /** * Verifies if this node is currently considered in sync * * @return <code>true</code> if we are in sync, otherwise <code>false</code> */ boolean isInSync(); }
326
18.235294
80
java
iri
iri-master/src/main/java/com/iota/iri/service/milestone/MilestoneException.java
package com.iota.iri.service.milestone; /** * This class is used to wrap exceptions that are specific to the milestone logic. * * It allows us to distinct between the different kinds of errors that can happen during the execution of the code. */ public class MilestoneException extends Exception { /** * Constructor of the exception which allows us to provide a specific error message and the cause of the error. * * @param message reason why this error occurred * @param cause wrapped exception that caused this error */ public MilestoneException(String message, Throwable cause) { super(message, cause); } /** * Constructor of the exception which allows us to provide a specific error message without having an underlying * cause. * * @param message reason why this error occurred */ public MilestoneException(String message) { super(message); } /** * Constructor of the exception which allows us to wrap the underlying cause of the error without providing a * specific reason. * * @param cause wrapped exception that caused this error */ public MilestoneException(Throwable cause) { super(cause); } }
1,246
30.974359
116
java
iri
iri-master/src/main/java/com/iota/iri/service/milestone/MilestoneRepairer.java
package com.iota.iri.service.milestone; import com.iota.iri.controllers.MilestoneViewModel; /** * Contains the logic for comparing and repairing corrupted milestones. Used by the * {@link com.iota.iri.service.milestone.MilestoneSolidifier} to forward transactions to the * {@link MilestoneService#resetCorruptedMilestone(int)} method. */ public interface MilestoneRepairer { /** * <p> * Checks if we are currently trying to repair a milestone. * </p> * * @return {@code true} if we are trying to repair a milestone and {@code false} otherwise */ boolean isRepairRunning(); /** * <p> * Checks if we successfully repaired the corrupted milestone. * </p> * <p> * To determine if the repair routine was successful we check if the processed milestone has a higher index than the * one that initially could not get applied to the ledger. * </p> * * @param processedMilestone the currently processed milestone * @return {@code true} if we advanced to a milestone following the corrupted one and {@code false} otherwise */ boolean isRepairSuccessful(MilestoneViewModel processedMilestone); /** * <p> * Tries to actively repair the ledger by reverting the milestones preceding the given milestone. * </p> * <p> * It gets called when a milestone could not be applied to the ledger state because of problems like "inconsistent * balances". While this should theoretically never happen (because milestones are by definition "consistent"), it * can still happen because IRI crashed or got stopped in the middle of applying a milestone or if a milestone * was processed in the wrong order. * </p> * <p> * Every time we call this method the internal repairBackoffCounter is incremented which causes the next * call of this method to repair an additional milestone. This means that whenever we face an error we first try to * reset only the last milestone, then the two last milestones, then the three last milestones (and so on ...) until * the problem was fixed. * </p> * <p> * To be able to tell when the problem is fixed and the repairBackoffCounter can be reset, we store the * milestone index that caused the problem the first time we call this method. * </p> * * @param errorCausingMilestone the milestone that failed to be applied * @throws MilestoneException if we failed to reset the corrupted milestone */ void repairCorruptedMilestone(MilestoneViewModel errorCausingMilestone) throws MilestoneException; /** * <p> * Resets the internal variables that are used to keep track of the repair process. * </p> * <p> * It gets called whenever we advance to a milestone that has a higher milestone index than the milestone that * initially caused the repair routine to kick in (see {@link #repairCorruptedMilestone(MilestoneViewModel)}. * </p> */ void stopRepair(); }
3,037
41.788732
120
java
iri
iri-master/src/main/java/com/iota/iri/service/milestone/MilestoneService.java
package com.iota.iri.service.milestone; import com.iota.iri.controllers.MilestoneViewModel; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import java.util.Optional; /** * <p> * Represents the service that contains all the relevant business logic for interacting with milestones. * </p> * This class is stateless and does not hold any domain specific models. */ public interface MilestoneService { /** * <p> * Finds the latest solid milestone that was previously processed by IRI (before a restart) by performing a search * in the database. * </p> * <p> * It determines if the milestones were processed by checking the {@code snapshotIndex} value of their corresponding * transactions. * </p> * * @return the latest solid milestone that was previously processed by IRI or an empty value if no previously * processed solid milestone can be found * @throws MilestoneException if anything unexpected happend while performing the search */ Optional<MilestoneViewModel> findLatestProcessedSolidMilestoneInDatabase() throws MilestoneException; /** * <p> * Analyzes the given transaction to determine if it is a valid milestone. * </p> * </p> * It first checks if all transactions that belong to the milestone bundle are known already and only then verifies * the signature to analyze if the given milestone was really issued by the coordinator. * </p> * * @param transactionViewModel transaction that shall be analyzed * @param milestoneIndex milestone index of the transaction (see {@link #getMilestoneIndex(TransactionViewModel)}) * @return validity status of the transaction regarding its role as a milestone * @throws MilestoneException if anything unexpected goes wrong while validating the milestone transaction */ MilestoneValidity validateMilestone(TransactionViewModel transactionViewModel, int milestoneIndex) throws MilestoneException; /** * <p> * Updates the milestone index of all transactions that belong to a milestone. * </p> * <p> * It does that by iterating through all approvees of the milestone defined by the given {@code milestoneHash} until * it reaches transactions that have been approved by a previous milestone. This means that this method only works * if the transactions belonging to the previous milestone have been updated already. * </p> * <p> * While iterating through the transactions we also examine the milestone index that is currently set to detect * corruptions in the database where a following milestone was processed before the current one. If such a * corruption in the database is found we trigger a reset of the wrongly processed milestone to repair the ledger * state and recover from this error. * </p> * <p> * In addition to these checks we also update the solid entry points, if we detect that a transaction references a * transaction that dates back before the last local snapshot (and that has not been marked as a solid entry point, * yet). This allows us to handle back-referencing transactions and maintain local snapshot files that can always be * used to bootstrap a node, even if the coordinator suddenly approves really old transactions (this only works * if the transaction that got referenced is still "known" to the node by having a sufficiently high pruning * delay). * </p> * * @param milestoneHash the hash of the transaction * @param newIndex the milestone index that shall be set * @throws MilestoneException if anything unexpected happens while updating the milestone index */ void updateMilestoneIndexOfMilestoneTransactions(Hash milestoneHash, int newIndex) throws MilestoneException; /** * <p> * Resets all milestone related information of the transactions that were "confirmed" by the given milestone and * rolls back the ledger state to the moment before the milestone was applied. * </p> * <p> * This allows us to reprocess the milestone in case of errors where the given milestone could not be applied to the * ledger state. It is for example used by the automatic repair routine of the {@link MilestoneSolidifier} * (to recover from inconsistencies due to crashes of IRI). * </p> * <p> * It recursively resets additional milestones if inconsistencies are found within the resetted milestone (wrong * {@code milestoneIndex}es). * </p> * * @param index milestone index that shall be reverted * @throws MilestoneException if anything goes wrong while resetting the corrupted milestone */ void resetCorruptedMilestone(int index) throws MilestoneException; /** * <p> * Checks if the given transaction was confirmed by the milestone with the given index (or any of its * predecessors). * </p> * </p> * We determine if the transaction was confirmed by examining its {@code snapshotIndex} value. For this method to * work we require that the previous milestones have been processed already (which is enforced by the {@link * com.iota.iri.service.milestone.MilestoneSolidifier} which applies the milestones in the order that they * are issued by the coordinator). * </p> * * @param transaction the transaction that shall be examined * @param milestoneIndex the milestone index that we want to check against * @return {@code true} if the transaction belongs to the milestone and {@code false} otherwise */ boolean isTransactionConfirmed(TransactionViewModel transaction, int milestoneIndex); /** * Does the same as {@link #isTransactionConfirmed(TransactionViewModel, int)} but defaults to the latest solid * milestone index for the {@code milestoneIndex} which means that the transaction has been included in our current * ledger state. * * @param transaction the transaction that shall be examined * @return {@code true} if the transaction belongs to the milestone and {@code false} otherwise */ boolean isTransactionConfirmed(TransactionViewModel transaction); /** * <p> * Retrieves the milestone index of the given transaction by decoding the {@code OBSOLETE_TAG}. * </p> * <p> * The returned result will of cause only have a reasonable value if we hand in a transaction that represents a real * milestone. * </p> * * @param milestoneTransaction the transaction that shall have its milestone index retrieved * @return the milestone index of the transaction */ int getMilestoneIndex(TransactionViewModel milestoneTransaction); }
6,839
47.510638
120
java
iri
iri-master/src/main/java/com/iota/iri/service/milestone/MilestoneSolidifier.java
package com.iota.iri.service.milestone; import com.iota.iri.controllers.TransactionViewModel; import com.iota.iri.model.Hash; import java.util.List; import java.util.Map; /** * This interface defines the contract for a manager that tries to solidify unsolid milestones by incorporating a * background worker that periodically checks the solidity of the milestones and issues transaction requests for the * missing transactions until the milestones become solid. */ public interface MilestoneSolidifier { /** * This method allows us to add new milestones to the solidifier that will consequently be solidified. * * @param milestoneHash Hash of the milestone that shall be solidified * @param milestoneIndex index of the milestone that shall be solidified */ void addMilestoneCandidate(Hash milestoneHash, int milestoneIndex); /** * This method starts the background worker that asynchronously solidifies the milestones. */ void start(); /** * This method shuts down the background worker that asynchronously solidifies the milestones. */ void shutdown(); /** * This method returns the latest milestone index. * @return Latest Milestone Index */ int getLatestMilestoneIndex(); /** * This method returns the latest milestone hash. * @return Latest Milestone Hash */ Hash getLatestMilestoneHash(); /** * Checks if the MilestoneSolidifier has been initialised fully. This registers true if the solidifier has performed * an initial solidification of present elements in the db. * * @return Initialised state. */ boolean isInitialScanComplete(); /** * Add to the seen milestones queue to be held for processing solid milestones. In order to be added to the queue * the transaction must pass {@link MilestoneService#validateMilestone(TransactionViewModel, int)}. * * @param milestoneHash The {@link Hash} of the seen milestone * @param milestoneIndex The index of the seen milestone */ void addSeenMilestone(Hash milestoneHash, int milestoneIndex); /** * Removes the specified element from the unsolid milestones queue. In the event that a milestone manages to get * into the queue, but is later determined to be {@link MilestoneValidity#INVALID}, this method allows it to be * removed. * * @param milestoneHash The {@link Hash} of the milestone to be removed */ void removeFromQueues(Hash milestoneHash); /** * Set the latest milestone seen by the node. * * @param milestoneHash The latest milestone hash * @param milestoneIndex The latest milestone index */ void setLatestMilestone(Hash milestoneHash, int milestoneIndex); /** * Returns the oldest current milestone object in the unsolid milestone queue to be processed for solidification. * @return The oldest milestone hash to index mapping */ List<Map.Entry<Hash, Integer>> getOldestMilestonesInQueue(); /** * Set the latest milestone hash and index, publish and log the update. * @param oldMilestoneIndex Previous milestone index * @param newMilestoneIndex New milestone index * @param newMilestoneHash New milestone hash */ void registerNewMilestone(int oldMilestoneIndex, int newMilestoneIndex, Hash newMilestoneHash); }
3,418
35.763441
120
java
iri
iri-master/src/main/java/com/iota/iri/service/milestone/MilestoneValidity.java
package com.iota.iri.service.milestone; /** * Validity states of milestone transactions that are used to express their "relevance" for the ledger state. */ public enum MilestoneValidity { VALID, INVALID, INCOMPLETE }
232
20.181818
109
java
iri
iri-master/src/main/java/com/iota/iri/service/milestone/SeenMilestonesRetriever.java
package com.iota.iri.service.milestone; /** * <p> * Attempts to retrieve the milestones that have been defined in the local snapshots file. * </p> * <p> * The manager incorporates a background worker that proactively requests the missing milestones until all defined * milestones are known. After all milestones have been retrieved the manager shuts down automatically (to free the * unused resources). * </p> * <p> * Note: When we bootstrap a node with a local snapshot file, we are provided with a list of all seen milestones that * were known during the creation of the snapshot. This list allows new nodes or nodes that start over with an * empty database, to retrieve the missing milestones efficiently by directly requesting them from its neighbours * (without having to wait for them to be discovered during the solidification process). * </p> * <p> * This speeds up the sync-times massively and leads to nodes that are up within minutes rather than hours or even * days. * </p> */ public interface SeenMilestonesRetriever { /** * <p> * Triggers the retrieval of the milestones by issuing transaction requests to the nodes neighbours. * </p> * <p> * It gets periodically called by the background worker to automatically retrieve all missing milestones. * </p> */ void retrieveSeenMilestones(); /** * Starts the background worker that automatically calls {@link #retrieveSeenMilestones()} * periodically to retrieves all "seen" missing milestones. */ void start(); /** * Stops the background worker that retrieves all "seen" missing milestones. */ void shutdown(); /** * Initializes the instance by loading the known milestones. */ void init(); }
1,797
34.254902
119
java
iri
iri-master/src/main/java/com/iota/iri/service/milestone/impl/MilestoneInSyncService.java
package com.iota.iri.service.milestone.impl; import com.iota.iri.service.milestone.InSyncService; import com.iota.iri.service.milestone.MilestoneSolidifier; import com.iota.iri.service.snapshot.SnapshotProvider; import com.google.common.annotations.VisibleForTesting; import java.util.concurrent.atomic.AtomicBoolean; /** * * A node is defined in sync when the latest snapshot milestone index and the * latest milestone index are equal. In order to prevent a bounce between in and * out of sync, a buffer is added when a node became in sync. * * This will always return false if we are not done scanning milestone * candidates during initialization. * */ public class MilestoneInSyncService implements InSyncService { /** * To prevent jumping back and forth in and out of sync, there is a buffer in between. * Only when the latest milestone and latest snapshot differ more than this number, we fall out of sync */ @VisibleForTesting static final int LOCAL_SNAPSHOT_SYNC_BUFFER = 5; /** * If this node is currently seen as in sync */ private AtomicBoolean isInSync; /** * Data provider for the latest solid index */ private SnapshotProvider snapshotProvider; /** * Data provider for the latest index */ private MilestoneSolidifier milestoneSolidifier; /** * @param snapshotProvider data provider for the snapshots that are relevant for the node */ public MilestoneInSyncService(SnapshotProvider snapshotProvider, MilestoneSolidifier milestoneSolidifier) { this.snapshotProvider = snapshotProvider; this.milestoneSolidifier = milestoneSolidifier; this.isInSync = new AtomicBoolean(false); } @Override public boolean isInSync() { if (!milestoneSolidifier.isInitialScanComplete()) { return false; } int latestIndex = milestoneSolidifier.getLatestMilestoneIndex(); int latestSnapshot = snapshotProvider.getLatestSnapshot().getIndex(); // If we are out of sync, only a full sync will get us in if (!isInSync.get() && latestIndex == latestSnapshot) { isInSync.set(true); // When we are in sync, only dropping below the buffer gets us out of sync } else if (latestSnapshot < latestIndex - LOCAL_SNAPSHOT_SYNC_BUFFER) { isInSync.set(false); } return isInSync.get(); } }
2,462
31.407895
111
java
iri
iri-master/src/main/java/com/iota/iri/service/milestone/impl/MilestoneRepairerImpl.java
package com.iota.iri.service.milestone.impl; import com.iota.iri.controllers.MilestoneViewModel; import com.iota.iri.service.milestone.MilestoneException; import com.iota.iri.service.milestone.MilestoneRepairer; import com.iota.iri.service.milestone.MilestoneService; /** * Creates a {@link MilestoneRepairer} service to fix corrupted milestone objects. */ public class MilestoneRepairerImpl implements MilestoneRepairer { /** * A {@link MilestoneService} instance for repairing corrupted milestones */ private MilestoneService milestoneService; /** * Holds the milestone index of the milestone that caused the repair logic to get started. */ private int errorCausingMilestoneIndex = Integer.MAX_VALUE; /** * Counter for the backoff repair strategy (see {@link #repairCorruptedMilestone(MilestoneViewModel)}. */ private int repairBackoffCounter = 0; /** * Constructor for a {@link MilestoneRepairer} to be used for resetting corrupted milestone objects * @param milestoneService A {@link MilestoneService} instance to reset corrupted mielstones */ public MilestoneRepairerImpl(MilestoneService milestoneService) { this.milestoneService = milestoneService; } /** * {@inheritDoc} * * <p> * We simply use the {@link #repairBackoffCounter} as an indicator if a repair routine is running. * </p> */ @Override public boolean isRepairRunning() { return repairBackoffCounter != 0; } /** * {@inheritDoc} */ @Override public boolean isRepairSuccessful(MilestoneViewModel processedMilestone) { return processedMilestone.index() > errorCausingMilestoneIndex; } /** * {@inheritDoc} */ @Override public void stopRepair() { repairBackoffCounter = 0; errorCausingMilestoneIndex = Integer.MAX_VALUE; } /** * {@inheritDoc} */ public void repairCorruptedMilestone(MilestoneViewModel errorCausingMilestone) throws MilestoneException { if (repairBackoffCounter++ == 0) { errorCausingMilestoneIndex = errorCausingMilestone.index(); } for (int i = errorCausingMilestone.index(); i > errorCausingMilestone.index() - repairBackoffCounter; i--) { milestoneService.resetCorruptedMilestone(i); } } }
2,382
29.948052
116
java