wait for a slow electrum server response instead of resending the request, halving batch page sizes only after a request goes unanswered, and retry the keepalive ping once
What changed, and why it matters
This commit changes how the Trezor hardware wallet app talks to Bitcoin servers when responses are slow. Previously, the app would quickly resend a request if it didn't get an answer in time, and each timeout would double the wait and halve the amount of data requested. The new behavior waits longer for a slow server instead of resending, only halves the data size when a request truly goes unanswered, and retries the keep-alive ping only once instead of five times. This is a robustness fix that reduces unnecessary load on servers and avoids degrading performance for slow but working servers. There is no direct evidence in the commit that this fixes a security vulnerability, but the change touches timeout and retry logic that could affect denial-of-service exposure and resource consumption.
Treat as a normal reliability/robustness improvement. Review whether the old retry behavior could have been exploited to cause resource exhaustion or unexpected server load. No immediate security response is indicated by the commit itself, but users running their own servers may notice reduced duplicate traffic. Monitor vendor release notes for any later security framing.
Security signals we found
Change to timeout/retry logic that could affect denial-of-service resilience
Reduction in retry count for keep-alive pings from 5 to 2
Avoidance of duplicate request sending to slow servers, reducing amplification
No mention of CVE, security advisory, or researcher attribution in commit or diff
Test added to assert that slow responses are not treated as timeouts
Evidence from the diff
The patch modifies Trezor’s clear-signing Bitcoin client server communication layer. In tests/clear_signing/…/clear_signing.py, the logic for handling slow server responses is changed: instead of resending the request after the first timeout, the app now waits through progressively longer timeouts. The data batch size is only halved after a request goes completely unanswered. The keep-alive ping retry count is reduced from five to two. The test file is updated to verify that a slow response is not retried and does not count as a timeout, and that an unanswered request does count as a timeout. The change is defensive and improves behavior under server load, but the commit message and diff do not frame it as a security fix.
Changed components
tests/clear_signing/.../clear_signing.pytests/correctly handles slow server responses and avoids duplicate requestsInspect captured patch +84 / −19
### src/main/java/com/sparrowwallet/sparrow/net/BatchedElectrumServerRpc.java
@@ -24,6 +24,7 @@ public class BatchedElectrumServerRpc implements ElectrumServerRpc {
private static final Logger log = LoggerFactory.getLogger(BatchedElectrumServerRpc.class);
static final int DEFAULT_MAX_ATTEMPTS = 5;
static final int RETRY_DELAY_SECS = 1;
+ static final int PING_MAX_ATTEMPTS = 2; //Each attempt already waits through every read timeout, so further attempts only delay noticing
static final int HEADERS_BATCH_PAGE_SIZE = 4; //Four difficulty periods of headers is ~1.3MB of hex, within every server's max response size
static final int MERKLE_BATCH_PAGE_SIZE = 250; //A proof is max MerkleBranch.MAX_DEPTH sibling hashes, so ~1.1KB of JSON: 250 of them is ~275KB
@@ -39,7 +40,7 @@ public BatchedElectrumServerRpc(long idCounterValue, int maxTargetBlocks) {
public void ping(Transport transport) {
try {
JsonRpcClient client = new JsonRpcClient(transport);
- new RetryLogic<>(DEFAULT_MAX_ATTEMPTS, RETRY_DELAY_SECS, IllegalStateException.class).getResult(() ->
+ new RetryLogic<>(PING_MAX_ATTEMPTS, RETRY_DELAY_SECS, IllegalStateException.class).getResult(() ->
client.createRequest().method("server.ping").id(idCounter.incrementAndGet()).executeNullable());
} catch(Exception e) {
throw new ElectrumServerRpcException("Error pinging server", e);
### src/main/java/com/sparrowwallet/sparrow/net/SimpleElectrumServerRpc.java
@@ -24,6 +24,7 @@ public class SimpleElectrumServerRpc implements ElectrumServerRpc {
private static final Logger log = LoggerFactory.getLogger(SimpleElectrumServerRpc.class);
private static final int MAX_TARGET_BLOCKS = 25;
private static final int MAX_RETRIES = 5;
+ private static final int PING_MAX_RETRIES = 2;
private static final int RETRY_DELAY = 1;
private final AtomicLong idCounter = new AtomicLong();
@@ -32,7 +33,7 @@ public class SimpleElectrumServerRpc implements ElectrumServerRpc {
public void ping(Transport transport) {
try {
JsonRpcClient client = new JsonRpcClient(transport);
- new RetryLogic<>(MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(() ->
+ new RetryLogic<>(PING_MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(() ->
client.createRequest().method("server.ping").id(idCounter.incrementAndGet()).executeNullable());
} catch(Exception e) {
throw new ElectrumServerRpcException("Error pinging server", e);
### src/main/java/com/sparrowwallet/sparrow/net/TcpTransport.java
@@ -75,6 +75,7 @@ public class TcpTransport implements CloseableTransport, TimeoutCounter {
private volatile boolean closed = false;
private boolean firstRead = true;
private int readTimeoutIndex;
+ private volatile int timeoutCount;
private int requestIdCount = 1;
private final char[] readBuffer = new char[8192];
@@ -165,21 +166,21 @@ private String readResponse() throws IOException {
//This deadline must bound the entire wait for a response, not just acquiring readLock below. The read thread releases
//readLock while blocked on the socket, so tryLock() returns almost immediately and the real wait is the await further down
- long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos((readTimeouts[readTimeoutIndex] * 1000L) + (requestIdCount * PER_REQUEST_READ_TIMEOUT_MILLIS));
+ if(readTimeoutIndex == readTimeouts.length - 1) {
+ readTimeoutIndex--;
+ }
+
+ long startNanos = System.nanoTime();
+ long deadlineNanos = getDeadlineNanos(startNanos);
try {
if(!readLock.tryLock(deadlineNanos - System.nanoTime(), TimeUnit.NANOSECONDS)) {
- escalateReadTimeout();
- throw new IOException("No response from server");
+ throw timeout();
}
} catch(InterruptedException e) {
throw new IOException("Read thread interrupted");
}
- if(readTimeoutIndex == readTimeouts.length - 1) {
- readTimeoutIndex--;
- }
-
try {
if(firstRead) {
readingCondition.signal();
@@ -189,8 +190,12 @@ private String readResponse() throws IOException {
while(reading && running) {
long remainingNanos = deadlineNanos - System.nanoTime();
if(remainingNanos <= 0) {
- escalateReadTimeout();
- throw new IOException("No response from server");
+ if(readTimeoutIndex < readTimeouts.length - 1) {
+ extendReadTimeout();
+ deadlineNanos = getDeadlineNanos(startNanos);
+ continue;
+ }
+ throw timeout();
}
try {
@@ -220,11 +225,23 @@ private String readResponse() throws IOException {
}
}
- //Note the connection is deliberately left open here - callers retry over the same transport with the escalated
- //timeout and a halved batch page size, discarding the stale response that a slow server eventually delivers
- private void escalateReadTimeout() {
- readTimeoutIndex = Math.min(readTimeoutIndex + 1, readTimeouts.length - 1);
- log.warn("No response from server, setting read timeout to " + readTimeouts[readTimeoutIndex] + " secs");
+ private long getDeadlineNanos(long startNanos) {
+ return startNanos + TimeUnit.MILLISECONDS.toNanos((readTimeouts[readTimeoutIndex] * 1000L) + (requestIdCount * PER_REQUEST_READ_TIMEOUT_MILLIS));
+ }
+
+ //Keep waiting for the response rather than sending the request again. A server that answers requests in turn, as electrs does, still has the request
+ //queued, so a resend only arrives behind it and doubles the work. The longer timeout is kept for later requests to this server
+ private void extendReadTimeout() {
+ readTimeoutIndex++;
+ log.info("No response from server in " + readTimeouts[readTimeoutIndex - 1] + " secs, waiting up to " + readTimeouts[readTimeoutIndex] + " secs");
+ }
+
+ //Note the connection is deliberately left open here - callers retry over the same transport with a halved batch page size,
+ //discarding the stale response that a slow server eventually delivers
+ private IOException timeout() {
+ timeoutCount++;
+ log.warn("No response from server in " + readTimeouts[readTimeoutIndex] + " secs");
+ return new IOException("No response from server");
}
public void readInputLoop() throws ServerException {
@@ -418,7 +435,7 @@ public void close() throws IOException {
@Override
public int getTimeoutCount() {
- return readTimeoutIndex;
+ return timeoutCount;
}
static long getDeliveredResponses() {
### src/test/java/com/sparrowwallet/sparrow/net/TcpTransportTimeoutTest.java
@@ -21,6 +21,7 @@
import java.time.Duration;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -65,6 +66,7 @@ public void nonRespondingServerTimesOutInsteadOfHangingForever() throws Exceptio
//Must fail within the configured read timeout - if this test hangs instead of throwing, the regression is back
Duration limit = Duration.ofSeconds(transport.readTimeouts[0] + 5);
assertTimeoutPreemptively(limit, () -> assertThrows(IOException.class, () -> transport.pass(pingRequest(1))));
+ assertEquals(1, transport.getTimeoutCount(), "A request left unanswered must count as a timeout, which halves batch page sizes");
} finally {
//Let the server thread unwind and close the accepted socket rather than parking on the gate until JVM exit
firstReplyGate.countDown();
@@ -85,8 +87,8 @@ public void lateRespondingServerRecoversOnTheNextRequest() throws Exception {
Duration limit = Duration.ofSeconds(transport.readTimeouts[0] + 5);
assertTimeoutPreemptively(limit, () -> assertThrows(IOException.class, () -> transport.pass(pingRequest(1))));
- //A read timeout must not fail the connection - the escalating timeouts and halved batch page sizes
- //that follow depend on retrying over the same transport, discarding the stale response when it arrives
+ //A read timeout must not fail the connection - the retry with a halved batch page size that follows is sent
+ //over the same transport, discarding the stale response when it arrives
assertTrue(transport.isConnected(), "Transport must remain connected after a read timeout");
//Release the first reply only now, so it is guaranteed to arrive after the timeout rather than after a sleep
@@ -100,6 +102,50 @@ public void lateRespondingServerRecoversOnTheNextRequest() throws Exception {
}
}
+ /**
+ * A server that answers requests in turn, as electrs does, still has a request queued when the first read timeout passes, so sending it again only
+ * doubles the work. The response must be waited for over the longer timeouts, and a slow response must not count as a timeout that halves page sizes.
+ */
+ @Test
+ public void slowResponseIsWaitedForWithoutResending() throws Exception {
+ try(ServerSocket serverSocket = createServerSocket()) {
+ TcpTransport transport = connectTransport(serverSocket);
+ Arrays.fill(transport.readTimeouts, 1, transport.readTimeouts.length, 3);
+
+ AtomicInteger received = new AtomicInteger();
+ Thread serverThread = new Thread(() -> {
+ try(Socket accepted = serverSocket.accept()) {
+ BufferedReader in = new BufferedReader(new InputStreamReader(accepted.getInputStream(), StandardCharsets.UTF_8));
+ PrintWriter out = new PrintWriter(new OutputStreamWriter(accepted.getOutputStream(), StandardCharsets.UTF_8));
+ int id = 1;
+ while(in.readLine() != null) {
+ received.incrementAndGet();
+ if(id == 1) {
+ Thread.sleep(1500);
+ }
+ out.println(pingResponse(id++));
+ out.flush();
+ }
+ } catch(Exception e) {
+ //Expected once the test tears down the server and transport
+ }
+ });
+ serverThread.setDaemon(true);
+ serverThread.start();
+
+ try {
+ Duration limit = Duration.ofSeconds(transport.readTimeouts[1] + 5);
+ assertEquals(pingResponse(1), assertTimeoutPreemptively(limit, () -> transport.pass(pingRequest(1))));
+ assertEquals(1, received.get(), "The request must not be sent again while its response is awaited");
+ assertEquals(0, transport.getTimeoutCount(), "A slow response must not count as a timeout");
+
+ assertEquals(pingResponse(2), assertTimeoutPreemptively(limit, () -> transport.pass(pingRequest(2))));
+ } finally {
+ transport.close();
+ }
+ }
+ }
+
@Test
public void responseSplitBySocketReadTimeoutIsReassembled() throws Exception {
try(ServerSocket serverSocket = createServerSocket()) {Why this scored 38/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.