• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

knowledgepixels / nanopub-registry / 28439237911

30 Jun 2026 10:57AM UTC coverage: 32.308% (+0.5%) from 31.844%
28439237911

push

github

web-flow
Merge pull request #120 from knowledgepixels/fix/trust-state-snapshot-toload-leaf-119

fix(trust-state): exclude toLoad accounts from snapshot hash and snapshot (#119)

319 of 1116 branches covered (28.58%)

Branch coverage included in aggregate %.

1068 of 3177 relevant lines covered (33.62%)

5.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

71.13
src/main/java/com/knowledgepixels/registry/RegistryDB.java
1
package com.knowledgepixels.registry;
2

3
import com.knowledgepixels.registry.db.IndexInitializer;
4
import com.mongodb.*;
5
import com.mongodb.client.ClientSession;
6
import com.mongodb.client.MongoCollection;
7
import com.mongodb.client.MongoCursor;
8
import com.mongodb.client.MongoDatabase;
9
import com.mongodb.client.model.CountOptions;
10
import com.mongodb.client.model.FindOneAndUpdateOptions;
11
import com.mongodb.client.model.ReturnDocument;
12
import com.mongodb.client.model.UpdateOptions;
13
import net.trustyuri.TrustyUriUtils;
14
import org.bson.Document;
15
import org.bson.conversions.Bson;
16
import org.bson.types.Binary;
17
import org.eclipse.rdf4j.common.exception.RDF4JException;
18
import org.eclipse.rdf4j.model.IRI;
19
import org.eclipse.rdf4j.rio.RDFFormat;
20
import org.nanopub.MalformedNanopubException;
21
import org.nanopub.Nanopub;
22
import org.nanopub.NanopubUtils;
23
import org.nanopub.extra.security.MalformedCryptoElementException;
24
import org.nanopub.extra.security.NanopubSignatureElement;
25
import org.nanopub.extra.security.SignatureUtils;
26
import org.nanopub.jelly.JellyUtils;
27
import org.slf4j.Logger;
28
import org.slf4j.LoggerFactory;
29

30
import java.io.IOException;
31
import java.security.GeneralSecurityException;
32
import java.util.ArrayList;
33
import java.util.Calendar;
34
import java.util.HashSet;
35
import java.util.Set;
36

37
import static com.mongodb.client.model.Indexes.ascending;
38

39
public class RegistryDB {
40

41
    private RegistryDB() {
42
    }
43

44
    private static final String REGISTRY_DB_NAME = Utils.getEnv("REGISTRY_DB_NAME", "nanopubRegistry");
12✔
45

46
    private static final Logger logger = LoggerFactory.getLogger(RegistryDB.class);
9✔
47

48
    private static MongoClient mongoClient;
49
    private static MongoDatabase mongoDB;
50

51
    /**
52
     * Returns the MongoDB database instance.
53
     *
54
     * @return the MongoDatabase instance
55
     */
56
    public static MongoDatabase getDB() {
57
        return mongoDB;
6✔
58
    }
59

60
    /**
61
     * Returns the MongoDB client instance.
62
     *
63
     * @return the MongoClient instance
64
     */
65
    public static MongoClient getClient() {
66
        return mongoClient;
6✔
67
    }
68

69
    /**
70
     * Returns the specified collection from the MongoDB database.
71
     *
72
     * @param name the name of the collection
73
     * @return the MongoCollection instance
74
     */
75
    public static MongoCollection<Document> collection(String name) {
76
        return mongoDB.getCollection(name);
12✔
77
    }
78

79
    /**
80
     * Initializes the MongoDB connection and sets up collections and indexes if not already initialized.
81
     */
82
    public static void init() {
83
        if (mongoClient != null) {
6✔
84
            logger.info("RegistryDB already initialized (database: {})", REGISTRY_DB_NAME);
12✔
85
            return;
3✔
86
        }
87
        final String REGISTRY_DB_HOST = Utils.getEnv("REGISTRY_DB_HOST", "mongodb");
12✔
88
        final int REGISTRY_DB_PORT = Integer.parseInt(Utils.getEnv("REGISTRY_DB_PORT", String.valueOf(ServerAddress.defaultPort())));
18✔
89
        logger.info("Initializing RegistryDB connection to database '{}' at {}:{}", REGISTRY_DB_NAME, REGISTRY_DB_HOST, REGISTRY_DB_PORT);
54✔
90
        mongoClient = new MongoClient(REGISTRY_DB_HOST, REGISTRY_DB_PORT);
18✔
91
        mongoDB = mongoClient.getDatabase(REGISTRY_DB_NAME);
12✔
92

93
        try (ClientSession mongoSession = mongoClient.startSession()) {
9✔
94
            logger.debug("MongoDB client session started for initialization");
9✔
95
            if (!isInitialized(mongoSession)) {
9!
96
                logger.info("Database '{}' not initialized; creating collections and indexes", REGISTRY_DB_NAME);
12✔
97
                IndexInitializer.initCollections(mongoSession);
9✔
98
            } else {
99
                logger.debug("Database '{}' already has setupId", REGISTRY_DB_NAME);
×
100
            }
101
            initCounter(mongoSession);
6✔
102
        }
103
    }
3✔
104

105
    /**
106
     * Checks if the database has been initialized.
107
     *
108
     * @param mongoSession the MongoDB client session
109
     * @return true if initialized, false otherwise
110
     */
111
    public static boolean isInitialized(ClientSession mongoSession) {
112
        boolean initialized = getValue(mongoSession, Collection.SERVER_INFO.toString(), "setupId") != null;
24!
113
        logger.debug("isInitialized check for database '{}': {}", REGISTRY_DB_NAME, initialized);
18✔
114
        return initialized;
6✔
115
    }
116

117
    /**
118
     * Renames a collection in the database. If the new collection name already exists, it will be dropped first.
119
     *
120
     * @param oldCollectionName the current name of the collection
121
     * @param newCollectionName the new name for the collection
122
     */
123
    public static void rename(String oldCollectionName, String newCollectionName) {
124
        // Designed as idempotent operation: calling multiple times has same effect as calling once
125
        if (hasCollection(oldCollectionName)) {
9✔
126
            if (hasCollection(newCollectionName)) {
9✔
127
                collection(newCollectionName).drop();
9✔
128
            }
129
            collection(oldCollectionName).renameCollection(new MongoNamespace(REGISTRY_DB_NAME, newCollectionName));
24✔
130
        }
131
    }
3✔
132

133
    /**
134
     * Checks if a collection with the given name exists in the database.
135
     *
136
     * @param collectionName the name of the collection to check
137
     * @return true if the collection exists, false otherwise
138
     */
139
    public static boolean hasCollection(String collectionName) {
140
        boolean exists = mongoDB.listCollectionNames().into(new ArrayList<>()).contains(collectionName);
30✔
141
        logger.debug("Collection existence check for '{}': {}", collectionName, exists);
18✔
142
        return exists;
6✔
143
    }
144

145
    /**
146
     * Increases the trust state counter in the server info collection.
147
     *
148
     * @param mongoSession the MongoDB client session
149
     */
150
    public static void increaseStateCounter(ClientSession mongoSession) {
151
        MongoCursor<Document> cursor = collection(Collection.SERVER_INFO.toString()).find(mongoSession, new Document("_id", "trustStateCounter")).cursor();
36✔
152
        if (cursor.hasNext()) {
9✔
153
            long counter = cursor.next().getLong("value");
21✔
154
            collection(Collection.SERVER_INFO.toString()).updateOne(mongoSession, new Document("_id", "trustStateCounter"), new Document("$set", new Document("value", counter + 1)));
69✔
155
            logger.debug("Incremented trustStateCounter from {} to {}", counter, counter + 1);
27✔
156
        } else {
3✔
157
            collection(Collection.SERVER_INFO.toString()).insertOne(mongoSession, new Document("_id", "trustStateCounter").append("value", 0L));
42✔
158
            logger.info("Initialized trustStateCounter to 0 in collection '{}'", Collection.SERVER_INFO);
12✔
159
        }
160
    }
3✔
161

162
    /**
163
     * Checks if an element with the given name exists in the specified collection.
164
     *
165
     * @param mongoSession the MongoDB client session
166
     * @param collection   the name of the collection
167
     * @param elementName  the name of the element used as the _id field
168
     * @return true if the element exists, false otherwise
169
     */
170
    public static boolean has(ClientSession mongoSession, String collection, String elementName) {
171
        return has(mongoSession, collection, new Document("_id", elementName));
27✔
172
    }
173

174
    private static final CountOptions hasCountOptions = new CountOptions().limit(1);
21✔
175

176
    /**
177
     * Checks if any document matching the given filter exists in the specified collection.
178
     *
179
     * @param mongoSession the MongoDB client session
180
     * @param collection   the name of the collection
181
     * @param find         the filter to match documents
182
     * @return true if at least one matching document exists, false otherwise
183
     */
184
    public static boolean has(ClientSession mongoSession, String collection, Bson find) {
185
        boolean found = collection(collection).countDocuments(mongoSession, find, hasCountOptions) > 0;
39✔
186
        logger.debug("Existence check in collection '{}' for filter {}: {}", collection, find, found);
54✔
187
        return found;
6✔
188
    }
189

190
    /**
191
     * Retrieves a cursor for documents matching the given filter in the specified collection.
192
     *
193
     * @param mongoSession the MongoDB client session
194
     * @param collection   the name of the collection
195
     * @param find         the filter to match documents
196
     * @return a MongoCursor for the matching documents
197
     */
198
    public static MongoCursor<Document> get(ClientSession mongoSession, String collection, Bson find) {
199
        logger.trace("Querying collection '{}' with filter {}", collection, find);
15✔
200
        return collection(collection).find(mongoSession, find).cursor();
21✔
201
    }
202

203
    /**
204
     * Retrieves the value of an element with the given name from the specified collection.
205
     *
206
     * @param mongoSession the MongoDB client session
207
     * @param collection   the name of the collection
208
     * @param elementName  the name of the element used as the _id field
209
     * @return the value of the element, or null if not found
210
     */
211
    public static Object getValue(ClientSession mongoSession, String collection, String elementName) {
212
        logger.debug("Reading value of element '{}' from collection '{}'", elementName, collection);
15✔
213
        Document d = collection(collection).find(mongoSession, new Document("_id", elementName)).first();
36✔
214
        if (d == null) {
6✔
215
            logger.trace("Element '{}' not found in collection '{}'", elementName, collection);
15✔
216
            return null;
6✔
217
        }
218
        Object value = d.get("value");
12✔
219
        logger.debug("Found element '{}' in collection '{}' with value type {}", elementName, collection, value == null ? "null" : value.getClass().getSimpleName());
63!
220
        return value;
6✔
221
    }
222

223
    /**
224
     * Retrieves the boolean value of an element with the given name from the specified collection.
225
     *
226
     * @param mongoSession the MongoDB client session
227
     * @param collection   the name of the collection
228
     * @param elementName  the name of the element used as the _id field
229
     * @return the value of the element, or null if not found
230
     */
231
    public static boolean isSet(ClientSession mongoSession, String collection, String elementName) {
232
        Document d = collection(collection).find(mongoSession, new Document("_id", elementName)).first();
36✔
233
        if (d == null) {
6✔
234
            logger.trace("isSet: element '{}' not found in collection '{}'", elementName, collection);
15✔
235
            return false;
6✔
236
        }
237
        Boolean val = d.getBoolean("value");
12✔
238
        logger.debug("isSet: element '{}' in collection '{}' has boolean value {}", elementName, collection, val);
51✔
239
        return val;
9✔
240
    }
241

242
    /**
243
     * Retrieves a single document matching the given filter from the specified collection.
244
     *
245
     * @param mongoSession the MongoDB client session
246
     * @param collection   the name of the collection
247
     * @param find         the filter to match the document
248
     * @return the matching document, or null if not found
249
     */
250
    public static Document getOne(ClientSession mongoSession, String collection, Bson find) {
251
        logger.trace("getOne from '{}' with filter {}", collection, find);
15✔
252
        return collection(collection).find(mongoSession, find).first();
24✔
253
    }
254

255
    /**
256
     * Retrieves the maximum value of a specified field from the documents in the given collection.
257
     *
258
     * @param mongoSession the MongoDB client session
259
     * @param collection   the name of the collection
260
     * @param fieldName    the field for which to find the maximum value
261
     * @return the maximum value of the specified field, or null if no documents exist
262
     */
263
    public static Object getMaxValue(ClientSession mongoSession, String collection, String fieldName) {
264
        Document doc = collection(collection).find(mongoSession).projection(new Document(fieldName, 1)).sort(new Document(fieldName, -1)).first();
63✔
265
        if (doc == null) {
6✔
266
            logger.trace("getMaxValue: no documents in collection '{}' for field '{}'", collection, fieldName);
15✔
267
            return null;
6✔
268
        }
269
        Object val = doc.get(fieldName);
12✔
270
        logger.debug("getMaxValue: collection '{}' field '{}' max = {}", collection, fieldName, val);
51✔
271
        return val;
6✔
272
    }
273

274
    /**
275
     * Retrieves the document with the maximum value of a specified field from the documents matching the given filter in the specified collection.
276
     *
277
     * @param mongoSession the MongoDB client session
278
     * @param collection   the name of the collection
279
     * @param find         the filter to match documents
280
     * @param fieldName    the field for which to find the maximum value
281
     * @return the document with the maximum value of the specified field, or null if no matching documents exist
282
     */
283
    public static Document getMaxValueDocument(ClientSession mongoSession, String collection, Bson find, String fieldName) {
284
        logger.trace("getMaxValueDocument in '{}' with filter {} for field '{}'", collection, find, fieldName);
51✔
285
        return collection(collection).find(mongoSession, find).sort(new Document(fieldName, -1)).first();
45✔
286
    }
287

288
    /**
289
     * Sets or updates a document in the specified collection.
290
     *
291
     * @param mongoSession the MongoDB client session
292
     * @param collection   the name of the collection
293
     * @param update       the document to set or update (must contain an _id field)
294
     */
295
    public static void set(ClientSession mongoSession, String collection, Document update) {
296
        Bson find = new Document("_id", update.get("_id"));
24✔
297
        MongoCursor<Document> cursor = collection(collection).find(mongoSession, find).cursor();
21✔
298
        if (cursor.hasNext()) {
9✔
299
            collection(collection).updateOne(mongoSession, find, new Document("$set", update));
33✔
300
            logger.debug("Updated document with _id={} in collection '{}'", update.get("_id"), collection);
24✔
301
        } else {
302
            logger.debug("set: no existing document with _id={} in collection '{}'; update skipped", update.get("_id"), collection);
21✔
303
        }
304
    }
3✔
305

306
    /**
307
     * Inserts a document into the specified collection.
308
     *
309
     * @param mongoSession the MongoDB client session
310
     * @param collection   the name of the collection
311
     * @param doc          the document to insert
312
     */
313
    public static void insert(ClientSession mongoSession, String collection, Document doc) {
314
        collection(collection).insertOne(mongoSession, doc);
15✔
315
        logger.debug("Inserted document into '{}' with _id={}", collection, doc.get("_id"));
21✔
316
    }
3✔
317

318
    /**
319
     * Sets the value of an element with the given name in the specified collection.
320
     * If the element does not exist, it will be created.
321
     *
322
     * @param mongoSession the MongoDB client session
323
     * @param collection   the name of the collection
324
     * @param elementId    the name of the element used as the _id field
325
     * @param value        the value to set
326
     */
327
    public static void setValue(ClientSession mongoSession, String collection, String elementId, Object value) {
328
        logger.debug("Setting value for element '{}' in collection '{}' (upsert)", elementId, collection);
15✔
329
        collection(collection).updateOne(mongoSession, new Document("_id", elementId), new Document("$set", new Document("value", value)), new UpdateOptions().upsert(true));
72✔
330
    }
3✔
331

332
    /**
333
     * Records the hash of a given value in the "hashes" collection.
334
     * Uses upsert to avoid expensive exception-based duplicate handling.
335
     *
336
     * @param mongoSession the MongoDB client session
337
     * @param value        the value to hash and record
338
     */
339
    public static void recordHash(ClientSession mongoSession, String value) {
340
        String hash = Utils.getHash(value);
9✔
341
        try {
342
            collection("hashes").updateOne(mongoSession, new Document("value", value), new Document("$setOnInsert", new Document("value", value).append("hash", hash)), new UpdateOptions().upsert(true));
81✔
343
            logger.debug("Recorded hash for value (hash={})", hash);
12✔
344
        } catch (MongoWriteException e) {
×
345
            // Concurrent upsert race: another thread inserted the same hash — safe to ignore
346
            if (e.getError().getCategory() != ErrorCategory.DUPLICATE_KEY) {
×
347
                logger.error("Failed to record hash for value (hash={}): {}", hash, e.getMessage(), e);
×
348
                throw e;
×
349
            }
350
            logger.debug("Concurrent insertion for hash {} detected; duplicate ignored", hash);
×
351
        }
3✔
352
    }
3✔
353

354
    /**
355
     * Retrieves the original value corresponding to a given hash from the "hashes" collection.
356
     *
357
     * @param hash the hash to look up
358
     * @return the original value, or null if not found
359
     */
360
    public static String unhash(String hash) {
361
        try (var c = collection("hashes").find(new Document("hash", hash)).cursor()) {
30✔
362
            if (c.hasNext()) {
9✔
363
                String value = c.next().getString("value");
18✔
364
                logger.debug("Unhash found value for hash {}", hash);
12✔
365
                return value;
12✔
366
            }
367
            logger.debug("Unhash: no value found for hash {}", hash);
12✔
368
            return null;
12✔
369
        }
12!
370
    }
371

372
    /**
373
     * Initializes the counter document to the current maximum counter value
374
     * in the nanopubs collection.
375
     * Uses $max to ensure the counter is never decreased. Safe to call on every startup.
376
     */
377
    private static void initCounter(ClientSession mongoSession) {
378
        Long maxCounter = (Long) getMaxValue(mongoSession, Collection.NANOPUBS.toString(), "counter");
21✔
379
        long effective = maxCounter != null ? maxCounter : 0L;
21✔
380
        collection("counters").updateOne(mongoSession, new Document("_id", "nanopubs"), new Document("$max", new Document("value", effective)), new UpdateOptions().upsert(true));
75✔
381
        if (maxCounter != null) {
6✔
382
            logger.info("Nanopub counter resumed at {} (max found in DB)", effective);
18✔
383
        } else {
384
            logger.info("Nanopub counter initialized to 0 (no existing nanopubs found)");
9✔
385
        }
386
    }
3✔
387

388
    /**
389
     * Returns the next counter value for a nanopub via atomic increment.
390
     */
391
    private static long getNextCounter(ClientSession mongoSession) {
392
        Document result = collection("counters").findOneAndUpdate(mongoSession, new Document("_id", "nanopubs"), new Document("$inc", new Document("value", 1L)), new FindOneAndUpdateOptions().upsert(true).returnDocument(ReturnDocument.AFTER));
84✔
393
        return result.getLong("value");
15✔
394
    }
395

396
    /**
397
     * Loads a nanopublication into the database.
398
     *
399
     * @param mongoSession the MongoDB client session
400
     * @param nanopub      the nanopublication to load
401
     */
402
    public static boolean loadNanopub(ClientSession mongoSession, Nanopub nanopub) {
403
        return loadNanopub(mongoSession, nanopub, null);
21✔
404
    }
405

406
    /**
407
     * Loads a nanopublication into the database, optionally filtering by public key hash and types.
408
     *
409
     * @param mongoSession the MongoDB client session
410
     * @param nanopub      the nanopublication to load
411
     * @param pubkeyHash   the public key hash to filter by (can be null)
412
     * @param types        the types to filter by (can be empty)
413
     * @return true if the nanopublication was loaded, false otherwise
414
     */
415
    public static boolean loadNanopub(ClientSession mongoSession, Nanopub nanopub, String pubkeyHash, String... types) {
416
        String pubkey = getPubkey(nanopub);
9✔
417
        if (pubkey == null) {
6✔
418
            logger.warn("Ignoring nanopub {}: no valid public key / signature found", nanopub.getUri());
15✔
419
            return false;
6✔
420
        }
421
        return loadNanopubVerified(mongoSession, nanopub, pubkey, pubkeyHash, types);
21✔
422
    }
423

424
    /**
425
     * Loads a nanopublication with a pre-verified public key, skipping signature verification.
426
     * Use this when the caller has already verified the signature via getPubkey().
427
     */
428
    static boolean loadNanopubVerified(ClientSession mongoSession, Nanopub nanopub, String verifiedPubkey, String pubkeyHash, String... types) {
429
        if (nanopub.getTripleCount() > 1200) {
12!
430
            logger.error("Rejecting nanopub {}: triple count {} exceeds limit of 1200", nanopub.getUri(), nanopub.getTripleCount());
×
431
            return false;
×
432
        }
433
        if (nanopub.getByteCount() > 1000000) {
15!
434
            logger.error("Rejecting nanopub {}: size {} bytes exceeds limit of 1000000", nanopub.getUri(), nanopub.getByteCount());
×
435
            return false;
×
436
        }
437
        Calendar creationTime;
438
        try {
439
            creationTime = nanopub.getCreationTime();
9✔
440
        } catch (Exception ex) {
×
441
            logger.warn("Nanopub {} has a malformed timestamp; proceeding without one", nanopub.getUri());
×
442
            creationTime = null;
×
443
        }
3✔
444
        if (creationTime != null && creationTime.getTimeInMillis() > System.currentTimeMillis() + 60000) {
27!
445
            logger.error("Rejecting nanopub {}: timestamp {} is more than 60s in the future", nanopub.getUri(), creationTime.toInstant());
×
446
            return false;
×
447
        }
448
        String nanopubUriStr = nanopub.getUri().stringValue();
12✔
449
        for (IRI graphUri : nanopub.getGraphUris()) {
33✔
450
            if (!graphUri.stringValue().startsWith(nanopubUriStr)) {
15!
451
                logger.error("Rejecting nanopub {}: graph URI {} does not start with the nanopub base URI", nanopub.getUri(), graphUri);
×
452
                return false;
×
453
            }
454
        }
3✔
455
        String ph = Utils.getHash(verifiedPubkey);
9✔
456
        if (pubkeyHash != null && !pubkeyHash.equals(ph)) {
18!
457
            logger.error("Rejecting nanopub {}: provided pubkey hash {} does not match computed hash {}", nanopub.getUri(), pubkeyHash, ph);
×
458
            return false;
×
459
        }
460
        recordHash(mongoSession, verifiedPubkey);
9✔
461

462
        String ac = TrustyUriUtils.getArtifactCode(nanopub.getUri().stringValue());
15✔
463
        if (ac == null) {
6!
464
            // I don't think this ever happens, but checking here to be sure
465
            logger.error("Rejecting nanopub {}: could not extract artifact code from Trusty URI", nanopub.getUri());
×
466
            return false;
×
467
        }
468
        if (has(mongoSession, Collection.NANOPUBS.toString(), ac)) {
18✔
469
            logger.debug("Skipping nanopub {}: already present in the database", nanopub.getUri());
18✔
470
        } else {
471
            String nanopubString;
472
            byte[] jellyContent;
473
            try {
474
                nanopubString = NanopubUtils.writeToString(nanopub, RDFFormat.TRIG);
12✔
475
                // Save the same thing in the Jelly format for faster loading
476
                jellyContent = JellyUtils.writeNanopubForDB(nanopub);
9✔
477
            } catch (IOException ex) {
×
478
                logger.error("Failed to serialize nanopub {}: {}", nanopub.getUri(), ex.getMessage(), ex);
×
479
                throw new RuntimeException(ex);
×
480
            }
3✔
481
            long counter = getNextCounter(mongoSession);
9✔
482
            boolean inserted = false;
6✔
483
            try {
484
                collection(Collection.NANOPUBS.toString()).insertOne(mongoSession, new Document("_id", ac).append("fullId", nanopub.getUri().stringValue()).append("counter", counter).append("pubkey", ph).append("content", nanopubString).append("jelly", new Binary(jellyContent)));
93✔
485
                inserted = true;
6✔
486
                logger.info("Loaded nanopub {} (counter: {}, pubkey hash: {})", nanopub.getUri(), counter, ph);
57✔
487
            } catch (MongoWriteException e) {
×
488
                if (e.getError().getCategory() != ErrorCategory.DUPLICATE_KEY) {
×
489
                    logger.error("Failed to insert nanopub {} (artifact {}): {}", nanopub.getUri(), ac, e.getMessage(), e);
×
490
                    throw e;
×
491
                }
492
                // Another thread inserted this nanopub concurrently — safe to skip
493
                logger.debug("Skipping nanopub {}: inserted concurrently by another thread", nanopub.getUri());
×
494
            }
3✔
495

496
            if (inserted) {
6!
497
                for (IRI invalidatedId : Utils.getInvalidatedNanopubIds(nanopub)) {
33✔
498
                    String invalidatedAc = TrustyUriUtils.getArtifactCode(invalidatedId.stringValue());
12✔
499
                    if (invalidatedAc == null) {
6!
500
                        logger.warn("Nanopub {} references invalidated nanopub {} with an unresolvable artifact code; skipping", nanopub.getUri(), invalidatedId);
×
501
                        continue;  // This should never happen; checking here just to be sure
×
502
                    }
503

504
                    // Add this nanopub also to all lists of invalidated nanopubs:
505
                    logger.debug("Nanopub {} invalidates {}; updating list entries and trust edges", nanopub.getUri(), invalidatedId);
18✔
506
                    collection("invalidations").insertOne(mongoSession, new Document("invalidatingNp", ac).append("invalidatingPubkey", ph).append("invalidatedNp", invalidatedAc));
45✔
507
                    MongoCursor<Document> invalidatedEntries = collection("listEntries").find(mongoSession, new Document("np", invalidatedAc).append("pubkey", ph)).cursor();
42✔
508
                    while (invalidatedEntries.hasNext()) {
9!
509
                        Document invalidatedEntry = invalidatedEntries.next();
×
510
                        addToList(mongoSession, nanopub, ph, invalidatedEntry.getString("type"));
×
511
                    }
×
512

513
                    collection("listEntries").updateMany(mongoSession, new Document("np", invalidatedAc).append("pubkey", ph), new Document("$set", new Document("invalidated", true)));
69✔
514
                    collection("trustEdges").updateMany(mongoSession, new Document("source", invalidatedAc), new Document("$set", new Document("invalidated", true)));
60✔
515
                    logger.debug("Marked invalidated entries and trust edges for invalidated artifact {}", invalidatedAc);
12✔
516
                }
3✔
517
            }
518
        }
519

520
        if (pubkeyHash != null) {
6✔
521
            for (String type : types) {
48✔
522
                // TODO Check if nanopub really has the type?
523
                addToList(mongoSession, nanopub, pubkeyHash, Utils.getTypeHash(mongoSession, type));
21✔
524
                if (type.equals("$")) {
12!
525
                    for (IRI t : NanopubUtils.getTypes(nanopub)) {
33✔
526
                        String th = Utils.getTypeHash(mongoSession, t);
12✔
527
                        if (CoverageFilter.isCoveredType(th)) {
9!
528
                            addToList(mongoSession, nanopub, pubkeyHash, th);
15✔
529
                        }
530
                    }
3✔
531
                }
532
            }
533
        }
534

535
        // Add the invalidating nanopubs also to the lists of this nanopub:
536
        try (MongoCursor<Document> invalidations = collection("invalidations").find(mongoSession, new Document("invalidatedNp", ac).append("invalidatingPubkey", ph)).cursor()) {
42✔
537
            if (invalidations.hasNext()) {
9!
538
                collection("listEntries").updateMany(mongoSession, new Document("np", ac).append("pubkey", ph), new Document("$set", new Document("invalidated", true)));
×
539
                collection("trustEdges").updateMany(mongoSession, new Document("source", ac), new Document("$set", new Document("invalidated", true)));
×
540
                logger.debug("Marked existing list entries and trust edges for nanopub {} as invalidated due to invalidations", ac);
×
541
            }
542
            while (invalidations.hasNext()) {
9!
543
                String iac = invalidations.next().getString("invalidatingNp");
×
544
                try {
545
                    Document npDoc = collection(Collection.NANOPUBS.toString()).find(mongoSession, new Document("_id", iac)).projection(new Document("jelly", 1)).first();
×
546
                    Nanopub inp = JellyUtils.readFromDB(npDoc.get("jelly", Binary.class).getData());
×
547
                    for (IRI type : NanopubUtils.getTypes(inp)) {
×
548
                        addToList(mongoSession, inp, ph, Utils.getTypeHash(mongoSession, type));
×
549
                    }
×
550
                } catch (RDF4JException | MalformedNanopubException ex) {
×
551
                    logger.error("Failed to load invalidating nanopub {} for invalidation record; skipping", iac, ex);
×
552
                }
×
553
            }
×
554

555
        }
556

557
        return true;
6✔
558
    }
559

560
    private static void addToList(ClientSession mongoSession, Nanopub nanopub, String pubkeyHash, String typeHash) {
561
        String ac = TrustyUriUtils.getArtifactCode(nanopub.getUri().stringValue());
15✔
562
        try {
563
            insert(mongoSession, "lists", new Document("pubkey", pubkeyHash).append("type", typeHash).append("maxPosition", -1L));
45✔
564
            logger.debug("Ensured list document exists for pubkey={} type={}", pubkeyHash, typeHash);
15✔
565
        } catch (MongoWriteException e) {
×
566
            // Duplicate key error -- ignore it
567
            if (e.getError().getCategory() != ErrorCategory.DUPLICATE_KEY) {
×
568
                logger.error("Failed to create list document for pubkey={} type={}: {}", pubkeyHash, typeHash, e.getMessage(), e);
×
569
                throw e;
×
570
            }
571
            logger.trace("List document already existed for pubkey={} type={}", pubkeyHash, typeHash);
×
572
        }
3✔
573

574
        if (has(mongoSession, "listEntries", new Document("pubkey", pubkeyHash).append("type", typeHash).append("np", ac))) {
45!
575
            logger.debug("Already listed: nanopub {} (artifact {}) for pubkey={} type={}", nanopub.getUri(), ac, pubkeyHash, typeHash);
×
576
        } else {
577
            initListPositionIfNeeded(mongoSession, pubkeyHash, typeHash);
12✔
578

579
            for (int attempt = 0; ; attempt++) {
6✔
580
                // Atomically claim next position
581
                Document updated = collection("lists").findOneAndUpdate(mongoSession, new Document("pubkey", pubkeyHash).append("type", typeHash), new Document("$inc", new Document("maxPosition", 1L)), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER));
87✔
582
                long position = updated.getLong("maxPosition");
15✔
583

584
                // Get checksum from previous entry by exact position lookup (O(1) index hit)
585
                String checksum;
586
                if (position == 0) {
12!
587
                    checksum = NanopubUtils.updateXorChecksum(nanopub.getUri(), NanopubUtils.INIT_CHECKSUM);
18✔
588
                } else {
589
                    Document prevEntry = collection("listEntries").find(mongoSession, new Document("pubkey", pubkeyHash).append("type", typeHash).append("position", position - 1)).first();
×
590
                    String prevChecksum = (prevEntry != null) ? prevEntry.getString("checksum") : null;
×
591
                    if (prevChecksum == null) {
×
592
                        // Rare: previous entry not yet inserted by concurrent thread; fall back to sorted query
593
                        Document maxDoc = getMaxValueDocument(mongoSession, "listEntries", new Document("pubkey", pubkeyHash).append("type", typeHash), "position");
×
594
                        prevChecksum = (maxDoc != null) ? maxDoc.getString("checksum") : NanopubUtils.INIT_CHECKSUM;
×
595
                    }
596
                    checksum = NanopubUtils.updateXorChecksum(nanopub.getUri(), prevChecksum);
×
597
                }
598

599
                try {
600
                    collection("listEntries").insertOne(mongoSession, new Document("pubkey", pubkeyHash).append("type", typeHash).append("position", position).append("np", ac).append("checksum", checksum).append("invalidated", false));
78✔
601
                    logger.debug("Inserted list entry: pubkey={} type={} np={} position={} checksum={}", pubkeyHash, typeHash, ac, position, checksum);
78✔
602
                    break;
3✔
603
                } catch (MongoWriteException e) {
×
604
                    if (e.getError().getCategory() != ErrorCategory.DUPLICATE_KEY) {
×
605
                        logger.error("Failed to insert list entry for pubkey={} type={} np={}: {}", pubkeyHash, typeHash, ac, e.getMessage(), e);
×
606
                        throw e;
×
607
                    }
608
                    if (has(mongoSession, "listEntries", new Document("pubkey", pubkeyHash).append("type", typeHash).append("np", ac))) {
×
609
                        logger.debug("Concurrent insert detected and entry already exists for pubkey={} type={} np={}", pubkeyHash, typeHash, ac);
×
610
                        break; // Already listed by concurrent thread
×
611
                    }
612
                    if (attempt >= 100) {
×
613
                        logger.error("Failed to insert list entry after {} attempts for pubkey={} type={} np={}", attempt + 1, pubkeyHash, typeHash, ac);
×
614
                        throw new RuntimeException("Failed to insert list entry after " + (attempt + 1) + " attempts");
×
615
                    }
616
                    logger.debug("Retrying list entry insert (attempt {}) for pubkey={} type={} np={}", attempt + 1, pubkeyHash, typeHash, ac);
×
617
                }
618
            }
619
        }
620
    }
3✔
621

622
    /**
623
     * Lazily initializes the maxPosition field on a lists document for lists
624
     * created before this field existed. Uses a one-time sorted query, then
625
     * all subsequent calls use the atomic counter.
626
     */
627
    private static void initListPositionIfNeeded(ClientSession mongoSession, String pubkeyHash, String typeHash) {
628
        Document listDoc = collection("lists").find(mongoSession, new Document("pubkey", pubkeyHash).append("type", typeHash)).first();
45✔
629
        if (listDoc == null || listDoc.get("maxPosition") != null) {
18!
630
            logger.trace("initListPositionIfNeeded: no action needed for pubkey={} type={}", pubkeyHash, typeHash);
15✔
631
            return;
3✔
632
        }
633

634
        Document maxDoc = getMaxValueDocument(mongoSession, "listEntries", new Document("pubkey", pubkeyHash).append("type", typeHash), "position");
×
635
        long maxPos = (maxDoc != null) ? maxDoc.getLong("position") : -1L;
×
636

637
        // Conditional update: only set if maxPosition still doesn't exist (race-safe)
638
        collection("lists").updateOne(mongoSession, new Document("pubkey", pubkeyHash).append("type", typeHash).append("maxPosition", new Document("$exists", false)), new Document("$set", new Document("maxPosition", maxPos)));
×
639
        logger.debug("Initialized maxPosition={} for list pubkey={} type={}", maxPos, pubkeyHash, typeHash);
×
640
    }
×
641

642
    /**
643
     * Builds a comma-separated list of checksums at geometric positions for a given list,
644
     * for use with the afterChecksums parameter during peer sync.
645
     * Returns checksums at positions: max, max-10, max-100, max-1000, max-10000, ...
646
     * Returns null if the list has no entries.
647
     */
648
    public static String buildChecksumFallbacks(ClientSession mongoSession, String pubkeyHash, String typeHash) {
649
        Document maxDoc = getMaxValueDocument(mongoSession, "listEntries", new Document("pubkey", pubkeyHash).append("type", typeHash), "position");
39✔
650
        if (maxDoc == null) {
6✔
651
            logger.debug("buildChecksumFallbacks: no entries for pubkey={} type={}", pubkeyHash, typeHash);
15✔
652
            return null;
6✔
653
        }
654

655
        long maxPosition = maxDoc.getLong("position");
15✔
656
        StringBuilder sb = new StringBuilder();
12✔
657
        sb.append(maxDoc.getString("checksum"));
18✔
658

659
        for (long offset = 10; offset <= maxPosition; offset *= 10) {
33✔
660
            long targetPos = maxPosition - offset;
12✔
661
            Document entry = collection("listEntries").find(mongoSession, new Document("pubkey", pubkeyHash).append("type", typeHash).append("position", targetPos)).first();
57✔
662
            if (entry != null) {
6!
663
                sb.append(",").append(entry.getString("checksum"));
24✔
664
            }
665
        }
666
        String result = sb.toString();
9✔
667
        logger.debug("buildChecksumFallbacks for pubkey={} type={} -> {}", pubkeyHash, typeHash, result);
51✔
668
        return result;
6✔
669
    }
670

671
    /**
672
     * Returns the public key string of the Nanopub's signature, or null if not available or invalid.
673
     *
674
     * @param nanopub the nanopub to extract the public key from
675
     * @return The public key string, or null if not available or invalid.
676
     */
677
    public static String getPubkey(Nanopub nanopub) {
678
        // TODO shouldn't this be moved to a utility class in nanopub-java? there is a similar method in NanopubElement class of nanodash
679
        NanopubSignatureElement el;
680
        try {
681
            el = SignatureUtils.getSignatureElement(nanopub);
9✔
682
            if (el != null && SignatureUtils.hasValidSignature(el) && el.getPublicKeyString() != null) {
24!
683
                logger.trace("Valid signature found for nanopub {}", nanopub.getUri());
15✔
684
                return el.getPublicKeyString();
9✔
685
            }
686
            logger.debug("No valid signature element or public key present for nanopub {}", nanopub.getUri());
15✔
687
        } catch (MalformedCryptoElementException | GeneralSecurityException ex) {
×
688
            logger.error("Failed to verify signature of nanopub {}: {}", nanopub.getUri(), ex.getMessage(), ex);
×
689
        }
3✔
690
        return null;
6✔
691
    }
692

693
    /**
694
     * Calculates a hash representing the current state of the trust paths in the loading collection.
695
     *
696
     * @param mongoSession the MongoDB client session
697
     * @return the calculated trust state hash
698
     */
699
    public static String calculateTrustStateHash(ClientSession mongoSession) {
700
        // Accounts still in the 'toLoad' staging status are not yet servable and must not enter the
701
        // public trust state: a path's head account flips 'toLoad' -> 'loaded' between UPDATE cycles
702
        // (in LOAD_FULL) without changing any trust path, so if those paths were hashed, a leaf
703
        // account's promotion would never change the hash and never trigger a new snapshot, leaving
704
        // it published as 'toLoad' indefinitely (see issue #119). By excluding 'toLoad' paths here,
705
        // crossing out of 'toLoad' is itself a membership change -> hash change -> emission.
706
        Set<String> toLoadAccounts = new HashSet<>();
12✔
707
        try (MongoCursor<Document> ac = collection("accounts_loading")
21✔
708
                .find(mongoSession, new Document("status", EntryStatus.toLoad.getValue()))
21✔
709
                .projection(new Document("agent", 1).append("pubkey", 1))
21✔
710
                .cursor()) {
6✔
711
            while (ac.hasNext()) {
9✔
712
                Document a = ac.next();
12✔
713
                toLoadAccounts.add(a.getString("agent") + "|" + a.getString("pubkey"));
30✔
714
            }
3✔
715
        }
716

717
        MongoCursor<Document> tp = collection("trustPaths_loading").find(mongoSession).sort(ascending("_id")).cursor();
42✔
718
        // TODO Improve this so we don't create the full string just for calculating its hash:
719
        String s = "";
6✔
720
        while (tp.hasNext()) {
9✔
721
            Document d = tp.next();
12✔
722
            if (toLoadAccounts.contains(d.getString("agent") + "|" + d.getString("pubkey"))) {
30✔
723
                continue;
3✔
724
            }
725
            s += d.getString("_id") + " (" + d.getString("type") + ")\n";
27✔
726
        }
3✔
727
        String hash = Utils.getHash(s);
9✔
728
        logger.debug("Calculated trust state hash: {}", hash);
12✔
729
        return hash;
6✔
730
    }
731

732
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc