Search in sources :

Example 66 with Destination

use of net.i2p.data.Destination in project i2p.i2p-bote by i2p.

the class I2PPacketDispatcher method messageAvailable.

@Override
public void messageAvailable(I2PSession session, int msgId, long size) {
    byte[] msg = new byte[0];
    try {
        msg = session.receiveMessage(msgId);
    } catch (I2PSessionException e) {
        log.error("Can't get new message from I2PSession.", e);
    }
    if (msg == null) {
        log.error("I2PSession returned a null message: msgId=" + msgId + ", size=" + size + ", " + session);
        return;
    }
    I2PDatagramDissector datagramDissector = new I2PDatagramDissector();
    try {
        datagramDissector.loadI2PDatagram(msg);
        // TODO keep this line or remove it?
        datagramDissector.verifySignature();
        byte[] payload = datagramDissector.extractPayload();
        Destination sender = datagramDissector.getSender();
        dispatchPacket(payload, sender);
    } catch (DataFormatException e) {
        log.error("Invalid datagram received.", e);
    } catch (I2PInvalidDatagramException e) {
        log.error("Datagram failed verification.", e);
    } catch (Exception e) {
        log.error("Error processing datagram.", e);
    }
}
Also used : Destination(net.i2p.data.Destination) I2PDatagramDissector(net.i2p.client.datagram.I2PDatagramDissector) DataFormatException(net.i2p.data.DataFormatException) I2PSessionException(net.i2p.client.I2PSessionException) I2PInvalidDatagramException(net.i2p.client.datagram.I2PInvalidDatagramException) DataFormatException(net.i2p.data.DataFormatException) I2PSessionException(net.i2p.client.I2PSessionException) MalformedPacketException(i2p.bote.packet.MalformedPacketException) I2PInvalidDatagramException(net.i2p.client.datagram.I2PInvalidDatagramException)

Example 67 with Destination

use of net.i2p.data.Destination in project i2p.i2p-bote by i2p.

the class PeerList method toByteArray.

@Override
public byte[] toByteArray() {
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
    DataOutputStream dataStream = new DataOutputStream(arrayOutputStream);
    try {
        writeHeader(dataStream);
        dataStream.writeShort(peers.size());
        for (Destination peer : peers) // write the first 384 bytes (the two public keys)
        // TODO This is NOT compatible with newer key types!
        dataStream.write(peer.toByteArray(), 0, 384);
    } catch (IOException e) {
        log.error("Can't write to ByteArrayOutputStream.", e);
    }
    return arrayOutputStream.toByteArray();
}
Also used : Destination(net.i2p.data.Destination) DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 68 with Destination

use of net.i2p.data.Destination in project i2p.i2p-bote by i2p.

the class EmailPacketFolderTest method setUp.

@Before
public void setUp() throws Exception {
    File tempDir = new File(System.getProperty("java.io.tmpdir"));
    testDir = new File(tempDir, "EmailPacketFolderTest-" + System.currentTimeMillis());
    folderDir = new File(testDir, "dht_email_pkt");
    packetFolder = new EmailPacketFolder(folderDir);
    // make two UnencryptedEmailPackets with different contents
    byte[] content1 = "test TEST test ABCDEFGH asdfsadfsadf 3487562384".getBytes();
    byte[] content2 = "fdlkhgjfljh test 123456".getBytes();
    byte[] messageIdBytes = new byte[] { -69, -24, -109, 1, 69, -122, -69, 113, -68, -90, 55, -28, 105, 97, 125, 70, 51, 58, 14, 2, -13, -53, 90, -29, 36, 67, 36, -94, -108, -125, 11, 123 };
    UniqueId messageId = new UniqueId(messageIdBytes, 0);
    int fragmentIndex = 0;
    unencryptedPacket = new UnencryptedEmailPacket(new ByteArrayInputStream(content1), messageId, fragmentIndex, I2PBotePacket.MAX_DATAGRAM_SIZE);
    unencryptedPacket.setNumFragments(1);
    unencryptedPacket2 = new UnencryptedEmailPacket(new ByteArrayInputStream(content2), messageId, fragmentIndex, I2PBotePacket.MAX_DATAGRAM_SIZE);
    unencryptedPacket.setNumFragments(1);
    String base64Dest = "m-5~1dZ0MrGdyAWu-C2ecNAB5LCCsHQpeSfjn-r~mqMfNvroR98~BRmReUDmb0la-r-pBHLMtflrJE7aTrGwDTBm5~AJFEm-9SJPZnyGs-ed5pOj4Db65yJml1y1n77qr1~mM4GITl6KuIoxg8YwvPrCIlXe2hiiDCoC-uY9-np9UY";
    recipient = new EmailDestination(base64Dest);
    emailPacket = new EncryptedEmailPacket(unencryptedPacket, recipient);
    sender = new Destination("X3oKYQJ~1EAz7B1ZYGSrOTIMCW5Rnn2Svoc38dx5D9~zvz8vqiWcH-pCqQDwLgPWl9RTBzHtTmZcGRPXIv54i0XWeUfX6rTPDQGuZsnBMM0xrkH2FNLNFaJa0NgW3uKXWpNj9AI1AXUXzK-2MYTYoaZHx5SBoCaKfAGMcFJvTON1~kopxBxdBF9Q7T4~PJ3I2LeU-ycmUlehe9N9bIu7adUGyPGVl8Ka-UxwQromoJ~vSWHHl8HkwcDkW--v9Aj~wvFqxqriFkB1EeBiThi3V4XtVY~GUP4IkRj9YZGTsSBf3eS4xwXgnYWlB7IvxAGBfHY9MCg3lbAa1Dg~1IH6rhtXxsXUtGcXsz9yMZTxXHd~rGo~JrXeM1y~Vcenpr6tJcum6pxevkKzzT0qDegGPH3Zhqz7sSeeIaJEcPBUAkX89csqyFWFIjTMm6yZp2rW-QYUnVNLNTjf7vndYUAEICogAkq~btqpIzrGEpm3Pr9F23br3SpbOmdxQxg51AMmAAAA");
}
Also used : UniqueId(i2p.bote.UniqueId) EmailDestination(i2p.bote.email.EmailDestination) Destination(net.i2p.data.Destination) ByteArrayInputStream(java.io.ByteArrayInputStream) EncryptedEmailPacket(i2p.bote.packet.dht.EncryptedEmailPacket) EmailDestination(i2p.bote.email.EmailDestination) UnencryptedEmailPacket(i2p.bote.packet.dht.UnencryptedEmailPacket) File(java.io.File) Before(org.junit.Before)

