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 |
|---|---|---|---|---|---|---|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/NetStore.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import org.ethereum.config.SystemProperties;
import org.ethereum.manager.WorldManager;
import org.ethereum.net.swarm.bzz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* The main logic of communicating with BZZ peers.
* The class process local/remote retrieve/store requests and forwards them if necessary
* to the peers.
*
* Magic is happening here!
*
* Created by Anton Nashatyrev on 18.06.2015.
*/
@Component
public class NetStore implements ChunkStore {
private static NetStore INST;
public synchronized static NetStore getInstance() {
return INST;
}
@Autowired
WorldManager worldManager;
public int requesterCount = 3;
public int maxStorePeers = 3;
public int maxSearchPeers = 6;
public int timeout = 600 * 1000;
private LocalStore localStore;
private Hive hive;
private PeerAddress selfAddress;
@Autowired
public NetStore(SystemProperties config) {
this(new LocalStore(new MemStore(), new MemStore()), new Hive(new PeerAddress(new byte[] {127,0,0,1},
config.listenPort(), config.nodeId())));
start(hive.getSelfAddress());
// FIXME bad dirty hack to workaround Spring DI machinery
INST = this;
}
public NetStore(LocalStore localStore, Hive hive) {
this.localStore = localStore;
this.hive = hive;
}
public void start(PeerAddress self) {
this.selfAddress = self;
hive.start();
}
public void stop() {
hive.stop();
}
public Hive getHive() {
return hive;
}
public PeerAddress getSelfAddress() {
return selfAddress;
}
/******************************************
* Put methods
******************************************/
// called from dpa, entrypoint for *local* chunk store requests
@Override
public synchronized void put(Chunk chunk) {
// Chunk localChunk = localStore.get(chunk.getKey()); // ???
putImpl(chunk);
}
// store logic common to local and network chunk store requests
void putImpl(Chunk chunk) {
localStore.put(chunk);
if (chunkRequestMap.get(chunk.getKey()) != null &&
chunkRequestMap.get(chunk.getKey()).status == EntryReqStatus.Searching) {
// If this is response to retrieve message
chunkRequestMap.get(chunk.getKey()).status = EntryReqStatus.Found;
// Resend to all (max [3]) requesters
propagateResponse(chunk);
// TODO remove chunkRequest from map (memleak) ???
} else {
// If local, broadcast store request to hive peers
store(chunk);
}
}
// the entrypoint for network store requests
public void addStoreRequest(BzzStoreReqMessage msg) {
statInStoreReq.add(1);
Chunk chunk = localStore.get(msg.getKey()); // TODO hasKey() should be faster
if (chunk == null) {
// If not in local store yet
// but remember the request source to exclude it from store broadcast
chunk = new Chunk(msg.getKey(), msg.getData());
chunkSourceAddr.put(chunk, msg.getPeer().getNode());
putImpl(chunk);
}
}
// once a chunk is found propagate it its requesters unless timed out
private synchronized void propagateResponse(Chunk chunk) {
ChunkRequest chunkRequest = chunkRequestMap.get(chunk.getKey());
for (Promise<Chunk> localRequester : chunkRequest.localRequesters) {
localRequester.setSuccess(chunk);
}
for (Map.Entry<Long, Collection<BzzRetrieveReqMessage>> e :
chunkRequest.requesters.entrySet()) {
BzzStoreReqMessage msg = new BzzStoreReqMessage(e.getKey(), chunk.getKey(), chunk.getData());
int counter = requesterCount;
for (BzzRetrieveReqMessage r : e.getValue()) {
r.getPeer().sendMessage(msg);
statOutStoreReq.add(1);
if (--counter < 0) {
break;
}
}
}
}
// store propagates store requests to specific peers given by the kademlia hive
// except for peers that the store request came from (if any)
private void store(final Chunk chunk) {
final PeerAddress chunkStoreRequestSource = chunkSourceAddr.get(chunk);
hive.addTask(hive.new HiveTask(chunk.getKey(), timeout, maxStorePeers) {
@Override
protected void processPeer(BzzProtocol peer) {
if (chunkStoreRequestSource == null || !chunkStoreRequestSource.equals(peer.getNode())) {
BzzStoreReqMessage msg = new BzzStoreReqMessage(chunk.getKey(), chunk.getData());
peer.sendMessage(msg);
}
}
});
}
private Map<Chunk, PeerAddress> chunkSourceAddr = new IdentityHashMap<>();
private Map<Key, ChunkRequest> chunkRequestMap = new HashMap<>();
/******************************************
* Get methods
******************************************/
@Override
// Get is the entrypoint for local retrieve requests
// waits for response or times out
public Chunk get(Key key) {
try {
return getAsync(key).get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
public synchronized Future<Chunk> getAsync(Key key) {
Chunk chunk = localStore.get(key);
Promise<Chunk> ret = new DefaultPromise<Chunk>() {};
if (chunk == null) {
// long timeout = 0; // TODO
ChunkRequest chunkRequest = new ChunkRequest();
chunkRequest.localRequesters.add(ret);
chunkRequestMap.put(key, chunkRequest);
startSearch(-1, key, timeout);
} else {
ret.setSuccess(chunk);
}
return ret;
}
// entrypoint for network retrieve requests
public void addRetrieveRequest(BzzRetrieveReqMessage req) {
statInGetReq.add(1);
Chunk chunk = localStore.get(req.getKey());
ChunkRequest chunkRequest = chunkRequestMap.get(req.getKey());
if (chunk == null) {
peers(req, chunk, 0);
if (chunkRequest == null && !req.getKey().isZero()) {
chunkRequestMap.put(req.getKey(), new ChunkRequest());
long timeout = strategyUpdateRequest(chunkRequestMap.get(req.getKey()), req);
startSearch(req.getId(), req.getKey(), timeout);
}
// req.timeout = +10sec // TODO ???
} else {
long timeout = strategyUpdateRequest(chunkRequestMap.get(req.getKey()), req);
if (chunkRequest != null) {
chunkRequest.status = EntryReqStatus.Found;
}
deliver(req, chunk);
}
}
// logic propagating retrieve requests to peers given by the kademlia hive
// it's assumed that caller holds the lock
private Chunk startSearch(long id, Key key, long timeout) {
final ChunkRequest chunkRequest = chunkRequestMap.get(key);
chunkRequest.status = EntryReqStatus.Searching;
final BzzRetrieveReqMessage req = new BzzRetrieveReqMessage(key/*, timeout*/);
hive.addTask(hive.new HiveTask(key, timeout, maxSearchPeers) {
@Override
protected void processPeer(BzzProtocol peer) {
boolean requester = false;
out:
for (Collection<BzzRetrieveReqMessage> chReqColl : chunkRequest.requesters.values()) {
for (BzzRetrieveReqMessage chReq : chReqColl) {
if (chReq.getPeer().getNode().equals(peer.getNode())) {
requester = true;
break out;
}
}
}
if (!requester) {
statOutGetReq.add(1);
peer.sendMessage(req);
}
}
});
return null;
}
// add peer request the chunk and decides the timeout for the response if still searching
private long strategyUpdateRequest(ChunkRequest chunkRequest, BzzRetrieveReqMessage req) {
if (chunkRequest != null && chunkRequest.status == EntryReqStatus.Searching) {
addRequester(chunkRequest, req);
return searchingTimeout(chunkRequest, req);
} else {
return -1;
}
}
/*
adds a new peer to an existing open request
only add if less than requesterCount peers forwarded the same request id so far
note this is done irrespective of status (searching or found)
*/
void addRequester(ChunkRequest rs, BzzRetrieveReqMessage req) {
Collection<BzzRetrieveReqMessage> list = rs.requesters.get(req.getId());
if (list == null) {
list = new ArrayList<>();
rs.requesters.put(req.getId(), list);
}
list.add(req);
}
// called on each request when a chunk is found,
// delivery is done by sending a request to the requesting peer
private void deliver(BzzRetrieveReqMessage req, Chunk chunk) {
BzzStoreReqMessage msg = new BzzStoreReqMessage(req.getId(), req.getKey(), chunk.getData());
req.getPeer().sendMessage(msg);
statOutStoreReq.add(1);
}
// the immediate response to a retrieve request,
// sends relevant peer data given by the kademlia hive to the requester
private void peers(BzzRetrieveReqMessage req, Chunk chunk, long timeout) {
// Collection<BzzProtocol> peers = hive.getPeers(req.getKey(), maxSearchPeers/*(int) req.getMaxPeers()*/);
// List<PeerAddress> peerAddrs = new ArrayList<>();
// for (BzzProtocol peer : peers) {
// peerAddrs.add(peer.getNode());
// }
Key key = req.getKey();
if (key.isZero()) {
key = new Key(req.getPeer().getNode().getId()); // .getAddrKey();
}
Collection<PeerAddress> nodes = hive.getNodes(key, maxSearchPeers);
BzzPeersMessage msg = new BzzPeersMessage(new ArrayList<>(nodes), timeout, req.getKey(), req.getId());
req.getPeer().sendMessage(msg);
}
private long searchingTimeout(ChunkRequest chunkRequest, BzzRetrieveReqMessage req) {
// TODO
return 0;
}
private enum EntryReqStatus {
Searching,
Found
}
private class ChunkRequest {
EntryReqStatus status = EntryReqStatus.Searching;
Map<Long, Collection<BzzRetrieveReqMessage>> requesters = new HashMap<>();
List<Promise<Chunk>> localRequesters = new ArrayList<>();
}
// Statistics gathers
public final Statter statInMsg = Statter.create("net.swarm.bzz.inMessages");
public final Statter statOutMsg = Statter.create("net.swarm.bzz.outMessages");
public final Statter statHandshakes = Statter.create("net.swarm.bzz.handshakes");
public final Statter statInStoreReq = Statter.create("net.swarm.in.storeReq");
public final Statter statInGetReq = Statter.create("net.swarm.in.getReq");
public final Statter statOutStoreReq = Statter.create("net.swarm.out.storeReq");
public final Statter statOutGetReq = Statter.create("net.swarm.out.getReq");
}
| 12,530
| 35.640351
| 113
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/StringTrie.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
import java.util.*;
/**
* Trie (or prefix tree) structure, which stores Nodes with String keys in highly branched structure
* for quick search by string prefixes.
* E.g. if there is a single node 'aaa' and the node 'aab' is added then the tree will look like:
* aa
* / \
* a b
* Where leaf nodes correspond to added elements
*
* @param <P> Subclass of TrieNode
*/
public abstract class StringTrie<P extends StringTrie.TrieNode<P>> {
/**
* Tree Node
*/
public static abstract class TrieNode<N extends TrieNode<N>> {
N parent;
Map<String, N> children = new LinkedHashMap<>();
String path; // path relative to parent
/**
* Create a root node (null parent and empty path)
*/
protected TrieNode() {
this(null, "");
}
public TrieNode(N parent, String relPath) {
this.parent = parent;
this.path = relPath;
}
public String getRelativePath() {
return path;
}
/**
* Calculates absolute path relative to the root node
*/
public String getAbsolutePath() {
return (parent != null ? parent.getAbsolutePath() : "") + path;
}
public N getParent() {
return parent;
}
/**
* Finds the descendant which has longest common path prefix with the passed path
*/
N getMostSuitableChild(String relPath) {
N n = loadChildren().get(getKey(relPath));
if (n == null) return (N) this;
if (relPath.startsWith(n.getRelativePath())) {
return n.getMostSuitableChild(relPath.substring(n.getRelativePath().length()));
} else {
return (N) this;
}
}
/**
* @return the direct child which has the key the same as the relPath key
* null if no such child
*/
N getChild(String relPath) {
return loadChildren().get(getKey(relPath));
}
/**
* Add a new descendant with specified path
* @param relPath the path relative to this node
* @return added node wich path is [relPath] relative to this node
*/
N add(String relPath) {
return addChild(relPath);
}
N addChild(String relPath) {
N child = getChild(relPath);
if (child == null) {
N newNode = createNode((N) this, relPath);
putChild(newNode);
return newNode;
} else {
if (!child.isLeaf() && relPath.startsWith(child.getRelativePath())) {
return child.addChild(relPath.substring(child.getRelativePath().length()));
}
if (child.isLeaf() && relPath.equals(child.getRelativePath())) {
return child;
}
String commonPrefix = Util.getCommonPrefix(relPath, child.getRelativePath());
N newSubRoot = createNode((N) this, commonPrefix);
child.path = child.path.substring(commonPrefix.length());
child.parent = newSubRoot;
N newNode = createNode(newSubRoot, relPath.substring(commonPrefix.length()));
newSubRoot.putChild(child);
newSubRoot.putChild(newNode);
this.putChild(newSubRoot);
newSubRoot.nodeChanged();
this.nodeChanged();
child.nodeChanged();
return newNode;
}
}
/**
* Deletes current leaf node, rebalancing the tree if needed
* @throws RuntimeException if this node is not leaf
*/
void delete() {
if (!isLeaf()) throw new RuntimeException("Can't delete non-leaf entry: " + this);
N parent = getParent();
parent.loadChildren().remove(getKey(getRelativePath()));
if (parent.loadChildren().size() == 1 && parent.parent != null) {
Map<String, N> c = parent.loadChildren();
N singleChild = c.values().iterator().next();
singleChild.path = parent.path + singleChild.path;
singleChild.parent = parent.parent;
parent.parent.loadChildren().remove(getKey(parent.path));
parent.parent.putChild(singleChild);
parent.parent.nodeChanged();
singleChild.nodeChanged();
}
}
void putChild(N n) {
loadChildren().put(getKey(n.path), n);
}
/**
* Returns the children if any. Doesn't cause any lazy loading
*/
public Collection<N> getChildren() {
return children.values();
}
/**
* Returns the children after loading (if required)
*/
protected Map<String, N> loadChildren() {
return children;
}
public boolean isLeaf() {
return loadChildren().isEmpty();
}
/**
* Calculates the key for the string prefix.
* The longer the key the more children remain on the same tree level
* I.e. if the key is the first character of the path (e.g. with ASCII only chars),
* the max number of children in a single node is 128.
* @return Key corresponding to this path
*/
protected String getKey(String path) {
return path.length() > 0 ? path.substring(0,1) : "";
}
/**
* Subclass should create the instance of its own class
* normally the implementation should invoke TrieNode(parent, path) superconstructor.
*/
protected abstract N createNode(N parent, String path);
/**
* The node is notified on changes (either its path or direct children changed)
*/
protected void nodeChanged() {}
}
P rootNode;
public StringTrie(P rootNode) {
this.rootNode = rootNode;
}
public P get(String path) {
return rootNode.getMostSuitableChild(path);
}
public P add(String path) {
return add(rootNode, path);
}
public P add(P parent, String path) {
return parent.addChild(path);
}
public P delete(String path) {
P p = get(path);
if (path.equals(p.getAbsolutePath()) && p.isLeaf()) {
p.delete();
return p;
} else {
return null;
}
}
/**
* @return Pre-order walk tree elements iterator
*/
// public Iterator<P> iterator() {
// return new Iterator<P>() {
// P curNode = rootNode;
// Stack<Iterator<P>> childIndices = new Stack<>();
//
// @Override
// public boolean hasNext() {
// return curNode != null;
// }
//
// @Override
// public P next() {
// P ret = curNode;
// if (!curNode.getChildren().isEmpty()) {
// Iterator<P> it = curNode.getChildren().iterator();
// childIndices.push(it);
// curNode = it.next();
// } else {
// curNode = null;
// while(curNode != null && !childIndices.isEmpty()) {
// Iterator<P> peek = childIndices.peek();
// if (peek.hasNext()) {
// curNode = peek.next();
// } else {
// childIndices.pop();
// }
// }
// }
// return ret;
// }
// };
// }
//
// /**
// * @return Pre-order walk tree non-leaf elements iterator
// */
// public Iterator<P> nonLeafIterator() {
// return new Iterator<P>() {
// Iterator<P> leafIt = iterator();
// P cur = findNext();
//
// @Override
// public boolean hasNext() {
// return cur != null;
// }
//
// @Override
// public P next() {
// P ret = cur;
// cur = findNext();
// return ret;
// }
//
// private P findNext() {
// P ret = null;
// while(leafIt.hasNext() && (ret = leafIt.next()).isLeaf());
// return ret;
// }
// };
// }
// protected abstract P createNode(P parent, String path);
//
// protected void nodeChanged(P node) {}
}
| 9,480
| 31.469178
| 100
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/TreeChunker.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
import org.ethereum.util.ByteUtil;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* From Go implementation:
*
* The distributed storage implemented in this package requires fix sized chunks of content
* Chunker is the interface to a component that is responsible for disassembling and assembling larger data.
* TreeChunker implements a Chunker based on a tree structure defined as follows:
* 1 each node in the tree including the root and other branching nodes are stored as a chunk.
* 2 branching nodes encode data contents that includes the size of the dataslice covered by its
* entire subtree under the node as well as the hash keys of all its children
* data_{i} := size(subtree_{i}) || key_{j} || key_{j+1} .... || key_{j+n-1}
* 3 Leaf nodes encode an actual subslice of the input data.
* 4 if data size is not more than maximum chunksize, the data is stored in a single chunk
* key = sha256(int64(size) + data)
* 2 if data size is more than chunksize*Branches^l, but no more than
* chunksize*Branches^l length (except the last one).
* key = sha256(int64(size) + key(slice0) + key(slice1) + ...)
* Tree chunker is a concrete implementation of data chunking.
* This chunker works in a simple way, it builds a tree out of the document so that each node either
* represents a chunk of real data or a chunk of data representing an branching non-leaf node of the tree.
* In particular each such non-leaf chunk will represent is a concatenation of the hash of its respective children.
* This scheme simultaneously guarantees data integrity as well as self addressing. Abstract nodes are
* transparent since their represented size component is strictly greater than their maximum data size,
* since they encode a subtree.
* If all is well it is possible to implement this by simply composing readers so that no extra allocation or
* buffering is necessary for the data splitting and joining. This means that in principle there
* can be direct IO between : memory, file system, network socket (bzz peers storage request is
* read from the socket ). In practice there may be need for several stages of internal buffering.
* Unfortunately the hashing itself does use extra copies and allocation though since it does need it.
*/
public class TreeChunker implements Chunker {
public static final MessageDigest DEFAULT_HASHER;
private static final int DEFAULT_BRANCHES = 128;
static {
try {
DEFAULT_HASHER = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e); // Can't happen.
}
}
public class TreeChunk extends Chunk {
private static final int DATA_OFFSET = 8;
public TreeChunk(int dataSize) {
super(null, new byte[DATA_OFFSET + dataSize]);
setSubtreeSize(dataSize);
}
public TreeChunk(Chunk chunk) {
super(chunk.getKey(), chunk.getData());
}
public void setSubtreeSize(long size) {
ByteBuffer.wrap(getData()).order(ByteOrder.LITTLE_ENDIAN).putLong(0, size);
}
public long getSubtreeSize() {
return ByteBuffer.wrap(getData()).order(ByteOrder.LITTLE_ENDIAN).getLong(0);
}
public int getDataOffset() {
return DATA_OFFSET;
}
public Key getKey() {
if (key == null) {
key = new Key(hasher.digest(getData()));
}
return key;
}
@Override
public String toString() {
String dataString = ByteUtil.toHexString(
Arrays.copyOfRange(getData(), getDataOffset(), getDataOffset() + 16)) + "...";
return "TreeChunk[" + getSubtreeSize() + ", " + getKey() + ", " + dataString + "]";
}
}
public class HashesChunk extends TreeChunk {
public HashesChunk(long subtreeSize) {
super(branches * hashSize);
setSubtreeSize(subtreeSize);
}
public HashesChunk(Chunk chunk) {
super(chunk);
}
public int getKeyCount() {
return branches;
}
public Key getKey(int idx) {
int off = getDataOffset() + idx * hashSize;
return new Key(Arrays.copyOfRange(getData(), off, off + hashSize));
}
public void setKey(int idx, Key key) {
int off = getDataOffset() + idx * hashSize;
System.arraycopy(key.getBytes(), 0, getData(), off, hashSize);
}
@Override
public String toString() {
String hashes = "{";
for (int i = 0; i < getKeyCount(); i++) {
hashes += (i == 0 ? "" : ", ") + getKey(i);
}
hashes += "}";
return "HashesChunk[" + getSubtreeSize() + ", " + getKey() + ", " + hashes + "]";
}
}
private class TreeSize {
int depth;
long treeSize;
public TreeSize(long dataSize) {
treeSize = chunkSize;
for (; treeSize < dataSize; treeSize *= branches) {
depth++;
}
}
}
private int branches;
private MessageDigest hasher;
private int hashSize;
private long chunkSize;
public TreeChunker() {
this(DEFAULT_BRANCHES, DEFAULT_HASHER);
}
public TreeChunker(int branches, MessageDigest hasher) {
this.branches = branches;
this.hasher = hasher;
hashSize = hasher.getDigestLength();
chunkSize = hashSize * branches;
}
public long getChunkSize() {
return chunkSize;
}
@Override
public Key split(SectionReader sectionReader, Collection<Chunk> consumer) {
TreeSize ts = new TreeSize(sectionReader.getSize());
return splitImpl(ts.depth, ts.treeSize/branches, sectionReader, consumer);
}
private Key splitImpl(int depth, long treeSize, SectionReader data, Collection<Chunk> consumer) {
long size = data.getSize();
TreeChunk newChunk;
while (depth > 0 && size < treeSize) {
treeSize /= branches;
depth--;
}
if (depth == 0) {
newChunk = new TreeChunk((int) size); // safe to cast since leaf chunk size < 2Gb
data.read(newChunk.getData(), newChunk.getDataOffset());
} else {
// intermediate chunk containing child nodes hashes
int branchCnt = (int) ((size + treeSize - 1) / treeSize);
HashesChunk hChunk = new HashesChunk(size);
long pos = 0;
long secSize;
// TODO the loop can be parallelized
for (int i = 0; i < branchCnt; i++) {
// the last item can have shorter data
if (size-pos < treeSize) {
secSize = size - pos;
} else {
secSize = treeSize;
}
// take the section of the data corresponding encoded in the subTree
SectionReader subTreeData = new SlicedReader(data, pos, secSize);
// the hash of that data
Key subTreeKey = splitImpl(depth-1, treeSize/branches, subTreeData, consumer);
hChunk.setKey(i, subTreeKey);
pos += treeSize;
}
// now we got the hashes in the chunk, then hash the chunk
newChunk = hChunk;
}
consumer.add(newChunk);
// report hash of this chunk one level up (keys corresponds to the proper subslice of the parent chunk)x
return newChunk.getKey();
}
@Override
public SectionReader join(ChunkStore chunkStore, Key key) {
return new LazyChunkReader(chunkStore, key);
}
@Override
public long keySize() {
return hashSize;
}
private class LazyChunkReader implements SectionReader {
Key key;
ChunkStore chunkStore;
final long size;
final Chunk root;
public LazyChunkReader(ChunkStore chunkStore, Key key) {
this.chunkStore = chunkStore;
this.key = key;
root = chunkStore.get(key);
this.size = new TreeChunk(root).getSubtreeSize();
}
@Override
public int readAt(byte[] dest, int destOff, long readerOffset) {
int size = dest.length - destOff;
TreeSize ts = new TreeSize(this.size);
return readImpl(dest, destOff, root, ts.treeSize, 0, readerOffset,
readerOffset + min(size, this.size - readerOffset));
}
private int readImpl(byte[] dest, int destOff, Chunk chunk, long chunkWidth, long chunkStart,
long readStart, long readEnd) {
long chunkReadStart = max(readStart - chunkStart, 0);
long chunkReadEnd = min(chunkWidth, readEnd - chunkStart);
int ret = 0;
if (chunkWidth > chunkSize) {
long subChunkWidth = chunkWidth / branches;
if (chunkReadStart >= chunkWidth || chunkReadEnd <= 0) {
throw new RuntimeException("Not expected.");
}
int startSubChunk = (int) (chunkReadStart / subChunkWidth);
int lastSubChunk = (int) ((chunkReadEnd - 1) / subChunkWidth);
// TODO the loop can be parallelized
for (int i = startSubChunk; i <= lastSubChunk; i++) {
HashesChunk hChunk = new HashesChunk(chunk);
Chunk subChunk = chunkStore.get(hChunk.getKey(i));
ret += readImpl(dest, (int) (destOff + (i - startSubChunk) * subChunkWidth),
subChunk, subChunkWidth, chunkStart + i * subChunkWidth, readStart, readEnd);
}
} else {
TreeChunk dataChunk = new TreeChunk(chunk);
ret = (int) (chunkReadEnd - chunkReadStart);
System.arraycopy(dataChunk.getData(), (int) (dataChunk.getDataOffset() + chunkReadStart),
dest, destOff, ret);
}
return ret;
}
@Override
public long seek(long offset, int whence) {
throw new RuntimeException("Not implemented");
}
@Override
public long getSize() {
return size;
}
@Override
public int read(byte[] dest, int destOff) {
return readAt(dest, destOff, 0);
}
}
/**
* A 'subReader'
*/
public static class SlicedReader implements SectionReader {
SectionReader delegate;
long offset;
long len;
public SlicedReader(SectionReader delegate, long offset, long len) {
this.delegate = delegate;
this.offset = offset;
this.len = len;
}
@Override
public long seek(long offset, int whence) {
return delegate.seek(this.offset + offset, whence);
}
@Override
public int read(byte[] dest, int destOff) {
return delegate.readAt(dest, destOff, offset);
}
@Override
public int readAt(byte[] dest, int destOff, long readerOffset) {
return delegate.readAt(dest, destOff, offset + readerOffset);
}
@Override
public long getSize() {
return len;
}
}
}
| 12,525
| 34.585227
| 117
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/SectionReader.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
/**
* Interface similar to ByteBuffer for reading large streaming or random access data
*
* Created by Anton Nashatyrev on 18.06.2015.
*/
public interface SectionReader {
long seek(long offset, int whence /* ??? */);
int read(byte[] dest, int destOff);
int readAt(byte[] dest, int destOff, long readerOffset);
long getSize();
}
| 1,175
| 32.6
| 84
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/Chunk.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
/**
* Any binary data with its key
* The key is normally SHA3(data)
*/
public class Chunk {
protected Key key;
protected byte[] data;
public Chunk(Key key, byte[] data) {
this.key = key;
this.data = data;
}
public Key getKey() {
return key;
}
public byte[] getData() {
return data;
}
}
| 1,183
| 26.534884
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/ChunkStore.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
/**
* Self-explanatory interface
*
* Created by Anton Nashatyrev on 18.06.2015.
*/
public interface ChunkStore {
void put(Chunk chunk);
Chunk get(Key key);
}
| 995
| 31.129032
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/LocalStore.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
/**
* Manages the local ChunkStore
*
* Uses {@link DBStore} for slow access long living data
* and {@link MemStore} for fast access short living
*
* Created by Anton Nashatyrev on 18.06.2015.
*/
public class LocalStore implements ChunkStore {
public ChunkStore dbStore;
ChunkStore memStore;
public LocalStore(ChunkStore dbStore, ChunkStore memStore) {
this.dbStore = dbStore;
this.memStore = memStore;
}
@Override
public void put(Chunk chunk) {
memStore.put(chunk);
// TODO make sure this is non-blocking call
dbStore.put(chunk);
}
@Override
public Chunk get(Key key) {
Chunk chunk = memStore.get(key);
if (chunk == null) {
chunk = dbStore.get(key);
}
return chunk;
}
// for testing
public void clean() {
for (ChunkStore chunkStore : new ChunkStore[]{dbStore, memStore}) {
if (chunkStore instanceof MemStore) {
((MemStore)chunkStore).clear();
}
}
}
}
| 1,878
| 28.825397
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/Hive.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.rlpx.discover.table.NodeEntry;
import org.ethereum.net.rlpx.discover.table.NodeTable;
import org.ethereum.net.swarm.bzz.BzzPeersMessage;
import org.ethereum.net.swarm.bzz.BzzProtocol;
import org.ethereum.net.swarm.bzz.PeerAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.util.*;
/**
* Serves as an interface to the Kademlia. Manages the database of Nodes reported
* by all the peers and selects from DB the nearest nodes to the specified hash Key
*
* Created by Anton Nashatyrev on 18.06.2015.
*/
public class Hive {
private final static Logger LOG = LoggerFactory.getLogger("net.bzz");
private PeerAddress thisAddress;
protected NodeTable nodeTable;
private Map<Node, BzzProtocol> connectedPeers = new IdentityHashMap<>();
public Hive(PeerAddress thisAddress) {
this.thisAddress = thisAddress;
nodeTable = new NodeTable(thisAddress.toNode());
}
public void start() {}
public void stop() {}
public PeerAddress getSelfAddress() {
return thisAddress;
}
public void addPeer(BzzProtocol peer) {
Node node = peer.getNode().toNode();
nodeTable.addNode(node);
connectedPeers.put(node, peer);
LOG.info("Hive added a new peer: " + peer);
peersAdded();
}
public void removePeer(BzzProtocol peer) {
nodeTable.dropNode(peer.getNode().toNode());
}
/**
* Finds the nodes which are not connected yet
* TODO review this method later
*/
public Collection<PeerAddress> getNodes(Key key, int max) {
List<Node> closestNodes = nodeTable.getClosestNodes(key.getBytes());
ArrayList<PeerAddress> ret = new ArrayList<>();
for (Node node : closestNodes) {
ret.add(new PeerAddress(node));
if (--max == 0) break;
}
return ret;
}
/**
* Returns the peers in the DB which are closest to the specified key
* but not more peers than {#maxCount}
*/
public Collection<BzzProtocol> getPeers(Key key, int maxCount) {
List<Node> closestNodes = nodeTable.getClosestNodes(key.getBytes());
ArrayList<BzzProtocol> ret = new ArrayList<>();
for (Node node : closestNodes) {
// TODO connect to Node
// ret.add(thisPeer.getPeer(new PeerAddress(node)));
BzzProtocol peer = connectedPeers.get(node);
if (peer != null) {
ret.add(peer);
if (--maxCount == 0) break;
} else {
LOG.info("Hive connects to node " + node);
NetStore.getInstance().worldManager.getActivePeer().connect(node.getHost(), node.getPort(), Hex.toHexString(node.getId()));
}
}
return ret;
}
public void newNodeRecord(PeerAddress addr) {}
/**
* Adds the nodes received in the {@link BzzPeersMessage}
*/
public void addPeerRecords(BzzPeersMessage req) {
for (PeerAddress peerAddress : req.getPeers()) {
nodeTable.addNode(peerAddress.toNode());
}
LOG.debug("Hive added new nodes: " + req.getPeers());
peersAdded();
}
protected void peersAdded() {
for (HiveTask task : new ArrayList<>(hiveTasks.keySet())) {
if (!task.peersAdded()) {
hiveTasks.remove(task);
LOG.debug("HiveTask removed from queue: " + task);
}
}
}
/**
* For testing
*/
public Map<Node, BzzProtocol> getAllEntries() {
Map<Node, BzzProtocol> ret = new LinkedHashMap<>();
for (NodeEntry entry : nodeTable.getAllNodes()) {
Node node = entry.getNode();
BzzProtocol bzz = connectedPeers.get(node);
ret.put(node, bzz);
}
return ret;
}
/**
* Adds a task with a search Key parameter. The task has a limited life time
* ({@link org.ethereum.net.swarm.Hive.HiveTask#expireTime} and a limited number of
* peers to process ({@link org.ethereum.net.swarm.Hive.HiveTask#maxPeers}).
* Until the task is alive and new Peer(s) is discovered by the Hive this task
* is invoked with another one closest Peer.
* This task may complete synchronously (i.e. before the method return) if the
* number of Peers in the Hive >= maxPeers for that task.
*/
public void addTask(HiveTask t) {
if (t.peersAdded()) {
LOG.debug("Added a HiveTask to queue: " + t);
hiveTasks.put(t, null);
}
}
private Map<HiveTask, Object> hiveTasks = new IdentityHashMap<>();
/**
* The task to be executed when another one closest Peer is discovered
* until the timeout or maxPeers is reached.
*/
public abstract class HiveTask {
Key targetKey;
Map<BzzProtocol, Object> processedPeers = new IdentityHashMap<>();
long expireTime;
int maxPeers;
public HiveTask(Key targetKey, long timeout, int maxPeers) {
this.targetKey = targetKey;
this.expireTime = Util.curTime() + timeout;
this.maxPeers = maxPeers;
}
/**
* Notifies the task that new peers were connected.
* @return true if the task wants to wait further for another peers
* false if the task is completed
*/
public boolean peersAdded() {
if (Util.curTime() > expireTime) return false;
Collection<BzzProtocol> peers = getPeers(targetKey, maxPeers);
for (BzzProtocol peer : peers) {
if (!processedPeers.containsKey(peer)) {
processPeer(peer);
processedPeers.put(peer, null);
if (processedPeers.size() > maxPeers) {
return false;
}
}
}
return true;
}
protected abstract void processPeer(BzzProtocol peer);
}
}
| 6,913
| 33.919192
| 139
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/DPA.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
/**
* Distributed Preimage Archive
* Acts as a high-level API to the Swarm
*
* From Go implementation:
* DPA provides the client API entrypoints Store and Retrieve to store and retrieve
* It can store anything that has a byte slice representation, so files or serialised objects etc.
* Storage: DPA calls the Chunker to segment the input datastream of any size to a merkle hashed tree of chunks.
* The key of the root block is returned to the client.
* Retrieval: given the key of the root block, the DPA retrieves the block chunks and reconstructs the original
* data and passes it back as a lazy reader. A lazy reader is a reader with on-demand delayed processing,
* i.e. the chunks needed to reconstruct a large file are only fetched and processed if that particular part
* of the document is actually read.
* As the chunker produces chunks, DPA dispatches them to the chunk store for storage or retrieval.
* The ChunkStore interface is implemented by :
* - memStore: a memory cache
* - dbStore: local disk/db store
* - localStore: a combination (sequence of) memStore and dbStore
* - netStore: dht storage
*
* Created by Anton Nashatyrev on 18.06.2015.
*/
public class DPA {
// this is now the default and the only possible Chunker implementation
private Chunker chunker = new TreeChunker();
private ChunkStore chunkStore;
public DPA(ChunkStore chunkStore) {
this.chunkStore = chunkStore;
}
/**
* Main entry point for document storage directly. Used by the
* FS-aware API and httpaccess
*
* @return key
*/
public Key store(SectionReader reader) {
return chunker.split(reader, new Util.ChunkConsumer(chunkStore));
}
/**
* Main entry point for document retrieval directly. Used by the
* FS-aware API and httpaccess
* Chunk retrieval blocks on netStore requests with a timeout so reader will
* report error if retrieval of chunks within requested range time out.
*
* @return key
*/
public SectionReader retrieve(Key key) {
return chunker.join(chunkStore, key);
}
}
| 2,943
| 39.328767
| 112
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/Key.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
import org.ethereum.util.ByteUtil;
import org.spongycastle.util.encoders.Hex;
import java.util.Arrays;
/**
* Data key, just a wrapper for byte array. Normally the SHA(data)
*
* Created by Anton Nashatyrev on 18.06.2015.
*/
public class Key {
public static Key zeroKey() {
return new Key(new byte[0]);
}
private final byte[] bytes;
public Key(byte[] bytes) {
this.bytes = bytes;
}
public Key(String hexKey) {
this(Hex.decode(hexKey));
}
public byte[] getBytes() {
return bytes;
}
public boolean isZero() {
if (bytes == null || bytes.length == 0) return true;
for (byte b: bytes) {
if (b != 0) return false;
}
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
return Arrays.equals(bytes, key.bytes);
}
public String getHexString() {
return Hex.toHexString(getBytes());
}
@Override
public int hashCode() {
return Arrays.hashCode(bytes);
}
@Override
public String toString() {
return getBytes() == null ? "<null>" : ByteUtil.toHexString(getBytes());
}
}
| 2,127
| 24.95122
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/Util.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.Utils;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.LinkedBlockingQueue;
import static java.lang.Math.min;
/**
* Created by Admin on 17.06.2015.
*/
public class Util {
public static class ChunkConsumer extends LinkedBlockingQueue<Chunk> {
ChunkStore destination;
boolean synchronous = true;
public ChunkConsumer(ChunkStore destination) {
this.destination = destination;
}
@Override
public boolean add(Chunk chunk) {
if (synchronous) {
destination.put(chunk);
return true;
} else {
return super.add(chunk);
}
}
}
public static class ArrayReader implements SectionReader {
byte[] arr;
public ArrayReader(byte[] arr) {
this.arr = arr;
}
@Override
public long seek(long offset, int whence) {
throw new RuntimeException("Not implemented");
}
@Override
public int read(byte[] dest, int destOff) {
return readAt(dest, destOff, 0);
}
@Override
public int readAt(byte[] dest, int destOff, long readerOffset) {
int len = min(dest.length - destOff, arr.length - (int)readerOffset);
System.arraycopy(arr, (int) readerOffset, dest, destOff, len);
return len;
}
@Override
public long getSize() {
return arr.length;
}
}
// for testing purposes when the timer might be changed
// to manage current time according to test scenarios
public static Timer TIMER = new Timer();
public static class Timer {
public long curTime() {
return System.currentTimeMillis();
}
}
public static String getCommonPrefix(String s1, String s2) {
int pos = 0;
while(pos < s1.length() && pos < s2.length() && s1.charAt(pos) == s2.charAt(pos)) pos++;
return s1.substring(0, pos);
}
public static String ipBytesToString(byte[] ipAddr) {
StringBuilder sip = new StringBuilder();
for (int i = 0; i < ipAddr.length; i++) {
sip.append(i == 0 ? "" : ".").append(0xFF & ipAddr[i]);
}
return sip.toString();
}
public static <P extends StringTrie.TrieNode<P>> String dumpTree(P n) {
return dumpTree(n, 0);
}
private static <P extends StringTrie.TrieNode<P>> String dumpTree(P n, int indent) {
String ret = Utils.repeat(" ", indent) + "[" + n.path + "] " + n + "\n";
for (P c: n.getChildren()) {
ret += dumpTree(c, indent + 1);
}
return ret;
}
public static byte[] uInt16ToBytes(int uInt16) {
return new byte[] {(byte) ((uInt16 >> 8) & 0xFF), (byte) (uInt16 & 0xFF)};
}
public static long curTime() { return TIMER.curTime();}
public static byte[] rlpEncodeLong(long n) {
// TODO for now leaving int cast
return RLP.encodeInt((int) n);
}
public static byte rlpDecodeByte(RLPElement elem) {
return (byte) rlpDecodeInt(elem);
}
public static long rlpDecodeLong(RLPElement elem) {
return rlpDecodeInt(elem);
}
public static int rlpDecodeInt(RLPElement elem) {
byte[] b = elem.getRLPData();
if (b == null) return 0;
return ByteUtil.byteArrayToInt(b);
}
public static String rlpDecodeString(RLPElement elem) {
byte[] b = elem.getRLPData();
if (b == null) return null;
return new String(b);
}
public static byte[] rlpEncodeList(Object ... elems) {
byte[][] encodedElems = new byte[elems.length][];
for (int i =0; i < elems.length; i++) {
if (elems[i] instanceof Byte) {
encodedElems[i] = RLP.encodeByte((Byte) elems[i]);
} else if (elems[i] instanceof Integer) {
encodedElems[i] = RLP.encodeInt((Integer) elems[i]);
} else if (elems[i] instanceof Long) {
encodedElems[i] = rlpEncodeLong((Long) elems[i]);
} else if (elems[i] instanceof String) {
encodedElems[i] = RLP.encodeString((String) elems[i]);
} else if (elems[i] instanceof byte[]) {
encodedElems[i] = ((byte[]) elems[i]);
} else {
throw new RuntimeException("Unsupported object: " + elems[i]);
}
}
return RLP.encodeList(encodedElems);
}
public static SectionReader stringToReader(String s) {
return new ArrayReader(s.getBytes(StandardCharsets.UTF_8));
}
public static String readerToString(SectionReader sr) {
byte[] bb = new byte[(int) sr.getSize()];
sr.read(bb, 0);
String s = new String(bb, StandardCharsets.UTF_8);
return s;
}
}
| 5,829
| 30.857923
| 96
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/BzzStoreReqMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import org.ethereum.net.client.Capability;
import org.ethereum.net.swarm.Key;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BzzStoreReqMessage extends BzzMessage {
private Key key;
private byte[] data;
// optional
byte[] metadata = new byte[0];
public BzzStoreReqMessage(byte[] encoded) {
super(encoded);
}
public BzzStoreReqMessage(long id, Key key, byte[] data) {
this.id = id;
this.key = key;
this.data = data;
}
public BzzStoreReqMessage(Key key, byte[] data) {
this.key = key;
this.data = data;
}
@Override
protected void decode() {
RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
key = new Key(paramsList.get(0).getRLPData());
data = paramsList.get(1).getRLPData();
if (paramsList.size() > 2) {
id = ByteUtil.byteArrayToLong(paramsList.get(2).getRLPData());
}
if (paramsList.size() > 3) {
metadata = paramsList.get(2).getRLPData();
}
parsed = true;
}
private void encode() {
List<byte[]> elems = new ArrayList<>();
elems.add(RLP.encodeElement(key.getBytes()));
elems.add(RLP.encodeElement(data));
// if (id >= 0 || metadata != null) {
elems.add(RLP.encodeInt((int) id));
// }
// if (metadata != null) {
elems.add(RLP.encodeList(metadata));
// }
this.encoded = RLP.encodeList(elems.toArray(new byte[0][]));
}
@Override
public byte[] getEncoded() {
if (encoded == null) encode();
return encoded;
}
@Override
public Class<?> getAnswerMessage() {
return null;
}
@Override
public BzzMessageCodes getCommand() {
return BzzMessageCodes.STORE_REQUEST;
}
public Key getKey() {
return key;
}
public byte[] getData() {
return data;
}
public byte[] getMetadata() {
return metadata;
}
@Override
public String toString() {
return "BzzStoreReqMessage{" +
"key=" + key +
", data=" + Arrays.toString(data) +
", id=" + id +
", metadata=" + Arrays.toString(metadata) +
'}';
}
}
| 3,298
| 26.040984
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/BzzProtocol.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import org.ethereum.net.client.Capability;
import org.ethereum.net.swarm.Key;
import org.ethereum.net.swarm.NetStore;
import org.ethereum.net.swarm.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import static java.lang.Math.min;
/**
* The class is the lowest level right above the network layer.
* Responsible for BZZ handshaking, brokering inbound messages
* and delivering outbound messages.
*
* Created by Anton Nashatyrev on 18.06.2015.
*/
public class BzzProtocol implements Consumer<BzzMessage> {
private final static Logger LOG = LoggerFactory.getLogger("net.bzz");
private final static AtomicLong idGenerator = new AtomicLong(0);
public final static int Version = 0;
public final static long ProtocolLength = 8;
public final static long ProtocolMaxMsgSize = 10 * 1024 * 1024;
public final static int NetworkId = 0;
public final static int Strategy = 0;
private NetStore netStore;
private Consumer<BzzMessage> messageSender;
private PeerAddress node;
private boolean handshaken = false;
private boolean handshakeOut = false;
private List<BzzMessage> pendingHandshakeOutMessages = new ArrayList<>();
private List<BzzMessage> pendingHandshakeInMessages = new ArrayList<>();
public BzzProtocol(NetStore netStore) {
this.netStore = netStore;
}
/**
* Installs the message sender.
* Normally this is BzzHandler which just sends the message to the peer over the wire
* In the testing environment this could be a special handler which delivers the message
* without network stack
*/
public void setMessageSender(Consumer<BzzMessage> messageSender) {
this.messageSender = messageSender;
}
public void start() {
handshakeOut();
}
/**
* Gets the address of the Peer connected to this instance.
*/
public PeerAddress getNode() {
return node;
}
/**
* Sends the Status message to the peer
*/
private void handshakeOut() {
if (!handshakeOut) {
handshakeOut = true;
BzzStatusMessage outStatus = new BzzStatusMessage(Version, "honey",
netStore.getSelfAddress(), NetworkId,
Collections.singletonList(new Capability(Capability.BZZ, (byte) 0)));
LOG.info("Outbound handshake: " + outStatus);
sendMessageImpl(outStatus);
}
}
/**
* Handles inbound Status Message
*/
private void handshakeIn(BzzStatusMessage msg) {
if (!handshaken) {
LOG.info("Inbound handshake: " + msg);
netStore.statHandshakes.add(1);
// TODO check status parameters
node = msg.getAddr();
netStore.getHive().addPeer(this);
handshaken = true;
handshakeOut();
start();
if (!pendingHandshakeOutMessages.isEmpty()) {
LOG.info("Send pending handshake messages: " + pendingHandshakeOutMessages.size());
for (BzzMessage pmsg : pendingHandshakeOutMessages) {
sendMessageImpl(pmsg);
}
}
pendingHandshakeOutMessages = null;
// ping the peer for self neighbours
sendMessageImpl(new BzzRetrieveReqMessage(Key.zeroKey()));
if (!pendingHandshakeInMessages.isEmpty()) {
LOG.info("Processing pending handshake inbound messages: " + pendingHandshakeInMessages.size());
for (BzzMessage pmsg : pendingHandshakeInMessages) {
handleMsg(pmsg);
}
}
pendingHandshakeInMessages = null;
} else {
LOG.warn("Double inbound status message (ignore): " + msg);
}
}
public synchronized void sendMessage(BzzMessage msg) {
if (handshaken) {
sendMessageImpl(msg);
} else {
pendingHandshakeOutMessages.add(msg);
}
}
private void sendMessageImpl(BzzMessage msg) {
netStore.statOutMsg.add(1);
msg.setId(idGenerator.incrementAndGet());
LOG.debug("<=== (to " + addressToShortString(getNode()) + ") " + msg);
messageSender.accept(msg);
}
@Override
public void accept(BzzMessage bzzMessage) {
handleMsg(bzzMessage);
}
private void handleMsg(BzzMessage msg) {
synchronized (netStore) {
netStore.statInMsg.add(1);
msg.setPeer(this);
if (LOG.isDebugEnabled()) {
LOG.debug(" ===>(from " + addressToShortString(getNode()) + ") " + msg);
}
if (msg.getCommand() == BzzMessageCodes.STATUS) {
handshakeIn((BzzStatusMessage) msg);
} else {
if (!handshaken) {
pendingHandshakeInMessages.add(msg);
} else {
switch (msg.getCommand()) {
case STORE_REQUEST:
netStore.addStoreRequest((BzzStoreReqMessage) msg);
break;
case RETRIEVE_REQUEST:
netStore.addRetrieveRequest((BzzRetrieveReqMessage) msg);
break;
case PEERS:
netStore.getHive().addPeerRecords((BzzPeersMessage) msg);
break;
default:
LOG.error("Invalid BZZ command: " + msg.getCommand() + ": " + msg);
}
}
}
}
}
public static String addressToShortString(PeerAddress addr) {
if (addr == null) return "<null>";
String s = Hex.toHexString(addr.getId());
s = s.substring(0, min(8, s.length()));
return s + "@" + Util.ipBytesToString(addr.getIp()) + ":" + addr.getPort();
}
@Override
public String toString() {
return "BzzProtocol[" + netStore.getSelfAddress() + " => " + node + "]";
}
}
| 7,145
| 34.029412
| 112
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/BzzStatusMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import org.ethereum.net.client.Capability;
import org.ethereum.net.swarm.Util;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.ethereum.net.swarm.Util.*;
/**
* BZZ handshake message
*/
public class BzzStatusMessage extends BzzMessage {
private long version;
private String id;
private PeerAddress addr;
private long networkId;
private List<Capability> capabilities;
public BzzStatusMessage(byte[] encoded) {
super(encoded);
}
public BzzStatusMessage(int version, String id, PeerAddress addr, long networkId, List<Capability> capabilities) {
this.version = version;
this.id = id;
this.addr = addr;
this.networkId = networkId;
this.capabilities = capabilities;
parsed = true;
}
@Override
protected void decode() {
RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
version = rlpDecodeLong(paramsList.get(0));
id = rlpDecodeString(paramsList.get(1));
addr = PeerAddress.parse((RLPList) paramsList.get(2));
networkId = rlpDecodeInt(paramsList.get(3));
capabilities = new ArrayList<>();
RLPList caps = (RLPList) paramsList.get(4);
for (RLPElement c : caps) {
RLPList e = (RLPList) c;
capabilities.add(new Capability(rlpDecodeString(e.get(0)), rlpDecodeByte(e.get(1))));
}
parsed = true;
}
private void encode() {
byte[][] capabilities = new byte[this.capabilities.size()][];
for (int i = 0; i < this.capabilities.size(); i++) {
Capability capability = this.capabilities.get(i);
capabilities[i] = rlpEncodeList(capability.getName(),capability.getVersion());
}
this.encoded = rlpEncodeList(version, id, addr.encodeRlp(), networkId, rlpEncodeList(capabilities));
}
@Override
public byte[] getEncoded() {
if (encoded == null) encode();
return encoded;
}
/**
* BZZ protocol version
*/
public long getVersion() {
return version;
}
/**
* Gets the remote peer address
*/
public PeerAddress getAddr() {
return addr;
}
public long getNetworkId() {
return networkId;
}
public List<Capability> getCapabilities() {
return capabilities;
}
@Override
public Class<?> getAnswerMessage() {
return null;
}
@Override
public BzzMessageCodes getCommand() {
return BzzMessageCodes.STATUS;
}
@Override
public String toString() {
return "BzzStatusMessage{" +
"version=" + version +
", id='" + id + '\'' +
", addr=" + addr +
", networkId=" + networkId +
", capabilities=" + capabilities +
'}';
}
}
| 3,820
| 27.514925
| 118
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/BzzRetrieveReqMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import org.ethereum.net.swarm.Key;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Used for several purposes
* - the main is to ask for a {@link org.ethereum.net.swarm.Chunk} with the specified hash
* - ask to send back {#PEERS} message with the known nodes nearest to the specified hash
* - initial request after handshake with zero hash. On this request the nearest known
* neighbours are sent back with the {#PEERS} message.
*/
public class BzzRetrieveReqMessage extends BzzMessage {
private Key key;
// optional
private long maxSize = -1;
private long maxPeers = -1;
private long timeout = -1;
public BzzRetrieveReqMessage(byte[] encoded) {
super(encoded);
}
public BzzRetrieveReqMessage(Key key) {
this.key = key;
}
@Override
protected void decode() {
RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
key = new Key(paramsList.get(0).getRLPData());
if (paramsList.size() > 1) {
id = ByteUtil.byteArrayToLong(paramsList.get(1).getRLPData());
}
if (paramsList.size() > 2) {
maxSize = ByteUtil.byteArrayToLong(paramsList.get(2).getRLPData());
}
if (paramsList.size() > 3) {
maxPeers = ByteUtil.byteArrayToLong(paramsList.get(3).getRLPData());
}
if (paramsList.size() > 4) {
timeout = ByteUtil.byteArrayToLong(paramsList.get(3).getRLPData());
}
parsed = true;
}
private void encode() {
List<byte[]> elems = new ArrayList<>();
elems.add(RLP.encodeElement(key.getBytes()));
elems.add(RLP.encodeInt((int) id));
elems.add(RLP.encodeInt((int) maxSize));
elems.add(RLP.encodeInt((int) maxPeers));
elems.add(RLP.encodeInt((int) timeout));
this.encoded = RLP.encodeList(elems.toArray(new byte[0][]));
}
@Override
public byte[] getEncoded() {
if (encoded == null) encode();
return encoded;
}
public Key getKey() {
return key;
}
public long getMaxSize() {
return maxSize;
}
public long getMaxPeers() {
return maxPeers;
}
public long getTimeout() {
return timeout;
}
@Override
public Class<?> getAnswerMessage() {
return null;
}
@Override
public BzzMessageCodes getCommand() {
return BzzMessageCodes.RETRIEVE_REQUEST;
}
@Override
public String toString() {
return "BzzRetrieveReqMessage{" +
"key=" + key +
", id=" + id +
", maxSize=" + maxSize +
", maxPeers=" + maxPeers +
'}';
}
}
| 3,667
| 27.434109
| 90
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/BzzPeersMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import org.ethereum.net.swarm.Key;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPList;
import java.util.ArrayList;
import java.util.List;
/**
* The message is the immediate response on the {#RETRIEVE_REQUEST} with the nearest known nodes
* of the requested hash.
* Contains a list of nearest Nodes (addresses) to the requested hash.
*/
public class BzzPeersMessage extends BzzMessage {
private List<PeerAddress> peers;
long timeout;
// optional
private Key key;
public BzzPeersMessage(byte[] encoded) {
super(encoded);
}
public BzzPeersMessage(List<PeerAddress> peers, long timeout, Key key, long id) {
this.peers = peers;
this.timeout = timeout;
this.key = key;
this.id = id;
}
public BzzPeersMessage(List<PeerAddress> peers) {
this.peers = peers;
}
@Override
protected void decode() {
RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
peers = new ArrayList<>();
RLPList addrs = (RLPList) paramsList.get(0);
for (RLPElement a : addrs) {
peers.add(PeerAddress.parse((RLPList) a));
}
timeout = ByteUtil.byteArrayToLong(paramsList.get(1).getRLPData());;
if (paramsList.size() > 2) {
key = new Key(paramsList.get(2).getRLPData());
}
if (paramsList.size() > 3) {
id = ByteUtil.byteArrayToLong(paramsList.get(3).getRLPData());;
}
parsed = true;
}
private void encode() {
byte[][] bPeers = new byte[this.peers.size()][];
for (int i = 0; i < this.peers.size(); i++) {
PeerAddress peer = this.peers.get(i);
bPeers[i] = peer.encodeRlp();
}
byte[] bPeersList = RLP.encodeList(bPeers);
byte[] bTimeout = RLP.encodeInt((int) timeout);
if (key == null) {
this.encoded = RLP.encodeList(bPeersList, bTimeout);
} else {
this.encoded = RLP.encodeList(bPeersList,
bTimeout,
RLP.encodeElement(key.getBytes()),
RLP.encodeInt((int) id));
}
}
@Override
public byte[] getEncoded() {
if (encoded == null) encode();
return encoded;
}
public List<PeerAddress> getPeers() {
return peers;
}
public Key getKey() {
return key;
}
public long getId() {
return id;
}
@Override
public Class<?> getAnswerMessage() {
return null;
}
@Override
public BzzMessageCodes getCommand() {
return BzzMessageCodes.PEERS;
}
@Override
public String toString() {
return "BzzPeersMessage{" +
"peers=" + peers +
", key=" + key +
", id=" + id +
'}';
}
}
| 3,748
| 27.401515
| 96
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/BzzHandler.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.ethereum.listener.EthereumListener;
import org.ethereum.net.MessageQueue;
import org.ethereum.net.swarm.NetStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.function.Consumer;
/**
* Process the messages between peers with 'bzz' capability on the network.
*/
@Component
@Scope("prototype")
public class BzzHandler extends SimpleChannelInboundHandler<BzzMessage>
implements Consumer<BzzMessage> {
public final static byte VERSION = 0;
private MessageQueue msgQueue = null;
private boolean active = false;
private final static Logger logger = LoggerFactory.getLogger("net");
BzzProtocol bzzProtocol;
@Autowired
EthereumListener ethereumListener;
@Autowired
NetStore netStore;
public BzzHandler() {
}
public BzzHandler(MessageQueue msgQueue) {
this.msgQueue = msgQueue;
}
@Override
public void channelRead0(final ChannelHandlerContext ctx, BzzMessage msg) throws InterruptedException {
if (!isActive()) return;
if (BzzMessageCodes.inRange(msg.getCommand().asByte()))
logger.debug("BzzHandler invoke: [{}]", msg.getCommand());
ethereumListener.trace(String.format("BzzHandler invoke: [%s]", msg.getCommand()));
if (bzzProtocol != null) {
bzzProtocol.accept(msg);
}
}
@Override
public void accept(BzzMessage bzzMessage) {
msgQueue.sendMessage(bzzMessage);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("Bzz handling failed", cause);
super.exceptionCaught(ctx, cause);
ctx.close();
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
active = false;
logger.debug("handlerRemoved: ... ");
}
public void activate() {
logger.info("BZZ protocol activated");
ethereumListener.trace("BZZ protocol activated");
createBzzProtocol();
this.active = true;
}
private void createBzzProtocol() {
bzzProtocol = new BzzProtocol(netStore /*NetStore.getInstance()*/);
bzzProtocol.setMessageSender(this);
bzzProtocol.start();
}
public boolean isActive() {
return active;
}
public void setMsgQueue(MessageQueue msgQueue) {
this.msgQueue = msgQueue;
}
}
| 3,518
| 29.336207
| 107
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/BzzMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import org.ethereum.net.message.Message;
/**
* Base class for all BZZ messages
*/
public abstract class BzzMessage extends Message {
// non-null for incoming messages
private BzzProtocol peer;
protected long id = -1;
protected BzzMessage() {
}
protected BzzMessage(byte[] encoded) {
super(encoded);
decode();
}
public BzzMessageCodes getCommand() {
return BzzMessageCodes.fromByte(code);
}
protected abstract void decode();
/**
* Returns the {@link BzzProtocol} associated with incoming message
*/
public BzzProtocol getPeer() {
return peer;
}
/**
* Message ID. Should be unique across all outgoing messages
*/
public long getId() {
return id;
}
void setPeer(BzzProtocol peer) {
this.peer = peer;
}
void setId(long id) {
this.id = id;
}
}
| 1,734
| 24.895522
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/BzzMessageCodes.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import java.util.HashMap;
import java.util.Map;
public enum BzzMessageCodes {
/**
* Handshake BZZ message
*/
STATUS(0x00),
/**
* Request to store a {@link org.ethereum.net.swarm.Chunk}
*/
STORE_REQUEST(0x01),
/**
* Used for several purposes
* - the main is to ask for a {@link org.ethereum.net.swarm.Chunk} with the specified hash
* - ask to send back {#PEERS} message with the known nodes nearest to the specified hash
* - initial request after handshake with zero hash. On this request the nearest known
* neighbours are sent back with the {#PEERS} message.
*/
RETRIEVE_REQUEST(0x02),
/**
* The message is the immediate response on the {#RETRIEVE_REQUEST} with the nearest known nodes
* of the requested hash.
*/
PEERS(0x03);
private int cmd;
private static final Map<Integer, BzzMessageCodes> intToTypeMap = new HashMap<>();
static {
for (BzzMessageCodes type : BzzMessageCodes.values()) {
intToTypeMap.put(type.cmd, type);
}
}
BzzMessageCodes(int cmd) {
this.cmd = cmd;
}
public static BzzMessageCodes fromByte(byte i) {
return intToTypeMap.get((int) i);
}
public static boolean inRange(byte code) {
return code >= STATUS.asByte() && code <= PEERS.asByte();
}
public byte asByte() {
return (byte) (cmd);
}
}
| 2,258
| 28.723684
| 100
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/PeerAddress.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import com.google.common.base.Joiner;
import org.apache.commons.codec.binary.StringUtils;
import org.ethereum.net.p2p.Peer;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.swarm.Key;
import org.ethereum.net.swarm.Util;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Class similar for {@link Node} used in the swarm
*
* Created by Admin on 25.06.2015.
*/
public class PeerAddress {
private byte[] ip;
private int port;
private byte[] id;
private Key addrKeyCached = null;
private PeerAddress() {
}
public PeerAddress(Node discoverNode) {
try {
port = discoverNode.getPort();
id = discoverNode.getId();
ip = InetAddress.getByName(discoverNode.getHost()).getAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public PeerAddress(byte[] ip, int port, byte[] id) {
this.ip = ip;
this.port = port;
this.id = id;
}
public Node toNode() {
try {
return new Node(id, InetAddress.getByAddress(ip).getHostAddress(), port);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
/**
* Gets the SHA3 hash if this node ID
*/
public Key getAddrKey() {
if (addrKeyCached == null) {
addrKeyCached = new Key(sha3(id));
}
return addrKeyCached;
}
public byte[] getIp() {
return ip;
}
public int getPort() {
return port;
}
public byte[] getId() {
return id;
}
static PeerAddress parse(RLPList l) {
PeerAddress ret = new PeerAddress();
ret.ip = l.get(0).getRLPData();
ret.port = ByteUtil.byteArrayToInt(l.get(1).getRLPData());
ret.id = l.get(2).getRLPData();
return ret;
}
byte[] encodeRlp() {
return RLP.encodeList(RLP.encodeElement(ip),
RLP.encodeInt(port),
RLP.encodeElement(id));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PeerAddress that = (PeerAddress) o;
if (port != that.port) return false;
return Arrays.equals(ip, that.ip);
}
@Override
public int hashCode() {
int result = ip != null ? Arrays.hashCode(ip) : 0;
result = 31 * result + port;
return result;
}
@Override
public String toString() {
return "PeerAddress{" +
"ip=" + Util.ipBytesToString(ip) +
", port=" + port +
", id=" + toHexString(id) +
'}';
}
}
| 3,812
| 26.235714
| 85
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/bzz/BzzMessageFactory.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.swarm.bzz;
import org.ethereum.net.message.Message;
import org.ethereum.net.message.MessageFactory;
/**
* @author Mikhail Kalinin
* @since 20.08.2015
*/
public class BzzMessageFactory implements MessageFactory {
@Override
public Message create(byte code, byte[] encoded) {
BzzMessageCodes receivedCommand = BzzMessageCodes.fromByte(code);
switch (receivedCommand) {
case STATUS:
return new BzzStatusMessage(encoded);
case STORE_REQUEST:
return new BzzStoreReqMessage(encoded);
case RETRIEVE_REQUEST:
return new BzzRetrieveReqMessage(encoded);
case PEERS:
return new BzzPeersMessage(encoded);
default:
throw new IllegalArgumentException("No such message");
}
}
}
| 1,660
| 34.340426
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/client/ConfigCapabilities.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.client;
import org.ethereum.config.SystemProperties;
import org.ethereum.net.eth.EthVersion;
import org.ethereum.net.shh.ShhHandler;
import org.ethereum.net.swarm.bzz.BzzHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.ethereum.net.eth.EthVersion.fromCode;
import static org.ethereum.net.client.Capability.*;
/**
* Created by Anton Nashatyrev on 13.10.2015.
*/
@Component
public class ConfigCapabilities {
SystemProperties config;
private SortedSet<Capability> AllCaps = new TreeSet<>();
@Autowired
public ConfigCapabilities(final SystemProperties config) {
this.config = config;
if (config.syncVersion() != null) {
EthVersion eth = fromCode(config.syncVersion());
if (eth != null) AllCaps.add(new Capability(ETH, eth.getCode()));
} else {
for (EthVersion v : EthVersion.supported())
AllCaps.add(new Capability(ETH, v.getCode()));
}
AllCaps.add(new Capability(SHH, ShhHandler.VERSION));
AllCaps.add(new Capability(BZZ, BzzHandler.VERSION));
}
/**
* Gets the capabilities listed in 'peer.capabilities' config property
* sorted by their names.
*/
public List<Capability> getConfigCapabilities() {
List<Capability> ret = new ArrayList<>();
List<String> caps = config.peerCapabilities();
for (Capability capability : AllCaps) {
if (caps.contains(capability.getName())) {
ret.add(capability);
}
}
return ret;
}
}
| 2,557
| 32.657895
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/client/Capability.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.client;
/**
* The protocols and versions of those protocols that this peer support
*/
public class Capability implements Comparable<Capability> {
public final static String P2P = "p2p";
public final static String ETH = "eth";
public final static String SHH = "shh";
public final static String BZZ = "bzz";
private String name;
private byte version;
public Capability(String name, byte version) {
this.name = name;
this.version = version;
}
public String getName() {
return name;
}
public byte getVersion() {
return version;
}
public boolean isEth() {
return ETH.equals(name);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Capability)) return false;
Capability other = (Capability) obj;
if (this.name == null)
return other.name == null;
else
return this.name.equals(other.name) && this.version == other.version;
}
@Override
public int compareTo(Capability o) {
int cmp = this.name.compareTo(o.name);
if (cmp != 0) {
return cmp;
} else {
return Byte.valueOf(this.version).compareTo(o.version);
}
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (int) version;
return result;
}
public String toString() {
return name + ":" + version;
}
}
| 2,348
| 27.646341
| 81
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/client/PeerClient.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.client;
import org.ethereum.config.SystemProperties;
import org.ethereum.listener.EthereumListener;
import org.ethereum.net.server.EthereumChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultMessageSizeEstimator;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class creates the connection to an remote address using the Netty framework
*
* @see <a href="http://netty.io">http://netty.io</a>
*/
@Component
public class PeerClient {
private static final Logger logger = LoggerFactory.getLogger("net");
@Autowired
SystemProperties config;
@Autowired
private ApplicationContext ctx;
@Autowired
EthereumListener ethereumListener;
private EventLoopGroup workerGroup;
public PeerClient() {
workerGroup = new NioEventLoopGroup(0, new ThreadFactory() {
AtomicInteger cnt = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "EthJClientWorker-" + cnt.getAndIncrement());
}
});
}
public void connect(String host, int port, String remoteId) {
connect(host, port, remoteId, false);
}
/**
* Connects to the node and returns only upon connection close
*/
public void connect(String host, int port, String remoteId, boolean discoveryMode) {
try {
ChannelFuture f = connectAsync(host, port, remoteId, discoveryMode);
f.sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
logger.debug("Connection is closed");
} catch (Exception e) {
if (discoveryMode) {
logger.trace("Exception:", e);
} else {
if (e instanceof IOException) {
logger.info("PeerClient: Can't connect to " + host + ":" + port + " (" + e.getMessage() + ")");
logger.debug("PeerClient.connect(" + host + ":" + port + ") exception:", e);
} else {
logger.error("Exception:", e);
}
}
}
}
public ChannelFuture connectAsync(String host, int port, String remoteId, boolean discoveryMode) {
ethereumListener.trace("Connecting to: " + host + ":" + port);
EthereumChannelInitializer ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, remoteId);
ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());
b.remoteAddress(host, port);
b.handler(ethereumChannelInitializer);
// Start the client.
return b.connect();
}
public void close() {
logger.info("Shutdown peerClient");
workerGroup.shutdownGracefully();
workerGroup.terminationFuture().syncUninterruptibly();
}
}
| 4,553
| 32.985075
| 120
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/BloomFilter.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import java.util.BitSet;
/**
* Created by Anton Nashatyrev on 24.09.2015.
*/
public class BloomFilter implements Cloneable {
private static final int BITS_PER_BLOOM = 3;
private static final int BLOOM_BYTES = 64;
BitSet mask = new BitSet(BLOOM_BYTES * 8);
int[] counters = new int[BLOOM_BYTES * 8];
private BloomFilter() {
}
public static BloomFilter createNone() {
return new BloomFilter();
}
public static BloomFilter createAll() {
BloomFilter bloomFilter = new BloomFilter();
bloomFilter.mask.set(0, bloomFilter.mask.length());
return bloomFilter;
}
public BloomFilter(Topic topic) {
addTopic(topic);
}
public BloomFilter(byte[] bloomMask) {
if (bloomMask.length != BLOOM_BYTES) throw new RuntimeException("Invalid bloom filter array length: " + bloomMask.length);
mask = BitSet.valueOf(bloomMask);
}
private void incCounters(BitSet bs) {
int idx = -1;
while(true) {
idx = bs.nextSetBit(idx + 1);
if (idx < 0) break;
counters[idx]++;
}
}
private void decCounters(BitSet bs) {
int idx = -1;
while(true) {
idx = bs.nextSetBit(idx + 1);
if (idx < 0) break;
if (counters[idx] > 0) counters[idx]--;
}
}
private BitSet getTopicMask(Topic topic) {
BitSet topicMask = new BitSet(BLOOM_BYTES * 8);
for (int i = 0; i < BITS_PER_BLOOM; i++) {
int x = topic.getBytes()[i] & 0xFF;
if ((topic.getBytes()[BITS_PER_BLOOM] & (1 << i)) != 0) {
x += 256;
}
topicMask.set(x);
}
return topicMask;
}
public void addTopic(Topic topic) {
BitSet topicMask = getTopicMask(topic);
incCounters(topicMask);
mask.or(topicMask);
}
public void removeTopic(Topic topic) {
BitSet topicMask = getTopicMask(topic);
decCounters(topicMask);
int idx = -1;
while(true) {
idx = topicMask.nextSetBit(idx + 1);
if (idx < 0) break;
if (counters[idx] == 0) mask.clear(idx);
}
}
public boolean hasTopic(Topic topic) {
BitSet m = new BloomFilter(topic).mask;
BitSet m1 = (BitSet) m.clone();
m1.and(mask);
return m1.equals(m);
}
public byte[] toBytes() {
byte[] ret = new byte[BLOOM_BYTES];
byte[] bytes = mask.toByteArray();
System.arraycopy(bytes, 0, ret, 0, bytes.length);
return ret;
}
@Override
public boolean equals(Object obj) {
return obj instanceof BloomFilter && mask.equals(((BloomFilter) obj).mask);
}
@Override
protected BloomFilter clone() throws CloneNotSupportedException {
try {
return (BloomFilter) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
| 3,834
| 28.274809
| 130
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/MessageWatcher.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import java.util.Arrays;
public abstract class MessageWatcher {
private String to;
private String from;
private Topic[] topics = null;
public MessageWatcher() {
}
public MessageWatcher(String to, String from, Topic[] topics) {
this.to = to;
this.from = from;
this.topics = topics;
}
public MessageWatcher setTo(String to) {
this.to = to;
return this;
}
public MessageWatcher setFrom(String from) {
this.from = from;
return this;
}
public MessageWatcher setFilterTopics(Topic[] topics) {
this.topics = topics;
return this;
}
public String getTo() {
return to;
}
public String getFrom() {
return from;
}
public Topic[] getTopics() {
return topics == null ? new Topic[0] : topics;
}
boolean match(String to, String from, Topic[] topics) {
if (this.to != null) {
if (!this.to.equals(to)) {
return false;
}
}
if (this.from != null) {
if (!this.from.equals(from)) {
return false;
}
}
if (this.topics != null) {
for (Topic watchTopic : this.topics) {
for (Topic msgTopic : topics) {
if (watchTopic.equals(msgTopic)) return true;
}
}
return false;
}
return true;
}
protected abstract void newMessage(WhisperMessage msg);
}
| 2,358
| 25.211111
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhStatusMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import static org.ethereum.net.shh.ShhMessageCodes.STATUS;
/**
* @author by Konstantin Shabalin
*/
public class ShhStatusMessage extends ShhMessage {
private byte protocolVersion;
public ShhStatusMessage(byte[] encoded) {
super(encoded);
}
public ShhStatusMessage(byte protocolVersion) {
this.protocolVersion = protocolVersion;
this.parsed = true;
}
private void encode() {
byte[] protocolVersion = RLP.encodeByte(this.protocolVersion);
this.encoded = RLP.encodeList(protocolVersion);
}
private void parse() {
RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
this.protocolVersion = paramsList.get(0).getRLPData()[0];
parsed = true;
}
@Override
public byte[] getEncoded() {
if (encoded == null) encode();
return encoded;
}
@Override
public Class<?> getAnswerMessage() {
return null;
}
@Override
public ShhMessageCodes getCommand() {
return STATUS;
}
@Override
public String toString() {
if (!parsed) parse();
return "[" + this.getCommand().name() +
" protocolVersion=" + this.protocolVersion + "]";
}
}
| 2,120
| 26.907895
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhFilterMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import static org.ethereum.net.shh.ShhMessageCodes.FILTER;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* @author by Konstantin Shabalin
*/
public class ShhFilterMessage extends ShhMessage {
private byte[] bloomFilter;
private ShhFilterMessage() {
}
public ShhFilterMessage(byte[] encoded) {
super(encoded);
parse();
}
static ShhFilterMessage createFromFilter(byte[] bloomFilter) {
ShhFilterMessage ret = new ShhFilterMessage();
ret.bloomFilter = bloomFilter;
ret.parsed = true;
return ret;
}
private void encode() {
byte[] protocolVersion = RLP.encodeElement(this.bloomFilter);
this.encoded = RLP.encodeList(protocolVersion);
}
private void parse() {
RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
this.bloomFilter = paramsList.get(0).getRLPData();
parsed = true;
}
@Override
public byte[] getEncoded() {
if (encoded == null) encode();
return encoded;
}
public byte[] getBloomFilter() {
return bloomFilter;
}
@Override
public Class<?> getAnswerMessage() {
return null;
}
@Override
public ShhMessageCodes getCommand() {
return FILTER;
}
@Override
public String toString() {
if (!parsed) parse();
return "[" + this.getCommand().name() +
" hash=" + toHexString(bloomFilter) + "]";
}
}
| 2,407
| 26.363636
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/Whisper.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.ethereum.crypto.ECKey;
import org.springframework.stereotype.Component;
/**
* Created by Anton Nashatyrev on 25.09.2015.
*/
@Component
public abstract class Whisper {
public abstract String addIdentity(ECKey key);
public abstract String newIdentity();
public abstract void watch(MessageWatcher f);
public abstract void unwatch(MessageWatcher f);
public void send(byte[] payload, Topic[] topics) {
send(null, null, payload, topics, 50, 50);
}
public void send(byte[] payload, Topic[] topics, int ttl, int workToProve) {
send(null, null, payload, topics, ttl, workToProve);
}
public void send(String toIdentity, byte[] payload, Topic[] topics) {
send(null, toIdentity, payload, topics, 50, 50);
}
public void send(String toIdentity, byte[] payload, Topic[] topics, int ttl, int workToProve) {
send(null, toIdentity, payload, topics, ttl, workToProve);
}
public void send(String fromIdentity, String toIdentity, byte[] payload, Topic[] topics) {
send(fromIdentity, toIdentity, payload, topics, 50, 50);
}
public abstract void send(String fromIdentity, String toIdentity, byte[] payload, Topic[] topics, int ttl, int workToProve);
}
| 2,071
| 36
| 128
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessageCodes.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import java.util.HashMap;
import java.util.Map;
/**
* A list of commands for the Whisper network protocol.
* <br>
* The codes for these commands are the first byte in every packet.
*
* @see <a href="https://github.com/ethereum/wiki/wiki/Wire-Protocol">
* https://github.com/ethereum/wiki/wiki/Wire-Protocol</a>
*/
public enum ShhMessageCodes {
/* Whisper Protocol */
/**
* [+0x00]
*/
STATUS(0x00),
/**
* [+0x01]
*/
MESSAGE(0x01),
/**
* [+0x02]
*/
FILTER(0x02);
private final int cmd;
private static final Map<Integer, ShhMessageCodes> intToTypeMap = new HashMap<>();
static {
for (ShhMessageCodes type : ShhMessageCodes.values()) {
intToTypeMap.put(type.cmd, type);
}
}
private ShhMessageCodes(int cmd) {
this.cmd = cmd;
}
public static ShhMessageCodes fromByte(byte i) {
return intToTypeMap.get((int) i);
}
public static boolean inRange(byte code) {
return code >= STATUS.asByte() && code <= FILTER.asByte();
}
public byte asByte() {
return (byte) (cmd);
}
}
| 1,966
| 24.881579
| 86
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/WhisperMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.ethereum.crypto.ECIESCoder;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.math.ec.ECPoint;
import org.spongycastle.util.BigIntegers;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.SignatureException;
import java.util.*;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.net.swarm.Util.rlpDecodeInt;
import static org.ethereum.util.ByteUtil.merge;
import static org.ethereum.util.ByteUtil.xor;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Created by Anton Nashatyrev on 25.09.2015.
*/
public class WhisperMessage extends ShhMessage {
private final static Logger logger = LoggerFactory.getLogger("net.shh");
public static final int SIGNATURE_FLAG = 1;
public static final int SIGNATURE_LENGTH = 65;
private Topic[] topics = new Topic[0];
private byte[] payload;
private byte flags;
private byte[] signature;
private String to;
private ECKey from;
private int expire;
private int ttl;
int nonce = 0;
private boolean encrypted = false;
private long pow = 0;
private byte[] messageBytes;
public WhisperMessage() {
setTtl(50);
setWorkToProve(50);
}
public WhisperMessage(byte[] encoded) {
super(encoded);
encrypted = true;
parse();
}
public Topic[] getTopics() {
return topics;
}
public byte[] getPayload() {
return payload;
}
public int getExpire() {
return expire;
}
public int getTtl() {
return ttl;
}
public long getPow() {
return pow;
}
public String getFrom() {
return from == null ? null : WhisperImpl.toIdentity(from);
}
public String getTo() {
return to;
}
/*********** Decode routines ************/
private void parse() {
if (!parsed) {
RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
this.expire = ByteUtil.byteArrayToInt(paramsList.get(0).getRLPData());
this.ttl = ByteUtil.byteArrayToInt(paramsList.get(1).getRLPData());
List<Topic> topics = new ArrayList<>();
RLPList topicsList = (RLPList) RLP.decode2(paramsList.get(2).getRLPData()).get(0);
for (RLPElement e : topicsList) {
topics.add(new Topic(e.getRLPData()));
}
this.topics = new Topic[topics.size()];
topics.toArray(this.topics);
messageBytes = paramsList.get(3).getRLPData();
this.nonce = rlpDecodeInt(paramsList.get(4));
payload = messageBytes;
pow = workProved();
this.parsed = true;
}
}
private boolean processSignature() {
flags = payload[0];
if ((flags & WhisperMessage.SIGNATURE_FLAG) != 0) {
if (payload.length < WhisperMessage.SIGNATURE_LENGTH) {
throw new RuntimeException("Unable to open the envelope. First bit set but len(data) < len(signature)");
}
signature = new byte[WhisperMessage.SIGNATURE_LENGTH];
System.arraycopy(payload, payload.length - WhisperMessage.SIGNATURE_LENGTH, signature, 0,
WhisperMessage.SIGNATURE_LENGTH);
byte[] msg = new byte[payload.length - WhisperMessage.SIGNATURE_LENGTH - 1];
System.arraycopy(payload, 1, msg, 0, msg.length);
payload = msg;
from = recover();
return true;
} else {
byte[] msg = new byte[payload.length - 1];
System.arraycopy(payload, 1, msg, 0, msg.length);
payload = msg;
return true;
}
}
public boolean decrypt(Collection<ECKey> identities, Collection<Topic> knownTopics) {
boolean ok = false;
for (ECKey key : identities) {
ok = decrypt(key);
if (ok) break;
}
if (!ok) {
// decrypting as broadcast
ok = openBroadcastMessage(knownTopics);
}
if (ok) {
return processSignature();
}
// the message might be either not-encrypted or encrypted but we have no receivers
// now way to know so just assuming that the message is broadcast and not encrypted
// setEncrypted(false);
return false;
}
private boolean decrypt(ECKey privateKey) {
try {
payload = ECIESCoder.decryptSimple(privateKey.getPrivKey(), payload);
to = WhisperImpl.toIdentity(privateKey);
encrypted = false;
return true;
} catch (Exception e) {
logger.trace("Message can't be opened with key: " + privateKey.getPubKeyPoint());
} catch (Throwable e) {
}
return false;
}
private boolean openBroadcastMessage(Collection<Topic> knownTopics) {
for (Topic kTopic : knownTopics) {
for (int i = 0; i < topics.length; i++) {
if (kTopic.equals(topics[i])) {
byte[] encryptedKey = Arrays.copyOfRange(payload, i * 2 * 32, i * 2 * 32 + 32);
byte[] salt = Arrays.copyOfRange(payload, (i * 2 + 1) * 32, (i * 2 + 2) * 32);
byte[] cipherText = Arrays.copyOfRange(payload, (topics.length * 2) * 32, payload.length);
byte[] gamma = sha3(xor(kTopic.getFullTopic(), salt));
ECKey key = ECKey.fromPrivate(xor(gamma, encryptedKey));
try {
payload = ECIESCoder.decryptSimple(key.getPrivKey(), cipherText);
} catch (Exception e) {
logger.warn("Error decrypting message with known topic: " + kTopic);
// the abridged topic clash can potentially happen, so just continue with other topics
continue;
}
encrypted = false;
return true;
}
}
}
return false;
}
private ECKey.ECDSASignature decodeSignature() {
if (signature == null) {
return null;
}
byte[] r = new byte[32];
byte[] s = new byte[32];
byte v = signature[64];
if (v == 1) v = 28;
if (v == 0) v = 27;
System.arraycopy(signature, 0, r, 0, 32);
System.arraycopy(signature, 32, s, 0, 32);
return ECKey.ECDSASignature.fromComponents(r, s, v);
}
private ECKey recover() {
ECKey.ECDSASignature signature = decodeSignature();
if (signature == null) return null;
byte[] msgHash = hash();
ECKey outKey = null;
try {
outKey = ECKey.signatureToKey(msgHash, signature);
} catch (SignatureException e) {
logger.warn("Exception recovering signature: ", e);
throw new RuntimeException(e);
}
return outKey;
}
public byte[] hash() {
return sha3(payload);
}
private int workProved() {
byte[] d = new byte[64];
System.arraycopy(sha3(encode(false)), 0, d, 0, 32);
ByteBuffer.wrap(d).putInt(32, nonce);
return getFirstBitSet(sha3(d));
}
/*********** Encode routines ************/
public WhisperMessage setTopics(Topic ... topics) {
this.topics = topics != null ? topics : new Topic[0];
return this;
}
public WhisperMessage setPayload(String payload) {
this.payload = payload.getBytes(StandardCharsets.UTF_8);
return this;
}
public WhisperMessage setPayload(byte[] payload) {
this.payload = payload;
return this;
}
/**
* If set the message will be encrypted with the receiver public key
* If not the message will be encrypted as broadcast with Topics
* @param to public key
*/
public WhisperMessage setTo(String to) {
this.to = to;
return this;
}
/**
* If set the message will be signed by the sender key
* @param from sender key
*/
public WhisperMessage setFrom(ECKey from) {
this.from = from;
return this;
}
public WhisperMessage setFrom(String from) {
this.from = WhisperImpl.fromIdentityToPub(from);
return this;
}
public WhisperMessage setTtl(int ttl) {
this.ttl = ttl;
expire = (int) (Utils.toUnixTime(System.currentTimeMillis()) + ttl);
return this;
}
public WhisperMessage setWorkToProve(long ms) {
this.pow = ms;
return this;
}
@Override
public byte[] getEncoded() {
if (encoded == null) {
if (from != null) {
sign();
}
payload = getBytes();
encrypt();
byte[] withoutNonce = encode(false);
nonce = seal(withoutNonce, pow);
encoded = encode(true);
}
return encoded;
}
public byte[] encode(boolean withNonce) {
byte[] expire = RLP.encode(this.expire);
byte[] ttl = RLP.encode(this.ttl);
List<byte[]> topics = new Vector<>();
for (Topic t : this.topics) {
topics.add(RLP.encodeElement(t.getBytes()));
}
byte[][] topicsArray = topics.toArray(new byte[topics.size()][]);
byte[] encodedTopics = RLP.encodeList(topicsArray);
byte[] data = RLP.encodeElement(payload);
byte[] nonce = RLP.encodeInt(this.nonce);
return withNonce ? RLP.encodeList(expire, ttl, encodedTopics, data, nonce) :
RLP.encodeList(expire, ttl, encodedTopics, data);
}
private int seal(byte[] encoded, long pow) {
int ret = 0;
byte[] d = new byte[64];
ByteBuffer byteBuffer = ByteBuffer.wrap(d);
System.arraycopy(sha3(encoded), 0, d, 0, 32);
long then = System.currentTimeMillis() + pow;
int nonce = 0;
for (int bestBit = 0; System.currentTimeMillis() < then;) {
for (int i = 0; i < 1024; ++i, ++nonce) {
byteBuffer.putInt(32, nonce);
int fbs = getFirstBitSet(sha3(d));
if (fbs > bestBit) {
ret = nonce;
bestBit = fbs;
}
}
}
return ret;
}
private int getFirstBitSet(byte[] bytes) {
BitSet b = BitSet.valueOf(bytes);
for (int i = 0; i < b.length(); i++) {
if (b.get(i)) {
return i;
}
}
return 0;
}
public byte[] getBytes() {
if (signature != null) {
return merge(new byte[]{flags}, payload, signature);
} else {
return merge(new byte[]{flags}, payload);
}
}
private void encrypt() {
try {
if (to != null) {
ECKey key = WhisperImpl.fromIdentityToPub(to);
ECPoint pubKeyPoint = key.getPubKeyPoint();
payload = ECIESCoder.encryptSimple(pubKeyPoint, payload);
} else if (topics.length > 0){
// encrypting as broadcast message
byte[] topicKeys = new byte[topics.length * 64];
ECKey key = new ECKey();
Random rnd = new Random();
byte[] salt = new byte[32];
for (int i = 0; i < topics.length; i++) {
rnd.nextBytes(salt);
byte[] gamma = sha3(xor(topics[i].getFullTopic(), salt));
byte[] encodedKey = xor(gamma, key.getPrivKeyBytes());
System.arraycopy(encodedKey, 0, topicKeys, i * 64, 32);
System.arraycopy(salt, 0, topicKeys, i * 64 + 32, 32);
}
ECPoint pubKeyPoint = key.getPubKeyPoint();
payload = ByteUtil.merge(topicKeys, ECIESCoder.encryptSimple(pubKeyPoint, payload));
} else {
logger.debug("No 'to' or topics for outbound message. Will not be encrypted.");
}
} catch (Exception e) {
logger.error("Unexpected error while encrypting: ", e);
}
encrypted = true;
}
private void sign() {
flags |= SIGNATURE_FLAG;
byte[] forSig = hash();
ECKey.ECDSASignature signature = from.sign(forSig);
byte v;
if (signature.v == 27) v = 0;
else if (signature.v == 28) v = 1;
else throw new RuntimeException("Invalid signature: " + signature);
this.signature =
merge(BigIntegers.asUnsignedByteArray(32, signature.r),
BigIntegers.asUnsignedByteArray(32, signature.s), new byte[]{v});
}
@Override
public Class<?> getAnswerMessage() {
return null;
}
@Override
public String toString() {
return "WhisperMessage[" +
"topics=" + Arrays.toString(topics) +
", payload=" + (encrypted ? "<encrypted " + payload.length + " bytes>" : new String(payload)) +
", to=" + (to == null ? "null" : to.substring(0, 16) + "...") +
", from=" + (from == null ? "null" : toHexString(from.getPubKey()).substring(0,16) + "...") +
", expire=" + expire +
", ttl=" + ttl +
", nonce=" + nonce +
']';
}
}
| 14,336
| 30.86
| 120
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessageFactory.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.ethereum.net.message.*;
import org.ethereum.net.message.Message;
/**
* @author Mikhail Kalinin
* @since 20.08.2015
*/
public class ShhMessageFactory implements MessageFactory {
@Override
public Message create(byte code, byte[] encoded) {
ShhMessageCodes receivedCommand = ShhMessageCodes.fromByte(code);
switch (receivedCommand) {
case STATUS:
return new ShhStatusMessage(encoded);
case MESSAGE:
return new ShhEnvelopeMessage(encoded);
case FILTER:
return new ShhFilterMessage(encoded);
default:
throw new IllegalArgumentException("No such message");
}
}
}
| 1,543
| 33.311111
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/WhisperImpl.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.apache.commons.collections4.map.LRUMap;
import org.ethereum.config.SystemProperties;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.ByteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.*;
@Component
public class WhisperImpl extends Whisper {
private final static Logger logger = LoggerFactory.getLogger("net.shh");
private Set<MessageWatcher> filters = new HashSet<>();
private List<Topic> knownTopics = new ArrayList<>();
private Map<WhisperMessage, ?> known = new LRUMap<>(1024); // essentially Set
private Map<String, ECKey> identities = new HashMap<>();
private List<ShhHandler> activePeers = new ArrayList<>();
BloomFilter hostBloomFilter = BloomFilter.createAll();
public WhisperImpl() {
}
@Override
public void send(String from, String to, byte[] payload, Topic[] topicList, int ttl, int workToProve) {
ECKey fromKey = null;
if (from != null && !from.isEmpty()) {
fromKey = getIdentity(from);
if (fromKey == null) {
throw new Error(String.format("Unknown identity to send from %s", from));
}
}
WhisperMessage m = new WhisperMessage()
.setFrom(fromKey)
.setTo(to)
.setPayload(payload)
.setTopics(topicList)
.setTtl(ttl)
.setWorkToProve(workToProve);
logger.info("Sending Whisper message: " + m);
addMessage(m, null);
}
public void processEnvelope(ShhEnvelopeMessage e, ShhHandler shhHandler) {
for (WhisperMessage message : e.getMessages()) {
message.decrypt(identities.values(), knownTopics);
logger.info("New Whisper message: " + message);
addMessage(message, shhHandler);
}
}
void addPeer(ShhHandler peer) {
activePeers.add(peer);
}
void removePeer(ShhHandler peer) {
activePeers.remove(peer);
}
public void watch(MessageWatcher f) {
filters.add(f);
for (Topic topic : f.getTopics()) {
hostBloomFilter.addTopic(topic);
knownTopics.add(topic);
}
notifyBloomFilterChanged();
}
public void unwatch(MessageWatcher f) {
filters.remove(f);
for (Topic topic : f.getTopics()) {
hostBloomFilter.removeTopic(topic);
}
notifyBloomFilterChanged();
}
private void notifyBloomFilterChanged() {
for (ShhHandler peer : activePeers) {
peer.sendHostBloom();
}
}
// Processing both messages:
// own outgoing messages (shhHandler == null)
// and inbound messages from peers
private void addMessage(WhisperMessage m, ShhHandler inboundPeer) {
if (!known.containsKey(m)) {
known.put(m, null);
if (inboundPeer != null) {
matchMessage(m);
}
for (ShhHandler peer : activePeers) {
if (peer != inboundPeer) {
peer.sendEnvelope(new ShhEnvelopeMessage(m));
}
}
}
}
private void matchMessage(WhisperMessage m) {
for (MessageWatcher f : filters) {
if (f.match(m.getTo(), m.getFrom(), m.getTopics())) {
f.newMessage(m);
}
}
}
public static String toIdentity(ECKey key) {
return Hex.toHexString(key.getNodeId());
}
public static ECKey fromIdentityToPub(String identity) {
try {
return identity == null ? null :
ECKey.fromPublicOnly(ByteUtil.merge(new byte[] {0x04}, Hex.decode(identity)));
} catch (Exception e) {
throw new RuntimeException("Converting identity '" + identity + "'", e);
}
}
@Override
public String addIdentity(ECKey key) {
String identity = toIdentity(key);
identities.put(identity, key);
return identity;
}
@Override
public String newIdentity() {
return addIdentity(new ECKey());
}
public ECKey getIdentity(String identity) {
if (identities.containsKey(identity)) {
return identities.get(identity);
}
return null;
}
}
| 5,257
| 29.569767
| 107
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhEnvelopeMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static org.ethereum.net.shh.ShhMessageCodes.MESSAGE;
/**
* Created by Anton Nashatyrev on 25.09.2015.
*/
public class ShhEnvelopeMessage extends ShhMessage {
private List<WhisperMessage> messages = new ArrayList<>();
public ShhEnvelopeMessage(byte[] encoded) {
super(encoded);
parse();
}
public ShhEnvelopeMessage(WhisperMessage ... msg) {
Collections.addAll(messages, msg);
parsed = true;
}
public ShhEnvelopeMessage(Collection<WhisperMessage> msg) {
messages.addAll(msg);
parsed = true;
}
@Override
public ShhMessageCodes getCommand() {
return MESSAGE;
}
public void addMessage(WhisperMessage msg) {
messages.add(msg);
}
public void parse() {
if (!parsed) {
RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
for (int i = 0; i < paramsList.size(); i++) {
messages.add(new WhisperMessage(paramsList.get(i).getRLPData()));
}
this.parsed = true;
}
}
@Override
public byte[] getEncoded() {
if (encoded == null) {
byte[][] encodedMessages = new byte[messages.size()][];
for (int i = 0; i < encodedMessages.length; i++) {
encodedMessages[i] = messages.get(i).getEncoded();
}
encoded = RLP.encodeList(encodedMessages);
}
return encoded;
}
public List<WhisperMessage> getMessages() {
return messages;
}
@Override
public Class<?> getAnswerMessage() {
return null;
}
@Override
public String toString() {
return "[ENVELOPE " + messages.toString() + "]";
}
}
| 2,733
| 26.897959
| 81
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/JsonRpcWhisper.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ethereum.crypto.ECKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Whisper implementation which works through JSON RPC API
*
* Created by Anton Nashatyrev on 05.10.2015.
*/
public class JsonRpcWhisper extends Whisper {
private final static Logger logger = LoggerFactory.getLogger("net.shh");
URL rpcUrl;
Map<Integer, MessageWatcher> watchers = new HashMap<>();
ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
public JsonRpcWhisper(URL rpcUrl) {
this.rpcUrl = rpcUrl;
poller.scheduleAtFixedRate(() -> {
try {
pollFilters();
} catch (Exception e) {
logger.error("Unhandled exception", e);
}
}, 1, 1, TimeUnit.SECONDS);
}
@Override
public String addIdentity(ECKey key) {
throw new RuntimeException("Not supported by public JSON RPC API");
}
@Override
public String newIdentity() {
SimpleResponse resp = sendJson(new JsonRpcRequest("shh_newIdentity", null), SimpleResponse.class);
return del0X(resp.result);
}
@Override
public void watch(MessageWatcher f) {
String[] topics = f.getTopics().length == 0 ? null : new String[f.getTopics().length];
for (int i = 0; i < f.getTopics().length; i++) {
topics[i] = f.getTopics()[i].getOriginalTopic();
}
FilterParams params = new FilterParams(add0X(f.getTo()), topics);
SimpleResponse resp = sendJson(new JsonRpcRequest("shh_newFilter", params), SimpleResponse.class);
int filterId = Integer.parseInt(del0X(resp.result), 16);
watchers.put(filterId, f);
}
@Override
public void unwatch(MessageWatcher f) {
int filterId = -1;
for (Map.Entry<Integer, MessageWatcher> entry : watchers.entrySet()) {
if (entry.getValue() == f) {
filterId = entry.getKey();
break;
}
}
if (filterId == -1) return;
sendJson(new JsonRpcRequest("shh_uninstallFilter",
add0X(Integer.toHexString(filterId))), SimpleResponse.class);
}
private String fromAddress(String s) {
if (s == null) return null;
s = del0X(s);
BigInteger i = new BigInteger(s, 16);
if (i.bitCount() > 0) {
return s;
}
return null;
}
private void pollFilters() {
for (Map.Entry<Integer, MessageWatcher> entry : watchers.entrySet()) {
MessagesResponse ret = sendJson(new JsonRpcRequest("shh_getFilterChanges",
add0X(Integer.toHexString(entry.getKey()))), MessagesResponse.class);
for (MessageParams msg : ret.result) {
Topic[] topics = msg.topics == null ? null : new Topic[msg.topics.length];
for (int i = 0; topics != null && i < topics.length; i++) {
topics[i] = new Topic(Hex.decode(del0X(msg.topics[i])));
}
WhisperMessage m = new WhisperMessage()
.setPayload(decodeString(msg.payload))
.setFrom(fromAddress(msg.from))
.setTo(fromAddress(msg.to))
.setTopics(topics);
entry.getValue().newMessage(m);
}
}
}
@Override
public void send(String from, String to, byte[] payload, Topic[] topics, int ttl, int workToProve) {
String[] topicsS = new String[topics.length];
for (int i = 0; i < topics.length; i++) {
topicsS[i] = topics[i].getOriginalTopic();
}
SimpleResponse res = sendJson(new JsonRpcRequest("shh_post",
new MessageParams(new String(payload), add0X(to), add0X(from),
topicsS, ttl, workToProve)), SimpleResponse.class);
if (!"true".equals(res.result)) {
throw new RuntimeException("Shh post failed: " + res);
}
}
private <RespType extends JsonRpcResponse> RespType sendJson(JsonRpcRequest req, Class<RespType> respClazz) {
String out = null, in = null;
try {
ObjectMapper om = new ObjectMapper();
out = om.writeValueAsString(req);
logger.debug("JSON RPC Outbound: " + out);
in = sendPost(out);
logger.debug("JSON RPC Inbound: " + in);
RespType resp = om.readValue(in, respClazz);
resp.throwIfError();
return resp;
} catch (IOException e) {
throw new RuntimeException("Error processing JSON (Sent: " + out + ", Received: " + in + ")", e);
}
}
private String sendPost(String urlParams) {
try {
HttpURLConnection con = (HttpURLConnection) rpcUrl.openConnection();
//add reuqest header
con.setRequestMethod("POST");
// Send post request
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(urlParams);
wr.flush();
}
int responseCode = con.getResponseCode();
if (responseCode != 200) {
throw new RuntimeException("HTTP Response: " + responseCode);
}
final StringBuffer response;
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
return response.toString();
} catch (IOException e) {
throw new RuntimeException("Error sending POST to " + rpcUrl, e);
}
}
static String add0X(String s) {
if (s == null) return null;
return s.startsWith("0x") ? s : "0x" + s;
}
static String del0X(String s) {
if (s == null) return null;
return s.startsWith("0x") ? s.substring(2) : s;
}
static String encodeString(String s) {
return s == null ? null : "0x" + Hex.toHexString(s.getBytes());
}
static String decodeString(String s) {
if (s.startsWith("0x")) s = s.substring(2);
return new String(Hex.decode(s));
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class JsonRpcRequest<ParamT> {
private static AtomicInteger idCount = new AtomicInteger(0);
public final String jsonrpc = "2.0";
public int id = idCount.incrementAndGet();
public String method;
public List<ParamT> params;
public JsonRpcRequest(String method, ParamT params) {
this.method = method;
this.params = params == null ? null : Collections.singletonList(params);
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class MessageParams {
public String payload;
public String to;
public String from;
public String[] topics;
public String ttl = "0x60";
public Integer priority;
// response fields
public String hash;
public String expiry;
public String sent;
public String workProved;
public MessageParams() {
}
public MessageParams(String payload, String to, String from, String[] topics, Integer ttl, Integer priority) {
this.payload = encodeString(payload);
this.to = to;
this.from = from;
this.topics = topics;
for (int i = 0; i < this.topics.length; i++) {
this.topics[i] = encodeString(this.topics[i]);
}
this.ttl = "0x" + Integer.toHexString(ttl);
this.priority = priority;
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class FilterParams {
public String to;
public String[] topics;
public FilterParams(String to, String[] topics) {
this.to = to;
this.topics = topics;
for (int i = 0; topics != null && i < this.topics.length; i++) {
this.topics[i] = encodeString(this.topics[i]);
}
}
}
public static class JsonRpcResponse {
public static class Error {
public int code;
public String message;
}
public int id;
public String jsonrpc;
public Error error;
public void throwIfError() {
if (error != null) {
throw new RuntimeException("JSON RPC returned error (" + error.code + "): " + error.message);
}
}
}
public static class SimpleResponse extends JsonRpcResponse {
public String result;
@Override
public String toString() {
return "JsonRpcResponse{" +
"id=" + id +
", jsonrpc='" + jsonrpc + '\'' +
", result='" + result + '\'' +
'}';
}
}
public static class MessagesResponse extends JsonRpcResponse {
public List<MessageParams> result;
@Override
public String toString() {
return "MessagesResponse{" +
"id=" + id +
", jsonrpc='" + jsonrpc + '\'' +
"result=" + result +
'}';
}
}
public static void main(String[] args) throws Exception {
String json = "{\"jsonrpc\":\"2.0\",\n" +
" \n" +
" \"method\":\"shh_newIdentity\",\n" +
" \"params\": [{ \"payload\": \"Hello\", \"ttl\": \"100\", \"to\" : \"0xbd27a63c91fe3233c5777e6d3d7b39204d398c8f92655947eb5a373d46e1688f022a1632d264725cbc7dc43ee1cfebde42fa0a86d08b55d2acfbb5e9b3b48dc5\", \"from\": \"id1\" }],\n" +
" \"id\":1001\n" +
"}";
JsonRpcWhisper rpcWhisper = new JsonRpcWhisper(new URL("http://localhost:8545"));
// JsonRpcResponse resp = rpcWhisper.sendJson(new JsonRpcRequest("shh_post",
// new PostParams("Hello").to("0xbd27a63c91fe3233c5777e6d3d7b39204d398c8f92655947eb5a373d46e1688f022a1632d264725cbc7dc43ee1cfebde42fa0a86d08b55d2acfbb5e9b3b48dc5")));
// Hex.decode("7d04a8170c432240dcf544e27610cc3a10a32c6a5f8ff8cf5a06d26ee0d37da4075701ff03cee88d50885ff56bcd9a5070ff98b9a3045d6ff32e0f1821c21f87")
rpcWhisper.send(null, null, "Hello C++ Whisper".getBytes(), Topic.createTopics("ATopic"), 60, 1);
rpcWhisper.watch(new MessageWatcher(null,
null, Topic.createTopics("ATopic")) {
@Override
protected void newMessage(WhisperMessage msg) {
System.out.println("JsonRpcWhisper.newMessage:" + "msg = [" + msg + "]");
}
});
Thread.sleep(1000000000);
// String resp = rpcWhisper.sendPost(json);
// System.out.println("Resp: " + resp);
}
}
| 12,545
| 35.365217
| 248
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.ethereum.net.message.Message;
public abstract class ShhMessage extends Message {
public ShhMessage() {
}
public ShhMessage(byte[] encoded) {
super(encoded);
}
public ShhMessageCodes getCommand() {
return ShhMessageCodes.fromByte(code);
}
}
| 1,116
| 30.914286
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhHandler.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.ethereum.listener.EthereumListener;
import org.ethereum.net.MessageQueue;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* Process the messages between peers with 'shh' capability on the network.
*
* Peers with 'shh' capability can send/receive:
*/
@Component
@Scope("prototype")
public class ShhHandler extends SimpleChannelInboundHandler<ShhMessage> {
private final static Logger logger = LoggerFactory.getLogger("net.shh");
public final static byte VERSION = 3;
private MessageQueue msgQueue = null;
private boolean active = false;
private BloomFilter peerBloomFilter = BloomFilter.createAll();
@Autowired
private EthereumListener ethereumListener;
@Autowired
private WhisperImpl whisper;
public ShhHandler() {
}
public ShhHandler(MessageQueue msgQueue) {
this.msgQueue = msgQueue;
}
@Override
public void channelRead0(final ChannelHandlerContext ctx, ShhMessage msg) throws InterruptedException {
if (!isActive()) return;
if (ShhMessageCodes.inRange(msg.getCommand().asByte()))
logger.info("ShhHandler invoke: [{}]", msg.getCommand());
ethereumListener.trace(String.format("ShhHandler invoke: [%s]", msg.getCommand()));
switch (msg.getCommand()) {
case STATUS:
ethereumListener.trace("[Recv: " + msg + "]");
break;
case MESSAGE:
whisper.processEnvelope((ShhEnvelopeMessage) msg, this);
break;
case FILTER:
setBloomFilter((ShhFilterMessage) msg);
break;
default:
logger.error("Unknown SHH message type: " + msg.getCommand());
break;
}
}
private void setBloomFilter(ShhFilterMessage msg) {
peerBloomFilter = new BloomFilter(msg.getBloomFilter());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("Shh handling failed", cause);
super.exceptionCaught(ctx, cause);
ctx.close();
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
active = false;
whisper.removePeer(this);
logger.debug("handlerRemoved: ... ");
}
public void activate() {
logger.info("SHH protocol activated");
ethereumListener.trace("SHH protocol activated");
whisper.addPeer(this);
sendStatus();
sendHostBloom();
this.active = true;
}
private void sendStatus() {
byte protocolVersion = ShhHandler.VERSION;
ShhStatusMessage msg = new ShhStatusMessage(protocolVersion);
sendMessage(msg);
}
void sendHostBloom() {
ShhFilterMessage msg = ShhFilterMessage.createFromFilter(whisper.hostBloomFilter.toBytes());
sendMessage(msg);
}
void sendEnvelope(ShhEnvelopeMessage env) {
sendMessage(env);
// Topic[] topics = env.getTopics();
// for (Topic topic : topics) {
// if (peerBloomFilter.hasTopic(topic)) {
// sendMessage(env);
// break;
// }
// }
}
void sendMessage(ShhMessage msg) {
msgQueue.sendMessage(msg);
}
public boolean isActive() {
return active;
}
public void setMsgQueue(MessageQueue msgQueue) {
this.msgQueue = msgQueue;
}
}
| 4,569
| 30.088435
| 107
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/shh/Topic.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.shh;
import org.ethereum.util.RLP;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* @author by Konstantin Shabalin
*/
public class Topic {
private String originalTopic;
private byte[] fullTopic;
private byte[] abrigedTopic = new byte[4];
public Topic(byte[] data) {
this.abrigedTopic = data;
}
public Topic(String data) {
originalTopic = data;
fullTopic = sha3(RLP.encode(originalTopic));
this.abrigedTopic = buildAbrigedTopic(fullTopic);
}
public byte[] getBytes() {
return abrigedTopic;
}
private byte[] buildAbrigedTopic(byte[] data) {
byte[] hash = sha3(data);
byte[] topic = new byte[4];
System.arraycopy(hash, 0, topic, 0, 4);
return topic;
}
public static Topic[] createTopics(String ... topicsString) {
if (topicsString == null) return new Topic[0];
Topic[] topics = new Topic[topicsString.length];
for (int i = 0; i < topicsString.length; i++) {
topics[i] = new Topic(topicsString[i]);
}
return topics;
}
public byte[] getAbrigedTopic() {
return abrigedTopic;
}
public byte[] getFullTopic() {
return fullTopic;
}
public String getOriginalTopic() {
return originalTopic;
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj == this) return true;
if (!(obj instanceof Topic))return false;
return Arrays.equals(this.abrigedTopic, ((Topic) obj).getBytes());
}
@Override
public String toString() {
return "#" + toHexString(abrigedTopic) + (originalTopic == null ? "" : "(" + originalTopic + ")");
}
}
| 2,685
| 28.516484
| 106
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/AuthInitiateMessageV4.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import org.spongycastle.math.ec.ECPoint;
import static org.ethereum.util.ByteUtil.merge;
import static org.spongycastle.util.BigIntegers.asUnsignedByteArray;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Auth Initiate message defined by EIP-8
*
* @author mkalinin
* @since 17.02.2016
*/
public class AuthInitiateMessageV4 {
ECKey.ECDSASignature signature; // 65 bytes
ECPoint publicKey; // 64 bytes - uncompressed and no type byte
byte[] nonce; // 32 bytes
int version = 4; // 4 bytes
public AuthInitiateMessageV4() {
}
static AuthInitiateMessageV4 decode(byte[] wire) {
AuthInitiateMessageV4 message = new AuthInitiateMessageV4();
RLPList params = (RLPList) RLP.decode2OneItem(wire, 0);
byte[] signatureBytes = params.get(0).getRLPData();
int offset = 0;
byte[] r = new byte[32];
byte[] s = new byte[32];
System.arraycopy(signatureBytes, offset, r, 0, 32);
offset += 32;
System.arraycopy(signatureBytes, offset, s, 0, 32);
offset += 32;
int v = signatureBytes[offset] + 27;
message.signature = ECKey.ECDSASignature.fromComponents(r, s, (byte)v);
byte[] publicKeyBytes = params.get(1).getRLPData();
byte[] bytes = new byte[65];
System.arraycopy(publicKeyBytes, 0, bytes, 1, 64);
bytes[0] = 0x04; // uncompressed
message.publicKey = ECKey.CURVE.getCurve().decodePoint(bytes);
message.nonce = params.get(2).getRLPData();
byte[] versionBytes = params.get(3).getRLPData();
message.version = ByteUtil.byteArrayToInt(versionBytes);
return message;
}
public byte[] encode() {
byte[] rsigPad = new byte[32];
byte[] rsig = asUnsignedByteArray(signature.r);
System.arraycopy(rsig, 0, rsigPad, rsigPad.length - rsig.length, rsig.length);
byte[] ssigPad = new byte[32];
byte[] ssig = asUnsignedByteArray(signature.s);
System.arraycopy(ssig, 0, ssigPad, ssigPad.length - ssig.length, ssig.length);
byte[] publicKey = new byte[64];
System.arraycopy(this.publicKey.getEncoded(false), 1, publicKey, 0, publicKey.length);
byte[] sigBytes = RLP.encode(merge(rsigPad, ssigPad, new byte[]{EncryptionHandshake.recIdFromSignatureV(signature.v)}));
byte[] publicBytes = RLP.encode(publicKey);
byte[] nonceBytes = RLP.encode(nonce);
byte[] versionBytes = RLP.encodeInt(version);
return RLP.encodeList(sigBytes, publicBytes, nonceBytes, versionBytes);
}
@Override
public String toString() {
byte[] sigBytes = merge(asUnsignedByteArray(signature.r),
asUnsignedByteArray(signature.s), new byte[]{EncryptionHandshake.recIdFromSignatureV(signature.v)});
return "AuthInitiateMessage{" +
"\n sigBytes=" + toHexString(sigBytes) +
"\n publicKey=" + toHexString(publicKey.getEncoded(false)) +
"\n nonce=" + toHexString(nonce) +
"\n version=" + version +
"\n}";
}
}
| 4,065
| 35.630631
| 128
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/EncryptionHandshake.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import org.ethereum.crypto.ECIESCoder;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.ByteUtil;
import org.spongycastle.crypto.InvalidCipherTextException;
import org.spongycastle.crypto.digests.KeccakDigest;
import org.spongycastle.math.ec.ECPoint;
import javax.annotation.Nullable;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import static org.ethereum.crypto.HashUtil.sha3;
/**
* Created by devrandom on 2015-04-08.
*/
public class EncryptionHandshake {
public static final int NONCE_SIZE = 32;
public static final int MAC_SIZE = 256;
public static final int SECRET_SIZE = 32;
private SecureRandom random = new SecureRandom();
private boolean isInitiator;
private ECKey ephemeralKey;
private ECPoint remotePublicKey;
private ECPoint remoteEphemeralKey;
private byte[] initiatorNonce;
private byte[] responderNonce;
private Secrets secrets;
public EncryptionHandshake(ECPoint remotePublicKey) {
this.remotePublicKey = remotePublicKey;
ephemeralKey = new ECKey(random);
initiatorNonce = new byte[NONCE_SIZE];
random.nextBytes(initiatorNonce);
isInitiator = true;
}
EncryptionHandshake(ECPoint remotePublicKey, ECKey ephemeralKey, byte[] initiatorNonce, byte[] responderNonce, boolean isInitiator) {
this.remotePublicKey = remotePublicKey;
this.ephemeralKey = ephemeralKey;
this.initiatorNonce = initiatorNonce;
this.responderNonce = responderNonce;
this.isInitiator = isInitiator;
}
public EncryptionHandshake() {
ephemeralKey = new ECKey(random);
responderNonce = new byte[NONCE_SIZE];
random.nextBytes(responderNonce);
isInitiator = false;
}
/**
* Create a handshake auth message defined by EIP-8
*
* @param key our private key
*/
public AuthInitiateMessageV4 createAuthInitiateV4(ECKey key) {
AuthInitiateMessageV4 message = new AuthInitiateMessageV4();
BigInteger secretScalar = key.keyAgreement(remotePublicKey);
byte[] token = ByteUtil.bigIntegerToBytes(secretScalar, NONCE_SIZE);
byte[] nonce = initiatorNonce;
byte[] signed = xor(token, nonce);
message.signature = ephemeralKey.sign(signed);
message.publicKey = key.getPubKeyPoint();
message.nonce = initiatorNonce;
return message;
}
public byte[] encryptAuthInitiateV4(AuthInitiateMessageV4 message) {
byte[] msg = message.encode();
byte[] padded = padEip8(msg);
return encryptAuthEIP8(padded);
}
public AuthInitiateMessageV4 decryptAuthInitiateV4(byte[] in, ECKey myKey) throws InvalidCipherTextException {
try {
byte[] prefix = new byte[2];
System.arraycopy(in, 0, prefix, 0, 2);
short size = ByteUtil.bigEndianToShort(prefix, 0);
byte[] ciphertext = new byte[size];
System.arraycopy(in, 2, ciphertext, 0, size);
byte[] plaintext = ECIESCoder.decrypt(myKey.getPrivKey(), ciphertext, prefix);
return AuthInitiateMessageV4.decode(plaintext);
} catch (InvalidCipherTextException e) {
throw e;
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
public byte[] encryptAuthResponseV4(AuthResponseMessageV4 message) {
byte[] msg = message.encode();
byte[] padded = padEip8(msg);
return encryptAuthEIP8(padded);
}
public AuthResponseMessageV4 decryptAuthResponseV4(byte[] in, ECKey myKey) {
try {
byte[] prefix = new byte[2];
System.arraycopy(in, 0, prefix, 0, 2);
short size = ByteUtil.bigEndianToShort(prefix, 0);
byte[] ciphertext = new byte[size];
System.arraycopy(in, 2, ciphertext, 0, size);
byte[] plaintext = ECIESCoder.decrypt(myKey.getPrivKey(), ciphertext, prefix);
return AuthResponseMessageV4.decode(plaintext);
} catch (IOException | InvalidCipherTextException e) {
throw Throwables.propagate(e);
}
}
AuthResponseMessageV4 makeAuthInitiateV4(AuthInitiateMessageV4 initiate, ECKey key) {
initiatorNonce = initiate.nonce;
remotePublicKey = initiate.publicKey;
BigInteger secretScalar = key.keyAgreement(remotePublicKey);
byte[] token = ByteUtil.bigIntegerToBytes(secretScalar, NONCE_SIZE);
byte[] signed = xor(token, initiatorNonce);
ECKey ephemeral = ECKey.recoverFromSignature(recIdFromSignatureV(initiate.signature.v),
initiate.signature, signed);
if (ephemeral == null) {
throw new RuntimeException("failed to recover signatue from message");
}
remoteEphemeralKey = ephemeral.getPubKeyPoint();
AuthResponseMessageV4 response = new AuthResponseMessageV4();
response.ephemeralPublicKey = ephemeralKey.getPubKeyPoint();
response.nonce = responderNonce;
return response;
}
public AuthResponseMessageV4 handleAuthResponseV4(ECKey myKey, byte[] initiatePacket, byte[] responsePacket) {
AuthResponseMessageV4 response = decryptAuthResponseV4(responsePacket, myKey);
remoteEphemeralKey = response.ephemeralPublicKey;
responderNonce = response.nonce;
agreeSecret(initiatePacket, responsePacket);
return response;
}
byte[] encryptAuthEIP8(byte[] msg) {
short size = (short) (msg.length + ECIESCoder.getOverhead());
byte[] prefix = ByteUtil.shortToBytes(size);
byte[] encrypted = ECIESCoder.encrypt(remotePublicKey, msg, prefix);
byte[] out = new byte[prefix.length + encrypted.length];
int offset = 0;
System.arraycopy(prefix, 0, out, offset, prefix.length);
offset += prefix.length;
System.arraycopy(encrypted, 0, out, offset, encrypted.length);
return out;
}
/**
* Create a handshake auth message
*
* @param token previous token if we had a previous session
* @param key our private key
*/
public AuthInitiateMessage createAuthInitiate(@Nullable byte[] token, ECKey key) {
AuthInitiateMessage message = new AuthInitiateMessage();
boolean isToken;
if (token == null) {
isToken = false;
BigInteger secretScalar = key.keyAgreement(remotePublicKey);
token = ByteUtil.bigIntegerToBytes(secretScalar, NONCE_SIZE);
} else {
isToken = true;
}
byte[] nonce = initiatorNonce;
byte[] signed = xor(token, nonce);
message.signature = ephemeralKey.sign(signed);
message.isTokenUsed = isToken;
message.ephemeralPublicHash = sha3(ephemeralKey.getPubKey(), 1, 64);
message.publicKey = key.getPubKeyPoint();
message.nonce = initiatorNonce;
return message;
}
private static byte[] xor(byte[] b1, byte[] b2) {
Preconditions.checkArgument(b1.length == b2.length);
byte[] out = new byte[b1.length];
for (int i = 0; i < b1.length; i++) {
out[i] = (byte) (b1[i] ^ b2[i]);
}
return out;
}
public byte[] encryptAuthMessage(AuthInitiateMessage message) {
return ECIESCoder.encrypt(remotePublicKey, message.encode());
}
public byte[] encryptAuthResponse(AuthResponseMessage message) {
return ECIESCoder.encrypt(remotePublicKey, message.encode());
}
public AuthResponseMessage decryptAuthResponse(byte[] ciphertext, ECKey myKey) {
try {
byte[] plaintext = ECIESCoder.decrypt(myKey.getPrivKey(), ciphertext);
return AuthResponseMessage.decode(plaintext);
} catch (IOException | InvalidCipherTextException e) {
throw Throwables.propagate(e);
}
}
public AuthInitiateMessage decryptAuthInitiate(byte[] ciphertext, ECKey myKey) throws InvalidCipherTextException {
try {
byte[] plaintext = ECIESCoder.decrypt(myKey.getPrivKey(), ciphertext);
return AuthInitiateMessage.decode(plaintext);
} catch (InvalidCipherTextException e) {
throw e;
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
public AuthResponseMessage handleAuthResponse(ECKey myKey, byte[] initiatePacket, byte[] responsePacket) {
AuthResponseMessage response = decryptAuthResponse(responsePacket, myKey);
remoteEphemeralKey = response.ephemeralPublicKey;
responderNonce = response.nonce;
agreeSecret(initiatePacket, responsePacket);
return response;
}
void agreeSecret(byte[] initiatePacket, byte[] responsePacket) {
BigInteger secretScalar = ephemeralKey.keyAgreement(remoteEphemeralKey);
byte[] agreedSecret = ByteUtil.bigIntegerToBytes(secretScalar, SECRET_SIZE);
byte[] sharedSecret = sha3(agreedSecret, sha3(responderNonce, initiatorNonce));
byte[] aesSecret = sha3(agreedSecret, sharedSecret);
secrets = new Secrets();
secrets.aes = aesSecret;
secrets.mac = sha3(agreedSecret, aesSecret);
secrets.token = sha3(sharedSecret);
// System.out.println("mac " + Hex.toHexString(secrets.mac));
// System.out.println("aes " + Hex.toHexString(secrets.aes));
// System.out.println("shared " + Hex.toHexString(sharedSecret));
// System.out.println("ecdhe " + Hex.toHexString(agreedSecret));
KeccakDigest mac1 = new KeccakDigest(MAC_SIZE);
mac1.update(xor(secrets.mac, responderNonce), 0, secrets.mac.length);
byte[] buf = new byte[32];
new KeccakDigest(mac1).doFinal(buf, 0);
mac1.update(initiatePacket, 0, initiatePacket.length);
new KeccakDigest(mac1).doFinal(buf, 0);
KeccakDigest mac2 = new KeccakDigest(MAC_SIZE);
mac2.update(xor(secrets.mac, initiatorNonce), 0, secrets.mac.length);
new KeccakDigest(mac2).doFinal(buf, 0);
mac2.update(responsePacket, 0, responsePacket.length);
new KeccakDigest(mac2).doFinal(buf, 0);
if (isInitiator) {
secrets.egressMac = mac1;
secrets.ingressMac = mac2;
} else {
secrets.egressMac = mac2;
secrets.ingressMac = mac1;
}
}
public byte[] handleAuthInitiate(byte[] initiatePacket, ECKey key) throws InvalidCipherTextException {
AuthResponseMessage response = makeAuthInitiate(initiatePacket, key);
byte[] responsePacket = encryptAuthResponse(response);
agreeSecret(initiatePacket, responsePacket);
return responsePacket;
}
AuthResponseMessage makeAuthInitiate(byte[] initiatePacket, ECKey key) throws InvalidCipherTextException {
AuthInitiateMessage initiate = decryptAuthInitiate(initiatePacket, key);
return makeAuthInitiate(initiate, key);
}
AuthResponseMessage makeAuthInitiate(AuthInitiateMessage initiate, ECKey key) {
initiatorNonce = initiate.nonce;
remotePublicKey = initiate.publicKey;
BigInteger secretScalar = key.keyAgreement(remotePublicKey);
byte[] token = ByteUtil.bigIntegerToBytes(secretScalar, NONCE_SIZE);
byte[] signed = xor(token, initiatorNonce);
ECKey ephemeral = ECKey.recoverFromSignature(recIdFromSignatureV(initiate.signature.v),
initiate.signature, signed);
if (ephemeral == null) {
throw new RuntimeException("failed to recover signatue from message");
}
remoteEphemeralKey = ephemeral.getPubKeyPoint();
AuthResponseMessage response = new AuthResponseMessage();
response.isTokenUsed = initiate.isTokenUsed;
response.ephemeralPublicKey = ephemeralKey.getPubKeyPoint();
response.nonce = responderNonce;
return response;
}
/**
* Pads messages with junk data,
* pad data length is random value satisfying 100 < len < 300.
* It's necessary to make messages described by EIP-8 distinguishable from pre-EIP-8 msgs
*
* @param msg message to pad
* @return padded message
*/
private byte[] padEip8(byte[] msg) {
byte[] paddedMessage = new byte[msg.length + random.nextInt(200) + 100];
random.nextBytes(paddedMessage);
System.arraycopy(msg, 0, paddedMessage, 0, msg.length);
return paddedMessage;
}
static public byte recIdFromSignatureV(int v) {
if (v >= 31) {
// compressed
v -= 4;
}
return (byte)(v - 27);
}
public Secrets getSecrets() {
return secrets;
}
public ECPoint getRemotePublicKey() {
return remotePublicKey;
}
public static class Secrets {
byte[] aes;
byte[] mac;
byte[] token;
KeccakDigest egressMac;
KeccakDigest ingressMac;
public byte[] getAes() {
return aes;
}
public byte[] getMac() {
return mac;
}
public byte[] getToken() {
return token;
}
public KeccakDigest getIngressMac() {
return ingressMac;
}
public KeccakDigest getEgressMac() {
return egressMac;
}
}
public boolean isInitiator() {
return isInitiator;
}
}
| 14,346
| 35.506361
| 137
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/MessageCodesResolver.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.net.client.Capability;
import org.ethereum.net.eth.EthVersion;
import org.ethereum.net.eth.message.EthMessageCodes;
import org.ethereum.net.p2p.P2pMessageCodes;
import org.ethereum.net.shh.ShhMessageCodes;
import org.ethereum.net.swarm.bzz.BzzMessageCodes;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.ethereum.net.eth.EthVersion.*;
/**
* @author Mikhail Kalinin
* @since 14.07.2015
*/
public class MessageCodesResolver {
private Map<String, Integer> offsets = new HashMap<>();
public MessageCodesResolver() {
}
public MessageCodesResolver(List<Capability> caps) {
init(caps);
}
public void init(List<Capability> caps) {
Collections.sort(caps);
int offset = P2pMessageCodes.USER.asByte() + 1;
for (Capability capability : caps) {
if (capability.getName().equals(Capability.ETH)) {
setEthOffset(offset);
EthVersion v = fromCode(capability.getVersion());
offset += EthMessageCodes.maxCode(v) + 1; // +1 is essential cause STATUS code starts from 0x0
}
if (capability.getName().equals(Capability.SHH)) {
setShhOffset(offset);
offset += ShhMessageCodes.values().length;
}
if (capability.getName().equals(Capability.BZZ)) {
setBzzOffset(offset);
offset += BzzMessageCodes.values().length + 4;
// FIXME: for some reason Go left 4 codes between BZZ and ETH message codes
}
}
}
public byte withP2pOffset(byte code) {
return withOffset(code, Capability.P2P);
}
public byte withBzzOffset(byte code) {
return withOffset(code, Capability.BZZ);
}
public byte withEthOffset(byte code) {
return withOffset(code, Capability.ETH);
}
public byte withShhOffset(byte code) {
return withOffset(code, Capability.SHH);
}
public byte withOffset(byte code, String cap) {
byte offset = getOffset(cap);
return (byte)(code + offset);
}
public byte resolveP2p(byte code) {
return resolve(code, Capability.P2P);
}
public byte resolveBzz(byte code) {
return resolve(code, Capability.BZZ);
}
public byte resolveEth(byte code) {
return resolve(code, Capability.ETH);
}
public byte resolveShh(byte code) {
return resolve(code, Capability.SHH);
}
private byte resolve(byte code, String cap) {
byte offset = getOffset(cap);
return (byte)(code - offset);
}
private byte getOffset(String cap) {
Integer offset = offsets.get(cap);
return offset == null ? 0 : offset.byteValue();
}
public void setBzzOffset(int offset) {
setOffset(Capability.BZZ, offset);
}
public void setEthOffset(int offset) {
setOffset(Capability.ETH, offset);
}
public void setShhOffset(int offset) {
setOffset(Capability.SHH, offset);
}
private void setOffset(String cap, int offset) {
offsets.put(cap, offset);
}
}
| 4,025
| 28.602941
| 110
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/HandshakeHandler.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import com.google.common.io.ByteStreams;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.timeout.ReadTimeoutException;
import org.ethereum.config.SystemProperties;
import org.ethereum.crypto.ECIESCoder;
import org.ethereum.crypto.ECKey;
import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.DisconnectMessage;
import org.ethereum.net.p2p.HelloMessage;
import org.ethereum.net.p2p.P2pMessageCodes;
import org.ethereum.net.p2p.P2pMessageFactory;
import org.ethereum.net.rlpx.discover.NodeManager;
import org.ethereum.net.server.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.crypto.InvalidCipherTextException;
import org.spongycastle.math.ec.ECPoint;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import static org.ethereum.net.rlpx.FrameCodec.Frame;
import static org.ethereum.util.ByteUtil.bigEndianToShort;
/**
* The Netty handler which manages initial negotiation with peer
* (when either we initiating connection or remote peer initiates)
*
* The initial handshake includes:
* - first AuthInitiate -> AuthResponse messages when peers exchange with secrets
* - second P2P Hello messages when P2P protocol and subprotocol capabilities are negotiated
*
* After the handshake is done this handler reports secrets and other data to the Channel
* which installs further handlers depending on the protocol parameters.
* This handler is finally removed from the pipeline.
*/
@Component
@Scope("prototype")
public class HandshakeHandler extends ByteToMessageDecoder {
private static final Logger loggerWire = LoggerFactory.getLogger("wire");
private static final Logger loggerNet = LoggerFactory.getLogger("net");
private FrameCodec frameCodec;
private final ECKey myKey;
private byte[] nodeId;
private byte[] remoteId;
private EncryptionHandshake handshake;
private byte[] initiatePacket;
private Channel channel;
private boolean isHandshakeDone;
private final SystemProperties config;
private final NodeManager nodeManager;
@Autowired
public HandshakeHandler(final SystemProperties config, final NodeManager nodeManager) {
this.config = config;
this.nodeManager = nodeManager;
myKey = config.getMyKey();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
channel.setInetSocketAddress((InetSocketAddress) ctx.channel().remoteAddress());
if (remoteId.length == 64) {
channel.initWithNode(remoteId);
initiate(ctx);
} else {
handshake = new EncryptionHandshake();
nodeId = myKey.getNodeId();
}
}
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
loggerWire.debug("Decoding handshake... (" + in.readableBytes() + " bytes available)");
decodeHandshake(ctx, in);
if (isHandshakeDone) {
loggerWire.debug("Handshake done, removing HandshakeHandler from pipeline.");
ctx.pipeline().remove(this);
}
}
public void initiate(ChannelHandlerContext ctx) throws Exception {
loggerNet.debug("RLPX protocol activated");
nodeId = myKey.getNodeId();
handshake = new EncryptionHandshake(ECKey.fromNodeId(this.remoteId).getPubKeyPoint());
Object msg;
if (config.eip8()) {
AuthInitiateMessageV4 initiateMessage = handshake.createAuthInitiateV4(myKey);
initiatePacket = handshake.encryptAuthInitiateV4(initiateMessage);
msg = initiateMessage;
} else {
AuthInitiateMessage initiateMessage = handshake.createAuthInitiate(null, myKey);
initiatePacket = handshake.encryptAuthMessage(initiateMessage);
msg = initiateMessage;
}
final ByteBuf byteBufMsg = ctx.alloc().buffer(initiatePacket.length);
byteBufMsg.writeBytes(initiatePacket);
ctx.writeAndFlush(byteBufMsg).sync();
channel.getNodeStatistics().rlpxAuthMessagesSent.add();
if (loggerNet.isDebugEnabled())
loggerNet.debug("To: {} Send: {}", ctx.channel().remoteAddress(), msg);
}
// consume handshake, producing no resulting message to upper layers
private void decodeHandshake(final ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
if (handshake.isInitiator()) {
if (frameCodec == null) {
byte[] responsePacket = new byte[AuthResponseMessage.getLength() + ECIESCoder.getOverhead()];
if (!buffer.isReadable(responsePacket.length))
return;
buffer.readBytes(responsePacket);
try {
// trying to decode as pre-EIP-8
AuthResponseMessage response = handshake.handleAuthResponse(myKey, initiatePacket, responsePacket);
loggerNet.debug("From: {} Recv: {}", ctx.channel().remoteAddress(), response);
} catch (Throwable t) {
// it must be format defined by EIP-8 then
responsePacket = readEIP8Packet(buffer, responsePacket);
if (responsePacket == null) return;
AuthResponseMessageV4 response = handshake.handleAuthResponseV4(myKey, initiatePacket, responsePacket);
loggerNet.debug("From: {} Recv: {}", ctx.channel().remoteAddress(), response);
}
EncryptionHandshake.Secrets secrets = this.handshake.getSecrets();
this.frameCodec = new FrameCodec(secrets);
loggerNet.debug("auth exchange done");
channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId));
} else {
loggerWire.info("MessageCodec: Buffer bytes: " + buffer.readableBytes());
List<Frame> frames = frameCodec.readFrames(buffer);
if (frames == null || frames.isEmpty())
return;
Frame frame = frames.get(0);
byte[] payload = ByteStreams.toByteArray(frame.getStream());
if (frame.getType() == P2pMessageCodes.HELLO.asByte()) {
HelloMessage helloMessage = new HelloMessage(payload);
if (loggerNet.isDebugEnabled())
loggerNet.debug("From: {} Recv: {}", ctx.channel().remoteAddress(), helloMessage);
isHandshakeDone = true;
this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, helloMessage);
} else {
DisconnectMessage message = new DisconnectMessage(payload);
if (loggerNet.isDebugEnabled())
loggerNet.debug("From: {} Recv: {}", channel, message);
channel.getNodeStatistics().nodeDisconnectedRemote(message.getReason());
}
}
} else {
loggerWire.debug("Not initiator.");
if (frameCodec == null) {
loggerWire.debug("FrameCodec == null");
byte[] authInitPacket = new byte[AuthInitiateMessage.getLength() + ECIESCoder.getOverhead()];
if (!buffer.isReadable(authInitPacket.length))
return;
buffer.readBytes(authInitPacket);
this.handshake = new EncryptionHandshake();
byte[] responsePacket;
try {
// trying to decode as pre-EIP-8
AuthInitiateMessage initiateMessage = handshake.decryptAuthInitiate(authInitPacket, myKey);
loggerNet.debug("From: {} Recv: {}", ctx.channel().remoteAddress(), initiateMessage);
AuthResponseMessage response = handshake.makeAuthInitiate(initiateMessage, myKey);
loggerNet.debug("To: {} Send: {}", ctx.channel().remoteAddress(), response);
responsePacket = handshake.encryptAuthResponse(response);
} catch (Throwable t) {
// it must be format defined by EIP-8 then
try {
authInitPacket = readEIP8Packet(buffer, authInitPacket);
if (authInitPacket == null) return;
AuthInitiateMessageV4 initiateMessage = handshake.decryptAuthInitiateV4(authInitPacket, myKey);
loggerNet.debug("From: {} Recv: {}", ctx.channel().remoteAddress(), initiateMessage);
AuthResponseMessageV4 response = handshake.makeAuthInitiateV4(initiateMessage, myKey);
loggerNet.debug("To: {} Send: {}", ctx.channel().remoteAddress(), response);
responsePacket = handshake.encryptAuthResponseV4(response);
} catch (InvalidCipherTextException ce) {
loggerNet.warn("Can't decrypt AuthInitiateMessage from " + ctx.channel().remoteAddress() +
". Most likely the remote peer used wrong public key (NodeID) to encrypt message.");
return;
}
}
handshake.agreeSecret(authInitPacket, responsePacket);
EncryptionHandshake.Secrets secrets = this.handshake.getSecrets();
this.frameCodec = new FrameCodec(secrets);
ECPoint remotePubKey = this.handshake.getRemotePublicKey();
byte[] compressed = remotePubKey.getEncoded();
this.remoteId = new byte[compressed.length - 1];
System.arraycopy(compressed, 1, this.remoteId, 0, this.remoteId.length);
final ByteBuf byteBufMsg = ctx.alloc().buffer(responsePacket.length);
byteBufMsg.writeBytes(responsePacket);
ctx.writeAndFlush(byteBufMsg).sync();
} else {
List<Frame> frames = frameCodec.readFrames(buffer);
if (frames == null || frames.isEmpty())
return;
Frame frame = frames.get(0);
Message message = new P2pMessageFactory().create((byte) frame.getType(),
ByteStreams.toByteArray(frame.getStream()));
loggerNet.debug("From: {} Recv: {}", ctx.channel().remoteAddress(), message);
if (frame.getType() == P2pMessageCodes.DISCONNECT.asByte()) {
loggerNet.debug("Active remote peer disconnected right after handshake.");
return;
}
if (frame.getType() != P2pMessageCodes.HELLO.asByte()) {
throw new RuntimeException("The message type is not HELLO or DISCONNECT: " + message);
}
final HelloMessage inboundHelloMessage = (HelloMessage) message;
// now we know both remote nodeId and port
// let's set node, that will cause registering node in NodeManager
channel.initWithNode(remoteId, inboundHelloMessage.getListenPort());
// Secret authentication finish here
channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId));
isHandshakeDone = true;
this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, inboundHelloMessage);
channel.getNodeStatistics().rlpxInHello.add();
}
}
}
private byte[] readEIP8Packet(ByteBuf buffer, byte[] plainPacket) {
int size = bigEndianToShort(plainPacket);
if (size < plainPacket.length)
throw new IllegalArgumentException("AuthResponse packet size is too low");
int bytesLeft = size - plainPacket.length + 2;
byte[] restBytes = new byte[bytesLeft];
if (!buffer.isReadable(restBytes.length))
return null;
buffer.readBytes(restBytes);
byte[] fullResponse = new byte[size + 2];
System.arraycopy(plainPacket, 0, fullResponse, 0, plainPacket.length);
System.arraycopy(restBytes, 0, fullResponse, plainPacket.length, restBytes.length);
return fullResponse;
}
public void setRemoteId(String remoteId, Channel channel){
this.remoteId = Hex.decode(remoteId);
this.channel = channel;
}
public byte[] getRemoteId() {
return remoteId;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (channel.isDiscoveryMode()) {
loggerNet.trace("Handshake failed: " + cause);
} else {
if (cause instanceof IOException || cause instanceof ReadTimeoutException) {
loggerNet.debug("Handshake failed: " + ctx.channel().remoteAddress() + ": " + cause);
} else {
loggerNet.warn("Handshake failed: ", cause);
}
}
ctx.close();
}
}
| 14,200
| 41.517964
| 123
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/FrameCodec.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import org.ethereum.net.swarm.Util;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import org.spongycastle.crypto.BlockCipher;
import org.spongycastle.crypto.StreamCipher;
import org.spongycastle.crypto.digests.KeccakDigest;
import org.spongycastle.crypto.engines.AESEngine;
import org.spongycastle.crypto.modes.SICBlockCipher;
import org.spongycastle.crypto.params.KeyParameter;
import org.spongycastle.crypto.params.ParametersWithIV;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.ethereum.util.RLP.decode2OneItem;
/**
* Created by devrandom on 2015-04-11.
*/
public class FrameCodec {
private final StreamCipher enc;
private final StreamCipher dec;
private final KeccakDigest egressMac;
private final KeccakDigest ingressMac;
private final byte[] mac;
boolean isHeadRead;
private int totalBodySize;
private int contextId = -1;
private int totalFrameSize = -1;
private int protocol;
public FrameCodec(EncryptionHandshake.Secrets secrets) {
this.mac = secrets.mac;
BlockCipher cipher;
enc = new SICBlockCipher(cipher = new AESEngine());
enc.init(true, new ParametersWithIV(new KeyParameter(secrets.aes), new byte[cipher.getBlockSize()]));
dec = new SICBlockCipher(cipher = new AESEngine());
dec.init(false, new ParametersWithIV(new KeyParameter(secrets.aes), new byte[cipher.getBlockSize()]));
egressMac = secrets.egressMac;
ingressMac = secrets.ingressMac;
}
private AESEngine makeMacCipher() {
// Stateless AES encryption
AESEngine macc = new AESEngine();
macc.init(true, new KeyParameter(mac));
return macc;
}
public static class Frame {
long type;
int size;
InputStream payload;
int totalFrameSize = -1;
int contextId = -1;
public Frame(long type, int size, InputStream payload) {
this.type = type;
this.size = size;
this.payload = payload;
}
public Frame(int type, byte[] payload) {
this.type = type;
this.size = payload.length;
this.payload = new ByteArrayInputStream(payload);
}
public int getSize() {
return size;
}
public long getType() {return type;}
public InputStream getStream() {
return payload;
}
public boolean isChunked() {
return contextId >= 0;
}
}
public void writeFrame(Frame frame, ByteBuf buf) throws IOException {
writeFrame(frame, new ByteBufOutputStream(buf));
}
public void writeFrame(Frame frame, OutputStream out) throws IOException {
byte[] headBuffer = new byte[32];
byte[] ptype = RLP.encodeInt((int) frame.type); // FIXME encodeLong
int totalSize = frame.size + ptype.length;
headBuffer[0] = (byte)(totalSize >> 16);
headBuffer[1] = (byte)(totalSize >> 8);
headBuffer[2] = (byte)(totalSize);
List<byte[]> headerDataElems = new ArrayList<>();
headerDataElems.add(RLP.encodeInt(0));
if (frame.contextId >= 0) headerDataElems.add(RLP.encodeInt(frame.contextId));
if (frame.totalFrameSize >= 0) headerDataElems.add(RLP.encodeInt(frame.totalFrameSize));
byte[] headerData = RLP.encodeList(headerDataElems.toArray(new byte[0][]));
System.arraycopy(headerData, 0, headBuffer, 3, headerData.length);
enc.processBytes(headBuffer, 0, 16, headBuffer, 0);
// Header MAC
updateMac(egressMac, headBuffer, 0, headBuffer, 16, true);
byte[] buff = new byte[256];
out.write(headBuffer);
enc.processBytes(ptype, 0, ptype.length, buff, 0);
out.write(buff, 0, ptype.length);
egressMac.update(buff, 0, ptype.length);
while (true) {
int n = frame.payload.read(buff);
if (n <= 0) break;
enc.processBytes(buff, 0, n, buff, 0);
egressMac.update(buff, 0, n);
out.write(buff, 0, n);
}
int padding = 16 - (totalSize % 16);
byte[] pad = new byte[16];
if (padding < 16) {
enc.processBytes(pad, 0, padding, buff, 0);
egressMac.update(buff, 0, padding);
out.write(buff, 0, padding);
}
// Frame MAC
byte[] macBuffer = new byte[egressMac.getDigestSize()];
doSum(egressMac, macBuffer); // fmacseed
updateMac(egressMac, macBuffer, 0, macBuffer, 0, true);
out.write(macBuffer, 0, 16);
}
public List<Frame> readFrames(ByteBuf buf) throws IOException {
try (ByteBufInputStream bufInputStream = new ByteBufInputStream(buf)) {
return readFrames(bufInputStream);
}
}
public List<Frame> readFrames(DataInput inp) throws IOException {
if (!isHeadRead) {
byte[] headBuffer = new byte[32];
try {
inp.readFully(headBuffer);
} catch (EOFException e) {
return null;
}
// Header MAC
updateMac(ingressMac, headBuffer, 0, headBuffer, 16, false);
dec.processBytes(headBuffer, 0, 16, headBuffer, 0);
totalBodySize = headBuffer[0] & 0xFF;
totalBodySize = (totalBodySize << 8) + (headBuffer[1] & 0xFF);
totalBodySize = (totalBodySize << 8) + (headBuffer[2] & 0xFF);
RLPList rlpList = (RLPList) decode2OneItem(headBuffer, 3);
protocol = Util.rlpDecodeInt(rlpList.get(0));
contextId = -1;
totalFrameSize = -1;
if (rlpList.size() > 1) {
contextId = Util.rlpDecodeInt(rlpList.get(1));
if (rlpList.size() > 2) {
totalFrameSize = Util.rlpDecodeInt(rlpList.get(2));
}
}
isHeadRead = true;
}
int padding = 16 - (totalBodySize % 16);
if (padding == 16) padding = 0;
int macSize = 16;
byte[] buffer = new byte[totalBodySize + padding + macSize];
try {
inp.readFully(buffer);
} catch (EOFException e) {
return null;
}
int frameSize = buffer.length - macSize;
ingressMac.update(buffer, 0, frameSize);
dec.processBytes(buffer, 0, frameSize, buffer, 0);
int pos = 0;
long type = RLP.decodeLong(buffer, pos);
pos = RLP.getNextElementIndex(buffer, pos);
InputStream payload = new ByteArrayInputStream(buffer, pos, totalBodySize - pos);
int size = totalBodySize - pos;
byte[] macBuffer = new byte[ingressMac.getDigestSize()];
// Frame MAC
doSum(ingressMac, macBuffer); // fmacseed
updateMac(ingressMac, macBuffer, 0, buffer, frameSize, false);
isHeadRead = false;
Frame frame = new Frame(type, size, payload);
frame.contextId = contextId;
frame.totalFrameSize = totalFrameSize;
return Collections.singletonList(frame);
}
private byte[] updateMac(KeccakDigest mac, byte[] seed, int offset, byte[] out, int outOffset, boolean egress) throws IOException {
byte[] aesBlock = new byte[mac.getDigestSize()];
doSum(mac, aesBlock);
makeMacCipher().processBlock(aesBlock, 0, aesBlock, 0);
// Note that although the mac digest size is 32 bytes, we only use 16 bytes in the computation
int length = 16;
for (int i = 0; i < length; i++) {
aesBlock[i] ^= seed[i + offset];
}
mac.update(aesBlock, 0, length);
byte[] result = new byte[mac.getDigestSize()];
doSum(mac, result);
if (egress) {
System.arraycopy(result, 0, out, outOffset, length);
} else {
for (int i = 0; i < length; i++) {
if (out[i + outOffset] != result[i]) {
throw new IOException("MAC mismatch");
}
}
}
return result;
}
private void doSum(KeccakDigest mac, byte[] out) {
// doFinal without resetting the MAC by using clone of digest state
new KeccakDigest(mac).doFinal(out, 0);
}
}
| 9,249
| 34.714286
| 135
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/NettyByteToMessageCodec.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
/**
* Since decoder field is not modifiable in the ByteToMessageCodec this class
* overrides it to set the COMPOSITE_CUMULATOR for ByteToMessageDecoder as it
* is more effective than the default one.
*/
public abstract class NettyByteToMessageCodec<I> extends ByteToMessageCodec<I> {
private final ByteToMessageDecoder decoder = new ByteToMessageDecoder() {
{
setCumulator(COMPOSITE_CUMULATOR);
}
@Override
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
NettyByteToMessageCodec.this.decode(ctx, in, out);
}
@Override
protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
NettyByteToMessageCodec.this.decodeLast(ctx, in, out);
}
};
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
decoder.channelReadComplete(ctx);
super.channelReadComplete(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
decoder.channelInactive(ctx);
super.channelInactive(ctx);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
decoder.handlerAdded(ctx);
super.handlerAdded(ctx);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
decoder.handlerRemoved(ctx);
super.handlerRemoved(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
decoder.channelRead(ctx, msg);
}
}
| 2,707
| 34.631579
| 109
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/Node.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import org.ethereum.util.Utils;
import org.spongycastle.util.encoders.Hex;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.util.ByteUtil.byteArrayToInt;
import static org.ethereum.util.ByteUtil.bytesToIp;
import static org.ethereum.util.ByteUtil.hostToBytes;
import static org.ethereum.util.ByteUtil.toHexString;
public class Node implements Serializable {
private static final long serialVersionUID = -4267600517925770636L;
byte[] id;
String host;
int port;
// discovery endpoint doesn't have real nodeId for example
private boolean isFakeNodeId = false;
/**
* - create Node instance from enode if passed,
* - otherwise fallback to random nodeId, if supplied with only "address:port"
* NOTE: validation is absent as method is not heavily used
*/
public static Node instanceOf(String addressOrEnode) {
try {
URI uri = new URI(addressOrEnode);
if (uri.getScheme().equals("enode")) {
return new Node(addressOrEnode);
}
} catch (URISyntaxException e) {
// continue
}
final ECKey generatedNodeKey = ECKey.fromPrivate(sha3(addressOrEnode.getBytes()));
final String generatedNodeId = Hex.toHexString(generatedNodeKey.getNodeId());
final Node node = new Node("enode://" + generatedNodeId + "@" + addressOrEnode);
node.isFakeNodeId = true;
return node;
}
public Node(String enodeURL) {
try {
URI uri = new URI(enodeURL);
if (!uri.getScheme().equals("enode")) {
throw new RuntimeException("expecting URL in the format enode://PUBKEY@HOST:PORT");
}
this.id = Hex.decode(uri.getUserInfo());
this.host = uri.getHost();
this.port = uri.getPort();
} catch (URISyntaxException e) {
throw new RuntimeException("expecting URL in the format enode://PUBKEY@HOST:PORT", e);
}
}
public Node(byte[] id, String host, int port) {
this.id = id;
this.host = host;
this.port = port;
}
/**
* Instantiates node from RLP list containing node data.
* @throws IllegalArgumentException if node id is not a valid EC point.
*/
public Node(RLPList nodeRLP) {
byte[] hostB = nodeRLP.get(0).getRLPData();
byte[] portB = nodeRLP.get(1).getRLPData();
byte[] idB;
if (nodeRLP.size() > 3) {
idB = nodeRLP.get(3).getRLPData();
} else {
idB = nodeRLP.get(2).getRLPData();
}
int port = byteArrayToInt(portB);
this.host = bytesToIp(hostB);
this.port = port;
// a tricky way to check whether given data is a valid EC point or not
this.id = ECKey.fromNodeId(idB).getNodeId();
}
public Node(byte[] rlp) {
this((RLPList) RLP.decode2(rlp).get(0));
}
/**
* @return true if this node is endpoint for discovery loaded from config
*/
public boolean isDiscoveryNode() {
return isFakeNodeId;
}
public byte[] getId() {
return id;
}
public String getHexId() {
return Hex.toHexString(id);
}
public String getHexIdShort() {
return Utils.getNodeIdShort(getHexId());
}
public void setId(byte[] id) {
this.id = id;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public void setDiscoveryNode(boolean isDiscoveryNode) {
isFakeNodeId = isDiscoveryNode;
}
/**
* Full RLP
* [host, udpPort, tcpPort, nodeId]
* @return RLP-encoded node data
*/
public byte[] getRLP() {
byte[] rlphost = RLP.encodeElement(hostToBytes(host));
byte[] rlpTCPPort = RLP.encodeInt(port);
byte[] rlpUDPPort = RLP.encodeInt(port);
byte[] rlpId = RLP.encodeElement(id);
return RLP.encodeList(rlphost, rlpUDPPort, rlpTCPPort, rlpId);
}
/**
* RLP without nodeId
* [host, udpPort, tcpPort]
* @return RLP-encoded node data
*/
public byte[] getBriefRLP() {
byte[] rlphost = RLP.encodeElement(hostToBytes(host));
byte[] rlpTCPPort = RLP.encodeInt(port);
byte[] rlpUDPPort = RLP.encodeInt(port);
return RLP.encodeList(rlphost, rlpUDPPort, rlpTCPPort);
}
@Override
public String toString() {
return "Node{" +
" host='" + host + '\'' +
", port=" + port +
", id=" + toHexString(id) +
'}';
}
@Override
public int hashCode() {
return this.toString().hashCode();
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
if (o instanceof Node) {
return Arrays.equals(((Node) o).getId(), this.getId());
}
return false;
}
}
| 6,212
| 27.5
| 99
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/PongMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPItem;
import org.ethereum.util.RLPList;
public class PongMessage extends Message {
byte[] token; // token is the MDC of the ping
long expires;
public static PongMessage create(byte[] token, Node toNode, ECKey privKey) {
long expiration = 90 * 60 + System.currentTimeMillis() / 1000;
byte[] rlpToList = toNode.getBriefRLP();
/* RLP Encode data */
byte[] rlpToken = RLP.encodeElement(token);
byte[] tmpExp = ByteUtil.longToBytes(expiration);
byte[] rlpExp = RLP.encodeElement(ByteUtil.stripLeadingZeroes(tmpExp));
byte[] type = new byte[]{2};
byte[] data = RLP.encodeList(rlpToList, rlpToken, rlpExp);
PongMessage pong = new PongMessage();
pong.encode(type, data, privKey);
pong.token = token;
pong.expires = expiration;
return pong;
}
public static PongMessage create(byte[] token, ECKey privKey) {
return create(token, privKey, 3 + System.currentTimeMillis() / 1000);
}
static PongMessage create(byte[] token, ECKey privKey, long expiration) {
/* RLP Encode data */
byte[] rlpToken = RLP.encodeElement(token);
byte[] rlpExp = RLP.encodeElement(ByteUtil.longToBytes(expiration));
byte[] type = new byte[]{2};
byte[] data = RLP.encodeList(rlpToken, rlpExp);
PongMessage pong = new PongMessage();
pong.encode(type, data, privKey);
pong.token = token;
pong.expires = expiration;
return pong;
}
@Override
public void parse(byte[] data) {
RLPList list = (RLPList) RLP.decode2OneItem(data, 0);
this.token = list.get(0).getRLPData();
RLPItem expires = (RLPItem) list.get(1);
this.expires = ByteUtil.byteArrayToLong(expires.getRLPData());
}
public byte[] getToken() {
return token;
}
public long getExpires() {
return expires;
}
@Override
public String toString() {
long currTime = System.currentTimeMillis() / 1000;
String out = String.format("[PongMessage] \n token: %s \n expires in %d seconds \n %s\n",
ByteUtil.toHexString(token), (expires - currTime), super.toString());
return out;
}
}
| 3,211
| 29.590476
| 97
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/Message.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.FastByteComparisons;
import org.spongycastle.util.BigIntegers;
import java.security.SignatureException;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.util.ByteUtil.merge;
import static org.ethereum.util.ByteUtil.toHexString;
public abstract class Message {
byte[] wire;
byte[] mdc;
byte[] signature;
byte[] type;
byte[] data;
public static Message decode(byte[] wire) {
if (wire.length < 98) throw new RuntimeException("Bad message");
byte[] mdc = new byte[32];
System.arraycopy(wire, 0, mdc, 0, 32);
byte[] signature = new byte[65];
System.arraycopy(wire, 32, signature, 0, 65);
byte[] type = new byte[1];
type[0] = wire[97];
byte[] data = new byte[wire.length - 98];
System.arraycopy(wire, 98, data, 0, data.length);
byte[] mdcCheck = sha3(wire, 32, wire.length - 32);
int check = FastByteComparisons.compareTo(mdc, 0, mdc.length, mdcCheck, 0, mdcCheck.length);
if (check != 0) throw new RuntimeException("MDC check failed");
Message msg;
if (type[0] == 1) msg = new PingMessage();
else if (type[0] == 2) msg = new PongMessage();
else if (type[0] == 3) msg = new FindNodeMessage();
else if (type[0] == 4) msg = new NeighborsMessage();
else throw new RuntimeException("Unknown RLPx message: " + type[0]);
msg.mdc = mdc;
msg.signature = signature;
msg.type = type;
msg.data = data;
msg.wire = wire;
msg.parse(data);
return msg;
}
public Message encode(byte[] type, byte[] data, ECKey privKey) {
/* [1] Calc keccak - prepare for sig */
byte[] payload = new byte[type.length + data.length];
payload[0] = type[0];
System.arraycopy(data, 0, payload, 1, data.length);
byte[] forSig = sha3(payload);
/* [2] Crate signature*/
ECKey.ECDSASignature signature = privKey.sign(forSig);
signature.v -= 27;
byte[] sigBytes =
merge(BigIntegers.asUnsignedByteArray(32, signature.r),
BigIntegers.asUnsignedByteArray(32, signature.s), new byte[]{signature.v});
// [3] calculate MDC
byte[] forSha = merge(sigBytes, type, data);
byte[] mdc = sha3(forSha);
// wrap all the data in to the packet
this.mdc = mdc;
this.signature = sigBytes;
this.type = type;
this.data = data;
this.wire = merge(this.mdc, this.signature, this.type, this.data);
return this;
}
public ECKey getKey() {
byte[] r = new byte[32];
byte[] s = new byte[32];
byte v = signature[64];
// todo: remove this when cpp conclude what they do here
if (v == 1) v = 28;
if (v == 0) v = 27;
System.arraycopy(signature, 0, r, 0, 32);
System.arraycopy(signature, 32, s, 0, 32);
ECKey.ECDSASignature signature = ECKey.ECDSASignature.fromComponents(r, s, v);
byte[] msgHash = sha3(wire, 97, wire.length - 97);
ECKey outKey = null;
try {
outKey = ECKey.signatureToKey(msgHash, signature);
} catch (SignatureException e) {
e.printStackTrace();
}
return outKey;
}
public byte[] getNodeId() {
return getKey().getNodeId();
}
public byte[] getPacket() {
return wire;
}
public byte[] getMdc() {
return mdc;
}
public byte[] getSignature() {
return signature;
}
public byte[] getType() {
return type;
}
public byte[] getData() {
return data;
}
public abstract void parse(byte[] data);
@Override
public String toString() {
return "{" +
"mdc=" + toHexString(mdc) +
", signature=" + toHexString(signature) +
", type=" + toHexString(type) +
", data=" + toHexString(data) +
'}';
}
}
| 4,938
| 27.385057
| 100
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/FindNodeMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPItem;
import org.ethereum.util.RLPList;
import static org.ethereum.util.ByteUtil.longToBytesNoLeadZeroes;
import static org.ethereum.util.ByteUtil.toHexString;
public class FindNodeMessage extends Message {
byte[] target;
long expires;
@Override
public void parse(byte[] data) {
RLPList list = (RLPList) RLP.decode2OneItem(data, 0);
RLPItem target = (RLPItem) list.get(0);
RLPItem expires = (RLPItem) list.get(1);
this.target = target.getRLPData();
this.expires = ByteUtil.byteArrayToLong(expires.getRLPData());
}
public static FindNodeMessage create(byte[] target, ECKey privKey) {
long expiration = 90 * 60 + System.currentTimeMillis() / 1000;
/* RLP Encode data */
byte[] rlpToken = RLP.encodeElement(target);
byte[] rlpExp = longToBytesNoLeadZeroes(expiration);
rlpExp = RLP.encodeElement(rlpExp);
byte[] type = new byte[]{3};
byte[] data = RLP.encodeList(rlpToken, rlpExp);
FindNodeMessage findNode = new FindNodeMessage();
findNode.encode(type, data, privKey);
findNode.target = target;
findNode.expires = expiration;
return findNode;
}
public byte[] getTarget() {
return target;
}
public long getExpires() {
return expires;
}
@Override
public String toString() {
long currTime = System.currentTimeMillis() / 1000;
return String.format("[FindNodeMessage] \n target: %s \n expires in %d seconds \n %s\n",
toHexString(target), (expires - currTime), super.toString());
}
}
| 2,586
| 29.081395
| 96
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/PingMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPItem;
import org.ethereum.util.RLPList;
import static org.ethereum.util.ByteUtil.bytesToIp;
import static org.ethereum.util.ByteUtil.longToBytes;
import static org.ethereum.util.ByteUtil.stripLeadingZeroes;
public class PingMessage extends Message {
String toHost;
int toPort;
String fromHost;
int fromPort;
long expires;
int version;
public static PingMessage create(Node fromNode, Node toNode, ECKey privKey) {
return create(fromNode, toNode, privKey, 4);
}
public static PingMessage create(Node fromNode, Node toNode, ECKey privKey, int version) {
long expiration = 90 * 60 + System.currentTimeMillis() / 1000;
/* RLP Encode data */
byte[] tmpExp = longToBytes(expiration);
byte[] rlpExp = RLP.encodeElement(stripLeadingZeroes(tmpExp));
byte[] type = new byte[]{1};
byte[] rlpVer = RLP.encodeInt(version);
byte[] rlpFromList = fromNode.getBriefRLP();
byte[] rlpToList = toNode.getBriefRLP();
byte[] data = RLP.encodeList(rlpVer, rlpFromList, rlpToList, rlpExp);
PingMessage ping = new PingMessage();
ping.encode(type, data, privKey);
ping.expires = expiration;
ping.toHost = toNode.getHost();
ping.toPort = toNode.getPort();
ping.fromHost = fromNode.getHost();
ping.fromPort = fromNode.getPort();
return ping;
}
@Override
public void parse(byte[] data) {
RLPList dataList = (RLPList) RLP.decode2OneItem(data, 0);
RLPList fromList = (RLPList) dataList.get(1);
byte[] ipF = fromList.get(0).getRLPData();
this.fromHost = bytesToIp(ipF);
this.fromPort = ByteUtil.byteArrayToInt(fromList.get(1).getRLPData());
RLPList toList = (RLPList) dataList.get(2);
byte[] ipT = toList.get(0).getRLPData();
this.toHost = bytesToIp(ipT);
this.toPort = ByteUtil.byteArrayToInt(toList.get(1).getRLPData());
RLPItem expires = (RLPItem) dataList.get(3);
this.expires = ByteUtil.byteArrayToLong(expires.getRLPData());
this.version = ByteUtil.byteArrayToInt(dataList.get(0).getRLPData());
}
public String getToHost() {
return toHost;
}
public int getToPort() {
return toPort;
}
public String getFromHost() {
return fromHost;
}
public int getFromPort() {
return fromPort;
}
public long getExpires() {
return expires;
}
@Override
public String toString() {
long currTime = System.currentTimeMillis() / 1000;
String out = String.format("[PingMessage] \n %s:%d ==> %s:%d \n expires in %d seconds \n %s\n",
fromHost, fromPort, toHost, toPort, (expires - currTime), super.toString());
return out;
}
}
| 3,774
| 29.942623
| 103
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/AuthInitiateMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.spongycastle.math.ec.ECPoint;
import org.spongycastle.util.BigIntegers;
import java.util.Arrays;
import static org.ethereum.util.ByteUtil.merge;
import static org.spongycastle.util.BigIntegers.asUnsignedByteArray;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Authentication initiation message, to be wrapped inside
*
* Created by devrandom on 2015-04-07.
*/
public class AuthInitiateMessage {
ECKey.ECDSASignature signature; // 65 bytes
byte[] ephemeralPublicHash; // 32 bytes
ECPoint publicKey; // 64 bytes - uncompressed and no type byte
byte[] nonce; // 32 bytes
boolean isTokenUsed; // 1 byte - 0x00 or 0x01
public AuthInitiateMessage() {
}
public static int getLength() {
return 65+32+64+32+1;
}
static AuthInitiateMessage decode(byte[] wire) {
AuthInitiateMessage message = new AuthInitiateMessage();
int offset = 0;
byte[] r = new byte[32];
byte[] s = new byte[32];
System.arraycopy(wire, offset, r, 0, 32);
offset += 32;
System.arraycopy(wire, offset, s, 0, 32);
offset += 32;
int v = wire[offset] + 27;
offset += 1;
message.signature = ECKey.ECDSASignature.fromComponents(r, s, (byte)v);
message.ephemeralPublicHash = new byte[32];
System.arraycopy(wire, offset, message.ephemeralPublicHash, 0, 32);
offset += 32;
byte[] bytes = new byte[65];
System.arraycopy(wire, offset, bytes, 1, 64);
offset += 64;
bytes[0] = 0x04; // uncompressed
message.publicKey = ECKey.CURVE.getCurve().decodePoint(bytes);
message.nonce = new byte[32];
System.arraycopy(wire, offset, message.nonce, 0, 32);
offset += message.nonce.length;
byte tokenUsed = wire[offset];
offset += 1;
if (tokenUsed != 0x00 && tokenUsed != 0x01)
throw new RuntimeException("invalid boolean"); // TODO specific exception
message.isTokenUsed = (tokenUsed == 0x01);
return message;
}
public byte[] encode() {
byte[] rsigPad = new byte[32];
byte[] rsig = asUnsignedByteArray(signature.r);
System.arraycopy(rsig, 0, rsigPad, rsigPad.length - rsig.length, rsig.length);
byte[] ssigPad = new byte[32];
byte[] ssig = asUnsignedByteArray(signature.s);
System.arraycopy(ssig, 0, ssigPad, ssigPad.length - ssig.length, ssig.length);
byte[] sigBytes = merge(rsigPad, ssigPad, new byte[]{EncryptionHandshake.recIdFromSignatureV(signature.v)});
byte[] buffer = new byte[getLength()];
int offset = 0;
System.arraycopy(sigBytes, 0, buffer, offset, sigBytes.length);
offset += sigBytes.length;
System.arraycopy(ephemeralPublicHash, 0, buffer, offset, ephemeralPublicHash.length);
offset += ephemeralPublicHash.length;
byte[] publicBytes = publicKey.getEncoded(false);
System.arraycopy(publicBytes, 1, buffer, offset, publicBytes.length - 1);
offset += publicBytes.length - 1;
System.arraycopy(nonce, 0, buffer, offset, nonce.length);
offset += nonce.length;
buffer[offset] = (byte)(isTokenUsed ? 0x01 : 0x00);
offset += 1;
return buffer;
}
@Override
public String toString() {
byte[] sigBytes = merge(asUnsignedByteArray(signature.r),
asUnsignedByteArray(signature.s), new byte[]{EncryptionHandshake.recIdFromSignatureV(signature.v)});
return "AuthInitiateMessage{" +
"\n sigBytes=" + toHexString(sigBytes) +
"\n ephemeralPublicHash=" + toHexString(ephemeralPublicHash) +
"\n publicKey=" + toHexString(publicKey.getEncoded(false)) +
"\n nonce=" + toHexString(nonce) +
"\n}";
}
}
| 4,712
| 37.631148
| 116
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/AuthResponseMessageV4.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import org.spongycastle.math.ec.ECPoint;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Auth Response message defined by EIP-8
*
* @author mkalinin
* @since 17.02.2016
*/
public class AuthResponseMessageV4 {
ECPoint ephemeralPublicKey; // 64 bytes - uncompressed and no type byte
byte[] nonce; // 32 bytes
int version = 4; // 4 bytes
static AuthResponseMessageV4 decode(byte[] wire) {
AuthResponseMessageV4 message = new AuthResponseMessageV4();
RLPList params = (RLPList) RLP.decode2OneItem(wire, 0);
byte[] pubKeyBytes = params.get(0).getRLPData();
byte[] bytes = new byte[65];
System.arraycopy(pubKeyBytes, 0, bytes, 1, 64);
bytes[0] = 0x04; // uncompressed
message.ephemeralPublicKey = ECKey.CURVE.getCurve().decodePoint(bytes);
message.nonce = params.get(1).getRLPData();
byte[] versionBytes = params.get(2).getRLPData();
message.version = ByteUtil.byteArrayToInt(versionBytes);
return message;
}
public byte[] encode() {
byte[] publicKey = new byte[64];
System.arraycopy(ephemeralPublicKey.getEncoded(false), 1, publicKey, 0, publicKey.length);
byte[] publicBytes = RLP.encode(publicKey);
byte[] nonceBytes = RLP.encode(nonce);
byte[] versionBytes = RLP.encodeInt(version);
return RLP.encodeList(publicBytes, nonceBytes, versionBytes);
}
@Override
public String toString() {
return "AuthResponseMessage{" +
"\n ephemeralPublicKey=" + ephemeralPublicKey +
"\n nonce=" + toHexString(nonce) +
"\n version=" + version +
'}';
}
}
| 2,671
| 31.585366
| 98
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/MessageCodec.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import com.google.common.io.ByteStreams;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import org.apache.commons.collections4.map.LRUMap;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.SystemProperties;
import org.ethereum.listener.EthereumListener;
import org.ethereum.net.client.Capability;
import org.ethereum.net.eth.EthVersion;
import org.ethereum.net.eth.message.EthMessageCodes;
import org.ethereum.net.message.Message;
import org.ethereum.net.message.MessageFactory;
import org.ethereum.net.message.ReasonCode;
import org.ethereum.net.p2p.P2pMessageCodes;
import org.ethereum.net.server.Channel;
import org.ethereum.net.shh.ShhMessageCodes;
import org.ethereum.net.swarm.bzz.BzzMessageCodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.Math.min;
import static org.ethereum.net.rlpx.FrameCodec.Frame;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* The Netty codec which encodes/decodes RPLx frames to subprotocol Messages
*/
@Component
@Scope("prototype")
public class MessageCodec extends MessageToMessageCodec<Frame, Message> {
private static final Logger loggerWire = LoggerFactory.getLogger("wire");
private static final Logger loggerNet = LoggerFactory.getLogger("net");
public static final int NO_FRAMING = Integer.MAX_VALUE >> 1;
private int maxFramePayloadSize = NO_FRAMING;
private Channel channel;
private MessageCodesResolver messageCodesResolver;
private MessageFactory p2pMessageFactory;
private MessageFactory ethMessageFactory;
private MessageFactory shhMessageFactory;
private MessageFactory bzzMessageFactory;
private EthVersion ethVersion;
@Autowired
EthereumListener ethereumListener;
private SystemProperties config;
private boolean supportChunkedFrames = false;
Map<Integer, Pair<? extends List<Frame>, AtomicInteger>> incompleteFrames = new LRUMap<>(16);
// LRU avoids OOM on invalid peers
AtomicInteger contextIdCounter = new AtomicInteger(1);
public MessageCodec() {
}
@Autowired
private MessageCodec(final SystemProperties config) {
this.config = config;
setMaxFramePayloadSize(config.rlpxMaxFrameSize());
}
@Override
protected void decode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
Frame completeFrame = null;
if (frame.isChunked()) {
if (!supportChunkedFrames && frame.totalFrameSize > 0) {
throw new RuntimeException("Framing is not supported in this configuration.");
}
Pair<? extends List<Frame>, AtomicInteger> frameParts = incompleteFrames.get(frame.contextId);
if (frameParts == null) {
if (frame.totalFrameSize < 0) {
// loggerNet.warn("No initial frame received for context-id: " + frame.contextId + ". Discarding this frame as invalid.");
// TODO: refactor this logic (Cpp sends non-chunked frames with context-id)
Message message = decodeMessage(ctx, Collections.singletonList(frame));
if (message == null) return;
out.add(message);
return;
} else {
frameParts = Pair.of(new ArrayList<Frame>(), new AtomicInteger(0));
incompleteFrames.put(frame.contextId, frameParts);
}
} else {
if (frame.totalFrameSize >= 0) {
loggerNet.warn("Non-initial chunked frame shouldn't contain totalFrameSize field (context-id: " + frame.contextId + ", totalFrameSize: " + frame.totalFrameSize + "). Discarding this frame and all previous.");
incompleteFrames.remove(frame.contextId);
return;
}
}
frameParts.getLeft().add(frame);
int curSize = frameParts.getRight().addAndGet(frame.size);
if (loggerWire.isDebugEnabled())
loggerWire.debug("Recv: Chunked (" + curSize + " of " + frameParts.getLeft().get(0).totalFrameSize + ") [size: " + frame.getSize() + "]");
if (curSize > frameParts.getLeft().get(0).totalFrameSize) {
loggerNet.warn("The total frame chunks size (" + curSize + ") is greater than expected (" + frameParts.getLeft().get(0).totalFrameSize + "). Discarding the frame.");
incompleteFrames.remove(frame.contextId);
return;
}
if (curSize == frameParts.getLeft().get(0).totalFrameSize) {
Message message = decodeMessage(ctx, frameParts.getLeft());
incompleteFrames.remove(frame.contextId);
out.add(message);
}
} else {
Message message = decodeMessage(ctx, Collections.singletonList(frame));
out.add(message);
}
}
private Message decodeMessage(ChannelHandlerContext ctx, List<Frame> frames) throws IOException {
long frameType = frames.get(0).getType();
byte[] payload = new byte[frames.size() == 1 ? frames.get(0).getSize() : frames.get(0).totalFrameSize];
int pos = 0;
for (Frame frame : frames) {
pos += ByteStreams.read(frame.getStream(), payload, pos, frame.getSize());
}
if (loggerWire.isDebugEnabled())
loggerWire.debug("Recv: Encoded: {} [{}]", frameType, toHexString(payload));
Message msg;
try {
msg = createMessage((byte) frameType, payload);
if (loggerNet.isDebugEnabled())
loggerNet.debug("From: {} Recv: {}", channel, msg.toString());
} catch (Exception ex) {
loggerNet.debug(String.format("Incorrectly encoded message from: \t%s, dropping peer", channel), ex);
channel.disconnect(ReasonCode.BAD_PROTOCOL);
return null;
}
ethereumListener.onRecvMessage(channel, msg);
channel.getNodeStatistics().rlpxInMessages.add();
return msg;
}
@Override
protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
String output = String.format("To: \t%s \tSend: \t%s", ctx.channel().remoteAddress(), msg);
ethereumListener.trace(output);
if (loggerNet.isDebugEnabled())
loggerNet.debug("To: {} Send: {}", channel, msg);
byte[] encoded = msg.getEncoded();
if (loggerWire.isDebugEnabled())
loggerWire.debug("Send: Encoded: {} [{}]", getCode(msg.getCommand()), toHexString(encoded));
List<Frame> frames = splitMessageToFrames(msg);
out.addAll(frames);
channel.getNodeStatistics().rlpxOutMessages.add();
}
private List<Frame> splitMessageToFrames(Message msg) {
byte code = getCode(msg.getCommand());
List<Frame> ret = new ArrayList<>();
byte[] bytes = msg.getEncoded();
int curPos = 0;
while(curPos < bytes.length) {
int newPos = min(curPos + maxFramePayloadSize, bytes.length);
byte[] frameBytes = curPos == 0 && newPos == bytes.length ? bytes :
Arrays.copyOfRange(bytes, curPos, newPos);
ret.add(new Frame(code, frameBytes));
curPos = newPos;
}
if (ret.size() > 1) {
// frame has been split
int contextId = contextIdCounter.getAndIncrement();
ret.get(0).totalFrameSize = bytes.length;
loggerWire.debug("Message (size " + bytes.length + ") split to " + ret.size() + " frames. Context-id: " + contextId);
for (Frame frame : ret) {
frame.contextId = contextId;
}
}
return ret;
}
public void setSupportChunkedFrames(boolean supportChunkedFrames) {
this.supportChunkedFrames = supportChunkedFrames;
if (!supportChunkedFrames) {
setMaxFramePayloadSize(NO_FRAMING);
}
}
/* TODO: this dirty hack is here cause we need to use message
TODO: adaptive id on high message abstraction level,
TODO: need a solution here*/
private byte getCode(Enum msgCommand){
byte code = 0;
if (msgCommand instanceof P2pMessageCodes){
code = messageCodesResolver.withP2pOffset(((P2pMessageCodes) msgCommand).asByte());
}
if (msgCommand instanceof EthMessageCodes){
code = messageCodesResolver.withEthOffset(((EthMessageCodes) msgCommand).asByte());
}
if (msgCommand instanceof ShhMessageCodes){
code = messageCodesResolver.withShhOffset(((ShhMessageCodes)msgCommand).asByte());
}
if (msgCommand instanceof BzzMessageCodes){
code = messageCodesResolver.withBzzOffset(((BzzMessageCodes) msgCommand).asByte());
}
return code;
}
private Message createMessage(byte code, byte[] payload) {
byte resolved = messageCodesResolver.resolveP2p(code);
if (p2pMessageFactory != null && P2pMessageCodes.inRange(resolved)) {
return p2pMessageFactory.create(resolved, payload);
}
resolved = messageCodesResolver.resolveEth(code);
if (ethMessageFactory != null && EthMessageCodes.inRange(resolved, ethVersion)) {
return ethMessageFactory.create(resolved, payload);
}
resolved = messageCodesResolver.resolveShh(code);
if (shhMessageFactory != null && ShhMessageCodes.inRange(resolved)) {
return shhMessageFactory.create(resolved, payload);
}
resolved = messageCodesResolver.resolveBzz(code);
if (bzzMessageFactory != null && BzzMessageCodes.inRange(resolved)) {
return bzzMessageFactory.create(resolved, payload);
}
throw new IllegalArgumentException("No such message: " + code + " [" + toHexString(payload) + "]");
}
public void setChannel(Channel channel){
this.channel = channel;
}
public void setEthVersion(EthVersion ethVersion) {
this.ethVersion = ethVersion;
}
public void setMaxFramePayloadSize(int maxFramePayloadSize) {
this.maxFramePayloadSize = maxFramePayloadSize;
}
public void initMessageCodes(List<Capability> caps) {
this.messageCodesResolver = new MessageCodesResolver(caps);
}
public void setP2pMessageFactory(MessageFactory p2pMessageFactory) {
this.p2pMessageFactory = p2pMessageFactory;
}
public void setEthMessageFactory(MessageFactory ethMessageFactory) {
this.ethMessageFactory = ethMessageFactory;
}
public void setShhMessageFactory(MessageFactory shhMessageFactory) {
this.shhMessageFactory = shhMessageFactory;
}
public void setBzzMessageFactory(MessageFactory bzzMessageFactory) {
this.bzzMessageFactory = bzzMessageFactory;
}
}
| 12,098
| 38.282468
| 228
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/SnappyCodec.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import org.ethereum.net.message.ReasonCode;
import org.ethereum.net.server.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xerial.snappy.Snappy;
import java.io.IOException;
import java.util.List;
/**
* Snappy compression codec. <br>
*
* Check <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-706.md">EIP-706</a> for details
*
* @author Mikhail Kalinin
* @since 31.10.2017
*/
public class SnappyCodec extends MessageToMessageCodec<FrameCodec.Frame, FrameCodec.Frame> {
private static final Logger logger = LoggerFactory.getLogger("net");
private final static int SNAPPY_P2P_VERSION = 5;
private final static int MAX_SIZE = 16 * 1024 * 1024; // 16 mb
Channel channel;
public SnappyCodec(Channel channel) {
this.channel = channel;
}
public static boolean isSupported(int p2pVersion) {
return p2pVersion >= SNAPPY_P2P_VERSION;
}
@Override
protected void encode(ChannelHandlerContext ctx, FrameCodec.Frame msg, List<Object> out) throws Exception {
// stay consistent with decoding party
if (msg.size > MAX_SIZE) {
logger.info("{}: outgoing frame size exceeds the limit ({} bytes), disconnect", channel, msg.size);
channel.disconnect(ReasonCode.USELESS_PEER);
return;
}
byte[] in = new byte[msg.size];
msg.payload.read(in);
byte[] compressed = Snappy.rawCompress(in, in.length);
out.add(new FrameCodec.Frame((int) msg.type, compressed));
}
@Override
protected void decode(ChannelHandlerContext ctx, FrameCodec.Frame msg, List<Object> out) throws Exception {
byte[] in = new byte[msg.size];
msg.payload.read(in);
long uncompressedLength = Snappy.uncompressedLength(in) & 0xFFFFFFFFL;
if (uncompressedLength > MAX_SIZE) {
logger.info("{}: uncompressed frame size exceeds the limit ({} bytes), drop the peer", channel, uncompressedLength);
channel.disconnect(ReasonCode.BAD_PROTOCOL);
return;
}
byte[] uncompressed = new byte[(int) uncompressedLength];
try {
Snappy.rawUncompress(in, 0, in.length, uncompressed, 0);
} catch (IOException e) {
String detailMessage = e.getMessage();
// 5 - error code for framed snappy
if (detailMessage.startsWith("FAILED_TO_UNCOMPRESS") && detailMessage.contains("5")) {
logger.info("{}: Snappy frames are not allowed in DEVp2p protocol, drop the peer", channel);
channel.disconnect(ReasonCode.BAD_PROTOCOL);
return;
} else {
throw e;
}
}
out.add(new FrameCodec.Frame((int) msg.type, uncompressed));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (channel.isDiscoveryMode()) {
logger.trace("SnappyCodec failed: " + cause);
} else {
if (cause instanceof IOException) {
logger.debug("SnappyCodec failed: " + ctx.channel().remoteAddress() + ": " + cause);
} else {
logger.warn("SnappyCodec failed: ", cause);
}
}
ctx.close();
}
}
| 4,240
| 34.638655
| 128
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/NeighborsMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPItem;
import org.ethereum.util.RLPList;
import java.util.ArrayList;
import java.util.List;
import static org.ethereum.util.ByteUtil.longToBytesNoLeadZeroes;
public class NeighborsMessage extends Message {
List<Node> nodes;
long expires;
@Override
public void parse(byte[] data) {
RLPList list = (RLPList) RLP.decode2OneItem(data, 0);
RLPList nodesRLP = (RLPList) list.get(0);
RLPItem expires = (RLPItem) list.get(1);
nodes = new ArrayList<>();
for (int i = 0; i < nodesRLP.size(); ++i) {
RLPList nodeRLP = (RLPList) nodesRLP.get(i);
Node node = new Node(nodeRLP);
nodes.add(node);
}
this.expires = ByteUtil.byteArrayToLong(expires.getRLPData());
}
public static NeighborsMessage create(List<Node> nodes, ECKey privKey) {
long expiration = 90 * 60 + System.currentTimeMillis() / 1000;
byte[][] nodeRLPs = null;
if (nodes != null) {
nodeRLPs = new byte[nodes.size()][];
int i = 0;
for (Node node : nodes) {
nodeRLPs[i] = node.getRLP();
++i;
}
}
byte[] rlpListNodes = RLP.encodeList(nodeRLPs);
byte[] rlpExp = longToBytesNoLeadZeroes(expiration);
rlpExp = RLP.encodeElement(rlpExp);
byte[] type = new byte[]{4};
byte[] data = RLP.encodeList(rlpListNodes, rlpExp);
NeighborsMessage neighborsMessage = new NeighborsMessage();
neighborsMessage.encode(type, data, privKey);
neighborsMessage.nodes = nodes;
neighborsMessage.expires = expiration;
return neighborsMessage;
}
public List<Node> getNodes() {
return nodes;
}
public long getExpires() {
return expires;
}
@Override
public String toString() {
long currTime = System.currentTimeMillis() / 1000;
String out = String.format("[NeighborsMessage] \n nodes [%d]: %s \n expires in %d seconds \n %s\n",
this.getNodes().size(), this.getNodes(), (expires - currTime), super.toString());
return out;
}
}
| 3,114
| 28.386792
| 107
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/FrameCodecHandler.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.ethereum.net.server.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
/**
* The Netty handler responsible for decrypting/encrypting RLPx frames
* with the FrameCodec crated during HandshakeHandler initial work
*
* Created by Anton Nashatyrev on 15.10.2015.
*/
public class FrameCodecHandler extends NettyByteToMessageCodec<FrameCodec.Frame> {
private static final Logger loggerWire = LoggerFactory.getLogger("wire");
private static final Logger loggerNet = LoggerFactory.getLogger("net");
public FrameCodec frameCodec;
public Channel channel;
public FrameCodecHandler(FrameCodec frameCodec, Channel channel) {
this.frameCodec = frameCodec;
this.channel = channel;
}
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws IOException {
if (in.readableBytes() == 0) {
loggerWire.trace("in.readableBytes() == 0");
return;
}
loggerWire.trace("Decoding frame (" + in.readableBytes() + " bytes)");
List<FrameCodec.Frame> frames = frameCodec.readFrames(in);
// Check if a full frame was available. If not, we'll try later when more bytes come in.
if (frames == null || frames.isEmpty()) return;
for (int i = 0; i < frames.size(); i++) {
FrameCodec.Frame frame = frames.get(i);
channel.getNodeStatistics().rlpxInMessages.add();
}
out.addAll(frames);
}
@Override
protected void encode(ChannelHandlerContext ctx, FrameCodec.Frame frame, ByteBuf out) throws Exception {
frameCodec.writeFrame(frame, out);
channel.getNodeStatistics().rlpxOutMessages.add();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (channel.isDiscoveryMode()) {
loggerNet.trace("FrameCodec failed: " + cause);
} else {
if (cause instanceof IOException) {
loggerNet.debug("FrameCodec failed: " + ctx.channel().remoteAddress() + ": " + cause);
} else {
loggerNet.warn("FrameCodec failed: ", cause);
}
}
ctx.close();
}
}
| 3,188
| 34.043956
| 108
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/RlpxConnection.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.net.p2p.P2pMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.io.*;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Created by devrandom on 2015-04-12.
*/
public class RlpxConnection {
private static final Logger logger = LoggerFactory.getLogger("discover");
private final EncryptionHandshake.Secrets secrets;
private final FrameCodec codec;
private final DataInputStream inp;
private final OutputStream out;
private HandshakeMessage handshakeMessage;
public RlpxConnection(EncryptionHandshake.Secrets secrets, InputStream inp, OutputStream out) {
this.secrets = secrets;
this.inp = new DataInputStream(inp);
this.out = out;
this.codec = new FrameCodec(secrets);
}
public void sendProtocolHandshake(HandshakeMessage message) throws IOException {
logger.info("<=== " + message);
byte[] payload = message.encode();
codec.writeFrame(new FrameCodec.Frame(HandshakeMessage.HANDSHAKE_MESSAGE_TYPE, payload), out);
}
public void handleNextMessage() throws IOException {
FrameCodec.Frame frame = codec.readFrames(inp).get(0);
if (handshakeMessage == null) {
if (frame.type != HandshakeMessage.HANDSHAKE_MESSAGE_TYPE)
throw new IOException("expected handshake or disconnect");
// TODO handle disconnect
byte[] wire = new byte[frame.size];
frame.payload.read(wire);
System.out.println("packet " + toHexString(wire));
handshakeMessage = HandshakeMessage.parse(wire);
logger.info(" ===> " + handshakeMessage);
} else {
System.out.println("packet type " + frame.type);
byte[] wire = new byte[frame.size];
frame.payload.read(wire);
System.out.println("packet " + toHexString(wire));
}
}
public HandshakeMessage getHandshakeMessage() {
return handshakeMessage;
}
public void writeMessage(P2pMessage message) throws IOException {
byte[] payload = message.getEncoded();
codec.writeFrame(new FrameCodec.Frame(message.getCommand().asByte(), payload), out);
}
}
| 3,101
| 36.829268
| 102
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/HandshakeMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import com.google.common.collect.Lists;
import org.ethereum.net.client.Capability;
import org.ethereum.util.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import static org.ethereum.util.ByteUtil.longToBytes;
/**
* Created by devrandom on 2015-04-12.
*/
public class HandshakeMessage {
public static final int HANDSHAKE_MESSAGE_TYPE = 0x00;
long version;
String name;
List<Capability> caps;
long listenPort;
byte[] nodeId;
public static final int NODE_ID_BITS = 512;
public HandshakeMessage(long version, String name, List<Capability> caps, long listenPort, byte[] nodeId) {
this.version = version;
this.name = name;
this.caps = caps;
this.listenPort = listenPort;
this.nodeId = nodeId;
}
HandshakeMessage() {
}
static HandshakeMessage parse(byte[] wire) {
RLPList list = (RLPList) RLP.decode2(wire).get(0);
HandshakeMessage message = new HandshakeMessage();
Iterator<RLPElement> iter = list.iterator();
message.version = ByteUtil.byteArrayToInt(iter.next().getRLPData()); // FIXME long
message.name = new String(iter.next().getRLPData(), Charset.forName("UTF-8"));
// caps
message.caps = Lists.newArrayList();
for (RLPElement capEl : (RLPList)iter.next()) {
RLPList capElList = (RLPList)capEl;
String name = new String(capElList.get(0).getRLPData(), Charset.forName("UTF-8"));
long version = ByteUtil.byteArrayToInt(capElList.get(1).getRLPData());
message.caps.add(new Capability(name, (byte)version)); // FIXME long
}
message.listenPort = ByteUtil.byteArrayToInt(iter.next().getRLPData());
message.nodeId = iter.next().getRLPData();
return message;
}
public byte[] encode() {
List<byte[]> capsItemBytes = Lists.newArrayList();
for (Capability cap : caps) {
capsItemBytes.add(RLP.encodeList(
RLP.encodeElement(cap.getName().getBytes()),
RLP.encodeElement(ByteUtil.stripLeadingZeroes(longToBytes(cap.getVersion())))
));
}
return RLP.encodeList(
RLP.encodeElement(ByteUtil.stripLeadingZeroes(longToBytes(version))),
RLP.encodeElement(name.getBytes()),
RLP.encodeList(capsItemBytes.toArray(new byte[0][])),
RLP.encodeElement(ByteUtil.stripLeadingZeroes(longToBytes(listenPort))),
RLP.encodeElement(nodeId)
);
}
}
| 3,411
| 36.494505
| 111
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/AuthResponseMessage.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx;
import org.ethereum.crypto.ECKey;
import org.spongycastle.math.ec.ECPoint;
import java.util.Arrays;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* Authentication response message, to be wrapped inside
*
* Created by devrandom on 2015-04-07.
*/
public class AuthResponseMessage {
ECPoint ephemeralPublicKey; // 64 bytes - uncompressed and no type byte
byte[] nonce; // 32 bytes
boolean isTokenUsed; // 1 byte - 0x00 or 0x01
static AuthResponseMessage decode(byte[] wire) {
int offset = 0;
AuthResponseMessage message = new AuthResponseMessage();
byte[] bytes = new byte[65];
System.arraycopy(wire, offset, bytes, 1, 64);
offset += 64;
bytes[0] = 0x04; // uncompressed
message.ephemeralPublicKey = ECKey.CURVE.getCurve().decodePoint(bytes);
message.nonce = new byte[32];
System.arraycopy(wire, offset, message.nonce, 0, 32);
offset += message.nonce.length;
byte tokenUsed = wire[offset];
offset += 1;
if (tokenUsed != 0x00 && tokenUsed != 0x01)
throw new RuntimeException("invalid boolean"); // TODO specific exception
message.isTokenUsed = (tokenUsed == 0x01);
return message;
}
public static int getLength() {
return 64+32+1;
}
public byte[] encode() {
byte[] buffer = new byte[getLength()];
int offset = 0;
byte[] publicBytes = ephemeralPublicKey.getEncoded(false);
System.arraycopy(publicBytes, 1, buffer, offset, publicBytes.length - 1);
offset += publicBytes.length - 1;
System.arraycopy(nonce, 0, buffer, offset, nonce.length);
offset += nonce.length;
buffer[offset] = (byte)(isTokenUsed ? 0x01 : 0x00);
offset += 1;
return buffer;
}
@Override
public String toString() {
return "AuthResponseMessage{" +
"\n ephemeralPublicKey=" + ephemeralPublicKey +
"\n nonce=" + toHexString(nonce) +
"\n isTokenUsed=" + isTokenUsed +
'}';
}
}
| 2,923
| 34.658537
| 85
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/DiscoverTask.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;
import org.ethereum.crypto.ECKey;
import org.ethereum.net.rlpx.FindNodeMessage;
import org.ethereum.net.rlpx.Message;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.rlpx.discover.table.KademliaOptions;
import org.ethereum.net.rlpx.discover.table.NodeEntry;
import org.ethereum.net.rlpx.discover.table.NodeTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
public class DiscoverTask implements Runnable {
private static final Logger logger = LoggerFactory.getLogger("discover");
NodeManager nodeManager;
byte[] nodeId;
public DiscoverTask(NodeManager nodeManager) {
this.nodeManager = nodeManager;
nodeId = nodeManager.homeNode.getId();
}
@Override
public void run() {
discover(nodeId, 0, new ArrayList<Node>());
}
public synchronized void discover(byte[] nodeId, int round, List<Node> prevTried) {
try {
// if (!channel.isOpen() || round == KademliaOptions.MAX_STEPS) {
// logger.info("{}", String.format("Nodes discovered %d ", table.getAllNodes().size()));
// return;
// }
if (round == KademliaOptions.MAX_STEPS) {
logger.debug("Node table contains [{}] peers", nodeManager.getTable().getNodesCount());
logger.debug("{}", String.format("(KademliaOptions.MAX_STEPS) Terminating discover after %d rounds.", round));
logger.trace("{}\n{}", String.format("Nodes discovered %d ", nodeManager.getTable().getNodesCount()), dumpNodes());
return;
}
List<Node> closest = nodeManager.getTable().getClosestNodes(nodeId);
List<Node> tried = new ArrayList<>();
for (Node n : closest) {
if (!tried.contains(n) && !prevTried.contains(n)) {
try {
nodeManager.getNodeHandler(n).sendFindNode(nodeId);
tried.add(n);
Thread.sleep(50);
}catch (InterruptedException e) {
} catch (Exception ex) {
logger.error("Unexpected Exception " + ex, ex);
}
}
if (tried.size() == KademliaOptions.ALPHA) {
break;
}
}
// channel.flush();
if (tried.isEmpty()) {
logger.debug("{}", String.format("(tried.isEmpty()) Terminating discover after %d rounds.", round));
logger.trace("{}\n{}", String.format("Nodes discovered %d ", nodeManager.getTable().getNodesCount()), dumpNodes());
return;
}
tried.addAll(prevTried);
discover(nodeId, round + 1, tried);
} catch (Exception ex) {
logger.info("{}", ex);
}
}
private String dumpNodes() {
String ret = "";
for (NodeEntry entry : nodeManager.getTable().getAllNodes()) {
ret += " " + entry.getNode() + "\n";
}
return ret;
}
}
| 4,095
| 35.571429
| 131
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/PeerConnectionTester.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.codec.binary.Hex;
import org.ethereum.config.SystemProperties;
import org.ethereum.net.client.PeerClient;
import org.ethereum.net.rlpx.Node;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.*;
/**
* Makes test RLPx connection to the peers to acquire statistics
*
* Created by Anton Nashatyrev on 17.07.2015.
*/
@Component
public class PeerConnectionTester {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger("discover");
private int ConnectThreads;
private long ReconnectPeriod;
private long ReconnectMaxPeers;
@Autowired
private PeerClient peerClient;
private SystemProperties config = SystemProperties.getDefault();
// NodeHandler instance should be unique per Node instance
private Map<NodeHandler, ?> connectedCandidates = Collections.synchronizedMap(new IdentityHashMap());
// executor with Queue which picks up the Node with the best reputation
private ExecutorService peerConnectionPool;
private Timer reconnectTimer = new Timer("DiscoveryReconnectTimer");
private int reconnectPeersCount = 0;
private class ConnectTask implements Runnable {
NodeHandler nodeHandler;
public ConnectTask(NodeHandler nodeHandler) {
this.nodeHandler = nodeHandler;
}
@Override
public void run() {
try {
if (nodeHandler != null) {
nodeHandler.getNodeStatistics().rlpxConnectionAttempts.add();
logger.debug("Trying node connection: " + nodeHandler);
Node node = nodeHandler.getNode();
peerClient.connect(node.getHost(), node.getPort(),
Hex.encodeHexString(node.getId()), true);
logger.debug("Terminated node connection: " + nodeHandler);
nodeHandler.getNodeStatistics().disconnected();
if (!nodeHandler.getNodeStatistics().getEthTotalDifficulty().equals(BigInteger.ZERO) &&
ReconnectPeriod > 0 && (reconnectPeersCount < ReconnectMaxPeers || ReconnectMaxPeers == -1)) {
// trying to keep good peers information up-to-date
reconnectPeersCount++;
reconnectTimer.schedule(new TimerTask() {
@Override
public void run() {
logger.debug("Trying the node again: " + nodeHandler);
peerConnectionPool.execute(new ConnectTask(nodeHandler));
reconnectPeersCount--;
}
}, ReconnectPeriod);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connectedCandidates.remove(nodeHandler);
}
}
}
@Autowired
public PeerConnectionTester(final SystemProperties config) {
this.config = config;
ConnectThreads = config.peerDiscoveryWorkers();
ReconnectPeriod = config.peerDiscoveryTouchPeriod() * 1000;
ReconnectMaxPeers = config.peerDiscoveryTouchMaxNodes();
peerConnectionPool = new ThreadPoolExecutor(ConnectThreads,
ConnectThreads, 0L, TimeUnit.SECONDS,
new MutablePriorityQueue<>((Comparator<ConnectTask>) (h1, h2) ->
h2.nodeHandler.getNodeStatistics().getReputation() -
h1.nodeHandler.getNodeStatistics().getReputation()),
new ThreadFactoryBuilder().setDaemon(true).setNameFormat("discovery-tester-%d").build());
}
public void close() {
logger.info("Closing PeerConnectionTester...");
try {
peerConnectionPool.shutdownNow();
} catch (Exception e) {
logger.warn("Problems closing PeerConnectionTester", e);
}
try {
reconnectTimer.cancel();
} catch (Exception e) {
logger.warn("Problems cancelling reconnectTimer", e);
}
}
public void nodeStatusChanged(final NodeHandler nodeHandler) {
if (peerConnectionPool.isShutdown()) return;
if (connectedCandidates.size() < NodeManager.MAX_NODES
&& !connectedCandidates.containsKey(nodeHandler)
&& !nodeHandler.getNode().isDiscoveryNode()) {
logger.debug("Submitting node for RLPx connection : " + nodeHandler);
connectedCandidates.put(nodeHandler, null);
peerConnectionPool.execute(new ConnectTask(nodeHandler));
}
}
/**
* The same as PriorityBlockQueue but with assumption that elements are mutable
* and priority changes after enqueueing, thus the list is sorted by priority
* each time the head queue element is requested.
* The class has poor synchronization since the prioritization might be approximate
* though the implementation should be inheritedly thread-safe
*/
public static class MutablePriorityQueue<T, C extends T> extends LinkedBlockingQueue<T> {
Comparator<C> comparator;
public MutablePriorityQueue(Comparator<C> comparator) {
this.comparator = comparator;
}
@Override
public synchronized T take() throws InterruptedException {
if (isEmpty()) {
return super.take();
} else {
T ret = Collections.min(this, (Comparator<? super T>) comparator);
remove(ret);
return ret;
}
}
@Override
public synchronized T poll(long timeout, TimeUnit unit) throws InterruptedException {
if (isEmpty()) {
return super.poll(timeout, unit);
} else {
T ret = Collections.min(this, (Comparator<? super T>) comparator);
remove(ret);
return ret;
}
}
@Override
public synchronized T poll() {
if (isEmpty()) {
return super.poll();
} else {
T ret = Collections.min(this, (Comparator<? super T>) comparator);
remove(ret);
return ret;
}
}
@Override
public synchronized T peek() {
if (isEmpty()) {
return super.peek();
} else {
T ret = Collections.min(this, (Comparator<? super T>) comparator);
return ret;
}
}
}
}
| 7,701
| 37.89899
| 122
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/PacketDecoder.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.ethereum.crypto.ECKey;
import org.ethereum.net.rlpx.Message;
import org.slf4j.LoggerFactory;
import java.util.List;
import static org.ethereum.util.ByteUtil.toHexString;
public class PacketDecoder extends MessageToMessageDecoder<DatagramPacket> {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger("discover");
@Override
public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {
ByteBuf buf = packet.content();
byte[] encoded = new byte[buf.readableBytes()];
buf.readBytes(encoded);
try {
Message msg = Message.decode(encoded);
DiscoveryEvent event = new DiscoveryEvent(msg, packet.sender());
out.add(event);
} catch (Exception e) {
throw new RuntimeException("Exception processing inbound message from " + ctx.channel().remoteAddress() + ": " + toHexString(encoded), e);
}
}
}
| 1,986
| 38.74
| 150
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/RefreshTask.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import io.netty.channel.Channel;
import org.ethereum.crypto.ECKey;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.rlpx.discover.table.NodeTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Random;
public class RefreshTask extends DiscoverTask {
private static final Logger logger = LoggerFactory.getLogger("discover");
public RefreshTask(NodeManager nodeManager) {
super(nodeManager);
}
//
// RefreshTask(Channel channel, ECKey key, NodeTable table) {
// super(getNodeId(), channel, key, table);
// }
public static byte[] getNodeId() {
Random gen = new Random();
byte[] id = new byte[64];
gen.nextBytes(id);
return id;
}
@Override
public void run() {
discover(getNodeId(), 0, new ArrayList<Node>());
}
}
| 1,703
| 31.150943
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/DiscoverListener.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
/**
* Allows to handle discovered nodes state changes
*
* Created by Anton Nashatyrev on 21.07.2015.
*/
public interface DiscoverListener {
/**
* Invoked whenever a new node appeared which meets criteria specified
* in the {@link NodeManager#addDiscoverListener} method
*/
void nodeAppeared(NodeHandler handler);
/**
* Invoked whenever a node stops meeting criteria.
*/
void nodeDisappeared(NodeHandler handler);
class Adapter implements DiscoverListener {
public void nodeAppeared(NodeHandler handler) {}
public void nodeDisappeared(NodeHandler handler) {}
}
}
| 1,465
| 33.093023
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/DiscoveryExecutor.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import org.ethereum.net.rlpx.discover.table.KademliaOptions;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DiscoveryExecutor {
ScheduledExecutorService discoverer = Executors.newSingleThreadScheduledExecutor();
ScheduledExecutorService refresher = Executors.newSingleThreadScheduledExecutor();
NodeManager nodeManager;
public DiscoveryExecutor(NodeManager nodeManager) {
this.nodeManager = nodeManager;
}
public void start() {
discoverer.scheduleWithFixedDelay(
new DiscoverTask(nodeManager),
1, KademliaOptions.DISCOVER_CYCLE, TimeUnit.SECONDS);
refresher.scheduleWithFixedDelay(
new RefreshTask(nodeManager),
1, KademliaOptions.BUCKET_REFRESH, TimeUnit.MILLISECONDS);
}
public void close() {
discoverer.shutdownNow();
refresher.shutdownNow();
}
}
| 1,826
| 34.134615
| 87
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/NodeHandler.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import org.ethereum.net.rlpx.*;
import org.ethereum.net.rlpx.discover.table.KademliaOptions;
import org.ethereum.net.swarm.Util;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* The instance of this class responsible for discovery messages exchange with the specified Node
* It also manages itself regarding inclusion/eviction from Kademlia table
*
* Created by Anton Nashatyrev on 14.07.2015.
*/
public class NodeHandler {
static final org.slf4j.Logger logger = LoggerFactory.getLogger("discover");
static long PingTimeout = 15000; //KademliaOptions.REQ_TIMEOUT;
static final int WARN_PACKET_SIZE = 1400;
private static volatile int msgInCount = 0, msgOutCount = 0;
private static boolean initialLogging = true;
// gradually reducing log level for dumping discover messages
// they are not so informative when everything is already up and running
// but could be interesting when discovery just starts
private void logMessage(Message msg, boolean inbound) {
String s = String.format("%s[%s (%s)] %s", inbound ? " ===> " : "<=== ", msg.getClass().getSimpleName(),
msg.getPacket().length, this);
if (msgInCount > 1024) {
logger.trace(s);
} else {
logger.debug(s);
}
if (!inbound && msg.getPacket().length > WARN_PACKET_SIZE) {
logger.warn("Sending UDP packet exceeding safe size of {} bytes, actual: {} bytes",
WARN_PACKET_SIZE, msg.getPacket().length);
logger.warn(s);
}
if (initialLogging) {
if (msgOutCount == 0) {
logger.info("Pinging discovery nodes...");
}
if (msgInCount == 0 && inbound) {
logger.info("Received response.");
}
if (inbound && msg instanceof NeighborsMessage) {
logger.info("New peers discovered.");
initialLogging = false;
}
}
if (inbound) msgInCount++; else msgOutCount++;
}
public enum State {
/**
* The new node was just discovered either by receiving it with Neighbours
* message or by receiving Ping from a new node
* In either case we are sending Ping and waiting for Pong
* If the Pong is received the node becomes {@link #Alive}
* If the Pong was timed out the node becomes {@link #Dead}
*/
Discovered,
/**
* The node didn't send the Pong message back withing acceptable timeout
* This is the final state
*/
Dead,
/**
* The node responded with Pong and is now the candidate for inclusion to the table
* If the table has bucket space for this node it is added to table and becomes {@link #Active}
* If the table bucket is full this node is challenging with the old node from the bucket
* if it wins then old node is dropped, and this node is added and becomes {@link #Active}
* else this node becomes {@link #NonActive}
*/
Alive,
/**
* The node is included in the table. It may become {@link #EvictCandidate} if a new node
* wants to become Active but the table bucket is full.
*/
Active,
/**
* This node is in the table but is currently challenging with a new Node candidate
* to survive in the table bucket
* If it wins then returns back to {@link #Active} state, else is evicted from the table
* and becomes {@link #NonActive}
*/
EvictCandidate,
/**
* Veteran. It was Alive and even Active but is now retired due to loosing the challenge
* with another Node.
* For no this is the final state
* It's an option for future to return veterans back to the table
*/
NonActive
}
Node node;
NodeManager nodeManager;
private NodeStatistics nodeStatistics;
State state;
boolean waitForPong = false;
long pingSent;
int pingTrials = 3;
boolean waitForNeighbors = false;
NodeHandler replaceCandidate;
public NodeHandler(Node node, NodeManager nodeManager) {
this.node = node;
this.nodeManager = nodeManager;
changeState(State.Discovered);
}
public InetSocketAddress getInetSocketAddress() {
return new InetSocketAddress(node.getHost(), node.getPort());
}
public Node getNode() {
return node;
}
public State getState() {
return state;
}
public NodeStatistics getNodeStatistics() {
if (nodeStatistics == null) {
nodeStatistics = new NodeStatistics(node);
}
return nodeStatistics;
}
private void challengeWith(NodeHandler replaceCandidate) {
this.replaceCandidate = replaceCandidate;
changeState(State.EvictCandidate);
}
// Manages state transfers
private void changeState(State newState) {
State oldState = state;
if (newState == State.Discovered) {
// will wait for Pong to assume this alive
sendPing();
}
if (!node.isDiscoveryNode()) {
if (newState == State.Alive) {
Node evictCandidate = nodeManager.table.addNode(this.node);
if (evictCandidate == null) {
newState = State.Active;
} else {
NodeHandler evictHandler = nodeManager.getNodeHandler(evictCandidate);
if (evictHandler.state != State.EvictCandidate) {
evictHandler.challengeWith(this);
}
}
}
if (newState == State.Active) {
if (oldState == State.Alive) {
// new node won the challenge
nodeManager.table.addNode(node);
} else if (oldState == State.EvictCandidate) {
// nothing to do here the node is already in the table
} else {
// wrong state transition
}
}
if (newState == State.NonActive) {
if (oldState == State.EvictCandidate) {
// lost the challenge
// Removing ourselves from the table
nodeManager.table.dropNode(node);
// Congratulate the winner
replaceCandidate.changeState(State.Active);
} else if (oldState == State.Alive) {
// ok the old node was better, nothing to do here
} else {
// wrong state transition
}
}
}
if (newState == State.EvictCandidate) {
// trying to survive, sending ping and waiting for pong
sendPing();
}
state = newState;
stateChanged(oldState, newState);
}
protected void stateChanged(State oldState, State newState) {
logger.trace("State change " + oldState + " -> " + newState + ": " + this);
nodeManager.stateChanged(this, oldState, newState);
}
void handlePing(PingMessage msg) {
logMessage(msg, true);
// logMessage(" ===> [PING] " + this);
getNodeStatistics().discoverInPing.add();
if (!nodeManager.table.getNode().equals(node)) {
sendPong(msg.getMdc());
}
}
void handlePong(PongMessage msg) {
logMessage(msg, true);
// logMessage(" ===> [PONG] " + this);
if (waitForPong) {
waitForPong = false;
getNodeStatistics().discoverInPong.add();
getNodeStatistics().discoverMessageLatency.add(Util.curTime() - pingSent);
getNodeStatistics().lastPongReplyTime.set(Util.curTime());
changeState(State.Alive);
}
}
void handleNeighbours(NeighborsMessage msg) {
logMessage(msg, true);
// logMessage(" ===> [NEIGHBOURS] " + this + ", Count: " + msg.getNodes().size());
if (waitForNeighbors) {
waitForNeighbors = false;
getNodeStatistics().discoverInNeighbours.add();
for (Node n : msg.getNodes()) {
nodeManager.getNodeHandler(n);
}
}
}
void handleFindNode(FindNodeMessage msg) {
logMessage(msg, true);
// logMessage(" ===> [FIND_NODE] " + this);
getNodeStatistics().discoverInFind.add();
List<Node> closest = nodeManager.table.getClosestNodes(msg.getTarget());
Node publicHomeNode = nodeManager.getPublicHomeNode();
if (publicHomeNode != null) {
if (closest.size() == KademliaOptions.BUCKET_SIZE) closest.remove(closest.size() - 1);
closest.add(publicHomeNode);
}
sendNeighbours(closest);
}
void handleTimedOut() {
waitForPong = false;
if (--pingTrials > 0) {
sendPing();
} else {
if (state == State.Discovered) {
changeState(State.Dead);
} else if (state == State.EvictCandidate) {
changeState(State.NonActive);
} else {
// TODO just influence to reputation
}
}
}
void sendPing() {
if (waitForPong) {
logger.trace("<=/= [PING] (Waiting for pong) " + this);
}
// logMessage("<=== [PING] " + this);
Message ping = PingMessage.create(nodeManager.table.getNode(), getNode(), nodeManager.key);
logMessage(ping, false);
waitForPong = true;
pingSent = Util.curTime();
sendMessage(ping);
getNodeStatistics().discoverOutPing.add();
if (nodeManager.getPongTimer().isShutdown()) return;
nodeManager.getPongTimer().schedule(() -> {
try {
if (waitForPong) {
waitForPong = false;
handleTimedOut();
}
} catch (Throwable t) {
logger.error("Unhandled exception", t);
}
}, PingTimeout, TimeUnit.MILLISECONDS);
}
void sendPong(byte[] mdc) {
// logMessage("<=== [PONG] " + this);
Message pong = PongMessage.create(mdc, node, nodeManager.key);
logMessage(pong, false);
sendMessage(pong);
getNodeStatistics().discoverOutPong.add();
}
void sendNeighbours(List<Node> neighbours) {
// logMessage("<=== [NEIGHBOURS] " + this);
NeighborsMessage neighbors = NeighborsMessage.create(neighbours, nodeManager.key);
logMessage(neighbors, false);
sendMessage(neighbors);
getNodeStatistics().discoverOutNeighbours.add();
}
void sendFindNode(byte[] target) {
// logMessage("<=== [FIND_NODE] " + this);
Message findNode = FindNodeMessage.create(target, nodeManager.key);
logMessage(findNode, false);
waitForNeighbors = true;
sendMessage(findNode);
getNodeStatistics().discoverOutFind.add();
}
private void sendMessage(Message msg) {
nodeManager.sendOutbound(new DiscoveryEvent(msg, getInetSocketAddress()));
}
@Override
public String toString() {
return "NodeHandler[state: " + state + ", node: " + node.getHost() + ":" + node.getPort() + ", id="
+ (node.getId().length >= 4 ? Hex.toHexString(node.getId(), 0, 4) : "empty") + "]";
}
}
| 12,480
| 35.072254
| 114
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/DiscoveryEvent.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import org.ethereum.net.rlpx.Message;
import java.net.InetSocketAddress;
public class DiscoveryEvent {
private Message message;
private InetSocketAddress address;
public DiscoveryEvent(Message m, InetSocketAddress a) {
message = m;
address = a;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public InetSocketAddress getAddress() {
return address;
}
public void setAddress(InetSocketAddress address) {
this.address = address;
}
}
| 1,436
| 27.74
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/MessageHandler.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.function.Consumer;
public class MessageHandler extends SimpleChannelInboundHandler<DiscoveryEvent>
implements Consumer<DiscoveryEvent> {
static final org.slf4j.Logger logger = LoggerFactory.getLogger("discover");
public Channel channel;
NodeManager nodeManager;
public MessageHandler(NioDatagramChannel ch, NodeManager nodeManager) {
channel = ch;
this.nodeManager = nodeManager;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
nodeManager.channelActivated();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent event) throws Exception {
try {
nodeManager.handleInbound(event);
} catch (Throwable t) {
logger.info("Failed to process incoming message: {}, caused by: {}", event.getMessage(), t.toString());
}
}
@Override
public void accept(DiscoveryEvent discoveryEvent) {
InetSocketAddress address = discoveryEvent.getAddress();
sendPacket(discoveryEvent.getMessage().getPacket(), address);
}
void sendPacket(byte[] wire, InetSocketAddress address) {
DatagramPacket packet = new DatagramPacket(Unpooled.copiedBuffer(wire), address);
channel.write(packet);
channel.flush();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.debug("Discover channel error" + cause);
ctx.close();
// We don't close the channel because we can keep serving requests.
}
}
| 2,876
| 33.662651
| 115
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/UDPListener.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.ethereum.config.SystemProperties;
import org.ethereum.crypto.ECKey;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.WireTrafficStats;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.BindException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.ethereum.crypto.HashUtil.sha3;
@Component
public class UDPListener {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger("discover");
private int port;
private String address;
private String[] bootPeers;
@Autowired
private NodeManager nodeManager;
@Autowired
SystemProperties config = SystemProperties.getDefault();
@Autowired
WireTrafficStats stats;
private Channel channel;
private volatile boolean shutdown = false;
private DiscoveryExecutor discoveryExecutor;
@Autowired
public UDPListener(final SystemProperties config, final NodeManager nodeManager) {
this.config = config;
this.nodeManager = nodeManager;
this.address = config.bindIp();
port = config.listenPort();
if (config.peerDiscovery()) {
bootPeers = config.peerDiscoveryIPList().toArray(new String[0]);
}
if (config.peerDiscovery()) {
if (port == 0) {
logger.error("Discovery can't be started while listen port == 0");
} else {
new Thread(() -> {
try {
UDPListener.this.start(bootPeers);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}, "UDPListener").start();
}
}
}
public UDPListener(String address, int port) {
this.address = address;
this.port = port;
}
public static Node parseNode(String s) {
int idx1 = s.indexOf('@');
int idx2 = s.indexOf(':');
String id = s.substring(0, idx1);
String host = s.substring(idx1 + 1, idx2);
int port = Integer.parseInt(s.substring(idx2+1));
return new Node(Hex.decode(id), host, port);
}
public void start(String[] args) throws Exception {
logger.info("Discovery UDPListener started");
NioEventLoopGroup group = new NioEventLoopGroup(1);
final List<Node> bootNodes = new ArrayList<>();
for (String boot: args) {
// since discover IP list has no NodeIds we will generate random but persistent
bootNodes.add(Node.instanceOf(boot));
}
nodeManager.setBootNodes(bootNodes);
try {
discoveryExecutor = new DiscoveryExecutor(nodeManager);
discoveryExecutor.start();
while (!shutdown) {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
public void initChannel(NioDatagramChannel ch)
throws Exception {
ch.pipeline().addLast(stats.udp);
ch.pipeline().addLast(new PacketDecoder());
MessageHandler messageHandler = new MessageHandler(ch, nodeManager);
nodeManager.setMessageSender(messageHandler);
ch.pipeline().addLast(messageHandler);
}
});
channel = b.bind(address, port).sync().channel();
channel.closeFuture().sync();
if (shutdown) {
logger.info("Shutdown discovery UDPListener");
break;
}
logger.warn("UDP channel closed. Recreating after 5 sec pause...");
Thread.sleep(5000);
}
} catch (Exception e) {
if (e instanceof BindException && e.getMessage().contains("Address already in use")) {
logger.error("Port " + port + " is busy. Check if another instance is running with the same port.");
} else {
logger.error("Can't start discover: ", e);
}
} finally {
group.shutdownGracefully().sync();
}
}
public void close() {
logger.info("Closing UDPListener...");
shutdown = true;
if (channel != null) {
try {
channel.close().await(10, TimeUnit.SECONDS);
} catch (Exception e) {
logger.warn("Problems closing UDPListener", e);
}
}
if (discoveryExecutor != null) {
try {
discoveryExecutor.close();
} catch (Exception e) {
logger.warn("Problems closing DiscoveryExecutor", e);
}
}
}
public static void main(String[] args) throws Exception {
String address = "0.0.0.0";
int port = 30303;
if (args.length >= 2) {
address = args[0];
port = Integer.parseInt(args[1]);
}
new UDPListener(address, port).start(Arrays.copyOfRange(args, 2, args.length));
}
}
| 6,582
| 34.015957
| 116
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/NodeStatistics.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import org.ethereum.net.client.Capability;
import org.ethereum.net.eth.message.StatusMessage;
import org.ethereum.net.message.ReasonCode;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.swarm.Statter;
import org.ethereum.util.ByteUtil;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import static java.lang.Math.min;
import static org.ethereum.net.server.ChannelManager.INBOUND_CONNECTION_BAN_TIMEOUT;
/**
* Handles all possible statistics related to a Node
* The primary aim of this is collecting info about a Node
* for maintaining its reputation.
*
* Created by Anton Nashatyrev on 16.07.2015.
*/
public class NodeStatistics {
public final static int REPUTATION_PREDEFINED = 1000500;
public final static int REPUTATION_HANDSHAKE = 3000;
public final static int REPUTATION_AUTH = 1000;
public final static int REPUTATION_DISCOVER_PING = 1;
public class StatHandler {
AtomicLong count = new AtomicLong(0);
public void add() {count.incrementAndGet(); }
public void add(long delta) {count.addAndGet(delta); }
public long get() {return count.get();}
public String toString() {return count.toString();}
}
private final Node node;
private boolean isPredefined = false;
private int persistedReputation = 0;
// discovery stat
public final StatHandler discoverOutPing = new StatHandler();
public final StatHandler discoverInPong = new StatHandler();
public final StatHandler discoverOutPong = new StatHandler();
public final StatHandler discoverInPing = new StatHandler();
public final StatHandler discoverInFind = new StatHandler();
public final StatHandler discoverOutFind = new StatHandler();
public final StatHandler discoverInNeighbours = new StatHandler();
public final StatHandler discoverOutNeighbours = new StatHandler();
public final Statter.SimpleStatter discoverMessageLatency;
public final AtomicLong lastPongReplyTime = new AtomicLong(0l); // in milliseconds
// rlpx stat
public final StatHandler rlpxConnectionAttempts = new StatHandler();
public final StatHandler rlpxAuthMessagesSent = new StatHandler();
public final StatHandler rlpxOutHello = new StatHandler();
public final StatHandler rlpxInHello = new StatHandler();
public final StatHandler rlpxHandshake = new StatHandler();
public final StatHandler rlpxOutMessages = new StatHandler();
public final StatHandler rlpxInMessages = new StatHandler();
// Not the fork we are working on
// Set only after specific block hashes received
public boolean wrongFork;
private String clientId = "";
public final List<Capability> capabilities = new ArrayList<>();
private ReasonCode rlpxLastRemoteDisconnectReason = null;
private ReasonCode rlpxLastLocalDisconnectReason = null;
private long lastDisconnectedTime = 0;
// Eth stat
public final StatHandler ethHandshake = new StatHandler();
public final StatHandler ethInbound = new StatHandler();
public final StatHandler ethOutbound = new StatHandler();
private StatusMessage ethLastInboundStatusMsg = null;
private BigInteger ethTotalDifficulty = BigInteger.ZERO;
// Eth63 stat
public final StatHandler eth63NodesRequested = new StatHandler();
public final StatHandler eth63NodesReceived = new StatHandler();
public final StatHandler eth63NodesRetrieveTime = new StatHandler();
public NodeStatistics(Node node) {
this.node = node;
discoverMessageLatency = (Statter.SimpleStatter) Statter.create(getStatName() + ".discoverMessageLatency");
}
private int getSessionReputation() {
return getSessionFairReputation() + (isPredefined ? REPUTATION_PREDEFINED : 0);
}
private int getSessionFairReputation() {
int discoverReput = 0;
discoverReput += min(discoverInPong.get(), 10) * (discoverOutPing.get() == discoverInPong.get() ? 2 : 1);
discoverReput += min(discoverInNeighbours.get(), 10) * 2;
// discoverReput += 20 / (min((int)discoverMessageLatency.getAvrg(), 1) / 100);
int rlpxReput = 0;
rlpxReput += rlpxAuthMessagesSent.get() > 0 ? 10 : 0;
rlpxReput += rlpxHandshake.get() > 0 ? 20 : 0;
rlpxReput += min(rlpxInMessages.get(), 10) * 3;
if (wasDisconnected()) {
if (rlpxLastLocalDisconnectReason == null && rlpxLastRemoteDisconnectReason == null) {
// means connection was dropped without reporting any reason - bad
rlpxReput *= 0.3;
} else if (rlpxLastLocalDisconnectReason != ReasonCode.REQUESTED) {
// the disconnect was not initiated by discover mode
if (rlpxLastRemoteDisconnectReason == ReasonCode.TOO_MANY_PEERS) {
// The peer is popular, but we were unlucky
rlpxReput *= 0.3;
} else if (rlpxLastRemoteDisconnectReason != ReasonCode.REQUESTED) {
// other disconnect reasons
rlpxReput *= 0.2;
}
}
}
return discoverReput + 100 * rlpxReput;
}
public int getReputation() {
return isReputationPenalized() ? 0 : persistedReputation / 2 + getSessionReputation();
}
public boolean isReputationPenalized() {
if (wrongFork) return true;
if (wasDisconnected() && rlpxLastRemoteDisconnectReason == ReasonCode.TOO_MANY_PEERS &&
System.currentTimeMillis() - lastDisconnectedTime < INBOUND_CONNECTION_BAN_TIMEOUT) {
return true;
}
if (wasDisconnected() && rlpxLastRemoteDisconnectReason == ReasonCode.DUPLICATE_PEER &&
System.currentTimeMillis() - lastDisconnectedTime < INBOUND_CONNECTION_BAN_TIMEOUT) {
return true;
}
return rlpxLastLocalDisconnectReason == ReasonCode.NULL_IDENTITY ||
rlpxLastRemoteDisconnectReason == ReasonCode.NULL_IDENTITY ||
rlpxLastLocalDisconnectReason == ReasonCode.INCOMPATIBLE_PROTOCOL ||
rlpxLastRemoteDisconnectReason == ReasonCode.INCOMPATIBLE_PROTOCOL ||
rlpxLastLocalDisconnectReason == ReasonCode.USELESS_PEER ||
rlpxLastRemoteDisconnectReason == ReasonCode.USELESS_PEER ||
rlpxLastLocalDisconnectReason == ReasonCode.BAD_PROTOCOL ||
rlpxLastRemoteDisconnectReason == ReasonCode.BAD_PROTOCOL;
}
public void nodeDisconnectedRemote(ReasonCode reason) {
lastDisconnectedTime = System.currentTimeMillis();
rlpxLastRemoteDisconnectReason = reason;
}
public void nodeDisconnectedLocal(ReasonCode reason) {
lastDisconnectedTime = System.currentTimeMillis();
rlpxLastLocalDisconnectReason = reason;
}
public void disconnected() {
lastDisconnectedTime = System.currentTimeMillis();
}
public boolean wasDisconnected() {
return lastDisconnectedTime > 0;
}
public void ethHandshake(StatusMessage ethInboundStatus) {
this.ethLastInboundStatusMsg = ethInboundStatus;
this.ethTotalDifficulty = ethInboundStatus.getTotalDifficultyAsBigInt();
ethHandshake.add();
}
public BigInteger getEthTotalDifficulty() {
return ethTotalDifficulty;
}
public void setEthTotalDifficulty(BigInteger ethTotalDifficulty) {
this.ethTotalDifficulty = ethTotalDifficulty;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientId() {
return clientId;
}
public void setPredefined(boolean isPredefined) {
this.isPredefined = isPredefined;
}
public boolean isPredefined() {
return isPredefined;
}
public StatusMessage getEthLastInboundStatusMsg() {
return ethLastInboundStatusMsg;
}
private String getStatName() {
return "ethj.discover.nodes." + node.getHost() + ":" + node.getPort();
}
public int getPersistedReputation() {
return isReputationPenalized() ? 0 : (persistedReputation + getSessionFairReputation()) / 2;
}
public void setPersistedReputation(int persistedReputation) {
this.persistedReputation = persistedReputation;
}
@Override
public String toString() {
return "NodeStat[reput: " + getReputation() + "(" + persistedReputation + "), discover: " +
discoverInPong + "/" + discoverOutPing + " " +
discoverOutPong + "/" + discoverInPing + " " +
discoverInNeighbours + "/" + discoverOutFind + " " +
discoverOutNeighbours + "/" + discoverInFind + " " +
((int)discoverMessageLatency.getAvrg()) + "ms" +
", rlpx: " + rlpxHandshake + "/" + rlpxAuthMessagesSent + "/" + rlpxConnectionAttempts + " " +
rlpxInMessages + "/" + rlpxOutMessages +
", eth: " + ethHandshake + "/" + ethInbound + "/" + ethOutbound + " " +
(ethLastInboundStatusMsg != null ? ByteUtil.toHexString(ethLastInboundStatusMsg.getTotalDifficulty()) : "-") + " " +
(wasDisconnected() ? "X " : "") +
(rlpxLastLocalDisconnectReason != null ? ("<=" + rlpxLastLocalDisconnectReason) : " ") +
(rlpxLastRemoteDisconnectReason != null ? ("=>" + rlpxLastRemoteDisconnectReason) : " ") +
"[" + clientId + "]";
}
}
| 10,388
| 40.063241
| 132
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/NodeManager.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.SystemProperties;
import org.ethereum.crypto.ECKey;
import org.ethereum.db.PeerSource;
import org.ethereum.listener.EthereumListener;
import org.ethereum.net.rlpx.*;
import org.ethereum.net.rlpx.discover.table.NodeTable;
import org.ethereum.util.CollectionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.function.Predicate;
import static java.lang.Math.min;
/**
* The central class for Peer Discovery machinery.
*
* The NodeManager manages info on all the Nodes discovered by the peer discovery
* protocol, routes protocol messages to the corresponding NodeHandlers and
* supplies the info about discovered Nodes and their usage statistics
*
* Created by Anton Nashatyrev on 16.07.2015.
*/
@Component
public class NodeManager implements Consumer<DiscoveryEvent>{
static final org.slf4j.Logger logger = LoggerFactory.getLogger("discover");
private final boolean PERSIST;
private static final long LISTENER_REFRESH_RATE = 1000;
private static final long DB_COMMIT_RATE = 1 * 60 * 1000;
static final int MAX_NODES = 2000;
static final int NODES_TRIM_THRESHOLD = 3000;
PeerConnectionTester peerConnectionManager;
PeerSource peerSource;
EthereumListener ethereumListener;
SystemProperties config = SystemProperties.getDefault();
Consumer<DiscoveryEvent> messageSender;
NodeTable table;
private Map<String, NodeHandler> nodeHandlerMap = new HashMap<>();
final ECKey key;
final Node homeNode;
private List<Node> bootNodes;
// option to handle inbounds only from known peers (i.e. which were discovered by ourselves)
boolean inboundOnlyFromKnownNodes = false;
private boolean discoveryEnabled;
private Map<DiscoverListener, ListenerHandler> listeners = new IdentityHashMap<>();
private boolean inited = false;
private Timer logStatsTimer = new Timer();
private Timer nodeManagerTasksTimer = new Timer("NodeManagerTasks");;
private ScheduledExecutorService pongTimer;
@Autowired
public NodeManager(SystemProperties config, EthereumListener ethereumListener,
ApplicationContext ctx, PeerConnectionTester peerConnectionManager) {
this.config = config;
this.ethereumListener = ethereumListener;
this.peerConnectionManager = peerConnectionManager;
PERSIST = config.peerDiscoveryPersist();
if (PERSIST) peerSource = ctx.getBean(PeerSource.class);
discoveryEnabled = config.peerDiscovery();
key = config.getMyKey();
homeNode = new Node(config.nodeId(), config.externalIp(), config.listenPort());
table = new NodeTable(homeNode, config.isPublicHomeNode());
logStatsTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
logger.trace("Statistics:\n {}", dumpAllStatistics());
}
}, 1 * 1000, 60 * 1000);
this.pongTimer = Executors.newSingleThreadScheduledExecutor();
for (Node node : config.peerActive()) {
getNodeHandler(node).getNodeStatistics().setPredefined(true);
}
}
public ScheduledExecutorService getPongTimer() {
return pongTimer;
}
public void setBootNodes(List<Node> bootNodes) {
this.bootNodes = bootNodes;
}
void channelActivated() {
// channel activated now can send messages
if (!inited) {
// no another init on a new channel activation
inited = true;
// this task is done asynchronously with some fixed rate
// to avoid any overhead in the NodeStatistics classes keeping them lightweight
// (which might be critical since they might be invoked from time critical sections)
nodeManagerTasksTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
processListeners();
}
}, LISTENER_REFRESH_RATE, LISTENER_REFRESH_RATE);
if (PERSIST) {
dbRead();
nodeManagerTasksTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
dbWrite();
}
}, DB_COMMIT_RATE, DB_COMMIT_RATE);
}
for (Node node : bootNodes) {
getNodeHandler(node);
}
}
}
private void dbRead() {
logger.info("Reading Node statistics from DB: " + peerSource.getNodes().size() + " nodes.");
for (Pair<Node, Integer> nodeElement : peerSource.getNodes()) {
getNodeHandler(nodeElement.getLeft()).getNodeStatistics().setPersistedReputation(nodeElement.getRight());
}
}
private void dbWrite() {
List<Pair<Node, Integer>> batch = new ArrayList<>();
synchronized (this) {
for (NodeHandler handler : nodeHandlerMap.values()) {
batch.add(Pair.of(handler.getNode(), handler.getNodeStatistics().getPersistedReputation()));
}
}
peerSource.clear();
for (Pair<Node, Integer> nodeElement : batch) {
peerSource.getNodes().add(nodeElement);
}
peerSource.getNodes().flush();
logger.info("Write Node statistics to DB: " + peerSource.getNodes().size() + " nodes.");
}
public void setMessageSender(Consumer<DiscoveryEvent> messageSender) {
this.messageSender = messageSender;
}
private String getKey(Node n) {
return getKey(new InetSocketAddress(n.getHost(), n.getPort()));
}
private String getKey(InetSocketAddress address) {
InetAddress addr = address.getAddress();
// addr == null if the hostname can't be resolved
return (addr == null ? address.getHostString() : addr.getHostAddress()) + ":" + address.getPort();
}
public synchronized NodeHandler getNodeHandler(Node n) {
String key = getKey(n);
NodeHandler ret = nodeHandlerMap.get(key);
if (ret == null) {
trimTable();
ret = new NodeHandler(n ,this);
nodeHandlerMap.put(key, ret);
logger.debug(" +++ New node: " + ret + " " + n);
if (!n.isDiscoveryNode() && !n.getHexId().equals(homeNode.getHexId())) {
ethereumListener.onNodeDiscovered(ret.getNode());
}
} else if (ret.getNode().isDiscoveryNode() && !n.isDiscoveryNode()) {
// we found discovery node with same host:port,
// replace node with correct nodeId
ret.node = n;
if (!n.getHexId().equals(homeNode.getHexId())) {
ethereumListener.onNodeDiscovered(ret.getNode());
}
logger.debug(" +++ Found real nodeId for discovery endpoint {}", n);
}
return ret;
}
private void trimTable() {
if (nodeHandlerMap.size() > NODES_TRIM_THRESHOLD) {
List<NodeHandler> sorted = new ArrayList<>(nodeHandlerMap.values());
// reverse sort by reputation
sorted.sort((o1, o2) -> o1.getNodeStatistics().getReputation() - o2.getNodeStatistics().getReputation());
for (NodeHandler handler : sorted) {
nodeHandlerMap.remove(getKey(handler.getNode()));
if (nodeHandlerMap.size() <= MAX_NODES) break;
}
}
}
boolean hasNodeHandler(Node n) {
return nodeHandlerMap.containsKey(getKey(n));
}
public NodeTable getTable() {
return table;
}
public NodeStatistics getNodeStatistics(Node n) {
return getNodeHandler(n).getNodeStatistics();
}
/**
* Checks whether peers with such InetSocketAddress has penalize disconnect record
* @param addr Peer address
* @return true if penalized, false if not or no records
*/
public boolean isReputationPenalized(InetSocketAddress addr) {
return getNodeStatistics(new Node(new byte[0], addr.getHostString(),
addr.getPort())).isReputationPenalized();
}
@Override
public void accept(DiscoveryEvent discoveryEvent) {
handleInbound(discoveryEvent);
}
public void handleInbound(DiscoveryEvent discoveryEvent) {
Message m = discoveryEvent.getMessage();
InetSocketAddress sender = discoveryEvent.getAddress();
Node n = new Node(m.getNodeId(), sender.getHostString(), sender.getPort());
if (inboundOnlyFromKnownNodes && !hasNodeHandler(n)) {
logger.debug("=/=> (" + sender + "): inbound packet from unknown peer rejected due to config option.");
return;
}
NodeHandler nodeHandler = getNodeHandler(n);
logger.trace("===> ({}) {} [{}] {}", sender, m.getClass().getSimpleName(), nodeHandler, m);
byte type = m.getType()[0];
switch (type) {
case 1:
nodeHandler.handlePing((PingMessage) m);
break;
case 2:
nodeHandler.handlePong((PongMessage) m);
break;
case 3:
nodeHandler.handleFindNode((FindNodeMessage) m);
break;
case 4:
nodeHandler.handleNeighbours((NeighborsMessage) m);
break;
}
}
public void sendOutbound(DiscoveryEvent discoveryEvent) {
if (discoveryEnabled && messageSender != null) {
logger.trace(" <===({}) {} [{}] {}", discoveryEvent.getAddress(),
discoveryEvent.getMessage().getClass().getSimpleName(), this, discoveryEvent.getMessage());
messageSender.accept(discoveryEvent);
}
}
public void stateChanged(NodeHandler nodeHandler, NodeHandler.State oldState, NodeHandler.State newState) {
if (discoveryEnabled && peerConnectionManager != null) { // peerConnectionManager can be null if component not inited yet
peerConnectionManager.nodeStatusChanged(nodeHandler);
}
}
public synchronized List<NodeHandler> getNodes(int minReputation) {
List<NodeHandler> ret = new ArrayList<>();
for (NodeHandler nodeHandler : nodeHandlerMap.values()) {
if (nodeHandler.getNodeStatistics().getReputation() >= minReputation) {
ret.add(nodeHandler);
}
}
return ret;
}
/**
* Returns limited list of nodes matching {@code predicate} criteria<br>
* The nodes are sorted then by their totalDifficulties
*
* @param predicate only those nodes which are satisfied to its condition are included in results
* @param limit max size of returning list
*
* @return list of nodes matching criteria
*/
public List<NodeHandler> getNodes(
Predicate<NodeHandler> predicate,
int limit ) {
ArrayList<NodeHandler> filtered = new ArrayList<>();
synchronized (this) {
for (NodeHandler handler : nodeHandlerMap.values()) {
if (predicate.test(handler)) {
filtered.add(handler);
}
}
}
filtered.sort((o1, o2) -> o2.getNodeStatistics().getEthTotalDifficulty().compareTo(
o1.getNodeStatistics().getEthTotalDifficulty()));
return CollectionUtils.truncate(filtered, limit);
}
private synchronized void processListeners() {
for (ListenerHandler handler : listeners.values()) {
try {
handler.checkAll();
} catch (Exception e) {
logger.error("Exception processing listener: " + handler, e);
}
}
}
/**
* Add a listener which is notified when the node statistics starts or stops meeting
* the criteria specified by [filter] param.
*/
public synchronized void addDiscoverListener(DiscoverListener listener, Predicate<NodeStatistics> filter) {
listeners.put(listener, new ListenerHandler(listener, filter));
}
public synchronized void removeDiscoverListener(DiscoverListener listener) {
listeners.remove(listener);
}
public synchronized String dumpAllStatistics() {
List<NodeHandler> l = new ArrayList<>(nodeHandlerMap.values());
l.sort((o1, o2) -> -(o1.getNodeStatistics().getReputation() - o2.getNodeStatistics().getReputation()));
StringBuilder sb = new StringBuilder();
int zeroReputCount = 0;
for (NodeHandler nodeHandler : l) {
if (nodeHandler.getNodeStatistics().getReputation() > 0) {
sb.append(nodeHandler).append("\t").append(nodeHandler.getNodeStatistics()).append("\n");
} else {
zeroReputCount++;
}
}
sb.append("0 reputation: ").append(zeroReputCount).append(" nodes.\n");
return sb.toString();
}
/**
* @return home node if config defines it as public, otherwise null
*/
Node getPublicHomeNode() {
if (config.isPublicHomeNode()) {
return homeNode;
}
return null;
}
public void close() {
peerConnectionManager.close();
try {
nodeManagerTasksTimer.cancel();
if (PERSIST) {
try {
dbWrite();
} catch (Throwable e) { // IllegalAccessError is expected
// NOTE: logback stops context right after shutdown initiated. It is problematic to see log output
// System out could help
logger.warn("Problem during NodeManager persist in close: " + e.getMessage());
}
}
} catch (Exception e) {
logger.warn("Problems canceling nodeManagerTasksTimer", e);
}
try {
logger.info("Cancelling pongTimer");
pongTimer.shutdownNow();
} catch (Exception e) {
logger.warn("Problems cancelling pongTimer", e);
}
try {
logStatsTimer.cancel();
} catch (Exception e) {
logger.warn("Problems canceling logStatsTimer", e);
}
}
private class ListenerHandler {
Map<NodeHandler, Object> discoveredNodes = new IdentityHashMap<>();
DiscoverListener listener;
Predicate<NodeStatistics> filter;
ListenerHandler(DiscoverListener listener, Predicate<NodeStatistics> filter) {
this.listener = listener;
this.filter = filter;
}
void checkAll() {
for (NodeHandler handler : nodeHandlerMap.values()) {
boolean has = discoveredNodes.containsKey(handler);
boolean test = filter.test(handler.getNodeStatistics());
if (!has && test) {
listener.nodeAppeared(handler);
discoveredNodes.put(handler, null);
} else if (has && !test) {
listener.nodeDisappeared(handler);
discoveredNodes.remove(handler);
}
}
}
}
}
| 16,411
| 36.21542
| 130
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/table/TimeComparator.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover.table;
import java.util.Comparator;
/**
* Created by kest on 5/26/15.
*/
public class TimeComparator implements Comparator<NodeEntry> {
@Override
public int compare(NodeEntry e1, NodeEntry e2) {
long t1 = e1.getModified();
long t2 = e2.getModified();
if (t1 < t2) {
return 1;
} else if (t1 >= t2) {
return -1;
} else {
return 0;
}
}
}
| 1,267
| 29.926829
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/table/KademliaOptions.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover.table;
/**
* Created by kest on 5/25/15.
*/
public class KademliaOptions {
public static final int BUCKET_SIZE = 16;
public static final int ALPHA = 3;
public static final int BINS = 256;
public static final int MAX_STEPS = 8;
public static final long REQ_TIMEOUT = 300;
public static final long BUCKET_REFRESH = 7200; //bucket refreshing interval in millis
public static final long DISCOVER_CYCLE = 30; //discovery cycle interval in seconds
}
| 1,315
| 38.878788
| 94
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/table/NodeEntry.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover.table;
import org.ethereum.net.rlpx.Node;
import static org.ethereum.crypto.HashUtil.sha3;
/**
* Created by kest on 5/25/15.
*/
public class NodeEntry {
private byte[] ownerId;
Node node;
private String entryId;
private int distance;
private long modified;
public NodeEntry(Node n) {
this.node = n;
this.ownerId = n.getId();
entryId = n.toString();
distance = distance(ownerId, n.getId());
touch();
}
public NodeEntry(byte[] ownerId, Node n) {
this.node = n;
this.ownerId = ownerId;
entryId = n.toString();
distance = distance(ownerId, n.getId());
touch();
}
public void touch() {
modified = System.currentTimeMillis();
}
public int getDistance() {
return distance;
}
public String getId() {
return entryId;
}
public Node getNode() {
return node;
}
public long getModified() {
return modified;
}
@Override
public boolean equals(Object o) {
boolean ret = false;
if (o instanceof NodeEntry){
NodeEntry e = (NodeEntry) o;
ret = this.getId().equals(e.getId());
}
return ret;
}
@Override
public int hashCode() {
return this.node.hashCode();
}
public static int distance(byte[] ownerId, byte[] targetId) {
// byte[] h1 = keccak(targetId);
// byte[] h2 = keccak(ownerId);
byte[] h1 = targetId;
byte[] h2 = ownerId;
byte[] hash = new byte[Math.min(h1.length, h2.length)];
for (int i = 0; i < hash.length; i++) {
hash[i] = (byte) (((int) h1[i]) ^ ((int) h2[i]));
}
int d = KademliaOptions.BINS;
for (byte b : hash)
{
if (b == 0)
{
d -= 8;
}
else
{
int count = 0;
for (int i = 7; i >= 0; i--)
{
boolean a = (b & (1 << i)) == 0;
if (a)
{
count++;
}
else
{
break;
}
}
d -= count;
break;
}
}
return d;
}
}
| 3,215
| 23.549618
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/table/NodeTable.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover.table;
import org.ethereum.net.rlpx.Node;
import java.util.*;
/**
* Created by kest on 5/25/15.
*/
public class NodeTable {
private final Node node; // our node
private transient NodeBucket[] buckets;
private transient List<NodeEntry> nodes;
private Map<Node, Node> evictedCandidates = new HashMap<>();
private Map<Node, Date> expectedPongs = new HashMap<>();
public NodeTable(Node n) {
this(n, true);
}
public NodeTable(Node n, boolean includeHomeNode) {
this.node = n;
initialize();
if (includeHomeNode) {
addNode(this.node);
}
}
public Node getNode() {
return node;
}
public final void initialize()
{
nodes = new ArrayList<>();
buckets = new NodeBucket[KademliaOptions.BINS];
for (int i = 0; i < KademliaOptions.BINS; i++)
{
buckets[i] = new NodeBucket(i);
}
}
public synchronized Node addNode(Node n) {
NodeEntry e = new NodeEntry(node.getId(), n);
NodeEntry lastSeen = buckets[getBucketId(e)].addNode(e);
if (lastSeen != null) {
return lastSeen.getNode();
}
if (!nodes.contains(e)) {
nodes.add(e);
}
return null;
}
public synchronized void dropNode(Node n) {
NodeEntry e = new NodeEntry(node.getId(), n);
buckets[getBucketId(e)].dropNode(e);
nodes.remove(e);
}
public synchronized boolean contains(Node n) {
NodeEntry e = new NodeEntry(node.getId(), n);
for (NodeBucket b : buckets) {
if (b.getNodes().contains(e)) {
return true;
}
}
return false;
}
public synchronized void touchNode(Node n) {
NodeEntry e = new NodeEntry(node.getId(), n);
for (NodeBucket b : buckets) {
if (b.getNodes().contains(e)) {
b.getNodes().get(b.getNodes().indexOf(e)).touch();
break;
}
}
}
public int getBucketsCount() {
int i = 0;
for (NodeBucket b : buckets) {
if (b.getNodesCount() > 0) {
i++;
}
}
return i;
}
public synchronized NodeBucket[] getBuckets() {
return buckets;
}
public int getBucketId(NodeEntry e) {
int id = e.getDistance() - 1;
return id < 0 ? 0 : id;
}
public synchronized int getNodesCount() {
return nodes.size();
}
public synchronized List<NodeEntry> getAllNodes()
{
List<NodeEntry> nodes = new ArrayList<>();
for (NodeBucket b : buckets)
{
// nodes.addAll(b.getNodes());
for (NodeEntry e : b.getNodes())
{
if (!e.getNode().equals(node)) {
nodes.add(e);
}
}
}
// boolean res = nodes.remove(node);
return nodes;
}
public synchronized List<Node> getClosestNodes(byte[] targetId) {
List<NodeEntry> closestEntries = getAllNodes();
List<Node> closestNodes = new ArrayList<>();
Collections.sort(closestEntries, new DistanceComparator(targetId));
if (closestEntries.size() > KademliaOptions.BUCKET_SIZE) {
closestEntries = closestEntries.subList(0, KademliaOptions.BUCKET_SIZE);
}
for (NodeEntry e : closestEntries) {
if (!e.getNode().isDiscoveryNode()) {
closestNodes.add(e.getNode());
}
}
return closestNodes;
}
}
| 4,442
| 27.299363
| 84
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/table/DistanceComparator.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover.table;
import java.util.Comparator;
/**
* Created by kest on 5/26/15.
*/
public class DistanceComparator implements Comparator<NodeEntry> {
byte[] targetId;
DistanceComparator(byte[] targetId) {
this.targetId = targetId;
}
@Override
public int compare(NodeEntry e1, NodeEntry e2) {
int d1 = NodeEntry.distance(targetId, e1.getNode().getId());
int d2 = NodeEntry.distance(targetId, e2.getNode().getId());
if (d1 > d2) {
return 1;
} else if (d1 < d2) {
return -1;
} else {
return 0;
}
}
}
| 1,440
| 30.326087
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/rlpx/discover/table/NodeBucket.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.rlpx.discover.table;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Created by kest on 5/25/15.
*/
public class NodeBucket {
private final int depth;
private List<NodeEntry> nodes = new ArrayList<>();
NodeBucket(int depth) {
this.depth = depth;
}
public int getDepth() {
return depth;
}
public synchronized NodeEntry addNode(NodeEntry e) {
if (!nodes.contains(e)) {
if (nodes.size() >= KademliaOptions.BUCKET_SIZE) {
return getLastSeen();
} else {
nodes.add(e);
}
}
return null;
}
private NodeEntry getLastSeen() {
List<NodeEntry> sorted = nodes;
Collections.sort(sorted, new TimeComparator());
return sorted.get(0);
}
public synchronized void dropNode(NodeEntry entry) {
for (NodeEntry e : nodes) {
if (e.getId().equals(entry.getId())) {
nodes.remove(e);
break;
}
}
}
public int getNodesCount() {
return nodes.size();
}
public List<NodeEntry> getNodes() {
// List<NodeEntry> nodes = new ArrayList<>();
// for (NodeEntry e : this.nodes) {
// nodes.add(e);
// }
return nodes;
}
}
| 2,192
| 26.4125
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/submit/TransactionExecutor.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.submit;
import org.ethereum.core.Transaction;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author Roman Mandeleil
* @since 23.05.2014
*/
public class TransactionExecutor {
static {
instance = new TransactionExecutor();
}
public static TransactionExecutor instance;
private ExecutorService executor = Executors.newFixedThreadPool(1);
public Future<List<Transaction>> submitTransaction(TransactionTask task) {
return executor.submit(task);
}
}
| 1,411
| 31.090909
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/submit/WalletTransaction.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.submit;
import org.ethereum.core.Transaction;
/**
* @author Roman Mandeleil
* @since 23.05.2014
*/
public class WalletTransaction {
private final Transaction tx;
private int approved = 0; // each time the tx got from the wire this value increased
public WalletTransaction(Transaction tx) {
this.tx = tx;
}
public void incApproved() {
approved++;
}
public int getApproved() {
return approved;
}
}
| 1,276
| 28.697674
| 88
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/submit/TransactionTask.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.submit;
import org.ethereum.core.Transaction;
import org.ethereum.net.server.Channel;
import org.ethereum.net.server.ChannelManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import static java.lang.Thread.sleep;
/**
* @author Roman Mandeleil
* @since 23.05.2014
*/
public class TransactionTask implements Callable<List<Transaction>> {
private static final Logger logger = LoggerFactory.getLogger("net");
private final List<Transaction> txs;
private final ChannelManager channelManager;
private final Channel receivedFrom;
public TransactionTask(Transaction tx, ChannelManager channelManager) {
this(Collections.singletonList(tx), channelManager);
}
public TransactionTask(List<Transaction> txs, ChannelManager channelManager) {
this(txs, channelManager, null);
}
public TransactionTask(List<Transaction> txs, ChannelManager channelManager, Channel receivedFrom) {
this.txs = txs;
this.channelManager = channelManager;
this.receivedFrom = receivedFrom;
}
@Override
public List<Transaction> call() throws Exception {
try {
logger.info("submit txs: {}", txs.toString());
channelManager.sendTransaction(txs, receivedFrom);
return txs;
} catch (Throwable th) {
logger.warn("Exception caught: {}", th);
}
return null;
}
}
| 2,326
| 30.876712
| 104
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/message/StaticMessages.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.message;
import org.ethereum.config.SystemProperties;
import org.ethereum.net.client.Capability;
import org.ethereum.net.client.ConfigCapabilities;
import org.ethereum.net.p2p.*;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class contains static values of messages on the network. These message
* will always be the same and therefore don't need to be created each time.
*
* @author Roman Mandeleil
* @since 13.04.14
*/
@Component
public class StaticMessages {
@Autowired
SystemProperties config;
@Autowired
ConfigCapabilities configCapabilities;
public final static PingMessage PING_MESSAGE = new PingMessage();
public final static PongMessage PONG_MESSAGE = new PongMessage();
public final static GetPeersMessage GET_PEERS_MESSAGE = new GetPeersMessage();
public final static DisconnectMessage DISCONNECT_MESSAGE = new DisconnectMessage(ReasonCode.REQUESTED);
public static final byte[] SYNC_TOKEN = Hex.decode("22400891");
public HelloMessage createHelloMessage(String peerId) {
return createHelloMessage(peerId, config.listenPort());
}
public HelloMessage createHelloMessage(String peerId, int listenPort) {
String helloAnnouncement = buildHelloAnnouncement();
byte p2pVersion = (byte) config.defaultP2PVersion();
List<Capability> capabilities = configCapabilities.getConfigCapabilities();
return new HelloMessage(p2pVersion, helloAnnouncement,
capabilities, listenPort, peerId);
}
private String buildHelloAnnouncement() {
String version = config.projectVersion();
String numberVersion = version;
Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)*");
Matcher matcher = pattern.matcher(numberVersion);
if (matcher.find()) {
numberVersion = numberVersion.substring(matcher.start(), matcher.end());
}
String system = System.getProperty("os.name");
if (system.contains(" "))
system = system.substring(0, system.indexOf(" "));
if (System.getProperty("java.vm.vendor").contains("Android"))
system = "Android";
String phrase = config.helloPhrase();
return String.format("Ethereum(J)/v%s/%s/%s/Java/%s", numberVersion, system,
config.projectVersionModifier().equalsIgnoreCase("release") ? "Release" : "Dev", phrase);
}
}
| 3,415
| 38.264368
| 107
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/message/Message.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract message class for all messages on the Ethereum network
*
* @author Roman Mandeleil
* @since 06.04.14
*/
public abstract class Message {
protected static final Logger logger = LoggerFactory.getLogger("net");
protected boolean parsed;
protected byte[] encoded;
protected byte code;
public Message() {
}
public Message(byte[] encoded) {
this.encoded = encoded;
parsed = false;
}
/**
* Gets the RLP encoded byte array of this message
*
* @return RLP encoded byte array representation of this message
*/
public abstract byte[] getEncoded();
public abstract Class<?> getAnswerMessage();
/**
* Returns the message in String format
*
* @return A string with all attributes of the message
*/
public abstract String toString();
public abstract Enum getCommand();
public byte getCode() {
return code;
}
}
| 1,839
| 26.058824
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/message/ReasonCode.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.message;
import java.util.HashMap;
import java.util.Map;
/**
* Reason is an optional integer specifying one
* of a number of reasons for disconnect
*/
public enum ReasonCode {
/**
* [0x00] Disconnect request by other peer
*/
REQUESTED(0x00),
/**
* [0x01]
*/
TCP_ERROR(0x01),
/**
* [0x02] Packets can not be parsed
*/
BAD_PROTOCOL(0x02),
/**
* [0x03] This peer is too slow or delivers unreliable data
*/
USELESS_PEER(0x03),
/**
* [0x04] Already too many connections with other peers
*/
TOO_MANY_PEERS(0x04),
/**
* [0x05] Already have a running connection with this peer
*/
DUPLICATE_PEER(0x05),
/**
* [0x06] Version of the p2p protocol is not the same as ours
*/
INCOMPATIBLE_PROTOCOL(0x06),
/**
* [0x07]
*/
NULL_IDENTITY(0x07),
/**
* [0x08] Peer quit voluntarily
*/
PEER_QUITING(0x08),
UNEXPECTED_IDENTITY(0x09),
LOCAL_IDENTITY(0x0A),
PING_TIMEOUT(0x0B),
USER_REASON(0x10),
/**
* [0xFF] Reason not specified
*/
UNKNOWN(0xFF);
private int reason;
private static final Map<Integer, ReasonCode> intToTypeMap = new HashMap<>();
static {
for (ReasonCode type : ReasonCode.values()) {
intToTypeMap.put(type.reason, type);
}
}
private ReasonCode(int reason) {
this.reason = reason;
}
public static ReasonCode fromInt(int i) {
ReasonCode type = intToTypeMap.get(i);
if (type == null)
return ReasonCode.UNKNOWN;
return type;
}
public byte asByte() {
return (byte) reason;
}
}
| 2,524
| 21.345133
| 81
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/message/MessageFactory.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.message;
/**
* Factory interface to create messages
*
* @author Mikhail Kalinin
* @since 20.08.2015
*/
public interface MessageFactory {
/**
* Creates message by absolute message codes
* e.g. codes described in {@link org.ethereum.net.eth.message.EthMessageCodes}
*
* @param code message code
* @param encoded encoded message bytes
* @return created message
*
* @throws IllegalArgumentException if code is unknown
*/
Message create(byte code, byte[] encoded);
}
| 1,338
| 31.658537
| 83
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/server/WireTrafficStats.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.server;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.socket.DatagramPacket;
import org.ethereum.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.ethereum.util.Utils.sizeToStr;
/**
* Created by Anton Nashatyrev on 27.02.2017.
*/
@Component
public class WireTrafficStats implements Runnable {
private final static Logger logger = LoggerFactory.getLogger("net");
private ScheduledExecutorService executor;
public final TrafficStatHandler tcp = new TrafficStatHandler();
public final TrafficStatHandler udp = new TrafficStatHandler();
public WireTrafficStats() {
executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("WireTrafficStats-%d").build());
executor.scheduleAtFixedRate(this, 10, 10, TimeUnit.SECONDS);
}
@Override
public void run() {
logger.info("TCP: " + tcp.stats());
logger.info("UDP: " + udp.stats());
}
@PreDestroy
public void close() {
executor.shutdownNow();
}
@ChannelHandler.Sharable
static class TrafficStatHandler extends ChannelDuplexHandler {
long outSizeTot;
long inSizeTot;
AtomicLong outSize = new AtomicLong();
AtomicLong inSize = new AtomicLong();
AtomicLong outPackets = new AtomicLong();
AtomicLong inPackets = new AtomicLong();
long lastTime = System.currentTimeMillis();
public String stats() {
long out = outSize.getAndSet(0);
long outPac = outPackets.getAndSet(0);
long in = inSize.getAndSet(0);
long inPac = inPackets.getAndSet(0);
outSizeTot += out;
inSizeTot += in;
long curTime = System.currentTimeMillis();
long d = (curTime - lastTime);
long outSpeed = out * 1000 / d;
long inSpeed = in * 1000 / d;
lastTime = curTime;
return "Speed in/out " + sizeToStr(inSpeed) + " / " + sizeToStr(outSpeed) +
"(sec), packets in/out " + inPac + "/" + outPac +
", total in/out: " + sizeToStr(inSizeTot) + " / " + sizeToStr(outSizeTot);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
inPackets.incrementAndGet();
if (msg instanceof ByteBuf) {
inSize.addAndGet(((ByteBuf) msg).readableBytes());
} else if (msg instanceof DatagramPacket) {
inSize.addAndGet(((DatagramPacket) msg).content().readableBytes());
}
super.channelRead(ctx, msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
outPackets.incrementAndGet();
if (msg instanceof ByteBuf) {
outSize.addAndGet(((ByteBuf) msg).readableBytes());
} else if (msg instanceof DatagramPacket) {
outSize.addAndGet(((DatagramPacket) msg).content().readableBytes());
}
super.write(ctx, msg, promise);
}
}
}
| 4,489
| 37.050847
| 135
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/server/PeerServer.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.server;
import org.ethereum.config.SystemProperties;
import org.ethereum.listener.EthereumListener;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultMessageSizeEstimator;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* This class establishes a listener for incoming connections.
* See <a href="http://netty.io">http://netty.io</a>.
*
* @author Roman Mandeleil
* @since 01.11.2014
*/
@Component
public class PeerServer {
private static final Logger logger = LoggerFactory.getLogger("net");
private SystemProperties config;
private ApplicationContext ctx;
private EthereumListener ethereumListener;
public EthereumChannelInitializer ethereumChannelInitializer;
private boolean listening;
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
ChannelFuture channelFuture;
@Autowired
public PeerServer(final SystemProperties config, final ApplicationContext ctx,
final EthereumListener ethereumListener) {
this.ctx = ctx;
this.config = config;
this.ethereumListener = ethereumListener;
}
public void start(int port) {
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, "");
ethereumListener.trace("Listening on port " + port);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());
b.handler(new LoggingHandler());
b.childHandler(ethereumChannelInitializer);
// Start the client.
logger.info("Listening for incoming connections, port: [{}] ", port);
logger.info("NodeId: [{}] ", toHexString(config.nodeId()));
channelFuture = b.bind(port).sync();
listening = true;
// Wait until the connection is closed.
channelFuture.channel().closeFuture().sync();
logger.debug("Connection is closed");
} catch (Exception e) {
logger.error("Peer server error: {} ({})", e.getMessage(), e.getClass().getName());
throw new Error("Server Disconnected");
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
listening = false;
}
}
public void close() {
if (listening && channelFuture != null && channelFuture.channel().isOpen()) {
try {
logger.info("Closing PeerServer...");
channelFuture.channel().close().sync();
logger.info("PeerServer closed.");
} catch (Exception e) {
logger.warn("Problems closing server channel", e);
}
}
}
public boolean isListening() {
return listening;
}
}
| 4,506
| 32.385185
| 96
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/server/EthereumChannelInitializer.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.server;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.ethereum.net.rlpx.discover.NodeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* @author Roman Mandeleil
* @since 01.11.2014
*/
@Component
@Scope("prototype")
public class EthereumChannelInitializer extends ChannelInitializer<NioSocketChannel> {
private static final Logger logger = LoggerFactory.getLogger("net");
@Autowired
private ApplicationContext ctx;
@Autowired
ChannelManager channelManager;
@Autowired
NodeManager nodeManager;
private String remoteId;
private boolean peerDiscoveryMode = false;
public EthereumChannelInitializer(String remoteId) {
this.remoteId = remoteId;
}
@Override
public void initChannel(NioSocketChannel ch) throws Exception {
try {
if (!peerDiscoveryMode) {
logger.debug("Open {} connection, channel: {}", isInbound() ? "inbound" : "outbound", ch.toString());
}
if (notEligibleForIncomingConnection(ch)) {
ch.disconnect();
return;
}
final Channel channel = ctx.getBean(Channel.class);
channel.setInetSocketAddress(ch.remoteAddress());
channel.init(ch.pipeline(), remoteId, peerDiscoveryMode, channelManager);
if(!peerDiscoveryMode) {
channelManager.add(channel);
}
// limit the size of receiving buffer to 1024
ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(256 * 1024));
ch.config().setOption(ChannelOption.SO_RCVBUF, 256 * 1024);
ch.config().setOption(ChannelOption.SO_BACKLOG, 1024);
// be aware of channel closing
ch.closeFuture().addListener((ChannelFutureListener) future -> {
if (!peerDiscoveryMode) {
channelManager.notifyDisconnect(channel);
}
});
} catch (Exception e) {
logger.error("Unexpected error: ", e);
}
}
/**
* Tests incoming connection channel for usual abuse/attack vectors
* @param ch Channel
* @return true if we should refuse this connection, otherwise false
*/
private boolean notEligibleForIncomingConnection(NioSocketChannel ch) {
if(!isInbound()) return false;
// For incoming connection drop if..
// Bad remote address
if (ch.remoteAddress() == null) {
logger.debug("Drop connection - bad remote address, channel: {}", ch.toString());
return true;
}
// Drop if we have long waiting queue already
if (!channelManager.acceptingNewPeers()) {
logger.debug("Drop connection - many new peers are not processed, channel: {}", ch.toString());
return true;
}
// Refuse connections from ips that are already in connection queue
// Local and private network addresses are still welcome!
if (!ch.remoteAddress().getAddress().isLoopbackAddress() &&
!ch.remoteAddress().getAddress().isSiteLocalAddress() &&
channelManager.isAddressInQueue(ch.remoteAddress().getAddress())) {
logger.debug("Drop connection - already processing connection from this host, channel: {}", ch.toString());
return true;
}
// Avoid too frequent connection attempts
if (channelManager.isRecentlyDisconnected(ch.remoteAddress().getAddress())) {
logger.debug("Drop connection - the same IP was disconnected recently, channel: {}", ch.toString());
return true;
}
// Drop bad peers before creating channel
if (nodeManager.isReputationPenalized(ch.remoteAddress())) {
logger.debug("Drop connection - bad peer, channel: {}", ch.toString());
return true;
}
return false;
}
private boolean isInbound() {
return remoteId == null || remoteId.isEmpty();
}
public void setPeerDiscoveryMode(boolean peerDiscoveryMode) {
this.peerDiscoveryMode = peerDiscoveryMode;
}
}
| 5,264
| 35.5625
| 119
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/server/ChannelManager.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.server;
import org.apache.commons.collections4.map.LRUMap;
import org.ethereum.config.NodeFilter;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Block;
import org.ethereum.core.BlockWrapper;
import org.ethereum.core.PendingState;
import org.ethereum.core.Transaction;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.facade.Ethereum;
import org.ethereum.net.message.ReasonCode;
import org.ethereum.net.rlpx.Node;
import org.ethereum.sync.SyncManager;
import org.ethereum.sync.SyncPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.*;
import static org.ethereum.net.message.ReasonCode.DUPLICATE_PEER;
import static org.ethereum.net.message.ReasonCode.TOO_MANY_PEERS;
/**
* @author Roman Mandeleil
* @since 11.11.2014
*/
@Component
public class ChannelManager {
private static final Logger logger = LoggerFactory.getLogger("net");
// If the inbound peer connection was dropped by us with a reason message
// then we ban that peer IP on any connections for some time to protect from
// too active peers
public static final int INBOUND_CONNECTION_BAN_TIMEOUT = 120 * 1000;
private List<Channel> newPeers = new CopyOnWriteArrayList<>();
// Limiting number of new peers to avoid delays in processing
private static final int MAX_NEW_PEERS = 128;
private final Map<ByteArrayWrapper, Channel> activePeers = new ConcurrentHashMap<>();
private ScheduledExecutorService mainWorker = Executors.newSingleThreadScheduledExecutor();
private int maxActivePeers;
private Map<InetAddress, Date> recentlyDisconnected = Collections.synchronizedMap(new LRUMap<InetAddress, Date>(500));
private NodeFilter trustedPeers;
/**
* Queue with new blocks from other peers
*/
private BlockingQueue<BlockWrapper> newForeignBlocks = new LinkedBlockingQueue<>();
/**
* Queue with new peers used for after channel init tasks
*/
private BlockingQueue<Channel> newActivePeers = new LinkedBlockingQueue<>();
private Thread blockDistributeThread;
private Thread txDistributeThread;
Random rnd = new Random(); // Used for distributing new blocks / hashes logic
@Autowired
SyncPool syncPool;
@Autowired
private Ethereum ethereum;
@Autowired
private PendingState pendingState;
private SystemProperties config;
private SyncManager syncManager;
private PeerServer peerServer;
@Autowired
private ChannelManager(final SystemProperties config, final SyncManager syncManager,
final PeerServer peerServer) {
this.config = config;
this.syncManager = syncManager;
this.peerServer = peerServer;
maxActivePeers = config.maxActivePeers();
trustedPeers = config.peerTrusted();
mainWorker.scheduleWithFixedDelay(() -> {
try {
processNewPeers();
} catch (Throwable t) {
logger.error("Error", t);
}
}, 0, 1, TimeUnit.SECONDS);
if (config.listenPort() > 0) {
new Thread(() -> peerServer.start(config.listenPort()),
"PeerServerThread").start();
}
// Resending new blocks to network in loop
this.blockDistributeThread = new Thread(this::newBlocksDistributeLoop, "NewSyncThreadBlocks");
this.blockDistributeThread.start();
// Resending pending txs to newly connected peers
this.txDistributeThread = new Thread(this::newTxDistributeLoop, "NewPeersThread");
this.txDistributeThread.start();
}
public void connect(Node node) {
if (logger.isTraceEnabled()) logger.trace(
"Peer {}: initiate connection",
node.getHexIdShort()
);
if (nodesInUse().contains(node.getHexId())) {
if (logger.isTraceEnabled()) logger.trace(
"Peer {}: connection already initiated",
node.getHexIdShort()
);
return;
}
ethereum.connect(node);
}
public Set<String> nodesInUse() {
Set<String> ids = new HashSet<>();
for (Channel peer : getActivePeers()) {
ids.add(peer.getPeerId());
}
for (Channel peer : newPeers) {
ids.add(peer.getPeerId());
}
return ids;
}
private void processNewPeers() {
List<Runnable> noLockTasks = new ArrayList<>();
synchronized (this) {
if (newPeers.isEmpty()) return;
List<Channel> processed = new ArrayList<>();
int addCnt = 0;
for (Channel peer : newPeers) {
logger.debug("Processing new peer: " + peer);
if (peer.isProtocolsInitialized()) {
logger.debug("Protocols initialized");
if (!activePeers.containsKey(peer.getNodeIdWrapper())) {
if (!peer.isActive() &&
activePeers.size() >= maxActivePeers &&
!trustedPeers.accept(peer.getNode())) {
// restricting inbound connections unless this is a trusted peer
noLockTasks.add(() -> disconnect(peer, TOO_MANY_PEERS));
} else {
addCnt++;
process(peer);
}
} else {
noLockTasks.add(() -> disconnect(peer, DUPLICATE_PEER));
}
processed.add(peer);
}
}
if (addCnt > 0) {
logger.info("New peers processed: " + processed + ", active peers added: " + addCnt + ", total active peers: " + activePeers.size());
}
newPeers.removeAll(processed);
}
noLockTasks.forEach(Runnable::run);
}
public void disconnect(Channel peer, ReasonCode reason) {
logger.debug("Disconnecting peer with reason " + reason + ": " + peer);
peer.disconnect(reason);
recentlyDisconnected.put(peer.getInetSocketAddress().getAddress(), new Date());
}
/**
* Whether peer with the same ip is in newPeers, waiting for processing
* @param peerAddr Peer address
* @return true if we already have connection from this address, otherwise false
*/
public boolean isAddressInQueue(InetAddress peerAddr) {
for (Channel peer: newPeers) {
if (peer.getInetSocketAddress() != null &&
peer.getInetSocketAddress().getAddress().getHostAddress().equals(peerAddr.getHostAddress())) {
return true;
}
}
return false;
}
public boolean isRecentlyDisconnected(InetAddress peerAddr) {
Date disconnectTime = recentlyDisconnected.get(peerAddr);
if (disconnectTime != null &&
System.currentTimeMillis() - disconnectTime.getTime() < INBOUND_CONNECTION_BAN_TIMEOUT) {
return true;
} else {
recentlyDisconnected.remove(peerAddr);
return false;
}
}
private void process(Channel peer) {
if(peer.hasEthStatusSucceeded()) {
// prohibit transactions processing until main sync is done
if (syncManager.isSyncDone()) {
peer.onSyncDone(true);
// So we could perform some tasks on recently connected peer
newActivePeers.add(peer);
}
activePeers.put(peer.getNodeIdWrapper(), peer);
}
}
/**
* Propagates the transactions message across active peers with exclusion of
* 'receivedFrom' peer.
* @param txs transactions to be sent
* @param receivedFrom the peer which sent original message or null if
* the transactions were originated by this peer
*/
public void sendTransaction(List<Transaction> txs, Channel receivedFrom) {
for (Channel channel : activePeers.values()) {
if (channel != receivedFrom) {
channel.sendTransactionsCapped(txs);
}
}
}
/**
* Propagates the new block message across active peers
* Suitable only for self-mined blocks
* Use {@link #sendNewBlock(Block, Channel)} for sending blocks received from net
* @param block new Block to be sent
*/
public void sendNewBlock(Block block) {
for (Channel channel : activePeers.values()) {
channel.sendNewBlock(block);
}
}
/**
* Called on new blocks received from other peers
* @param blockWrapper Block with additional info
*/
public void onNewForeignBlock(BlockWrapper blockWrapper) {
newForeignBlocks.add(blockWrapper);
}
/**
* Processing new blocks received from other peers from queue
*/
private void newBlocksDistributeLoop() {
while (!Thread.currentThread().isInterrupted()) {
BlockWrapper wrapper = null;
try {
wrapper = newForeignBlocks.take();
Channel receivedFrom = getActivePeer(wrapper.getNodeId());
sendNewBlock(wrapper.getBlock(), receivedFrom);
} catch (InterruptedException e) {
break;
} catch (Throwable e) {
if (wrapper != null) {
logger.error("Error broadcasting new block {}: ", wrapper.getBlock().getShortDescr(), e);
logger.error("Block dump: {}", wrapper.getBlock());
} else {
logger.error("Error broadcasting unknown block", e);
}
}
}
}
/**
* Sends all pending txs to new active peers
*/
private void newTxDistributeLoop() {
while (!Thread.currentThread().isInterrupted()) {
Channel channel = null;
try {
channel = newActivePeers.take();
List<Transaction> pendingTransactions = pendingState.getPendingTransactions();
if (!pendingTransactions.isEmpty()) {
channel.sendTransactionsCapped(pendingTransactions);
}
} catch (InterruptedException e) {
break;
} catch (Throwable e) {
if (channel != null) {
logger.error("Error sending transactions to peer {}: ", channel.getNode().getHexIdShort(), e);
} else {
logger.error("Unknown error when sending transactions to new peer", e);
}
}
}
}
/**
* Propagates the new block message across active peers with exclusion of
* 'receivedFrom' peer.
* Distributes full block to 30% of peers and only its hash to remains
* @param block new Block to be sent
* @param receivedFrom the peer which sent original message
*/
private void sendNewBlock(Block block, Channel receivedFrom) {
for (Channel channel : activePeers.values()) {
if (channel == receivedFrom) continue;
if (rnd.nextInt(10) < 3) { // 30%
channel.sendNewBlock(block);
} else { // 70%
channel.sendNewBlockHashes(block);
}
}
}
public synchronized void add(Channel peer) {
logger.debug("New peer in ChannelManager {}", peer);
newPeers.add(peer);
}
public void notifyDisconnect(Channel channel) {
logger.debug("Peer {}: notifies about disconnect", channel);
channel.onDisconnect();
syncPool.onDisconnect(channel);
synchronized(this) {
activePeers.values().remove(channel);
newPeers.remove(channel);
}
}
public void onSyncDone(boolean done) {
for (Channel channel : activePeers.values())
channel.onSyncDone(done);
}
public Collection<Channel> getActivePeers() {
return new ArrayList<>(activePeers.values());
}
/**
* Checks whether newPeers is not full
* newPeers are used to fill up active peers
* @return True if there are free slots for new peers
*/
public boolean acceptingNewPeers() {
return newPeers.size() < Math.max(config.maxActivePeers(), MAX_NEW_PEERS);
}
public Channel getActivePeer(byte[] nodeId) {
return activePeers.get(new ByteArrayWrapper(nodeId));
}
public SyncManager getSyncManager() {
return syncManager;
}
public void close() {
try {
logger.info("Shutting down block and tx distribute threads...");
if (blockDistributeThread != null) blockDistributeThread.interrupt();
if (txDistributeThread != null) txDistributeThread.interrupt();
logger.info("Shutting down ChannelManager worker thread...");
mainWorker.shutdownNow();
mainWorker.awaitTermination(5, TimeUnit.SECONDS);
} catch (Exception e) {
logger.warn("Problems shutting down", e);
}
peerServer.close();
ArrayList<Channel> allPeers = new ArrayList<>(activePeers.values());
allPeers.addAll(newPeers);
for (Channel channel : allPeers) {
try {
channel.dropConnection();
} catch (Exception e) {
logger.warn("Problems disconnecting channel " + channel, e);
}
}
}
}
| 14,553
| 34.154589
| 149
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/server/PeerStatistics.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.server;
/**
* @author Mikhail Kalinin
* @since 29.02.2016
*/
public class PeerStatistics {
private double avgLatency = 0;
private long pingCount = 0;
public void pong(long pingStamp) {
long latency = System.currentTimeMillis() - pingStamp;
avgLatency = ((avgLatency * pingCount) + latency) / ++pingCount;
}
public double getAvgLatency() {
return avgLatency;
}
}
| 1,232
| 31.447368
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/server/Channel.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.net.server;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Block;
import org.ethereum.core.BlockHeaderWrapper;
import org.ethereum.core.Transaction;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.net.MessageQueue;
import org.ethereum.net.client.Capability;
import org.ethereum.net.eth.handler.Eth;
import org.ethereum.net.eth.handler.EthAdapter;
import org.ethereum.net.eth.handler.EthHandler;
import org.ethereum.net.eth.handler.EthHandlerFactory;
import org.ethereum.net.eth.EthVersion;
import org.ethereum.net.eth.message.Eth62MessageFactory;
import org.ethereum.net.eth.message.Eth63MessageFactory;
import org.ethereum.net.message.ReasonCode;
import org.ethereum.net.rlpx.*;
import org.ethereum.sync.SyncStatistics;
import org.ethereum.net.message.MessageFactory;
import org.ethereum.net.message.StaticMessages;
import org.ethereum.net.p2p.HelloMessage;
import org.ethereum.net.p2p.P2pHandler;
import org.ethereum.net.p2p.P2pMessageFactory;
import org.ethereum.net.rlpx.discover.NodeManager;
import org.ethereum.net.rlpx.discover.NodeStatistics;
import org.ethereum.net.shh.ShhHandler;
import org.ethereum.net.shh.ShhMessageFactory;
import org.ethereum.net.swarm.bzz.BzzHandler;
import org.ethereum.net.swarm.bzz.BzzMessageFactory;
import org.ethereum.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author Roman Mandeleil
* @since 01.11.2014
*/
@Component
@Scope("prototype")
public class Channel {
private final static Logger logger = LoggerFactory.getLogger("net");
@Autowired
SystemProperties config;
@Autowired
private MessageQueue msgQueue;
@Autowired
private P2pHandler p2pHandler;
@Autowired
private ShhHandler shhHandler;
@Autowired
private BzzHandler bzzHandler;
@Autowired
private MessageCodec messageCodec;
@Autowired
private HandshakeHandler handshakeHandler;
@Autowired
private NodeManager nodeManager;
@Autowired
private EthHandlerFactory ethHandlerFactory;
@Autowired
private StaticMessages staticMessages;
@Autowired
private WireTrafficStats stats;
private ChannelManager channelManager;
private Eth eth = new EthAdapter();
private InetSocketAddress inetSocketAddress;
private Node node;
private NodeStatistics nodeStatistics;
private boolean discoveryMode;
private boolean isActive;
private boolean isDisconnected;
private String remoteId;
private PeerStatistics peerStats = new PeerStatistics();
public static final int MAX_SAFE_TXS = 192;
public void init(ChannelPipeline pipeline, String remoteId, boolean discoveryMode, ChannelManager channelManager) {
this.channelManager = channelManager;
this.remoteId = remoteId;
isActive = remoteId != null && !remoteId.isEmpty();
pipeline.addLast("readTimeoutHandler",
new ReadTimeoutHandler(config.peerChannelReadTimeout(), TimeUnit.SECONDS));
pipeline.addLast(stats.tcp);
pipeline.addLast("handshakeHandler", handshakeHandler);
this.discoveryMode = discoveryMode;
if (discoveryMode) {
// temporary key/nodeId to not accidentally smear our reputation with
// unexpected disconnect
// handshakeHandler.generateTempKey();
}
handshakeHandler.setRemoteId(remoteId, this);
messageCodec.setChannel(this);
msgQueue.setChannel(this);
p2pHandler.setMsgQueue(msgQueue);
messageCodec.setP2pMessageFactory(new P2pMessageFactory());
shhHandler.setMsgQueue(msgQueue);
messageCodec.setShhMessageFactory(new ShhMessageFactory());
bzzHandler.setMsgQueue(msgQueue);
messageCodec.setBzzMessageFactory(new BzzMessageFactory());
}
public void publicRLPxHandshakeFinished(ChannelHandlerContext ctx, FrameCodec frameCodec,
HelloMessage helloRemote) throws IOException, InterruptedException {
logger.debug("publicRLPxHandshakeFinished with " + ctx.channel().remoteAddress());
messageCodec.setSupportChunkedFrames(false);
FrameCodecHandler frameCodecHandler = new FrameCodecHandler(frameCodec, this);
ctx.pipeline().addLast("medianFrameCodec", frameCodecHandler);
if (SnappyCodec.isSupported(Math.min(config.defaultP2PVersion(), helloRemote.getP2PVersion()))) {
ctx.pipeline().addLast("snappyCodec", new SnappyCodec(this));
logger.debug("{}: use snappy compression", ctx.channel());
}
ctx.pipeline().addLast("messageCodec", messageCodec);
ctx.pipeline().addLast(Capability.P2P, p2pHandler);
p2pHandler.setChannel(this);
p2pHandler.setHandshake(helloRemote, ctx);
getNodeStatistics().rlpxHandshake.add();
}
public void sendHelloMessage(ChannelHandlerContext ctx, FrameCodec frameCodec,
String nodeId) throws IOException, InterruptedException {
final HelloMessage helloMessage = staticMessages.createHelloMessage(nodeId);
ByteBuf byteBufMsg = ctx.alloc().buffer();
frameCodec.writeFrame(new FrameCodec.Frame(helloMessage.getCode(), helloMessage.getEncoded()), byteBufMsg);
ctx.writeAndFlush(byteBufMsg).sync();
if (logger.isDebugEnabled())
logger.debug("To: {} Send: {}", ctx.channel().remoteAddress(), helloMessage);
getNodeStatistics().rlpxOutHello.add();
}
public void activateEth(ChannelHandlerContext ctx, EthVersion version) {
EthHandler handler = ethHandlerFactory.create(version);
MessageFactory messageFactory = createEthMessageFactory(version);
messageCodec.setEthVersion(version);
messageCodec.setEthMessageFactory(messageFactory);
logger.debug("Eth{} [ address = {} | id = {} ]", handler.getVersion(), inetSocketAddress, getPeerIdShort());
ctx.pipeline().addLast(Capability.ETH, handler);
handler.setMsgQueue(msgQueue);
handler.setChannel(this);
handler.setPeerDiscoveryMode(discoveryMode);
handler.activate();
eth = handler;
}
private MessageFactory createEthMessageFactory(EthVersion version) {
switch (version) {
case V62: return new Eth62MessageFactory();
case V63: return new Eth63MessageFactory();
default: throw new IllegalArgumentException("Eth " + version + " is not supported");
}
}
public void activateShh(ChannelHandlerContext ctx) {
ctx.pipeline().addLast(Capability.SHH, shhHandler);
shhHandler.activate();
}
public void activateBzz(ChannelHandlerContext ctx) {
ctx.pipeline().addLast(Capability.BZZ, bzzHandler);
bzzHandler.activate();
}
public void setInetSocketAddress(InetSocketAddress inetSocketAddress) {
this.inetSocketAddress = inetSocketAddress;
}
public NodeStatistics getNodeStatistics() {
return nodeStatistics;
}
/**
* Set node and register it in NodeManager if it is not registered yet.
*/
public void initWithNode(byte[] nodeId, int remotePort) {
node = new Node(nodeId, inetSocketAddress.getHostString(), remotePort);
nodeStatistics = nodeManager.getNodeStatistics(node);
}
public void initWithNode(byte[] nodeId) {
initWithNode(nodeId, inetSocketAddress.getPort());
}
public Node getNode() {
return node;
}
public void initMessageCodes(List<Capability> caps) {
messageCodec.initMessageCodes(caps);
}
public boolean isProtocolsInitialized() {
return eth.hasStatusPassed();
}
public void onDisconnect() {
isDisconnected = true;
}
public boolean isDisconnected() {
return isDisconnected;
}
public void onSyncDone(boolean done) {
if (done) {
eth.enableTransactions();
} else {
eth.disableTransactions();
}
eth.onSyncDone(done);
}
public boolean isDiscoveryMode() {
return discoveryMode;
}
public String getPeerId() {
return node == null ? "<null>" : node.getHexId();
}
public String getPeerIdShort() {
return node == null ? (remoteId != null && remoteId.length() >= 8 ? remoteId.substring(0,8) :remoteId)
: node.getHexIdShort();
}
public byte[] getNodeId() {
return node == null ? null : node.getId();
}
/**
* Indicates whether this connection was initiated by our peer
*/
public boolean isActive() {
return isActive;
}
public ByteArrayWrapper getNodeIdWrapper() {
return node == null ? null : new ByteArrayWrapper(node.getId());
}
public void disconnect(ReasonCode reason) {
getNodeStatistics().nodeDisconnectedLocal(reason);
msgQueue.disconnect(reason);
}
public InetSocketAddress getInetSocketAddress() {
return inetSocketAddress;
}
public PeerStatistics getPeerStats() {
return peerStats;
}
// ETH sub protocol
public void fetchBlockBodies(List<BlockHeaderWrapper> headers) {
eth.fetchBodies(headers);
}
public boolean isEthCompatible(Channel peer) {
return peer != null && peer.getEthVersion().isCompatible(getEthVersion());
}
public Eth getEthHandler() {
return eth;
}
public boolean hasEthStatusSucceeded() {
return eth.hasStatusSucceeded();
}
public String logSyncStats() {
return eth.getSyncStats();
}
public BigInteger getTotalDifficulty() {
return getEthHandler().getTotalDifficulty();
}
public SyncStatistics getSyncStats() {
return eth.getStats();
}
public boolean isHashRetrievingDone() {
return eth.isHashRetrievingDone();
}
public boolean isHashRetrieving() {
return eth.isHashRetrieving();
}
public boolean isMaster() {
return eth.isHashRetrieving() || eth.isHashRetrievingDone();
}
public boolean isIdle() {
return eth.isIdle();
}
public void prohibitTransactionProcessing() {
eth.disableTransactions();
}
/**
* Send transactions from input to peer corresponded with channel
* Using {@link #sendTransactionsCapped(List)} is recommended instead
* @param txs Transactions
*/
public void sendTransactions(List<Transaction> txs) {
eth.sendTransaction(txs);
}
/**
* Sames as {@link #sendTransactions(List)} but input list is randomly sliced to
* contain not more than {@link #MAX_SAFE_TXS} if needed
* @param txs List of txs to send
*/
public void sendTransactionsCapped(List<Transaction> txs) {
List<Transaction> slicedTxs;
if (txs.size() <= MAX_SAFE_TXS) {
slicedTxs = txs;
} else {
slicedTxs = CollectionUtils.truncateRand(txs, MAX_SAFE_TXS);
}
eth.sendTransaction(slicedTxs);
}
public void sendNewBlock(Block block) {
eth.sendNewBlock(block);
}
public void sendNewBlockHashes(Block block) {
eth.sendNewBlockHashes(block);
}
public EthVersion getEthVersion() {
return eth.getVersion();
}
public void dropConnection() {
eth.dropConnection();
}
public ChannelManager getChannelManager() {
return channelManager;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Channel channel = (Channel) o;
if (inetSocketAddress != null ? !inetSocketAddress.equals(channel.inetSocketAddress) : channel.inetSocketAddress != null) return false;
if (node != null ? !node.equals(channel.node) : channel.node != null) return false;
return false;
}
@Override
public int hashCode() {
int result = inetSocketAddress != null ? inetSocketAddress.hashCode() : 0;
result = 31 * result + (node != null ? node.hashCode() : 0);
return result;
}
@Override
public String toString() {
return String.format("%s | %s", getPeerIdShort(), inetSocketAddress);
}
}
| 13,648
| 29.466518
| 143
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/BloomFilter.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import org.ethereum.util.ByteUtil;
import java.io.Serializable;
import java.util.BitSet;
/**
* The class mostly borrowed from http://github.com/magnuss/java-bloomfilter
*
* Implementation of a Bloom-filter, as described here:
* http://en.wikipedia.org/wiki/Bloom_filter
*
* For updates and bugfixes, see http://github.com/magnuss/java-bloomfilter
*
* Inspired by the SimpleBloomFilter-class written by Ian Clarke. This
* implementation provides a more evenly distributed Hash-function by
* using a proper digest instead of the Java RNG. Many of the changes
* were proposed in comments in his blog:
* http://blog.locut.us/2008/01/12/a-decent-stand-alone-java-bloom-filter-implementation/
*
* @author Magnus Skjegstad <magnus@skjegstad.com>
*/
public class BloomFilter implements Serializable {
private BitSet bitset;
private int bitSetSize;
private double bitsPerElement;
private int expectedNumberOfFilterElements; // expected (maximum) number of elements to be added
private int numberOfAddedElements; // number of elements actually added to the Bloom filter
private int k; // number of hash functions
/**
* Constructs an empty Bloom filter. The total length of the Bloom filter will be
* c*n.
*
* @param c is the number of bits used per element.
* @param n is the expected number of elements the filter will contain.
* @param k is the number of hash functions used.
*/
public BloomFilter(double c, int n, int k) {
this.expectedNumberOfFilterElements = n;
this.k = k;
this.bitsPerElement = c;
this.bitSetSize = (int)Math.ceil(c * n);
numberOfAddedElements = 0;
this.bitset = new BitSet(bitSetSize);
}
/**
* Constructs an empty Bloom filter. The optimal number of hash functions (k) is estimated from the total size of the Bloom
* and the number of expected elements.
*
* @param bitSetSize defines how many bits should be used in total for the filter.
* @param expectedNumberOElements defines the maximum number of elements the filter is expected to contain.
*/
public BloomFilter(int bitSetSize, int expectedNumberOElements) {
this(bitSetSize / (double)expectedNumberOElements,
expectedNumberOElements,
(int) Math.round((bitSetSize / (double) expectedNumberOElements) * Math.log(2.0)));
}
/**
* Constructs an empty Bloom filter with a given false positive probability. The number of bits per
* element and the number of hash functions is estimated
* to match the false positive probability.
*
* @param falsePositiveProbability is the desired false positive probability.
* @param expectedNumberOfElements is the expected number of elements in the Bloom filter.
*/
public BloomFilter(double falsePositiveProbability, int expectedNumberOfElements) {
this(Math.ceil(-(Math.log(falsePositiveProbability) / Math.log(2))) / Math.log(2), // c = k / ln(2)
expectedNumberOfElements,
(int)Math.ceil(-(Math.log(falsePositiveProbability) / Math.log(2)))); // k = ceil(-log_2(false prob.))
}
/**
* Construct a new Bloom filter based on existing Bloom filter data.
*
* @param bitSetSize defines how many bits should be used for the filter.
* @param expectedNumberOfFilterElements defines the maximum number of elements the filter is expected to contain.
* @param actualNumberOfFilterElements specifies how many elements have been inserted into the <code>filterData</code> BitSet.
* @param filterData a BitSet representing an existing Bloom filter.
*/
public BloomFilter(int bitSetSize, int expectedNumberOfFilterElements, int actualNumberOfFilterElements, BitSet filterData) {
this(bitSetSize, expectedNumberOfFilterElements);
this.bitset = filterData;
this.numberOfAddedElements = actualNumberOfFilterElements;
}
/**
* Compares the contents of two instances to see if they are equal.
*
* @param obj is the object to compare to.
* @return True if the contents of the objects are equal.
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BloomFilter other = (BloomFilter) obj;
if (this.expectedNumberOfFilterElements != other.expectedNumberOfFilterElements) {
return false;
}
if (this.k != other.k) {
return false;
}
if (this.bitSetSize != other.bitSetSize) {
return false;
}
if (this.bitset != other.bitset && (this.bitset == null || !this.bitset.equals(other.bitset))) {
return false;
}
return true;
}
/**
* Calculates a hash code for this class.
* @return hash code representing the contents of an instance of this class.
*/
@Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + (this.bitset != null ? this.bitset.hashCode() : 0);
hash = 61 * hash + this.expectedNumberOfFilterElements;
hash = 61 * hash + this.bitSetSize;
hash = 61 * hash + this.k;
return hash;
}
/**
* Calculates the expected probability of false positives based on
* the number of expected filter elements and the size of the Bloom filter.
* <br /><br />
* The value returned by this method is the <i>expected</i> rate of false
* positives, assuming the number of inserted elements equals the number of
* expected elements. If the number of elements in the Bloom filter is less
* than the expected value, the true probability of false positives will be lower.
*
* @return expected probability of false positives.
*/
public double expectedFalsePositiveProbability() {
return getFalsePositiveProbability(expectedNumberOfFilterElements);
}
/**
* Calculate the probability of a false positive given the specified
* number of inserted elements.
*
* @param numberOfElements number of inserted elements.
* @return probability of a false positive.
*/
public double getFalsePositiveProbability(double numberOfElements) {
// (1 - e^(-k * n / m)) ^ k
return Math.pow((1 - Math.exp(-k * (double) numberOfElements
/ (double) bitSetSize)), k);
}
/**
* Get the current probability of a false positive. The probability is calculated from
* the size of the Bloom filter and the current number of elements added to it.
*
* @return probability of false positives.
*/
public double getFalsePositiveProbability() {
return getFalsePositiveProbability(numberOfAddedElements);
}
/**
* Returns the value chosen for K.<br />
* <br />
* K is the optimal number of hash functions based on the size
* of the Bloom filter and the expected number of inserted elements.
*
* @return optimal k.
*/
public int getK() {
return k;
}
/**
* Sets all bits to false in the Bloom filter.
*/
public synchronized void clear() {
bitset.clear();
numberOfAddedElements = 0;
}
/**
* Adds an array of bytes to the Bloom filter.
*
* @param bytes array of bytes to add to the Bloom filter.
*/
public synchronized void add(byte[] bytes) {
int[] hashes = createHashes(bytes, k);
for (int hash : hashes)
bitset.set(Math.abs(hash % bitSetSize), true);
numberOfAddedElements ++;
}
private int[] createHashes(byte[] bytes, int k) {
int[] ret = new int[k];
if (bytes.length / 4 < k) {
int[] maxHashes = new int[bytes.length / 4];
ByteUtil.bytesToInts(bytes, maxHashes, false);
for (int i = 0; i < ret.length; i++) {
ret[i] = maxHashes[i % maxHashes.length];
}
} else {
ByteUtil.bytesToInts(bytes, ret, false);
}
return ret;
}
/**
* Returns true if the array of bytes could have been inserted into the Bloom filter.
* Use getFalsePositiveProbability() to calculate the probability of this
* being correct.
*
* @param bytes array of bytes to check.
* @return true if the array could have been inserted into the Bloom filter.
*/
public synchronized boolean contains(byte[] bytes) {
int[] hashes = createHashes(bytes, k);
for (int hash : hashes) {
if (!bitset.get(Math.abs(hash % bitSetSize))) {
return false;
}
}
return true;
}
/**
* Read a single bit from the Bloom filter.
* @param bit the bit to read.
* @return true if the bit is set, false if it is not.
*/
public synchronized boolean getBit(int bit) {
return bitset.get(bit);
}
/**
* Set a single bit in the Bloom filter.
* @param bit is the bit to set.
* @param value If true, the bit is set. If false, the bit is cleared.
*/
public synchronized void setBit(int bit, boolean value) {
bitset.set(bit, value);
}
/**
* Return the bit set used to store the Bloom filter.
* @return bit set representing the Bloom filter.
*/
public synchronized BitSet getBitSet() {
return bitset;
}
/**
* Returns the number of bits in the Bloom filter. Use count() to retrieve
* the number of inserted elements.
*
* @return the size of the bitset used by the Bloom filter.
*/
public synchronized int size() {
return this.bitSetSize;
}
/**
* Returns the number of elements added to the Bloom filter after it
* was constructed or after clear() was called.
*
* @return number of elements added to the Bloom filter.
*/
public synchronized int count() {
return this.numberOfAddedElements;
}
/**
* Returns the expected number of elements to be inserted into the filter.
* This value is the same value as the one passed to the constructor.
*
* @return expected number of elements.
*/
public int getExpectedNumberOfElements() {
return expectedNumberOfFilterElements;
}
/**
* Get expected number of bits per element when the Bloom filter is full. This value is set by the constructor
* when the Bloom filter is created. See also getBitsPerElement().
*
* @return expected number of bits per element.
*/
public double getExpectedBitsPerElement() {
return this.bitsPerElement;
}
/**
* Get actual number of bits per element based on the number of elements that have currently been inserted and the length
* of the Bloom filter. See also getExpectedBitsPerElement().
*
* @return number of bits per element.
*/
public double getBitsPerElement() {
return this.bitSetSize / (double)numberOfAddedElements;
}
}
| 11,991
| 35.012012
| 130
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/AsyncWriteCache.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import com.google.common.util.concurrent.*;
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
import org.ethereum.util.ALock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by Anton Nashatyrev on 18.01.2017.
*/
public abstract class AsyncWriteCache<Key, Value> extends AbstractCachedSource<Key, Value> implements AsyncFlushable {
private static final Logger logger = LoggerFactory.getLogger("db");
private static ListeningExecutorService flushExecutor = MoreExecutors.listeningDecorator(
Executors.newFixedThreadPool(2, new ThreadFactoryBuilder().setNameFormat("AsyncWriteCacheThread-%d").build()));
protected volatile WriteCache<Key, Value> curCache;
protected WriteCache<Key, Value> flushingCache;
private ListenableFuture<Boolean> lastFlush = Futures.immediateFuture(false);
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
private final ALock rLock = new ALock(rwLock.readLock());
private final ALock wLock = new ALock(rwLock.writeLock());
private String name = "<null>";
public AsyncWriteCache(Source<Key, Value> source) {
super(source);
flushingCache = createCache(source);
flushingCache.setFlushSource(true);
curCache = createCache(flushingCache);
}
protected abstract WriteCache<Key, Value> createCache(Source<Key, Value> source);
@Override
public Collection<Key> getModified() {
try (ALock l = rLock.lock()) {
return curCache.getModified();
}
}
@Override
public boolean hasModified() {
try (ALock l = rLock.lock()) {
return curCache.hasModified();
}
}
@Override
public void put(Key key, Value val) {
try (ALock l = rLock.lock()) {
curCache.put(key, val);
}
}
@Override
public void delete(Key key) {
try (ALock l = rLock.lock()) {
curCache.delete(key);
}
}
@Override
public Value get(Key key) {
try (ALock l = rLock.lock()) {
return curCache.get(key);
}
}
@Override
public synchronized boolean flush() {
try {
flipStorage();
flushAsync();
return flushingCache.hasModified();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
Entry<Value> getCached(Key key) {
return curCache.getCached(key);
}
@Override
public synchronized void flipStorage() throws InterruptedException {
// if previous flush still running
try {
if (!lastFlush.isDone()) logger.debug("AsyncWriteCache (" + name + "): waiting for previous flush to complete");
lastFlush.get();
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
try (ALock l = wLock.lock()) {
flushingCache.cache = curCache.cache;
curCache = createCache(flushingCache);
}
}
public synchronized ListenableFuture<Boolean> flushAsync() throws InterruptedException {
logger.debug("AsyncWriteCache (" + name + "): flush submitted");
lastFlush = flushExecutor.submit(() -> {
logger.debug("AsyncWriteCache (" + name + "): flush started");
long s = System.currentTimeMillis();
boolean ret = flushingCache.flush();
logger.debug("AsyncWriteCache (" + name + "): flush completed in " + (System.currentTimeMillis() - s) + " ms");
return ret;
});
return lastFlush;
}
@Override
public long estimateCacheSize() {
// 2.0 is upper cache size estimation to take into account there are two
// caches may exist simultaneously up to doubling cache size
return (long) (curCache.estimateCacheSize() * 2.0);
}
@Override
protected synchronized boolean flushImpl() {
return false;
}
public AsyncWriteCache<Key, Value> withName(String name) {
this.name = name;
return this;
}
}
| 5,090
| 31.634615
| 124
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/JournalSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import org.ethereum.datasource.inmem.HashMapDB;
import org.ethereum.db.prune.Pruner;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPElement;
import org.ethereum.util.RLPList;
import java.util.ArrayList;
import java.util.List;
/**
* The JournalSource records all the changes which were made before each commitUpdate
* Unlike 'put' deletes are not propagated to the backing Source immediately but are
* delayed until {@link Pruner} accepts and persists changes for the corresponding hash.
*
* Normally this class is used together with State pruning: we need all the state nodes for last N
* blocks to be able to get back to previous state for applying fork block
* however we would like to delete 'zombie' nodes which are not referenced anymore by
* persisting update for the block CurrentBlockNumber - N and we would
* also like to remove the updates made by the blocks which weren't too lucky
* to remain on the main chain by reverting update for such blocks
*
* @see Pruner
*
* Created by Anton Nashatyrev on 08.11.2016.
*/
public class JournalSource<V> extends AbstractChainedSource<byte[], V, byte[], V>
implements HashedKeySource<byte[], V> {
public static class Update {
byte[] updateHash;
List<byte[]> insertedKeys = new ArrayList<>();
List<byte[]> deletedKeys = new ArrayList<>();
public Update() {
}
public Update(byte[] bytes) {
parse(bytes);
}
public byte[] serialize() {
byte[][] insertedBytes = new byte[insertedKeys.size()][];
for (int i = 0; i < insertedBytes.length; i++) {
insertedBytes[i] = RLP.encodeElement(insertedKeys.get(i));
}
byte[][] deletedBytes = new byte[deletedKeys.size()][];
for (int i = 0; i < deletedBytes.length; i++) {
deletedBytes[i] = RLP.encodeElement(deletedKeys.get(i));
}
return RLP.encodeList(RLP.encodeElement(updateHash),
RLP.encodeList(insertedBytes), RLP.encodeList(deletedBytes));
}
private void parse(byte[] encoded) {
RLPList l = (RLPList) RLP.decode2(encoded).get(0);
updateHash = l.get(0).getRLPData();
for (RLPElement aRInserted : (RLPList) l.get(1)) {
insertedKeys.add(aRInserted.getRLPData());
}
for (RLPElement aRDeleted : (RLPList) l.get(2)) {
deletedKeys.add(aRDeleted.getRLPData());
}
}
public List<byte[]> getInsertedKeys() {
return insertedKeys;
}
public List<byte[]> getDeletedKeys() {
return deletedKeys;
}
}
private Update currentUpdate = new Update();
Source<byte[], Update> journal = new HashMapDB<>();
/**
* Constructs instance with the underlying backing Source
*/
public JournalSource(Source<byte[], V> src) {
super(src);
}
public void setJournalStore(Source<byte[], byte[]> journalSource) {
journal = new SourceCodec.BytesKey<>(journalSource,
new Serializer<Update, byte[]>() {
public byte[] serialize(Update object) { return object.serialize(); }
public Update deserialize(byte[] stream) { return stream == null ? null : new Update(stream); }
});
}
/**
* Inserts are immediately propagated to the backing Source
* though are still recorded to the current update
* The insert might later be reverted by {@link Pruner}
*/
@Override
public synchronized void put(byte[] key, V val) {
if (val == null) {
delete(key);
return;
}
getSource().put(key, val);
currentUpdate.insertedKeys.add(key);
}
/**
* Deletes are not propagated to the backing Source immediately
* but instead they are recorded to the current Update and
* might be later persisted
*/
@Override
public synchronized void delete(byte[] key) {
currentUpdate.deletedKeys.add(key);
}
@Override
public synchronized V get(byte[] key) {
return getSource().get(key);
}
/**
* Records all the changes made prior to this call to a single chunk
* with supplied hash.
* Later those updates could be either persisted to backing Source (deletes only)
* or reverted from the backing Source (inserts only)
*/
public synchronized Update commitUpdates(byte[] updateHash) {
currentUpdate.updateHash = updateHash;
journal.put(updateHash, currentUpdate);
Update committed = currentUpdate;
currentUpdate = new Update();
return committed;
}
public Source<byte[], Update> getJournal() {
return journal;
}
@Override
public synchronized boolean flushImpl() {
journal.flush();
return false;
}
}
| 5,780
| 33.410714
| 115
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/DbSettings.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Defines configurable database settings
*
* @author Mikhail Kalinin
* @since 26.04.2018
*/
public class DbSettings {
public static final DbSettings DEFAULT = new DbSettings()
.withMaxThreads(1)
.withMaxOpenFiles(32);
int maxOpenFiles;
int maxThreads;
private DbSettings() {
}
public static DbSettings newInstance() {
DbSettings settings = new DbSettings();
settings.maxOpenFiles = DEFAULT.maxOpenFiles;
settings.maxThreads = DEFAULT.maxThreads;
return settings;
}
public int getMaxOpenFiles() {
return maxOpenFiles;
}
public DbSettings withMaxOpenFiles(int maxOpenFiles) {
this.maxOpenFiles = maxOpenFiles;
return this;
}
public int getMaxThreads() {
return maxThreads;
}
public DbSettings withMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
return this;
}
}
| 1,776
| 27.206349
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/XorDataSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import org.ethereum.util.ByteUtil;
/**
* When propagating changes to the backing Source XORs keys
* with the specified value
*
* May be useful for merging several Sources into a single
*
* Created by Anton Nashatyrev on 18.02.2016.
*/
public class XorDataSource<V> extends AbstractChainedSource<byte[], V, byte[], V> {
private byte[] subKey;
/**
* Creates instance with a value all keys are XORed with
*/
public XorDataSource(Source<byte[], V> source, byte[] subKey) {
super(source);
this.subKey = subKey;
}
private byte[] convertKey(byte[] key) {
return ByteUtil.xorAlignRight(key, subKey);
}
@Override
public V get(byte[] key) {
return getSource().get(convertKey(key));
}
@Override
public void put(byte[] key, V value) {
getSource().put(convertKey(key), value);
}
@Override
public void delete(byte[] key) {
getSource().delete(convertKey(key));
}
@Override
protected boolean flushImpl() {
return false;
}
}
| 1,884
| 28
| 83
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/Serializers.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import org.ethereum.core.AccountState;
import org.ethereum.core.BlockHeader;
import org.ethereum.util.RLP;
import org.ethereum.util.Value;
import org.ethereum.vm.DataWord;
/**
* Collection of common Serializers
* Created by Anton Nashatyrev on 08.11.2016.
*/
public class Serializers {
/**
* No conversion
*/
public static class Identity<T> implements Serializer<T, T> {
@Override
public T serialize(T object) {
return object;
}
@Override
public T deserialize(T stream) {
return stream;
}
}
/**
* Serializes/Deserializes AccountState instances from the State Trie (part of Ethereum spec)
*/
public final static Serializer<AccountState, byte[]> AccountStateSerializer = new Serializer<AccountState, byte[]>() {
@Override
public byte[] serialize(AccountState object) {
return object.getEncoded();
}
@Override
public AccountState deserialize(byte[] stream) {
return stream == null || stream.length == 0 ? null : new AccountState(stream);
}
};
/**
* Contract storage key serializer
*/
public final static Serializer<DataWord, byte[]> StorageKeySerializer = new Serializer<DataWord, byte[]>() {
@Override
public byte[] serialize(DataWord object) {
return object.getData();
}
@Override
public DataWord deserialize(byte[] stream) {
return DataWord.of(stream);
}
};
/**
* Contract storage value serializer (part of Ethereum spec)
*/
public final static Serializer<DataWord, byte[]> StorageValueSerializer = new Serializer<DataWord, byte[]>() {
@Override
public byte[] serialize(DataWord object) {
return RLP.encodeElement(object.getNoLeadZeroesData());
}
@Override
public DataWord deserialize(byte[] stream) {
if (stream == null || stream.length == 0) return null;
byte[] dataDecoded = RLP.decode2(stream).get(0).getRLPData();
return DataWord.of(dataDecoded);
}
};
/**
* Trie node serializer (part of Ethereum spec)
*/
public final static Serializer<Value, byte[]> TrieNodeSerializer = new Serializer<Value, byte[]>() {
@Override
public byte[] serialize(Value object) {
return object.asBytes();
}
@Override
public Value deserialize(byte[] stream) {
return new Value(stream);
}
};
/**
* Trie node serializer (part of Ethereum spec)
*/
public final static Serializer<BlockHeader, byte[]> BlockHeaderSerializer = new Serializer<BlockHeader, byte[]>() {
@Override
public byte[] serialize(BlockHeader object) {
return object == null ? null : object.getEncoded();
}
@Override
public BlockHeader deserialize(byte[] stream) {
return stream == null ? null : new BlockHeader(stream);
}
};
/**
* AS IS serializer (doesn't change anything)
*/
public final static Serializer<byte[], byte[]> AsIsSerializer = new Serializer<byte[], byte[]>() {
@Override
public byte[] serialize(byte[] object) {
return object;
}
@Override
public byte[] deserialize(byte[] stream) {
return stream;
}
};
}
| 4,289
| 30.086957
| 122
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/BatchSourceWriter.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Clue class between Source and BatchSource
*
* Created by Anton Nashatyrev on 29.11.2016.
*/
public class BatchSourceWriter<Key, Value> extends AbstractChainedSource<Key, Value, Key, Value> {
Map<Key, Value> buf = new HashMap<>();
public BatchSourceWriter(BatchSource<Key, Value> src) {
super(src);
}
private BatchSource<Key, Value> getBatchSource() {
return (BatchSource<Key, Value>) getSource();
}
@Override
public synchronized void delete(Key key) {
buf.put(key, null);
}
@Override
public synchronized void put(Key key, Value val) {
buf.put(key, val);
}
@Override
public Value get(Key key) {
return getSource().get(key);
}
@Override
public synchronized boolean flushImpl() {
if (!buf.isEmpty()) {
getBatchSource().updateBatch(buf);
buf.clear();
return true;
} else {
return false;
}
}
}
| 1,906
| 27.462687
| 98
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/BloomedSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import org.ethereum.crypto.HashUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Special optimization when the majority of get requests to the slower underlying source
* are targeted to missing entries. The BloomFilter handles most of these requests.
*
* Created by Anton Nashatyrev on 16.01.2017.
*/
public class BloomedSource extends AbstractChainedSource<byte[], byte[], byte[], byte[]> {
private final static Logger logger = LoggerFactory.getLogger("db");
private byte[] filterKey = HashUtil.sha3("filterKey".getBytes());
QuotientFilter filter;
int hits = 0;
int misses = 0;
int falseMisses = 0;
boolean dirty = false;
int maxBloomSize;
public BloomedSource(Source<byte[], byte[]> source, int maxBloomSize) {
super(source);
this.maxBloomSize = maxBloomSize;
byte[] filterBytes = source.get(filterKey);
if (filterBytes != null) {
if (filterBytes.length > 0) {
filter = QuotientFilter.deserialize(filterBytes);
} else {
// filter size exceeded limit and is disabled forever
filter = null;
}
} else {
if (maxBloomSize > 0) {
filter = QuotientFilter.create(50_000_000, 100_000);
} else {
// we can't re-enable filter later
getSource().put(filterKey, new byte[0]);
}
}
//
// new Thread() {
// @Override
// public void run() {
// while(true) {
// synchronized (BloomedSource.this) {
// logger.debug("BloomedSource: hits: " + hits + ", misses: " + misses + ", false: " + falseMisses);
// hits = misses = falseMisses = 0;
// }
//
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {}
// }
// }
// }.start();
}
public void startBlooming(QuotientFilter filter) {
this.filter = filter;
}
public void stopBlooming() {
filter = null;
}
@Override
public void put(byte[] key, byte[] val) {
if (filter != null) {
filter.insert(key);
dirty = true;
if (filter.getAllocatedBytes() > maxBloomSize) {
logger.info("Bloom filter became too large (" + filter.getAllocatedBytes() + " exceeds max threshold " + maxBloomSize + ") and is now disabled forever.");
getSource().put(filterKey, new byte[0]);
filter = null;
dirty = false;
}
}
getSource().put(key, val);
}
@Override
public byte[] get(byte[] key) {
if (filter == null) return getSource().get(key);
if (!filter.maybeContains(key)) {
hits++;
return null;
} else {
byte[] ret = getSource().get(key);
if (ret == null) falseMisses++;
else misses++;
return ret;
}
}
@Override
public void delete(byte[] key) {
if (filter != null) filter.remove(key);
getSource().delete(key);
}
@Override
protected boolean flushImpl() {
if (filter != null && dirty) {
getSource().put(filterKey, filter.serialize());
dirty = false;
return true;
} else {
return false;
}
}
}
| 4,346
| 31.440299
| 170
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/QuotientFilter.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright (C) 2016 DataStax Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//Parts of this file are copyrighted by Vedant Kumar <vsk@berkeley.edu>
//https://github.com/aweisberg/quotient-filter/commit/54539e6e287c7f68139733c65ecc4873e2872d54
/*
* qf.c
*
* Copyright (c) 2014 Vedant Kumar <vsk@berkeley.edu>
*/
/*
Copyright (c) 2014 Vedant Kumar <vsk@berkeley.edu>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software. THE SOFTWARE IS
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
package org.ethereum.datasource;
import com.google.common.base.Preconditions;
import com.google.common.math.LongMath;
import com.google.common.primitives.Ints;
import org.ethereum.util.ByteUtil;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static java.lang.System.arraycopy;
import static java.lang.System.in;
import static java.util.Arrays.copyOfRange;
import static org.ethereum.util.ByteUtil.byteArrayToLong;
import static org.ethereum.util.ByteUtil.longToBytes;
//import net.jpountz.xxhash.XXHashFactory;
public class QuotientFilter implements Iterable<Long> {
// static final XXHashFactory hashFactory = XXHashFactory.fastestInstance();
byte QUOTIENT_BITS;
byte REMAINDER_BITS;
byte ELEMENT_BITS;
long INDEX_MASK;
long REMAINDER_MASK;
long ELEMENT_MASK;
long MAX_SIZE;
long MAX_INSERTIONS;
int MAX_DUPLICATES = 2;
long[] table;
boolean overflowed = false;
long entries;
public static QuotientFilter deserialize(byte[] bytes) {
QuotientFilter ret = new QuotientFilter();
ret.QUOTIENT_BITS = bytes[0];
ret.REMAINDER_BITS = bytes[1];
ret.ELEMENT_BITS = bytes[2];
ret.INDEX_MASK = byteArrayToLong(copyOfRange(bytes, 3, 11));
ret.REMAINDER_MASK = byteArrayToLong(copyOfRange(bytes, 11, 19));
ret.ELEMENT_MASK = byteArrayToLong(copyOfRange(bytes, 19, 27));
ret.MAX_SIZE = byteArrayToLong(copyOfRange(bytes, 27, 35));
ret.MAX_INSERTIONS = byteArrayToLong(copyOfRange(bytes, 35, 43));
ret.overflowed = bytes[43] > 0;
ret.entries = byteArrayToLong(copyOfRange(bytes, 44, 52));
ret.table = new long[(bytes.length - 52) / 8];
for (int i = 0; i < ret.table.length; i++) {
ret.table[i] = byteArrayToLong(copyOfRange(bytes, 52 + i * 8, 52 + i * 8 + 8));
}
return ret;
}
public synchronized byte[] serialize() {
byte[] ret = new byte[1 + 1 + 1 + 8 + 8 + 8 + 8 + 8 + 1 + 8 + table.length * 8];
ret[0] = QUOTIENT_BITS;
ret[1] = REMAINDER_BITS;
ret[2] = ELEMENT_BITS;
arraycopy(longToBytes(INDEX_MASK), 0, ret, 3, 8);
arraycopy(longToBytes(REMAINDER_MASK), 0, ret, 11, 8);
arraycopy(longToBytes(ELEMENT_MASK), 0, ret, 19, 8);
arraycopy(longToBytes(MAX_SIZE), 0, ret, 27, 8);
arraycopy(longToBytes(MAX_INSERTIONS), 0, ret, 35, 8);
ret[43] = (byte) (overflowed ? 1 : 0);
arraycopy(longToBytes(entries), 0, ret, 44, 8);
for (int i = 0; i < table.length; i++) {
arraycopy(longToBytes(table[i]), 0, ret, 52 + i * 8, 8);
}
return ret;
}
static long LOW_MASK(long n) {
return (1L << n) - 1L;
}
static int TABLE_SIZE(int quotientBits, int remainderBits) {
long bits = (1L << quotientBits) * (remainderBits + 3);
long longs = bits / 64;
return Ints.checkedCast((bits % 64) > 0 ? (longs + 1) : longs);
}
static int bitsForNumElementsWithLoadFactor(long numElements) {
if (numElements == 0) {
return 1;
}
int candidateBits = Long.bitCount(numElements) == 1 ?
Math.max(1, Long.numberOfTrailingZeros(numElements)) :
Long.numberOfTrailingZeros(Long.highestOneBit(numElements) << 1L);
//May need an extra bit due to load factor
if (((long) (LongMath.pow(2, candidateBits) * 0.75)) < numElements) {
candidateBits++;
}
return candidateBits;
}
public static QuotientFilter create(long largestNumberOfElements, long startingElements) {
Preconditions.checkArgument(largestNumberOfElements >= startingElements);
Preconditions.checkArgument(startingElements > 0);
Preconditions.checkArgument(largestNumberOfElements > 0);
/**
* The way sizing a quotient filter works is that the quotient bits + remainder bits
* is the maximum number of elements the filter can store before it runs out of fingerprint bits
* and can no longer be resized.
*/
int quotientBits = bitsForNumElementsWithLoadFactor(startingElements);
int remainderBits = bitsForNumElementsWithLoadFactor(largestNumberOfElements);
//I am pretty sure that even when completely full you want a non-zero number of remainder bits
//This also gives some emergency slack where even if you guess largest number of elements wrong it will
//keep working even if you are very wrong.
remainderBits += 8;
remainderBits -= quotientBits;
return new QuotientFilter(quotientBits, remainderBits);
}
private QuotientFilter() {}
public QuotientFilter(int quotientBits, int remainderBits) {
Preconditions.checkArgument(quotientBits > 0);
Preconditions.checkArgument(remainderBits > 0);
Preconditions.checkArgument(quotientBits + remainderBits <= 64);
QUOTIENT_BITS = (byte) quotientBits;
REMAINDER_BITS = (byte) remainderBits;
ELEMENT_BITS = (byte) (REMAINDER_BITS + 3);
INDEX_MASK = LOW_MASK(QUOTIENT_BITS);
REMAINDER_MASK = LOW_MASK(REMAINDER_BITS);
ELEMENT_MASK = LOW_MASK(ELEMENT_BITS);
MAX_SIZE = 1L << QUOTIENT_BITS;
MAX_INSERTIONS = (long) (MAX_SIZE * .75);
table = new long[TABLE_SIZE(QUOTIENT_BITS, REMAINDER_BITS)];
entries = 0;
}
public QuotientFilter withMaxDuplicates(int maxDuplicates) {
MAX_DUPLICATES = maxDuplicates;
return this;
}
/* Return QF[idx] in the lower bits. */
long getElement(long idx) {
long elt = 0;
long bitpos = ELEMENT_BITS * idx;
int tabpos = Ints.checkedCast(bitpos / 64);
long slotpos = bitpos % 64;
long spillbits = (slotpos + ELEMENT_BITS) - 64;
elt = (table[tabpos] >>> slotpos) & ELEMENT_MASK;
if (spillbits > 0) {
++tabpos;
long x = table[tabpos] & LOW_MASK(spillbits);
elt |= x << (ELEMENT_BITS - spillbits);
}
return elt;
}
/* Store the lower bits of elt into QF[idx]. */
void setElement(long idx, long elt) {
long bitpos = ELEMENT_BITS * idx;
int tabpos = Ints.checkedCast(bitpos / 64);
long slotpos = bitpos % 64;
long spillbits = (slotpos + ELEMENT_BITS) - 64;
elt &= ELEMENT_MASK;
table[tabpos] &= ~(ELEMENT_MASK << slotpos);
table[tabpos] |= elt << slotpos;
if (spillbits > 0) {
++tabpos;
table[tabpos] &= ~LOW_MASK(spillbits);
table[tabpos] |= elt >>> (ELEMENT_BITS - spillbits);
}
}
long incrementIndex(long idx) {
return (idx + 1) & INDEX_MASK;
}
long decrementIndex(long idx) {
return (idx - 1) & INDEX_MASK;
}
static boolean isElementOccupied(long elt) {
return (elt & 1) != 0;
}
static long setElementOccupied(long elt) {
return elt | 1;
}
static long clearElementOccupied(long elt) {
return elt & ~1;
}
static boolean isElementContinuation(long elt) {
return (elt & 2) != 0;
}
static long setElementContinuation(long elt) {
return elt | 2;
}
static long clearElementContinuation(long elt) {
return elt & ~2;
}
static boolean isElementShifted(long elt) {
return (elt & 4) != 0;
}
static long setElementShifted(long elt) {
return elt | 4;
}
static long clearElementShifted(long elt) {
return elt & ~4;
}
static long getElementRemainder(long elt) {
return elt >>> 3;
}
static boolean isElementEmpty(long elt) {
return (elt & 7) == 0;
}
static boolean isElementClusterStart(long elt) {
return isElementOccupied(elt) & !isElementContinuation(elt) & !isElementShifted(elt);
}
static boolean isElementRunStart(long elt) {
return !isElementContinuation(elt) & (isElementOccupied(elt) | isElementShifted(elt));
}
long hashToQuotient(long hash) {
return (hash >>> REMAINDER_BITS) & INDEX_MASK;
}
long hashToRemainder(long hash) {
return hash & REMAINDER_MASK;
}
/* Find the start index of the run for fq (given that the run exists). */
long findRunIndex(long fq) {
/* Find the start of the cluster. */
long b = fq;
while (isElementShifted(getElement(b))) {
b = decrementIndex(b);
}
/* Find the start of the run for fq. */
long s = b;
while (b != fq) {
do {
s = incrementIndex(s);
}
while (isElementContinuation(getElement(s)));
do {
b = incrementIndex(b);
}
while (!isElementOccupied(getElement(b)));
}
return s;
}
/* Insert elt into QF[s], shifting over elements as necessary. */
void insertInto(long s, long elt) {
long prev;
long curr = elt;
boolean empty;
do {
prev = getElement(s);
empty = isElementEmpty(prev);
if (!empty) {
/* Fix up `is_shifted' and `is_occupied'. */
prev = setElementShifted(prev);
if (isElementOccupied(prev)) {
curr = setElementOccupied(curr);
prev = clearElementOccupied(prev);
}
}
setElement(s, curr);
curr = prev;
s = incrementIndex(s);
}
while (!empty);
}
public boolean overflowed() {
return overflowed;
}
// public void insert(byte[] data)
// {
// insert(data, 0, data.length);
// }
//
// public void insert(byte[] data, int offset, int length) {
// insert(hashFactory.hash64().hash(data, offset, length, 0));
// }
protected long hash(byte[] bytes) {
return (bytes[0] & 0xFFL) << 56 |
(bytes[1] & 0xFFL) << 48 |
(bytes[2] & 0xFFL) << 40 |
(bytes[3] & 0xFFL) << 32 |
(bytes[4] & 0xFFL) << 24 |
(bytes[5] & 0xFFL) << 16 |
(bytes[6] & 0xFFL) << 8 |
(bytes[7] & 0xFFL);
}
public synchronized void insert(byte[] hash) {
insert(hash(hash));
}
public synchronized void insert(long hash) {
if (maybeContainsXTimes(hash, MAX_DUPLICATES)) return;
if (entries >= MAX_INSERTIONS | overflowed) {
//Can't safely process an after overflow
//Only a buggy program would attempt it
if (overflowed) {
throw new OverflowedError();
}
//Can still resize if we have enough remainder bits
if (REMAINDER_BITS > 1) {
selfResizeDouble();
} else {
//The filter can't accept more inserts and is effectively broken
overflowed = true;
throw new OverflowedError();
}
}
long fq = hashToQuotient(hash);
long fr = hashToRemainder(hash);
long T_fq = getElement(fq);
long entry = (fr << 3) & ~7;
/* Special-case filling canonical slots to simplify insert_into(). */
if (isElementEmpty(T_fq)) {
setElement(fq, setElementOccupied(entry));
++entries;
return;
}
if (!isElementOccupied(T_fq)) {
setElement(fq, setElementOccupied(T_fq));
}
long start = findRunIndex(fq);
long s = start;
if (isElementOccupied(T_fq)) {
/* Move the cursor to the insert position in the fq run. */
do {
long rem = getElementRemainder(getElement(s));
if (rem >= fr) {
break;
}
s = incrementIndex(s);
}
while (isElementContinuation(getElement(s)));
if (s == start) {
/* The old start-of-run becomes a continuation. */
long old_head = getElement(start);
setElement(start, setElementContinuation(old_head));
} else {
/* The new element becomes a continuation. */
entry = setElementContinuation(entry);
}
}
/* Set the shifted bit if we can't use the canonical slot. */
if (s != fq) {
entry = setElementShifted(entry);
}
insertInto(s, entry);
++entries;
return;
}
private void selfResizeDouble() {
QuotientFilter qf = resize(MAX_INSERTIONS * 2);
QUOTIENT_BITS = qf.QUOTIENT_BITS;
REMAINDER_BITS = qf.REMAINDER_BITS;
ELEMENT_BITS = qf.ELEMENT_BITS;
INDEX_MASK = qf.INDEX_MASK;
REMAINDER_MASK = qf.REMAINDER_MASK;
ELEMENT_MASK = qf.ELEMENT_MASK;
MAX_SIZE = qf.MAX_SIZE;
MAX_INSERTIONS = qf.MAX_INSERTIONS;
table = qf.table;
if (qf.entries != entries) {
throw new AssertionError();
}
}
public boolean maybeContains(byte[] hash) {
return maybeContains(hash(hash));
}
public synchronized boolean maybeContains(long hash) {
if (overflowed) {
//Can't check for existence after overflow occurred
//and things are missing
throw new OverflowedError();
}
long fq = hashToQuotient(hash);
long fr = hashToRemainder(hash);
long T_fq = getElement(fq);
/* If this quotient has no run, give up. */
if (!isElementOccupied(T_fq)) {
return false;
}
/* Scan the sorted run for the target remainder. */
long s = findRunIndex(fq);
do {
long rem = getElementRemainder(getElement(s));
if (rem == fr) {
return true;
} else if (rem > fr) {
return false;
}
s = incrementIndex(s);
}
while (isElementContinuation(getElement(s)));
return false;
}
public synchronized boolean maybeContainsXTimes(long hash, int num) {
if (overflowed) {
//Can't check for existence after overflow occurred
//and things are missing
throw new OverflowedError();
}
long fq = hashToQuotient(hash);
long fr = hashToRemainder(hash);
long T_fq = getElement(fq);
/* If this quotient has no run, give up. */
if (!isElementOccupied(T_fq)) {
return false;
}
/* Scan the sorted run for the target remainder. */
long s = findRunIndex(fq);
int counter = 0;
do {
long rem = getElementRemainder(getElement(s));
if (rem == fr) {
counter++;
} else if (rem > fr) {
break;
}
s = incrementIndex(s);
}
while (isElementContinuation(getElement(s)));
return counter >= num;
}
/* Remove the entry in QF[s] and slide the rest of the cluster forward. */
void deleteEntry(long s, long quot) {
long next;
long curr = getElement(s);
long sp = incrementIndex(s);
long orig = s;
/*
* FIXME(vsk): This loop looks ugly. Rewrite.
*/
while (true) {
next = getElement(sp);
boolean curr_occupied = isElementOccupied(curr);
if (isElementEmpty(next) | isElementClusterStart(next) | sp == orig) {
setElement(s, 0);
return;
} else {
/* Fix entries which slide into canonical slots. */
long updated_next = next;
if (isElementRunStart(next)) {
do {
quot = incrementIndex(quot);
}
while (!isElementOccupied(getElement(quot)));
if (curr_occupied && quot == s) {
updated_next = clearElementShifted(next);
}
}
setElement(s, curr_occupied ?
setElementOccupied(updated_next) :
clearElementOccupied(updated_next));
s = sp;
sp = incrementIndex(sp);
curr = next;
}
}
}
public void remove(byte[] hash) {
remove(hash(hash));
}
public synchronized void remove(long hash) {
if (maybeContainsXTimes(hash, MAX_DUPLICATES)) return;
//Can't safely process a remove after overflow
//Only a buggy program would attempt it
if (overflowed) {
throw new OverflowedError();
}
long fq = hashToQuotient(hash);
long fr = hashToRemainder(hash);
long T_fq = getElement(fq);
if (!isElementOccupied(T_fq) | entries == 0) {
//If you remove things that don't exist it's possible you will clobber
//somethign on a collision, your program is buggy
throw new NoSuchElementError();
}
long start = findRunIndex(fq);
long s = start;
long rem;
/* Find the offending table index (or give up). */
do {
rem = getElementRemainder(getElement(s));
if (rem == fr) {
break;
} else if (rem > fr) {
return;
}
s = incrementIndex(s);
} while (isElementContinuation(getElement(s)));
if (rem != fr) {
//If you remove things that don't exist it's possible you will clobber
//somethign on a collision, your program is buggy
throw new NoSuchElementError();
}
long kill = (s == fq) ? T_fq : getElement(s);
boolean replace_run_start = isElementRunStart(kill);
/* If we're deleting the last entry in a run, clear `is_occupied'. */
if (isElementRunStart(kill)) {
long next = getElement(incrementIndex(s));
if (!isElementContinuation(next)) {
T_fq = clearElementOccupied(T_fq);
setElement(fq, T_fq);
}
}
deleteEntry(s, fq);
if (replace_run_start) {
long next = getElement(s);
long updated_next = next;
if (isElementContinuation(next)) {
/* The new start-of-run is no longer a continuation. */
updated_next = clearElementContinuation(next);
}
if (s == fq && isElementRunStart(updated_next)) {
/* The new start-of-run is in the canonical slot. */
updated_next = clearElementShifted(updated_next);
}
if (updated_next != next) {
setElement(s, updated_next);
}
}
--entries;
}
// public static QuotientFilter merge(Collection<QuotientFilter> filters) {
// if (filters.stream().map(filter -> filter.REMAINDER_BITS + filter.QUOTIENT_BITS).distinct().count() != 1) {
// throw new IllegalArgumentException("All filters must have the same size fingerprint");
// }
//
// long totalEntries = filters.stream().collect(Collectors.summingLong(filter -> filter.entries));
// int requiredQuotientBits = bitsForNumElementsWithLoadFactor(totalEntries);
// int fingerprintBits = filters.iterator().next().QUOTIENT_BITS + filters.iterator().next().REMAINDER_BITS;
// int remainderBits = fingerprintBits - requiredQuotientBits;
//
// if (remainderBits < 1) {
// throw new IllegalArgumentException("Impossible to merge not enough fingerprint bits");
// }
//
// QuotientFilter resultFilter = new QuotientFilter(requiredQuotientBits, remainderBits);
//
// Iterable<QFIterator> iterators = (Iterable) filters.stream().map(filter -> filter.iterator()).collect(Collectors.toList());
// Iterator<Long> mergeQFIterator = Iterators.mergeSorted(iterators, Ordering.natural());
// while (mergeQFIterator.hasNext()) {
// resultFilter.insert(mergeQFIterator.next());
// }
// return resultFilter;
// }
// public QuotientFilter merge(QuotientFilter other) {
// return merge(ImmutableList.of(this, other));
// }
//
// public QuotientFilter merge(QuotientFilter... filters) {
// return merge(Arrays.asList(filters));
// }
/*
* Resizes the filter return a filter with the same contents and space for the minimum specified number
* of entries. This may allocate a new filter or return the existing filter.
*/
public QuotientFilter resize(long minimumEntries) {
if (minimumEntries <= MAX_INSERTIONS) {
return this;
}
int newQuotientBits = bitsForNumElementsWithLoadFactor(minimumEntries);
int newRemainderBits = QUOTIENT_BITS + REMAINDER_BITS - newQuotientBits;
if (newRemainderBits < 1) {
throw new IllegalArgumentException("Not enough fingerprint bits to resize");
}
QuotientFilter qf = new QuotientFilter(newQuotientBits, newRemainderBits);
QFIterator i = new QFIterator();
while (i.hasNext()) {
qf.insert(i.nextPrimitive());
}
return qf;
}
public int getAllocatedBytes() {
return table.length << 3;
}
public void clear() {
entries = 0;
Arrays.fill(table, 0L);
}
@Override
public QFIterator iterator() {
return new QFIterator();
}
class QFIterator implements LongIterator {
long index;
long quotient;
long visited;
QFIterator() {
/* Mark the iterator as done. */
visited = entries;
if (entries == 0) {
return;
}
/* Find the start of a cluster. */
long start;
for (start = 0; start < MAX_SIZE; ++start) {
if (isElementClusterStart(getElement(start))) {
break;
}
}
visited = 0;
index = start;
}
@Override
public boolean hasNext() {
return entries != visited;
}
@Override
public Long next() {
return nextPrimitive();
}
@Override
public void remove() {
}
public long nextPrimitive() {
while (hasNext()) {
long elt = getElement(index);
/* Keep track of the current run. */
if (isElementClusterStart(elt)) {
quotient = index;
} else {
if (isElementRunStart(elt)) {
long quot = quotient;
do {
quot = incrementIndex(quot);
}
while (!isElementOccupied(getElement(quot)));
quotient = quot;
}
}
index = incrementIndex(index);
if (!isElementEmpty(elt)) {
long quot = quotient;
long rem = getElementRemainder(elt);
long hash = (quot << REMAINDER_BITS) | rem;
++visited;
return hash;
}
}
throw new NoSuchElementException();
}
}
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
//
// int pad = ((int) (Math.ceil(QUOTIENT_BITS / Math.log(10.0)))) + 1;
//
// for (int i = 0; i < pad; ++i) {
// sb.append(' ');
// }
//
// sb.append(String.format("| is_shifted | is_continuation | is_occupied | remainder"
// + " nel=%d\n", entries));
//
// for (long idx = 0; idx < MAX_SIZE; ++idx) {
// String idxString = Long.toString(idx);
// sb.append(idx);
//
// int fillspace = pad - idxString.length();
// for (int i = 0; i < fillspace; ++i) {
// sb.append(' ');
// }
// sb.append("| ");
//
// long elt = getElement(idx);
// sb.append(String.format("%d | ", isElementShifted(elt) == false ? 0 : 1));
// sb.append(String.format("%d | ", isElementContinuation(elt) == false ? 0 : 1));
// sb.append(String.format("%d | ", isElementOccupied(elt) == false ? 0 : 1));
// sb.append(getElementRemainder(elt)).append(System.lineSeparator());
// }
// return sb.toString();
// }
public class OverflowedError extends AssertionError {
}
public class NoSuchElementError extends AssertionError {
}
public interface LongIterator extends Iterator<Long> {
long nextPrimitive();
@Override
Long next();
}
}
| 28,070
| 32.33848
| 133
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/CachedSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import java.util.Collection;
/**
* Source which internally caches underlying Source key-value pairs
*
* Created by Anton Nashatyrev on 21.10.2016.
*/
public interface CachedSource<Key, Value> extends Source<Key, Value> {
/**
* @return The underlying Source
*/
Source<Key, Value> getSource();
/**
* @return Modified entry keys if this is a write cache
*/
Collection<Key> getModified();
/**
* @return indicates the cache has modified entries
*/
boolean hasModified();
/**
* Estimates the size of cached entries in bytes.
* This value shouldn't be precise size of Java objects
* @return cache size in bytes
*/
long estimateCacheSize();
/**
* Just a convenient shortcut to the most popular Sources with byte[] key
*/
interface BytesKey<Value> extends CachedSource<byte[], Value> {}
}
| 1,714
| 29.625
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/AbstractChainedSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Abstract Source implementation with underlying backing Source
* The class has control whether the backing Source should be flushed
* in 'cascade' manner
*
* Created by Anton Nashatyrev on 06.12.2016.
*/
public abstract class AbstractChainedSource<Key, Value, SourceKey, SourceValue> implements Source<Key, Value> {
private Source<SourceKey, SourceValue> source;
protected boolean flushSource;
/**
* Intended for subclasses which wishes to initialize the source
* later via {@link #setSource(Source)} method
*/
protected AbstractChainedSource() {
}
public AbstractChainedSource(Source<SourceKey, SourceValue> source) {
this.source = source;
}
/**
* Intended for subclasses which wishes to initialize the source later
*/
protected void setSource(Source<SourceKey, SourceValue> src) {
source = src;
}
public Source<SourceKey, SourceValue> getSource() {
return source;
}
public void setFlushSource(boolean flushSource) {
this.flushSource = flushSource;
}
/**
* Invokes {@link #flushImpl()} and does backing Source flush if required
* @return true if this or source flush did any changes
*/
@Override
public synchronized boolean flush() {
boolean ret = flushImpl();
if (flushSource) {
ret |= getSource().flush();
}
return ret;
}
/**
* Should be overridden to do actual source flush
*/
protected abstract boolean flushImpl();
}
| 2,372
| 30.223684
| 111
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.