Search in sources :

Example 1 with Hash

use of com.iota.iri.model.Hash in project iri by iotaledger.

the class API method getTransactionToApproveStatement.

public synchronized Hash[] getTransactionToApproveStatement(int depth, final String reference, final int numWalks) throws Exception {
    int tipsToApprove = 2;
    Hash[] tips = new Hash[tipsToApprove];
    final SecureRandom random = new SecureRandom();
    final int randomWalkCount = numWalks > maxRandomWalks || numWalks < 1 ? maxRandomWalks : numWalks;
    Hash referenceHash = null;
    int maxDepth = instance.tipsManager.getMaxDepth();
    if (depth > maxDepth) {
        depth = maxDepth;
    }
    if (reference != null) {
        referenceHash = new Hash(reference);
        if (!TransactionViewModel.exists(instance.tangle, referenceHash)) {
            throw new RuntimeException(REFERENCE_TRANSACTION_NOT_FOUND);
        } else {
            TransactionViewModel transactionViewModel = TransactionViewModel.fromHash(instance.tangle, referenceHash);
            if (transactionViewModel.snapshotIndex() != 0 && transactionViewModel.snapshotIndex() < instance.milestone.latestSolidSubtangleMilestoneIndex - depth) {
                throw new RuntimeException(REFERENCE_TRANSACTION_TOO_OLD);
            }
        }
    }
    instance.milestone.latestSnapshot.rwlock.readLock().lock();
    try {
        Set<Hash> visitedHashes = new HashSet<>();
        Map<Hash, Long> diff = new HashMap<>();
        for (int i = 0; i < tipsToApprove; i++) {
            tips[i] = instance.tipsManager.transactionToApprove(visitedHashes, diff, referenceHash, tips[0], depth, randomWalkCount, random);
            // update world view, so next tips selected will be inter-consistent
            if (tips[i] == null || !instance.ledgerValidator.updateDiff(visitedHashes, diff, tips[i])) {
                return null;
            }
        }
        API.incCounter_getTxToApprove();
        if ((getCounter_getTxToApprove() % 100) == 0) {
            String sb = "Last 100 getTxToApprove consumed " + API.getEllapsedTime_getTxToApprove() / 1000000000L + " seconds processing time.";
            log.info(sb);
            counter_getTxToApprove = 0;
            ellapsedTime_getTxToApprove = 0L;
        }
        if (instance.ledgerValidator.checkConsistency(Arrays.asList(tips))) {
            return tips;
        }
    } finally {
        instance.milestone.latestSnapshot.rwlock.readLock().unlock();
    }
    throw new RuntimeException("inconsistent tips pair selected");
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) AtomicLong(java.util.concurrent.atomic.AtomicLong) SecureRandom(java.security.SecureRandom) HttpString(io.undertow.util.HttpString) Hash(com.iota.iri.model.Hash) HashSet(java.util.HashSet)

Example 2 with Hash

use of com.iota.iri.model.Hash in project iri by iotaledger.

the class API method readPreviousEpochsSpentAddresses.

private void readPreviousEpochsSpentAddresses() {
    if (!SignedFiles.isFileSignatureValid("/previousEpochsSpentAddresses.txt", "/previousEpochsSpentAddresses.sig", Snapshot.SNAPSHOT_PUBKEY, Snapshot.SNAPSHOT_PUBKEY_DEPTH, Snapshot.SPENT_ADDRESSES_INDEX)) {
        throw new RuntimeException("Failed to load previousEpochsSpentAddresses - signature failed.");
    }
    InputStream in = Snapshot.class.getResourceAsStream("/previousEpochsSpentAddresses.txt");
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line;
    try {
        while ((line = reader.readLine()) != null) {
            previousEpochsSpentAddresses.put(new Hash(line), true);
        }
    } catch (IOException e) {
        log.error("Failed to load previousEpochsSpentAddresses.");
    }
}
Also used : ChannelInputStream(org.xnio.streams.ChannelInputStream) HttpString(io.undertow.util.HttpString) Hash(com.iota.iri.model.Hash)

Example 3 with Hash

use of com.iota.iri.model.Hash in project iri by iotaledger.

the class API method getBalancesStatement.

