Search in sources :

Example 36 with AddressBook

use of com.hedera.mirror.common.domain.addressbook.AddressBook in project hedera-mirror-node by hashgraph.

the class AddressBookRepositoryTest method findLatestTimestamp.

@Test
void findLatestTimestamp() {
    EntityId fileId = EntityId.of(101L, EntityType.FILE);
    assertThat(addressBookRepository.findLatestTimestamp(fileId.getId())).isEmpty();
    domainBuilder.addressBook().customize(a -> a.fileId(EntityId.of(999L, EntityType.FILE))).persist();
    assertThat(addressBookRepository.findLatestTimestamp(fileId.getId())).isEmpty();
    AddressBook addressBook2 = domainBuilder.addressBook().customize(a -> a.fileId(fileId)).persist();
    assertThat(addressBookRepository.findLatestTimestamp(fileId.getId())).get().isEqualTo(addressBook2.getStartConsensusTimestamp());
    AddressBook addressBook3 = domainBuilder.addressBook().customize(a -> a.fileId(fileId)).persist();
    assertThat(addressBookRepository.findLatestTimestamp(fileId.getId())).get().isEqualTo(addressBook3.getStartConsensusTimestamp());
}
Also used : EntityId(com.hedera.mirror.common.domain.entity.EntityId) Test(org.junit.jupiter.api.Test) EntityId(com.hedera.mirror.common.domain.entity.EntityId) GrpcIntegrationTest(com.hedera.mirror.grpc.GrpcIntegrationTest) AddressBook(com.hedera.mirror.common.domain.addressbook.AddressBook) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) DomainBuilder(com.hedera.mirror.common.domain.DomainBuilder) Resource(javax.annotation.Resource) EntityType(com.hedera.mirror.common.domain.entity.EntityType) Transactional(org.springframework.transaction.annotation.Transactional) AddressBook(com.hedera.mirror.common.domain.addressbook.AddressBook) Test(org.junit.jupiter.api.Test) GrpcIntegrationTest(com.hedera.mirror.grpc.GrpcIntegrationTest)

Example 37 with AddressBook

use of com.hedera.mirror.common.domain.addressbook.AddressBook in project hedera-mirror-node by hashgraph.

the class Downloader method downloadAndParseSigFiles.

/**
 * Download and parse all signature files with a timestamp later than the last valid file. Put signature files into
 * a multi-map sorted and grouped by the timestamp.
 *
 * @param addressBook the current address book
 * @return a multi-map of signature file objects from different nodes, grouped by filename
 */
