Search in sources :

Example 1 with ProtectedStorageEntry

use of io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry in project bitsquare by bitsquare.

the class P2PDataStorage method init.

private void init(File storageDir) {
    sequenceNumberMapStorage.setNumMaxBackupFiles(5);
    persistedEntryMapStorage.setNumMaxBackupFiles(1);
    HashMap<ByteArray, MapValue> persistedSequenceNumberMap = sequenceNumberMapStorage.<HashMap<ByteArray, MapValue>>initAndGetPersistedWithFileName("SequenceNumberMap");
    if (persistedSequenceNumberMap != null)
        sequenceNumberMap = getPurgedSequenceNumberMap(persistedSequenceNumberMap);
    final String storageFileName = "PersistedP2PStorageData";
    File dbDir = new File(storageDir.getAbsolutePath());
    if (!dbDir.exists() && !dbDir.mkdir())
        log.warn("make dir failed.\ndbDir=" + dbDir.getAbsolutePath());
    final File destinationFile = new File(Paths.get(storageDir.getAbsolutePath(), storageFileName).toString());
    if (!destinationFile.exists()) {
        try {
            FileUtil.resourceToFile(storageFileName, destinationFile);
        } catch (ResourceNotFoundException | IOException e) {
            e.printStackTrace();
            log.error("Could not copy the " + storageFileName + " resource file to the db directory.\n" + e.getMessage());
        }
    } else {
        log.debug(storageFileName + " file exists already.");
    }
    HashMap<ByteArray, ProtectedStorageEntry> persisted = persistedEntryMapStorage.<HashMap<ByteArray, MapValue>>initAndGetPersistedWithFileName(storageFileName);
    if (persisted != null) {
        persistedMap = persisted;
        map.putAll(persistedMap);
        // In case another object is already listening...
        map.values().stream().forEach(protectedStorageEntry -> hashMapChangedListeners.stream().forEach(e -> e.onAdded(protectedStorageEntry)));
    }
}
Also used : Version(io.bitsquare.app.Version) KeyPair(java.security.KeyPair) java.util(java.util) io.bitsquare.p2p.storage.payload(io.bitsquare.p2p.storage.payload) ProtectedStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry) Hex(org.spongycastle.util.encoders.Hex) LoggerFactory(org.slf4j.LoggerFactory) Timer(io.bitsquare.common.Timer) Tuple2(io.bitsquare.common.util.Tuple2) CryptoException(io.bitsquare.common.crypto.CryptoException) StringUtils(org.apache.commons.lang3.StringUtils) io.bitsquare.p2p.network(io.bitsquare.p2p.network) ResourceNotFoundException(io.bitsquare.storage.ResourceNotFoundException) Nullable(javax.annotation.Nullable) Log(io.bitsquare.app.Log) Hash(io.bitsquare.common.crypto.Hash) BroadcastHandler(io.bitsquare.p2p.peers.BroadcastHandler) Utilities(io.bitsquare.common.util.Utilities) FileUtil(io.bitsquare.storage.FileUtil) Logger(org.slf4j.Logger) ProtectedMailboxStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedMailboxStorageEntry) UserThread(io.bitsquare.common.UserThread) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Message(io.bitsquare.p2p.Message) NodeAddress(io.bitsquare.p2p.NodeAddress) IOException(java.io.IOException) PublicKey(java.security.PublicKey) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) Collectors(java.util.stream.Collectors) File(java.io.File) Sig(io.bitsquare.common.crypto.Sig) Serializable(java.io.Serializable) io.bitsquare.p2p.storage.messages(io.bitsquare.p2p.storage.messages) TimeUnit(java.util.concurrent.TimeUnit) Payload(io.bitsquare.common.wire.Payload) Broadcaster(io.bitsquare.p2p.peers.Broadcaster) Paths(java.nio.file.Paths) Storage(io.bitsquare.storage.Storage) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Persistable(io.bitsquare.common.persistance.Persistable) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) ResourceNotFoundException(io.bitsquare.storage.ResourceNotFoundException) File(java.io.File) ProtectedStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry)

Example 2 with ProtectedStorageEntry

use of io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry in project bitsquare by bitsquare.

the class P2PDataStorage method refreshTTL.

