cap sparrow.log at 10mb with one rolled backup, and ignore server notifications that match no subscription
What changed, and why it matters
This commit makes two unrelated changes to the Sparrow Wallet desktop app. First, it caps the app's log file at 10 MB and keeps one rolled backup, preventing the log from growing forever and filling up disk space. Second, it tightens how the app handles messages from a Bitcoin Electrum server: instead of treating any message with a 'method' field as a subscription notification, it now checks whether the method name and parameters match one of the subscriptions the app actually registered for. Messages that don't match are classified as unexpected notifications and are ignored, with a warning logged at most once per minute. The change is defensive and reduces the chance that a malicious or misbehaving server could confuse the wallet by sending unexpected notifications.
Review the parameter-matching logic for completeness and ensure all future subscription methods are annotated correctly so their notifications are not accidentally dropped. Confirm that 10 MB log retention is sufficient for support diagnostics. No urgent security patch is indicated, but users should upgrade normally to benefit from the hardening.
Security signals we found
Server-to-client notification filtering now validates method name and parameter schema before dispatch
Unexpected notifications are dropped instead of being passed to the JSON-RPC handler
Log file growth is bounded, mitigating disk-space exhaustion from verbose logging
Warning for ignored notifications is rate-limited to once per minute to avoid log spam
Unit tests added for accepted, refused, and response message classifications
Evidence from the diff
The patch modifies TcpTransport to replace the simple isNotification() check with getMessageType(), which introspects SubscriptionService’s @JsonRpcMethod-annotated methods to build a map of expected notification methods and their required/optional parameters. Incoming server messages are parsed with Jackson and classified as RESPONSE, SUBSCRIPTION_NOTIFICATION, or OTHER_NOTIFICATION. Only SUBSCRIPTION_NOTIFICATION messages are dispatched to jsonRpcServer.handle(); OTHER_NOTIFICATION messages are dropped and a rate-limited warning is emitted. The logback.xml change switches the FILE appender from FileAppender to RollingFileAppender with FixedWindowRollingPolicy (minIndex=1, maxIndex=1) and SizeBasedTriggeringPolicy (maxFileSize=10MB), limiting sparrow.log to 10 MB plus one backup. A new unit test verifies the classification logic.
Changed components
src/main/java/com/sparrowwallet/sparrow/net/TcpTransport.javasrc/main/resources/logback.xmlElectrum server JSON-RPC message handlingLocal log file rotation policyInspect captured patch +119 / −9
### src/main/java/com/sparrowwallet/sparrow/net/TcpTransport.java
@@ -3,6 +3,9 @@
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
+import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcMethod;
+import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcOptional;
+import com.github.arteam.simplejsonrpc.core.annotation.JsonRpcParam;
import com.github.arteam.simplejsonrpc.server.JsonRpcServer;
import com.google.common.base.Splitter;
import com.google.common.net.HostAndPort;
@@ -21,6 +24,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
+import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -29,6 +33,7 @@
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
public class TcpTransport implements CloseableTransport, TimeoutCounter {
private static final Logger log = LoggerFactory.getLogger(TcpTransport.class);
@@ -251,8 +256,11 @@ public void readInputLoop() throws ServerException {
try {
String received = readInputStream(in);
wireLog.info("< " + received);
- if(isNotification(received)) {
+ MessageType messageType = getMessageType(received);
+ if(messageType == MessageType.SUBSCRIPTION_NOTIFICATION) {
jsonRpcServer.handle(received, subscriptionService);
+ } else if(messageType == MessageType.OTHER_NOTIFICATION) {
+ warnUnhandledNotification();
} else {
deliverResponse(received);
}
@@ -418,23 +426,73 @@ static long getLastResponseSequence() {
return sequence == null ? 0L : sequence;
}
- private static boolean isNotification(String json) {
+ //The params of each notification the subscription service handles, by name, and those of them it requires
+ private record SubscriptionParams(Set<String> names, Set<String> required) {}
+
+ private static final Map<String, SubscriptionParams> SUBSCRIPTION_PARAMS = Arrays.stream(SubscriptionService.class.getMethods())
+ .filter(method -> method.isAnnotationPresent(JsonRpcMethod.class))
+ .collect(Collectors.toUnmodifiableMap(method -> method.getAnnotation(JsonRpcMethod.class).value(), method -> new SubscriptionParams(
+ Arrays.stream(method.getParameters()).map(parameter -> parameter.getAnnotation(JsonRpcParam.class).value()).collect(Collectors.toUnmodifiableSet()),
+ Arrays.stream(method.getParameters()).filter(parameter -> !parameter.isAnnotationPresent(JsonRpcOptional.class))
+ .map(parameter -> parameter.getAnnotation(JsonRpcParam.class).value()).collect(Collectors.toUnmodifiableSet()))));
+
+ private static final long UNHANDLED_NOTIFICATION_WARNING_MILLIS = TimeUnit.MINUTES.toMillis(1);
+ private static final AtomicLong lastUnhandledNotificationWarning = new AtomicLong();
+
+ enum MessageType { RESPONSE, SUBSCRIPTION_NOTIFICATION, OTHER_NOTIFICATION }
+
+ //A notification names a method, and is passed on only where the subscription service handles that method with these params
+ static MessageType getMessageType(String json) {
try(JsonParser parser = JSON_FACTORY.createParser(json)) {
if(parser.nextToken() != JsonToken.START_OBJECT) {
- return false;
+ return MessageType.RESPONSE;
}
+
+ String method = null;
+ int paramCount = -1;
+ Set<String> paramNames = null;
while(parser.nextToken() == JsonToken.FIELD_NAME) {
String field = parser.currentName();
JsonToken value = parser.nextToken();
- if("method".equals(field)) {
- return value == JsonToken.VALUE_STRING;
+ if("method".equals(field) && value == JsonToken.VALUE_STRING) {
+ method = parser.getText();
+ } else if("params".equals(field) && value == JsonToken.START_ARRAY) {
+ paramCount = 0;
+ while(parser.nextToken() != JsonToken.END_ARRAY) {
+ parser.skipChildren();
+ paramCount++;
+ }
+ } else if("params".equals(field) && value == JsonToken.START_OBJECT) {
+ paramNames = new LinkedHashSet<>();
+ while(parser.nextToken() == JsonToken.FIELD_NAME) {
+ paramNames.add(parser.currentName());
+ parser.nextToken();
+ parser.skipChildren();
+ }
+ } else {
+ parser.skipChildren();
}
- parser.skipChildren();
}
- return false;
+
+ if(method == null) {
+ return MessageType.RESPONSE;
+ }
+
+ SubscriptionParams params = SUBSCRIPTION_PARAMS.get(method);
+ boolean handled = params != null && (paramNames != null ? params.names().containsAll(paramNames) && paramNames.containsAll(params.required())
+ : paramCount >= params.required().size() && paramCount <= params.names().size());
+ return handled ? MessageType.SUBSCRIPTION_NOTIFICATION : MessageType.OTHER_NOTIFICATION;
} catch(Exception e) {
log.warn("Could not parse JSON-RPC message from server: " + e.getMessage());
- return false;
+ return MessageType.RESPONSE;
+ }
+ }
+
+ private static void warnUnhandledNotification() {
+ long now = System.currentTimeMillis();
+ long last = lastUnhandledNotificationWarning.get();
+ if(now - last >= UNHANDLED_NOTIFICATION_WARNING_MILLIS && lastUnhandledNotificationWarning.compareAndSet(last, now)) {
+ log.warn("Ignoring notifications from server that do not match a subscription");
}
}
### src/main/resources/logback.xml
@@ -31,8 +31,16 @@
<application>sparrow</application>
</define>
- <appender name="FILE" class="ch.qos.logback.core.FileAppender">
+ <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${appDir}/sparrow.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${appDir}/sparrow.%i.log</fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>1</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>10MB</maxFileSize>
+ </triggeringPolicy>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
### src/test/java/com/sparrowwallet/sparrow/net/SubscriptionNotificationTest.java
@@ -0,0 +1,44 @@
+package com.sparrowwallet.sparrow.net;
+
+import org.junit.jupiter.api.Test;
+
+import static com.sparrowwallet.sparrow.net.TcpTransport.MessageType.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class SubscriptionNotificationTest {
+ //Single quotes in the message stand for double quotes, for readability
+ private static TcpTransport.MessageType type(String message) {
+ return TcpTransport.getMessageType(message.replace('\'', '"'));
+ }
+
+ private static String notification(String method, String params) {
+ return "{'jsonrpc':'2.0','method':'blockchain." + method + "'" + (params == null ? "" : ",'params':" + params) + "}";
+ }
+
+ @Test
+ public void acceptsSubscriptionNotifications() {
+ assertEquals(SUBSCRIPTION_NOTIFICATION, type(notification("headers.subscribe", "[{'height':1,'hex':'00'}]")));
+ assertEquals(SUBSCRIPTION_NOTIFICATION, type(notification("scripthash.subscribe", "['ab','cd']")));
+ assertEquals(SUBSCRIPTION_NOTIFICATION, type(notification("scripthash.subscribe", "['ab']")));
+ assertEquals(SUBSCRIPTION_NOTIFICATION, type("{'params':['ab',null],'method':'blockchain.scripthash.subscribe','jsonrpc':'2.0'}"));
+ assertEquals(SUBSCRIPTION_NOTIFICATION, type(notification("silentpayments.subscribe", "[{'address':'sp'},0.5,[]]")));
+ assertEquals(SUBSCRIPTION_NOTIFICATION, type(notification("silentpayments.subscribe", "{'subscription':{},'progress':1.0,'history':[]}")));
+ }
+
+ @Test
+ public void refusesOtherNotifications() {
+ assertEquals(OTHER_NOTIFICATION, type(notification("unknown", "[]")));
+ assertEquals(OTHER_NOTIFICATION, type(notification("scripthash.subscribe", "[]")));
+ assertEquals(OTHER_NOTIFICATION, type(notification("scripthash.subscribe", "['ab','cd','ef']")));
+ assertEquals(OTHER_NOTIFICATION, type(notification("scripthash.subscribe", "'ab'")));
+ assertEquals(OTHER_NOTIFICATION, type(notification("scripthash.subscribe", null)));
+ assertEquals(OTHER_NOTIFICATION, type(notification("silentpayments.subscribe", "{'subscription':{},'other':1}")));
+ assertEquals(OTHER_NOTIFICATION, type(notification("headers.subscribe", "[{},{}]")));
+ }
+
+ @Test
+ public void classifiesResponses() {
+ assertEquals(RESPONSE, type("{'jsonrpc':'2.0','id':1,'result':['ab']}"));
+ assertEquals(RESPONSE, type("not json"));
+ }
+}Why this scored 47/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.