private Multimap<String, FileStreamSignature> downloadAndParseSigFiles(AddressBook addressBook) throws InterruptedException {
    String startAfterFilename = getStartAfterFilename();
    Multimap<String, FileStreamSignature> sigFilesMap = Multimaps.synchronizedSortedSetMultimap(TreeMultimap.create());
    Set<EntityId> nodeAccountIds = addressBook.getNodeSet();
    List<Callable<Object>> tasks = new ArrayList<>(nodeAccountIds.size());
    AtomicInteger totalDownloads = new AtomicInteger();
    log.info("Downloading signature files created after file: {}", startAfterFilename);
    /*
         * For each node, create a thread that will make S3 ListObject requests as many times as necessary to
         * start maxDownloads download operations.
         */
    for (EntityId nodeAccountId : nodeAccountIds) {
        tasks.add(Executors.callable(() -> {
            String nodeAccountIdStr = nodeAccountId.entityIdToString();
            Stopwatch stopwatch = Stopwatch.createStarted();
            try {
                List<S3Object> s3Objects = listFiles(startAfterFilename, nodeAccountIdStr);
                List<PendingDownload> pendingDownloads = downloadSignatureFiles(nodeAccountIdStr, s3Objects);
                AtomicInteger count = new AtomicInteger();
                pendingDownloads.forEach(pendingDownload -> {
                    try {
                        parseSignatureFile(pendingDownload, nodeAccountId).ifPresent(fileStreamSignature -> {
                            sigFilesMap.put(fileStreamSignature.getFilename(), fileStreamSignature);
                            count.incrementAndGet();
                            totalDownloads.incrementAndGet();
                        });
                    } catch (InterruptedException ex) {
                        log.warn("Failed downloading {} in {}", pendingDownload.getS3key(), pendingDownload.getStopwatch(), ex);
                        Thread.currentThread().interrupt();
                    } catch (Exception ex) {
                        log.warn("Failed to parse signature file {}: {}", pendingDownload.getS3key(), ex);
                    }
                });
                if (count.get() > 0) {
                    log.info("Downloaded {} signatures for node {} in {}", count.get(), nodeAccountIdStr, stopwatch);
                }
            } catch (InterruptedException e) {
                log.error("Error downloading signature files for node {} after {}", nodeAccountIdStr, stopwatch, e);
                Thread.currentThread().interrupt();
            } catch (Exception e) {
                log.error("Error downloading signature files for node {} after {}", nodeAccountIdStr, stopwatch, e);
            }
        }));
    }
    // Wait for all tasks to complete.
    // invokeAll() does return Futures, but it waits for all to complete (so they're returned in a completed state).
    Stopwatch stopwatch = Stopwatch.createStarted();
    signatureDownloadThreadPool.invokeAll(tasks);
    if (totalDownloads.get() > 0) {
        var rate = (int) (1000000.0 * totalDownloads.get() / stopwatch.elapsed(TimeUnit.MICROSECONDS));
        log.info("Downloaded {} signatures in {} ({}/s)", totalDownloads, stopwatch, rate);
    }
    return sigFilesMap;
}
Also used : EntityId(com.hedera.mirror.common.domain.entity.EntityId) AddressBook(com.hedera.mirror.common.domain.addressbook.AddressBook) FileStreamSignature(com.hedera.mirror.importer.domain.FileStreamSignature) TreeMultimap(com.google.common.collect.TreeMultimap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) GetObjectRequest(software.amazon.awssdk.services.s3.model.GetObjectRequest) AsyncResponseTransformer(software.amazon.awssdk.core.async.AsyncResponseTransformer) Path(java.nio.file.Path) Utility(com.hedera.mirror.importer.util.Utility) ListObjectsRequest(software.amazon.awssdk.services.s3.model.ListObjectsRequest) S3AsyncClient(software.amazon.awssdk.services.s3.S3AsyncClient) SIGNATURE(com.hedera.mirror.importer.domain.StreamFilename.FileType.SIGNATURE) Collection(java.util.Collection) StreamType(com.hedera.mirror.common.domain.StreamType) Set(java.util.Set) HashMismatchException(com.hedera.mirror.importer.exception.HashMismatchException) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) InvalidStreamFileException(com.hedera.mirror.importer.exception.InvalidStreamFileException) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Optional(java.util.Optional) SHA384(com.hedera.mirror.common.domain.DigestAlgorithm.SHA384) ShutdownHelper(com.hedera.mirror.importer.util.ShutdownHelper) StreamFileData(com.hedera.mirror.importer.domain.StreamFileData) Stopwatch(com.google.common.base.Stopwatch) S3Object(software.amazon.awssdk.services.s3.model.S3Object) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) Callable(java.util.concurrent.Callable) Multimap(com.google.common.collect.Multimap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Multimaps(com.google.common.collect.Multimaps) ArrayList(java.util.ArrayList) RequestPayer(software.amazon.awssdk.services.s3.model.RequestPayer) AddressBookService(com.hedera.mirror.importer.addressbook.AddressBookService) Timer(io.micrometer.core.instrument.Timer) StreamFilename(com.hedera.mirror.importer.domain.StreamFilename) ExecutorService(java.util.concurrent.ExecutorService) MirrorDateRangePropertiesProcessor(com.hedera.mirror.importer.config.MirrorDateRangePropertiesProcessor) StreamFileReader(com.hedera.mirror.importer.reader.StreamFileReader) SignatureFileReader(com.hedera.mirror.importer.reader.signature.SignatureFileReader) Collectors.maxBy(java.util.stream.Collectors.maxBy) StreamFile(com.hedera.mirror.common.domain.StreamFile) SignatureVerificationException(com.hedera.mirror.importer.exception.SignatureVerificationException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) MirrorProperties(com.hedera.mirror.importer.MirrorProperties) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) LogManager(org.apache.logging.log4j.LogManager) ArrayList(java.util.ArrayList) Stopwatch(com.google.common.base.Stopwatch) FileStreamSignature(com.hedera.mirror.importer.domain.FileStreamSignature) Callable(java.util.concurrent.Callable) HashMismatchException(com.hedera.mirror.importer.exception.HashMismatchException) InvalidStreamFileException(com.hedera.mirror.importer.exception.InvalidStreamFileException) SignatureVerificationException(com.hedera.mirror.importer.exception.SignatureVerificationException) ExecutionException(java.util.concurrent.ExecutionException) EntityId(com.hedera.mirror.common.domain.entity.EntityId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) List(java.util.List) ArrayList(java.util.ArrayList)