private AbstractResponse getBalancesStatement(final List<String> addrss, final List<String> tips, final int threshold) throws Exception {
    if (threshold <= 0 || threshold > 100) {
        return ErrorResponse.create("Illegal 'threshold'");
    }
    final List<Hash> addresses = addrss.stream().map(address -> (new Hash(address))).collect(Collectors.toCollection(LinkedList::new));
    final List<Hash> hashes;
    final Map<Hash, Long> balances = new HashMap<>();
    instance.milestone.latestSnapshot.rwlock.readLock().lock();
    final int index = instance.milestone.latestSnapshot.index();
    if (tips == null || tips.size() == 0) {
        hashes = Collections.singletonList(instance.milestone.latestSolidSubtangleMilestone);
    } else {
        hashes = tips.stream().map(address -> (new Hash(address))).collect(Collectors.toCollection(LinkedList::new));
    }
    try {
        for (final Hash address : addresses) {
            Long value = instance.milestone.latestSnapshot.getBalance(address);
            if (value == null) {
                value = 0L;
            }
            balances.put(address, value);
        }
        final Set<Hash> visitedHashes;
        final Map<Hash, Long> diff;
        visitedHashes = new HashSet<>();
        diff = new HashMap<>();
        for (Hash tip : hashes) {
            if (!TransactionViewModel.exists(instance.tangle, tip)) {
                return ErrorResponse.create("Tip not found: " + tip.toString());
            }
            if (!instance.ledgerValidator.updateDiff(visitedHashes, diff, tip)) {
                return ErrorResponse.create("Tips are not consistent");
            }
        }
        diff.forEach((key, value) -> balances.computeIfPresent(key, (hash, aLong) -> value + aLong));
    } finally {
        instance.milestone.latestSnapshot.rwlock.readLock().unlock();
    }
    final List<String> elements = addresses.stream().map(address -> balances.get(address).toString()).collect(Collectors.toCollection(LinkedList::new));
    return GetBalancesResponse.create(elements, hashes.stream().map(h -> h.toString()).collect(Collectors.toList()), index);
}
Also used : Arrays(java.util.Arrays) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) HttpServerExchange(io.undertow.server.HttpServerExchange) com.iota.iri.controllers(com.iota.iri.controllers) Configuration(com.iota.iri.conf.Configuration) ByteBuffer(java.nio.ByteBuffer) GsonBuilder(com.google.gson.GsonBuilder) SecurityInitialHandler(io.undertow.security.handlers.SecurityInitialHandler) Undertow(io.undertow.Undertow) HttpString(io.undertow.util.HttpString) InetAddress(java.net.InetAddress) SecureRandom(java.security.SecureRandom) HeaderMap(io.undertow.util.HeaderMap) AuthenticationMechanismsHandler(io.undertow.security.handlers.AuthenticationMechanismsHandler) Matcher(java.util.regex.Matcher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Gson(com.google.gson.Gson) Map(java.util.Map) IdentityManager(io.undertow.security.idm.IdentityManager) com.iota.iri.network(com.iota.iri.network) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) URI(java.net.URI) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) com.iota.iri(com.iota.iri) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) Curl(com.iota.iri.hash.Curl) PearlDiver(com.iota.iri.hash.PearlDiver) Methods(io.undertow.util.Methods) Queue(java.util.Queue) Pattern(java.util.regex.Pattern) Handlers.path(io.undertow.Handlers.path) BasicAuthenticationMechanism(io.undertow.security.impl.BasicAuthenticationMechanism) HashMap(java.util.HashMap) Hash(com.iota.iri.model.Hash) HashSet(java.util.HashSet) MimeMappings(io.undertow.util.MimeMappings) MapIdentityManager(com.iota.iri.utils.MapIdentityManager) Converter(com.iota.iri.utils.Converter) LinkedList(java.util.LinkedList) StatusCodes(io.undertow.util.StatusCodes) Logger(org.slf4j.Logger) AuthenticationConstraintHandler(io.undertow.security.handlers.AuthenticationConstraintHandler) com.iota.iri.service.dto(com.iota.iri.service.dto) AuthenticationMode(io.undertow.security.api.AuthenticationMode) HttpHandler(io.undertow.server.HttpHandler) AtomicLong(java.util.concurrent.atomic.AtomicLong) DefaultConfSettings(com.iota.iri.conf.Configuration.DefaultConfSettings) java.io(java.io) AuthenticationMechanism(io.undertow.security.api.AuthenticationMechanism) ChannelInputStream(org.xnio.streams.ChannelInputStream) AuthenticationCallHandler(io.undertow.security.handlers.AuthenticationCallHandler) Headers(io.undertow.util.Headers) Collections(java.util.Collections) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) HttpString(io.undertow.util.HttpString) Hash(com.iota.iri.model.Hash) LinkedList(java.util.LinkedList) AtomicLong(java.util.concurrent.atomic.AtomicLong)

