|
| 1 | +/* |
| 2 | + * Copyright 2025 IEXEC BLOCKCHAIN TECH |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.iexec.worker.chain; |
| 18 | + |
| 19 | +import com.iexec.commons.poco.chain.SignerService; |
| 20 | +import com.iexec.worker.chain.event.LatestBlockEvent; |
| 21 | +import com.iexec.worker.config.ConfigServerConfigurationService; |
| 22 | +import com.iexec.worker.config.WorkerConfigurationService; |
| 23 | +import io.micrometer.core.instrument.Metrics; |
| 24 | +import io.micrometer.core.instrument.Tag; |
| 25 | +import io.reactivex.Flowable; |
| 26 | +import io.reactivex.disposables.Disposable; |
| 27 | +import lombok.extern.slf4j.Slf4j; |
| 28 | +import org.springframework.context.ApplicationEventPublisher; |
| 29 | +import org.springframework.scheduling.annotation.Scheduled; |
| 30 | +import org.springframework.stereotype.Service; |
| 31 | +import org.web3j.protocol.Web3j; |
| 32 | +import org.web3j.protocol.core.DefaultBlockParameterName; |
| 33 | +import org.web3j.protocol.core.Request; |
| 34 | +import org.web3j.protocol.core.methods.response.EthSubscribe; |
| 35 | +import org.web3j.protocol.http.HttpService; |
| 36 | +import org.web3j.protocol.websocket.WebSocketService; |
| 37 | +import org.web3j.protocol.websocket.events.NewHeadsNotification; |
| 38 | +import org.web3j.utils.Async; |
| 39 | +import org.web3j.utils.Numeric; |
| 40 | + |
| 41 | +import java.io.IOException; |
| 42 | +import java.math.BigInteger; |
| 43 | +import java.net.ConnectException; |
| 44 | +import java.util.List; |
| 45 | +import java.util.Map; |
| 46 | +import java.util.concurrent.atomic.AtomicLong; |
| 47 | + |
| 48 | +@Slf4j |
| 49 | +@Service |
| 50 | +public class WebSocketBlockchainListener { |
| 51 | + |
| 52 | + static final String LATEST_BLOCK_METRIC_NAME = "iexec.chain.block.latest"; |
| 53 | + static final String TX_COUNT_METRIC_NAME = "iexec.chain.wallet.tx-count"; |
| 54 | + |
| 55 | + private static final String SUBSCRIBE_METHOD = "eth_subscribe"; |
| 56 | + private static final String UNSUBSCRIBE_METHOD = "eth_unsubscribe"; |
| 57 | + |
| 58 | + private final ApplicationEventPublisher applicationEventPublisher; |
| 59 | + private final String walletAddress; |
| 60 | + private final Web3j web3Client; |
| 61 | + private final WebSocketService webSocketService; |
| 62 | + private final AtomicLong lastSeenBlock; |
| 63 | + private final AtomicLong latestTxGauge; |
| 64 | + private final AtomicLong pendingTxGauge; |
| 65 | + private Disposable newHeads; |
| 66 | + |
| 67 | + public WebSocketBlockchainListener(final ApplicationEventPublisher applicationEventPublisher, |
| 68 | + final ConfigServerConfigurationService configServerConfigurationService, |
| 69 | + final SignerService signerService, |
| 70 | + final WorkerConfigurationService workerConfigurationService) { |
| 71 | + this.applicationEventPublisher = applicationEventPublisher; |
| 72 | + this.walletAddress = signerService.getAddress(); |
| 73 | + final String nodeUrl = !workerConfigurationService.getOverrideBlockchainNodeAddress().isEmpty() ? |
| 74 | + workerConfigurationService.getOverrideBlockchainNodeAddress() : |
| 75 | + configServerConfigurationService.getChainNodeUrl(); |
| 76 | + final String wsUrl = nodeUrl.replace("http", "ws"); |
| 77 | + this.webSocketService = new WebSocketService(wsUrl, false); |
| 78 | + this.web3Client = Web3j.build(new HttpService(nodeUrl), |
| 79 | + configServerConfigurationService.getBlockTime().toMillis(), Async.defaultExecutorService()); |
| 80 | + lastSeenBlock = Metrics.gauge(LATEST_BLOCK_METRIC_NAME, new AtomicLong(0)); |
| 81 | + latestTxGauge = Metrics.gauge(TX_COUNT_METRIC_NAME, List.of(Tag.of("block", "latest")), new AtomicLong(0)); |
| 82 | + pendingTxGauge = Metrics.gauge(TX_COUNT_METRIC_NAME, List.of(Tag.of("block", "pending")), new AtomicLong(0)); |
| 83 | + } |
| 84 | + |
| 85 | + @Scheduled(fixedRate = 5000) |
| 86 | + public void run() throws ConnectException { |
| 87 | + if (newHeads != null && !newHeads.isDisposed()) { |
| 88 | + return; |
| 89 | + } |
| 90 | + |
| 91 | + log.warn("web socket disconnection detected"); |
| 92 | + webSocketService.connect(); |
| 93 | + |
| 94 | + final Request<?, EthSubscribe> newHeadsRequest = new Request<>( |
| 95 | + SUBSCRIBE_METHOD, |
| 96 | + List.of("newHeads", Map.of()), |
| 97 | + webSocketService, |
| 98 | + EthSubscribe.class |
| 99 | + ); |
| 100 | + |
| 101 | + final Flowable<NewHeadsNotification> newHeadsEvents = webSocketService.subscribe( |
| 102 | + newHeadsRequest, UNSUBSCRIBE_METHOD, NewHeadsNotification.class); |
| 103 | + newHeads = newHeadsEvents.subscribe(this::processHead, this::handleError); |
| 104 | + } |
| 105 | + |
| 106 | + private void processHead(final NewHeadsNotification event) throws IOException { |
| 107 | + final long blockNumber = Numeric.toBigInt(event.getParams().getResult().getNumber()).longValue(); |
| 108 | + final String blockHash = event.getParams().getResult().getHash(); |
| 109 | + final long blockTimestamp = Numeric.toBigInt(event.getParams().getResult().getTimestamp()).longValue(); |
| 110 | + lastSeenBlock.set(blockNumber); |
| 111 | + final BigInteger pendingTxCount = web3Client.ethGetTransactionCount(walletAddress, |
| 112 | + DefaultBlockParameterName.PENDING).send().getTransactionCount(); |
| 113 | + final BigInteger latestTxCount = web3Client.ethGetTransactionCount(walletAddress, |
| 114 | + DefaultBlockParameterName.LATEST).send().getTransactionCount(); |
| 115 | + log.info("Transaction count [block:{}, pending:{}, latest:{}]", |
| 116 | + lastSeenBlock, pendingTxCount, latestTxCount); |
| 117 | + pendingTxGauge.set(pendingTxCount.longValue()); |
| 118 | + latestTxGauge.set(latestTxCount.longValue()); |
| 119 | + applicationEventPublisher.publishEvent(new LatestBlockEvent(this, blockNumber, blockHash, blockTimestamp)); |
| 120 | + } |
| 121 | + |
| 122 | + private void handleError(final Throwable t) { |
| 123 | + log.error("An error happened during subscription", t); |
| 124 | + } |
| 125 | + |
| 126 | +} |
0 commit comments