Example 38 with AddressBook

use of com.hedera.mirror.common.domain.addressbook.AddressBook in project hedera-mirror-node by hashgraph.

the class NodeSignatureVerifier method verify.

/**
 * Verifies that the signature files satisfy the consensus requirement:
 * <ol>
 *  <li>At least 1/3 signature files are present</li>
 *  <li>For a signature file, we validate it by checking if it's signed by corresponding node's PublicKey. For valid
 *      signature files, we compare their hashes to see if at least 1/3 have hashes that match. If a signature is
 *      valid, we put the hash in its content and its file to the map, to see if at least 1/3 valid signatures have
 *      the same hash</li>
 * </ol>
 *
 * @param signatures a list of signature files which have the same filename
 * @throws SignatureVerificationException
 */
public void verify(Collection<FileStreamSignature> signatures) throws SignatureVerificationException {
    AddressBook currentAddressBook = addressBookService.getCurrent();
    Map<String, PublicKey> nodeAccountIDPubKeyMap = currentAddressBook.getNodeAccountIDPubKeyMap();
    Multimap<String, FileStreamSignature> signatureHashMap = HashMultimap.create();
    String filename = signatures.stream().map(FileStreamSignature::getFilename).findFirst().orElse("unknown");
    int consensusCount = 0;
    long sigFileCount = signatures.size();
    long nodeCount = nodeAccountIDPubKeyMap.size();
    if (!canReachConsensus(sigFileCount, nodeCount)) {
        throw new SignatureVerificationException(String.format("Insufficient downloaded signature file count, requires at least %.03f to reach consensus, got %d" + " out of %d for file %s: %s", commonDownloaderProperties.getConsensusRatio(), sigFileCount, nodeCount, filename, statusMap(signatures, nodeAccountIDPubKeyMap)));
    }
    for (FileStreamSignature fileStreamSignature : signatures) {
        if (verifySignature(fileStreamSignature, nodeAccountIDPubKeyMap)) {
            fileStreamSignature.setStatus(SignatureStatus.VERIFIED);
            signatureHashMap.put(fileStreamSignature.getFileHashAsHex(), fileStreamSignature);
        }
    }
    if (commonDownloaderProperties.getConsensusRatio() == 0 && signatureHashMap.size() > 0) {
        log.debug("Signature file {} does not require consensus, skipping consensus check", filename);
        return;
    }
    for (String key : signatureHashMap.keySet()) {
        Collection<FileStreamSignature> validatedSignatures = signatureHashMap.get(key);
        if (canReachConsensus(validatedSignatures.size(), nodeCount)) {
            consensusCount += validatedSignatures.size();
            validatedSignatures.forEach(s -> s.setStatus(SignatureStatus.CONSENSUS_REACHED));
        }
    }
    if (consensusCount == nodeCount) {
        log.debug("Verified signature file {} reached consensus", filename);
        return;
    } else if (consensusCount > 0) {
        log.warn("Verified signature file {} reached consensus but with some errors: {}", filename, statusMap(signatures, nodeAccountIDPubKeyMap));
        return;
    }
    throw new SignatureVerificationException("Signature verification failed for file " + filename + ": " + statusMap(signatures, nodeAccountIDPubKeyMap));
}
Also used : AddressBook(com.hedera.mirror.common.domain.addressbook.AddressBook) PublicKey(java.security.PublicKey) SignatureVerificationException(com.hedera.mirror.importer.exception.SignatureVerificationException) FileStreamSignature(com.hedera.mirror.importer.domain.FileStreamSignature)