Example 69 with Destination

use of net.i2p.data.Destination in project i2p.i2p-bote by i2p.

the class BucketManagerTest method test.

@Test
public void test() throws Exception {
    assertEquals(0, bucketManager.getPeerCount());
    assertEquals(0, bucketManager.getAllPeers().size());
    assertEquals(1, getNumKBuckets());
    // add S destinations
    for (int i = 0; i < S; i++) bucketManager.addOrUpdate(new KademliaPeer(peers[i]));
    assertEquals(S, bucketManager.getPeerCount());
    assertEquals(S, bucketManager.getAllPeers().size());
    assertEquals(1, getNumKBuckets());
    // add another K destinations
    int startIndex = S;
    for (int i = 0; i < K; i++) bucketManager.addOrUpdate(new KademliaPeer(peers[startIndex + i]));
    assertEquals(S + K, bucketManager.getPeerCount());
    assertEquals(S + K, bucketManager.getAllPeers().size());
    assertEquals(1, getNumKBuckets());
    // add one more destination, which should split the k-bucket
    int index = S + K;
    bucketManager.addOrUpdate(new KademliaPeer(peers[index]));
    assertEquals(S + K + 1, bucketManager.getPeerCount());
    assertEquals(S + K + 1, bucketManager.getAllPeers().size());
    // there should be at least 2 buckets after the split
    assertTrue(getNumKBuckets() >= 2);
    // add 4*K-1 more peers for a total of S + 5 * K
    startIndex = S + K + 1;
    for (int i = 0; i < 4 * K - 1; i++) bucketManager.addOrUpdate(new KademliaPeer(peers[startIndex + i]));
    // check that all peers are still there
    int totalPeersAdded = S + 5 * K;
    for (int i = 0; i < totalPeersAdded; i++) assertTrue(bucketManager.getAllPeers().contains(peers[i]));
    checkBucketConsistency();
    // remove peers one at a time and check that it got removed from the right bucket
    // sizes of the k-buckets by bucket index
    List<Integer> bucketSizes = new ArrayList<Integer>();
    List<KBucket> kBuckets = getKBuckets();
    for (KBucket bucket : kBuckets) bucketSizes.add(bucket.size());
    int peersRemaining = totalPeersAdded;
    while (peersRemaining > 0) {
        Destination peer = peers[peersRemaining - 1];
        BigInteger peerId = new BigInteger(1, peer.calculateHash().getData());
        boolean isSibling = bucketManager.getSBucket().contains(peer);
        bucketManager.remove(peer);
        peersRemaining--;
        assertEquals(peersRemaining, bucketManager.getPeerCount());
        if (isSibling) {
            // the removed peer was a sibling, so a k-peer should have taken its place unless there were no k-peers left
            assertTrue(bucketManager.getSBucket().isFull() || getKPeers().isEmpty());
            // if the s-bucket is still full, a k-peer became a sibling, so update bucketSizes
            if (bucketManager.getSBucket().isFull())
                for (int i = 0; i < kBuckets.size(); i++) if (getKBuckets().get(i).size() == bucketSizes.get(i) - 1)
                    bucketSizes.set(i, bucketSizes.get(i) - 1);
        } else
            // one of the k-buckets just became one smaller, find out which one and check that it is the correct one
            for (int i = 0; i < kBuckets.size(); i++) {
                KBucket bucket = kBuckets.get(i);
                if (bucket.size() == bucketSizes.get(i) - 1) {
                    bucketSizes.set(i, bucketSizes.get(i) - 1);
                    BigInteger startId = bucket.getStartId();
                    BigInteger endId = bucket.getEndId();
                    assertTrue("Peer is in the wrong bucket: peer id=" + peerId + ", bucket start=" + startId + " bucket end=" + endId, startId.compareTo(peerId) <= 0 && endId.compareTo(peerId) >= 0);
                } else
                    assertEquals(bucket.size(), bucketSizes.get(i).intValue());
            }
        checkBucketConsistency();
    }
}
Also used : BigInteger(java.math.BigInteger) Destination(net.i2p.data.Destination) ArrayList(java.util.ArrayList) BigInteger(java.math.BigInteger) Test(org.junit.Test)