public boolean refreshTTL(RefreshTTLMessage refreshTTLMessage, @Nullable NodeAddress sender, boolean isDataOwner) {
    Log.traceCall();
    byte[] hashOfDataAndSeqNr = refreshTTLMessage.hashOfDataAndSeqNr;
    byte[] signature = refreshTTLMessage.signature;
    ByteArray hashOfPayload = new ByteArray(refreshTTLMessage.hashOfPayload);
    int sequenceNumber = refreshTTLMessage.sequenceNumber;
    if (map.containsKey(hashOfPayload)) {
        ProtectedStorageEntry storedData = map.get(hashOfPayload);
        if (sequenceNumberMap.containsKey(hashOfPayload) && sequenceNumberMap.get(hashOfPayload).sequenceNr == sequenceNumber) {
            log.trace("We got that message with that seq nr already from another peer. We ignore that message.");
            return true;
        } else {
            PublicKey ownerPubKey = storedData.getStoragePayload().getOwnerPubKey();
            final boolean checkSignature = checkSignature(ownerPubKey, hashOfDataAndSeqNr, signature);
            final boolean hasSequenceNrIncreased = hasSequenceNrIncreased(sequenceNumber, hashOfPayload);
            final boolean checkIfStoredDataPubKeyMatchesNewDataPubKey = checkIfStoredDataPubKeyMatchesNewDataPubKey(ownerPubKey, hashOfPayload);
            boolean allValid = checkSignature && hasSequenceNrIncreased && checkIfStoredDataPubKeyMatchesNewDataPubKey;
            // printData("before refreshTTL");
            if (allValid) {
                log.debug("refreshDate called for storedData:\n\t" + StringUtils.abbreviate(storedData.toString(), 100));
                storedData.refreshTTL();
                storedData.updateSequenceNumber(sequenceNumber);
                storedData.updateSignature(signature);
                printData("after refreshTTL");
                sequenceNumberMap.put(hashOfPayload, new MapValue(sequenceNumber, System.currentTimeMillis()));
                sequenceNumberMapStorage.queueUpForSave(new HashMap<>(sequenceNumberMap), 1000);
                broadcast(refreshTTLMessage, sender, null, isDataOwner);
            }
            return allValid;
        }
    } else {
        log.debug("We don't have data for that refresh message in our map. That is expected if we missed the data publishing.");
        return false;
    }
}
Also used : PublicKey(java.security.PublicKey) ProtectedStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry)

Example 3 with ProtectedStorageEntry

use of io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry in project bitsquare by bitsquare.

the class P2PDataStorage method checkIfStoredMailboxDataMatchesNewMailboxData.

private boolean checkIfStoredMailboxDataMatchesNewMailboxData(PublicKey receiversPubKey, ByteArray hashOfData) {
    ProtectedStorageEntry storedData = map.get(hashOfData);
    if (storedData instanceof ProtectedMailboxStorageEntry) {
        ProtectedMailboxStorageEntry entry = (ProtectedMailboxStorageEntry) storedData;
        // publicKey is not the same (stored: sender, new: receiver)
        boolean result = entry.receiversPubKey.equals(receiversPubKey) && getHashAsByteArray(entry.getStoragePayload()).equals(hashOfData);
        if (!result)
            log.warn("New data entry does not match our stored data. entry.receiversPubKey=" + entry.receiversPubKey + ", receiversPubKey=" + receiversPubKey);
        return result;
    } else {
        log.error("We expected a MailboxData but got other type. That must never happen. storedData=" + storedData);
        return false;
    }
}
Also used : ProtectedMailboxStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedMailboxStorageEntry) ProtectedStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry)

Example 4 with ProtectedStorageEntry

use of io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry in project bitsquare by bitsquare.

the class ProtectedDataStorageTest method testRefreshTTL.

/* //@Test
     public void testRePublish() throws InterruptedException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException, CryptoException, SignatureException, InvalidKeyException, NoSuchProviderException {
         mockData.ttl = (int) (P2PDataStorage.CHECK_TTL_INTERVAL_MILLIS * 1.5);
         ProtectedData data = dataStorage1.getDataWithSignedSeqNr(mockData, storageSignatureKeyPair1);
         Assert.assertTrue(dataStorage1.add(data, null));
         Assert.assertEquals(1, dataStorage1.getMap().size());
         Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_MILLIS);
         log.debug("test 1");
         Assert.assertEquals(1, dataStorage1.getMap().size());
 
         data = dataStorage1.getDataWithSignedSeqNr(mockData, storageSignatureKeyPair1);
         Assert.assertTrue(dataStorage1.rePublish(data, null));
         Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_MILLIS);
         log.debug("test 2");
         Assert.assertEquals(1, dataStorage1.getMap().size());
 
         data = dataStorage1.getDataWithSignedSeqNr(mockData, storageSignatureKeyPair1);
         Assert.assertTrue(dataStorage1.rePublish(data, null));
         Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_MILLIS);
         log.debug("test 3");
         Assert.assertEquals(1, dataStorage1.getMap().size());
 
         Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_MILLIS);
         log.debug("test 4");
         Assert.assertEquals(1, dataStorage1.getMap().size());
 
         Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_MILLIS * 2);
         log.debug("test 5 removed");
         Assert.assertEquals(0, dataStorage1.getMap().size());
     }
 */