Example 39 with AddressBook

use of com.hedera.mirror.common.domain.addressbook.AddressBook in project hedera-mirror-node by hashgraph.

the class NetworkControllerTest method nullFields.

@Test
void nullFields() {
    AddressBook addressBook = addressBook();
    AddressBookEntry addressBookEntry = domainBuilder.addressBookEntry().customize(a -> a.consensusTimestamp(CONSENSUS_TIMESTAMP).description(null).memo(null).nodeCertHash(null).publicKey(null).stake(null)).persist();
    AddressBookQuery query = AddressBookQuery.newBuilder().setFileId(FileID.newBuilder().setFileNum(addressBook.getFileId().getEntityNum()).build()).build();
    reactiveService.getNodes(Mono.just(query)).as(StepVerifier::create).thenAwait(Duration.ofMillis(50)).consumeNextWith(n -> assertThat(n).isNotNull().returns("", NodeAddress::getDescription).returns(ByteString.EMPTY, NodeAddress::getMemo).returns(addressBookEntry.getNodeAccountId(), t -> EntityId.of(n.getNodeAccountId())).returns(ByteString.EMPTY, NodeAddress::getNodeCertHash).returns(addressBookEntry.getNodeId(), NodeAddress::getNodeId).returns("", NodeAddress::getRSAPubKey).returns(0L, NodeAddress::getStake)).expectComplete().verify(Duration.ofSeconds(1L));
}
Also used : FileID(com.hederahashgraph.api.proto.java.FileID) AddressBookQuery(com.hedera.mirror.api.proto.AddressBookQuery) ServiceEndpoint(com.hederahashgraph.api.proto.java.ServiceEndpoint) GrpcClient(net.devh.boot.grpc.client.inject.GrpcClient) StepVerifier(reactor.test.StepVerifier) EntityId(com.hedera.mirror.common.domain.entity.EntityId) GrpcIntegrationTest(com.hedera.mirror.grpc.GrpcIntegrationTest) AddressBook(com.hedera.mirror.common.domain.addressbook.AddressBook) ProtoUtil(com.hedera.mirror.grpc.util.ProtoUtil) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Resource(javax.annotation.Resource) Mono(reactor.core.publisher.Mono) AddressBookEntry(com.hedera.mirror.common.domain.addressbook.AddressBookEntry) ByteString(com.google.protobuf.ByteString) StatusRuntimeException(io.grpc.StatusRuntimeException) InetAddress(java.net.InetAddress) Test(org.junit.jupiter.api.Test) ReactorNetworkServiceGrpc(com.hedera.mirror.api.proto.ReactorNetworkServiceGrpc) Duration(java.time.Duration) DomainBuilder(com.hedera.mirror.common.domain.DomainBuilder) Log4j2(lombok.extern.log4j.Log4j2) NodeAddress(com.hederahashgraph.api.proto.java.NodeAddress) Status(io.grpc.Status) AddressBookQuery(com.hedera.mirror.api.proto.AddressBookQuery) AddressBook(com.hedera.mirror.common.domain.addressbook.AddressBook) AddressBookEntry(com.hedera.mirror.common.domain.addressbook.AddressBookEntry) NodeAddress(com.hederahashgraph.api.proto.java.NodeAddress) StepVerifier(reactor.test.StepVerifier) GrpcIntegrationTest(com.hedera.mirror.grpc.GrpcIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 40 with AddressBook

use of com.hedera.mirror.common.domain.addressbook.AddressBook in project hedera-mirror-node by hashgraph.

the class NetworkControllerTest method noLimit.

@Test
void noLimit() {
    AddressBook addressBook = addressBook();
    AddressBookEntry addressBookEntry1 = addressBookEntry();
    AddressBookEntry addressBookEntry2 = addressBookEntry();
    AddressBookQuery query = AddressBookQuery.newBuilder().setFileId(FileID.newBuilder().setFileNum(addressBook.getFileId().getEntityNum()).build()).build();
    reactiveService.getNodes(Mono.just(query)).as(StepVerifier::create).thenAwait(Duration.ofMillis(50)).consumeNextWith(n -> assertEntry(addressBookEntry1, n)).consumeNextWith(n -> assertEntry(addressBookEntry2, n)).expectComplete().verify(Duration.ofSeconds(1L));
}
Also used : FileID(com.hederahashgraph.api.proto.java.FileID) AddressBookQuery(com.hedera.mirror.api.proto.AddressBookQuery) ServiceEndpoint(com.hederahashgraph.api.proto.java.ServiceEndpoint) GrpcClient(net.devh.boot.grpc.client.inject.GrpcClient) StepVerifier(reactor.test.StepVerifier) EntityId(com.hedera.mirror.common.domain.entity.EntityId) GrpcIntegrationTest(com.hedera.mirror.grpc.GrpcIntegrationTest) AddressBook(com.hedera.mirror.common.domain.addressbook.AddressBook) ProtoUtil(com.hedera.mirror.grpc.util.ProtoUtil) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Resource(javax.annotation.Resource) Mono(reactor.core.publisher.Mono) AddressBookEntry(com.hedera.mirror.common.domain.addressbook.AddressBookEntry) ByteString(com.google.protobuf.ByteString) StatusRuntimeException(io.grpc.StatusRuntimeException) InetAddress(java.net.InetAddress) Test(org.junit.jupiter.api.Test) ReactorNetworkServiceGrpc(com.hedera.mirror.api.proto.ReactorNetworkServiceGrpc) Duration(java.time.Duration) DomainBuilder(com.hedera.mirror.common.domain.DomainBuilder) Log4j2(lombok.extern.log4j.Log4j2) NodeAddress(com.hederahashgraph.api.proto.java.NodeAddress) Status(io.grpc.Status) AddressBookQuery(com.hedera.mirror.api.proto.AddressBookQuery) AddressBook(com.hedera.mirror.common.domain.addressbook.AddressBook) AddressBookEntry(com.hedera.mirror.common.domain.addressbook.AddressBookEntry) GrpcIntegrationTest(com.hedera.mirror.grpc.GrpcIntegrationTest) Test(org.junit.jupiter.api.Test)

Aggregations

AddressBook (com.hedera.mirror.common.domain.addressbook.AddressBook)43 Test (org.junit.jupiter.api.Test)33 IntegrationTest (com.hedera.mirror.importer.IntegrationTest)17 NodeAddressBook (com.hederahashgraph.api.proto.java.NodeAddressBook)17 AddressBookEntry (com.hedera.mirror.common.domain.addressbook.AddressBookEntry)12 GrpcIntegrationTest (com.hedera.mirror.grpc.GrpcIntegrationTest)11 ServiceEndpoint (com.hederahashgraph.api.proto.java.ServiceEndpoint)10 AddressBookServiceEndpoint (com.hedera.mirror.common.domain.addressbook.AddressBookServiceEndpoint)9 EntityId (com.hedera.mirror.common.domain.entity.EntityId)6 AddressBookFilter (com.hedera.mirror.grpc.domain.AddressBookFilter)6 Resource (javax.annotation.Resource)5 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)5 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)5 ByteString (com.google.protobuf.ByteString)4 DomainBuilder (com.hedera.mirror.common.domain.DomainBuilder)4 NodeAddress (com.hederahashgraph.api.proto.java.NodeAddress)4 StepVerifier (reactor.test.StepVerifier)4 AddressBookQuery (com.hedera.mirror.api.proto.AddressBookQuery)3 EntityType (com.hedera.mirror.common.domain.entity.EntityType)3 SignatureVerificationException (com.hedera.mirror.importer.exception.SignatureVerificationException)3