Example 70 with Destination

use of net.i2p.data.Destination in project i2p.i2p-bote by i2p.

the class BucketManagerTest method checkBucketConsistency.

private void checkBucketConsistency() throws Exception {
    Iterator<KBucket> iter = bucketManager.iterator();
    KBucket bucket1 = iter.next();
    while (iter.hasNext()) {
        KBucket bucket2 = iter.next();
        // check that all peers in bucket n have lower keys than those in bucket n+1
        for (KademliaPeer peer1 : bucket1) {
            BigInteger peer1Key = new BigInteger(1, peer1.calculateHash().getData());
            for (KademliaPeer peer2 : bucket2) {
                BigInteger peer2Key = new BigInteger(1, peer2.calculateHash().getData());
                assertTrue(peer1Key.compareTo(peer2Key) == -1);
            }
        }
        // start ID of bucket n+1 should be the end ID of bucket n
        assertEquals(bucket1.getEndId(), bucket2.getStartId());
        bucket1 = bucket2;
    }
    // check that all peer IDs are within the start/end id of their bucket
    for (KBucket bucket : bucketManager) for (KademliaPeer peer : bucket) {
        BigInteger peerId = new BigInteger(1, peer.calculateHash().getData());
        assertTrue(bucket.getStartId().compareTo(peerId) <= 0);
        assertTrue(bucket.getEndId().compareTo(peerId) >= 0);
    }
    // TODO and all bits above it
    for (KBucket bucket : bucketManager) {
        int depth = KademliaTestUtil.getDepth(bucket);
        int bitIndex = Hash.HASH_LENGTH * 8 - depth;
        Boolean previousBit = null;
        for (KademliaPeer peer : bucket) {
            BigInteger peerId = new BigInteger(1, peer.getDestinationHash().getData());
            boolean currentBit = peerId.testBit(bitIndex);
            if (previousBit == null)
                previousBit = currentBit;
            else
                assertEquals("Bit " + bitIndex + " in peer ID " + peerId + " should be " + previousBit + "; bucket start = " + bucket.getStartId() + ", bucket end = " + bucket.getEndId(), previousBit, currentBit);
        }
    }
    // the local destination should not be in any bucket
    assertFalse(bucketManager.getAllPeers().contains(localDestination));
    // check that siblings are closer to the local destination than all k-bucket peers
    PeerDistanceComparator comparator = new PeerDistanceComparator(localDestination.calculateHash());
    for (KademliaPeer sibling : bucketManager.getSBucket()) for (KademliaPeer peer : getKPeers()) assertTrue(comparator.compare(sibling, peer) <= 0);
    // check that every hash falls into a bucket's key range
    for (Destination peer : peers) {
        KBucket bucket = getKBucket(peer.calculateHash());
        assertNotNull(bucket);
    }
}
Also used : Destination(net.i2p.data.Destination) BigInteger(java.math.BigInteger)

Aggregations

Destination (net.i2p.data.Destination)149 IOException (java.io.IOException)46 DataFormatException (net.i2p.data.DataFormatException)33 Properties (java.util.Properties)29 I2PException (net.i2p.I2PException)26 Hash (net.i2p.data.Hash)18 ArrayList (java.util.ArrayList)13 File (java.io.File)12 I2PSessionException (net.i2p.client.I2PSessionException)12 SigType (net.i2p.crypto.SigType)12 ByteArrayInputStream (java.io.ByteArrayInputStream)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 I2PSession (net.i2p.client.I2PSession)10 I2PSocket (net.i2p.client.streaming.I2PSocket)10 FileInputStream (java.io.FileInputStream)7 InputStream (java.io.InputStream)7 OutputStream (java.io.OutputStream)7 I2PClient (net.i2p.client.I2PClient)7 I2PSocketOptions (net.i2p.client.streaming.I2PSocketOptions)7 Test (org.junit.Test)6