Example 4 with Hash

use of com.iota.iri.model.Hash in project iri by iotaledger.

the class TipsManager method scanTipsForSolidity.

private void scanTipsForSolidity() throws Exception {
    int size = tipsViewModel.nonSolidSize();
    if (size != 0) {
        Hash hash = tipsViewModel.getRandomNonSolidTipHash();
        boolean isTip = true;
        if (hash != null && TransactionViewModel.fromHash(tangle, hash).getApprovers(tangle).size() != 0) {
            tipsViewModel.removeTipHash(hash);
            isTip = false;
        }
        if (hash != null && isTip && transactionValidator.checkSolidity(hash, false)) {
            // if(hash != null && TransactionViewModel.fromHash(hash).isSolid() && isTip) {
            tipsViewModel.setSolid(hash);
        }
    }
}
Also used : Hash(com.iota.iri.model.Hash)

Example 5 with Hash

use of com.iota.iri.model.Hash in project iri by iotaledger.

the class TipsManager method markovChainMonteCarlo.

Hash markovChainMonteCarlo(final Set<Hash> visitedHashes, final Map<Hash, Long> diff, final Hash tip, final Hash extraTip, final Map<Hash, Long> ratings, final int iterations, final int maxDepth, final Set<Hash> maxDepthOk, final Random seed) throws Exception {
    Map<Hash, Integer> monteCarloIntegrations = new HashMap<>();
    Hash tail;
    for (int i = iterations; i-- > 0; ) {
        tail = randomWalk(visitedHashes, diff, tip, extraTip, ratings, maxDepth, maxDepthOk, seed);
        if (monteCarloIntegrations.containsKey(tail)) {
            monteCarloIntegrations.put(tail, monteCarloIntegrations.get(tail) + 1);
        } else {
            monteCarloIntegrations.put(tail, 1);
        }
    }
    return monteCarloIntegrations.entrySet().stream().reduce((a, b) -> {
        if (a.getValue() > b.getValue()) {
            return a;
        } else if (a.getValue() < b.getValue()) {
            return b;
        } else if (seed.nextBoolean()) {
            return a;
        } else {
            return b;
        }
    }).map(Map.Entry::getKey).orElse(null);
}
Also used : Hash(com.iota.iri.model.Hash)

Aggregations

Hash (com.iota.iri.model.Hash)75 Test (org.junit.Test)16 TransactionViewModel (com.iota.iri.controllers.TransactionViewModel)12 RocksDBPersistenceProviderTest (com.iota.iri.storage.rocksDB.RocksDBPersistenceProviderTest)12 HttpString (io.undertow.util.HttpString)8 TransactionViewModelTest.getRandomTransactionHash (com.iota.iri.controllers.TransactionViewModelTest.getRandomTransactionHash)6 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)4 Map (java.util.Map)4 Curl (com.iota.iri.hash.Curl)3 PearlDiver (com.iota.iri.hash.PearlDiver)3 TransactionRequester (com.iota.iri.network.TransactionRequester)3 Converter (com.iota.iri.utils.Converter)3 LinkedList (java.util.LinkedList)3 List (java.util.List)3 Gson (com.google.gson.Gson)2 GsonBuilder (com.google.gson.GsonBuilder)2 com.iota.iri (com.iota.iri)2 Configuration (com.iota.iri.conf.Configuration)2 DefaultConfSettings (com.iota.iri.conf.Configuration.DefaultConfSettings)2