@Test
public void testRefreshTTL() throws InterruptedException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException, CryptoException, SignatureException, InvalidKeyException, NoSuchProviderException {
    mockData.ttl = (int) (P2PDataStorage.CHECK_TTL_INTERVAL_SEC * 1.5);
    ProtectedStorageEntry data = dataStorage1.getProtectedData(mockData, storageSignatureKeyPair1);
    Assert.assertTrue(dataStorage1.add(data, null, null, true));
    Assert.assertEquals(1, dataStorage1.getMap().size());
    Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_SEC);
    log.debug("test 1");
    Assert.assertEquals(1, dataStorage1.getMap().size());
    RefreshTTLMessage refreshTTLMessage = dataStorage1.getRefreshTTLMessage(mockData, storageSignatureKeyPair1);
    Assert.assertTrue(dataStorage1.refreshTTL(refreshTTLMessage, null, true));
    Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_SEC);
    log.debug("test 2");
    Assert.assertEquals(1, dataStorage1.getMap().size());
    refreshTTLMessage = dataStorage1.getRefreshTTLMessage(mockData, storageSignatureKeyPair1);
    Assert.assertTrue(dataStorage1.refreshTTL(refreshTTLMessage, null, true));
    Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_SEC);
    log.debug("test 3");
    Assert.assertEquals(1, dataStorage1.getMap().size());
    Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_SEC);
    log.debug("test 4");
    Assert.assertEquals(1, dataStorage1.getMap().size());
    Thread.sleep(P2PDataStorage.CHECK_TTL_INTERVAL_SEC * 2);
    log.debug("test 5 removed");
    Assert.assertEquals(0, dataStorage1.getMap().size());
}
Also used : RefreshTTLMessage(io.bitsquare.p2p.storage.messages.RefreshTTLMessage) ProtectedStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry)

Example 5 with ProtectedStorageEntry

use of io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry in project bitsquare by bitsquare.

the class ProtectedDataStorageTest method testAddAndRemove.

//@Test
public void testAddAndRemove() throws InterruptedException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException, CryptoException, SignatureException, InvalidKeyException, NoSuchProviderException {
    ProtectedStorageEntry data = dataStorage1.getProtectedData(mockData, storageSignatureKeyPair1);
    Assert.assertTrue(dataStorage1.add(data, null, null, true));
    Assert.assertEquals(1, dataStorage1.getMap().size());
    int newSequenceNumber = data.sequenceNumber + 1;
    byte[] hashOfDataAndSeqNr = Hash.getHash(new P2PDataStorage.DataAndSeqNrPair(data.getStoragePayload(), newSequenceNumber));
    byte[] signature = Sig.sign(storageSignatureKeyPair1.getPrivate(), hashOfDataAndSeqNr);
    ProtectedStorageEntry dataToRemove = new ProtectedStorageEntry(data.getStoragePayload(), data.ownerPubKey, newSequenceNumber, signature);
    Assert.assertTrue(dataStorage1.remove(dataToRemove, null, true));
    Assert.assertEquals(0, dataStorage1.getMap().size());
}
Also used : ProtectedStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry)

Aggregations

ProtectedStorageEntry (io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry)13 CryptoException (io.bitsquare.common.crypto.CryptoException)4 Utilities (io.bitsquare.common.util.Utilities)3 NodeAddress (io.bitsquare.p2p.NodeAddress)3 StoragePayload (io.bitsquare.p2p.storage.payload.StoragePayload)3 ProtectedMailboxStorageEntry (io.bitsquare.p2p.storage.storageentry.ProtectedMailboxStorageEntry)3 Storage (io.bitsquare.storage.Storage)3 PublicKey (java.security.PublicKey)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 Log (io.bitsquare.app.Log)2 Version (io.bitsquare.app.Version)2 Timer (io.bitsquare.common.Timer)2 UserThread (io.bitsquare.common.UserThread)2 Hash (io.bitsquare.common.crypto.Hash)2 Sig (io.bitsquare.common.crypto.Sig)2 Persistable (io.bitsquare.common.persistance.Persistable)2 Tuple2 (io.bitsquare.common.util.Tuple2)2 Payload (io.bitsquare.common.wire.Payload)2 Message (io.bitsquare.p2p.Message)2 io.bitsquare.p2p.network (io.bitsquare.p2p.network)2