nostralink 0.2.4

Linked data library for nostr
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! Web of Trust

use super::manager::{RdfEventsStore, RdfStoreError};
use super::prelude::*;
use super::util::{subl, subnn};
use crate::niri::{FromNamedNode, ToNamedNode};
use crate::querydb::nrq_get;
use nostr::PublicKey;
use oxigraph::model::vocab::rdf;
use rand_09::seq::IndexedRandom;
use std::collections::HashSet;
use std::sync::Arc;
use std::thread::sleep;
use std::time::Duration;

/// Trust level
pub enum TrustLevel {
    DontKnow,
    NoTrust,
    Marginal,
    Full,
}

/// Direct or Indirect trust
#[derive(PartialEq)]
pub enum TrustType {
    Direct,
    Indirect,
}

/// Ring ccircle radius algorithm
#[derive(PartialEq)]
pub enum TrustRingRadiusAlgo {
    Linear,
    Double,
    Power(u8),
}

/// Predicate to express trust from one person to another
pub const PRED_WOT_TRUSTS: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/trusts");

/// Indirect trust (unused)
pub const PRED_WOT_TRUSTS_INDIRECT: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/trusts_indirect");

pub const PRED_WOT_TRUST_LEVEL: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/trust_level");

/// The trust score of a person (float)
pub const PRED_WOT_TRUST_SCORE: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/trust_score");

pub const PRED_WOT_RING: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/wot_ring");

/// RDF type of trust rings
pub const RING_RDF_TYPE: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing");
/// Ring creator
pub const PRED_RING_CREATOR: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#creator");
/// Ring center (who is the trusted subject of the ring)
pub const PRED_RING_CENTER: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#center");
/// Ring radius (integer)
pub const PRED_RING_RADIUS: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#radius");

pub const PRED_RING_CREATED_AT: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#created_at");

/// Ring color (hex)
pub const PRED_RING_COLOR_HEX: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#color_hex");

/// Ring type (integer)
pub const PRED_RING_KIND: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#kind");

pub const PRED_RING_PASSES: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#passes");
pub const PRED_RING_FROZEN: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#frozen");
pub const PRED_RING_FROZEN_AT: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#frozen_at");
/// PCL: Processed Contact List
pub const PRED_RING_PCL: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#pcl");

pub const PRED_RING_BELONGS_TO: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#belongs_to");
// nip21 "part of"
pub const PRED_RING_PART_OF: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#part_of");
pub const PRED_RING_MEMBER_OF: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#member_of");
pub const PRED_IN_RING: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#in_ring");
pub const PRED_RING_CONTAINS: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#contains");

/// A ring scored a person
pub const PRED_RING_SCORED: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRing#scored");

/// Ring ccircle radius
pub const PRED_CCIRCLE_RADIUS: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRingCircle#radius");

/// Ring ccircle index
pub const PRED_CCIRCLE_INDEX: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRingCircle#index");

/// ccircle weight
pub const PRED_CCIRCLE_WEIGHT: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked("http://nostralink.org/TrustRingCircle#weight");

/// ccircle color (hex)
pub const PRED_CCIRCLE_COLOR_HEX: NamedNodeRef<'static> =
    NamedNodeRef::new_unchecked(
        "http://nostralink.org/TrustRingCircle#color_hex",
    );

#[derive(Debug, Clone)]
pub struct QueryRings;
#[derive(Debug, Clone)]
pub struct QueryRingCircles;
#[derive(Debug, Clone)]
pub struct QueryRingWeb;
#[derive(Debug, Clone)]
pub struct QueryRingNet;

pub trait WebOfTrust {
    /// Establish a trust relationship between two nostr identities
    fn wot_trust(
        &self,
        truster: &PublicKey,
        trusted: &PublicKey,
        ttype: TrustType,
    ) -> Result<(), RdfStoreError>;
    /// Alter the trust score of a [`PublicKey`]
    fn wot_score_change(
        &self,
        trusted: &PublicKey,
        score: f32,
        ring_node: Option<NamedNode>,
    ) -> Result<(), RdfStoreError>;
    /// Does "truster" trust "trusted" ?
    fn wot_does_trust(
        &self,
        truster: &PublicKey,
        trusted: &PublicKey,
    ) -> Result<bool, RdfStoreError>;
    fn wot_trusted_list(
        &self,
        truster: &PublicKey,
    ) -> Result<Vec<PublicKey>, RdfStoreError>;
    /// Create a trust ring
    fn wot_ring_create(
        &self,
        my_pubk: &PublicKey,
        public_key: &PublicKey,
        ring_radius: i32,
        ring_color_hex: &str,
        radius_algo: Option<TrustRingRadiusAlgo>,
        kind: Option<i32>,
    ) -> Result<(), RdfStoreError>;
    /// Returns rings created by this key
    fn wot_rings_created_by(
        &self,
        pubk: &PublicKey,
    ) -> Result<Arc<TRdfResultSet<QueryRings>>, RdfStoreError>;
    /// Process the trust rings for this key
    fn wot_rings_process(
        &self,
        my_pubk: &PublicKey,
    ) -> Result<HashSet<PublicKey>, RdfStoreError>;
    /// Extend the ring recursively
    fn wot_ring_extend(
        &self,
        ring_node: NamedNodeRef,
        center_pubk: &PublicKey,
        my_pubk: &PublicKey,
        public_key: &PublicKey,
        ring_radius: i32,
        ring_ccircle_num: i32,
        contacts_set: &mut HashSet<PublicKey>,
        processed_keys: &mut Vec<String>,
        max_contacts: usize
    ) -> Result<(), RdfStoreError>;
    /// Return the ring's radius for this key
    fn wot_ring_radius(
        &self,
        my_pubk: &PublicKey,
        public_key: &PublicKey,
    ) -> Result<i32, RdfStoreError>;
    /// Returns the list of keys in the ring
    fn wot_ring_members_from_pubk(
        &self,
        my_pubk: &PublicKey,
        public_key: &PublicKey,
        depth: u32,
    ) -> Result<Vec<PublicKey>, RdfStoreError>;
    fn wot_ring_members(
        &self,
        ring_node: NamedNodeRef,
        depth: u32,
    ) -> Result<Vec<PublicKey>, RdfStoreError>;
}

fn ring_ccircle_pred(depth: i32) -> NamedNode {
    NamedNode::new_unchecked(format!(
        "http://nostralink.org/TrustRing#ccircle_{}",
        depth
    ))
}

fn ring_main_node(public_key: &PublicKey) -> Result<NamedNode, LDError> {
    public_key.named_node_with("/ring", None)
}

fn ring_ccircle_node(
    public_key: &PublicKey,
    ccircle: i32,
) -> Result<NamedNode, LDError> {
    public_key.named_node_with("/ring", Some(&ccircle.to_string()))
}

fn ring_ccircle_weight(ccircle_idx: i32) -> f32 {
    (50 / (ccircle_idx + 1)) as f32
}

fn comp_score(
    ccircle_radius: i32,
    ccircle_weight: i32,
    decay_factor: f32,
) -> f32 {
    let radius_factor = ccircle_radius as f32;
    let weight_factor = ccircle_weight as f32;
    
    weight_factor * (-decay_factor * radius_factor).exp()
}

fn rand_color() -> Literal {
    let colors = ["#7FFFD4", "#6495ED", "#DC143C", "#8FBC8F", "#008000", "#FF4500"];

    match colors.choose(&mut rand_09::rng()) {
        Some(c) => Literal::from(*c),
        None => Literal::from("#000000"),
    }
}

impl WebOfTrust for RdfEventsStore {
    fn wot_rings_created_by(
        &self,
        creator_pubk: &PublicKey,
    ) -> Result<Arc<TRdfResultSet<QueryRings>>, RdfStoreError> {
        let subs = [subnn("ring_creator", creator_pubk.named_node()?)?];

        self.run_query_typed(&nrq_get("wot_rings").unwrap(), None, subs, None)
    }

    fn wot_rings_process(
        &self,
        my_pubk: &PublicKey,
    ) -> Result<HashSet<PublicKey>, RdfStoreError> {
        let mut contacts_set = HashSet::new();
        let mut processed = vec![];

        let rings = self.wot_rings_created_by(my_pubk)?;

        for ring in &rings.rows {
            if let Some(_frozen) = ring.get("frozen") {
                // frozen ring
                continue;
            }

            let ring_node = ring.get_node("ring").unwrap();
            let creator = ring.get_node("ring_creator").unwrap();
            let center = ring.get_node("ring_center").unwrap();
            let radius = ring
                .get_string("ring_radius")
                .unwrap()
                .parse::<i32>()
                .map_err(|_| RdfStoreError::QueryError)?;

            self.wot_ring_extend(
                ring_node.as_ref(),
                &center.from_named_node()?,
                &creator.from_named_node()?,
                &center.from_named_node()?,
                radius,
                0,
                &mut contacts_set,
                &mut processed,
                64
            )?;
        }

        Ok(contacts_set)
    }

    fn wot_does_trust(
        &self,
        truster: &PublicKey,
        trusted: &PublicKey,
    ) -> Result<bool, RdfStoreError> {
        let truster_node = truster.named_node()?;
        let trusted_node = trusted.named_node()?;

        let results = self
            .store
            .quads_for_pattern(
                Some((&truster_node).into()),
                Some(PRED_WOT_TRUSTS),
                Some((&trusted_node).into()),
                None,
            )
            .collect::<Result<Vec<_>, _>>()
            .map_err(|_| RdfStoreError::QueryError)?;

        Ok(!results.is_empty())
    }

    fn wot_trust(
        &self,
        truster: &PublicKey,
        trusted: &PublicKey,
        ttype: TrustType,
    ) -> Result<(), RdfStoreError> {
        let truster_node = truster.named_node()?;
        let trusted_node = trusted.named_node()?;

        let pred = match ttype {
            TrustType::Direct => PRED_WOT_TRUSTS,
            TrustType::Indirect => PRED_WOT_TRUSTS_INDIRECT,
        };

        if ttype == TrustType::Direct {
            // Remove the "opposite" trust triple if there's one
            self.store.remove(QuadRef::new(
                &truster_node,
                PRED_WOT_TRUSTS_INDIRECT,
                &trusted_node,
                &GraphName::DefaultGraph,
            ))?;
        }

        let trust_quad = QuadRef::new(
            &truster_node,
            pred,
            &trusted_node,
            &GraphName::DefaultGraph,
        );

        self.store
            .insert(trust_quad)
            .map_err(|_| RdfStoreError::QuadInsertError)?;

        Ok(())
    }

    fn wot_trusted_list(
        &self,
        truster: &PublicKey,
    ) -> Result<Vec<PublicKey>, RdfStoreError> {
        let truster_node = truster.named_node()?;
        let results = self
            .store
            .quads_for_pattern(
                Some((&truster_node).into()),
                Some(PRED_WOT_TRUSTS),
                None,
                None,
            )
            .collect::<Result<Vec<_>, _>>()
            .map_err(|_| RdfStoreError::QueryError)?;

        // Extract trusted public keys from results
        let trusted_keys: Vec<PublicKey> = results
            .iter()
            .filter_map(|quad| match &quad.object {
                Term::NamedNode(node) => node.from_named_node().ok(),
                _ => None,
            })
            .collect();

        Ok(trusted_keys)
    }

    fn wot_score_change(
        &self,
        trusted: &PublicKey,
        score: f32,
        ring_node: Option<NamedNode>,
    ) -> Result<(), RdfStoreError> {
        let trusted_node = trusted.named_node()?;

        if let Some(node) = ring_node {
            if self
                .store
                .quads_for_pattern(
                    Some((&node).into()),
                    Some(PRED_RING_SCORED),
                    Some((&trusted_node).into()),
                    None,
                )
                .count()
                > 0
            {
                return Ok(());
            }

            self.store.insert(QuadRef::new(
                &node,
                PRED_RING_SCORED,
                &trusted_node,
                &GraphName::DefaultGraph,
            ))?;
        }

        // get the current score
        let mut cur_score = self
            .store
            .quads_for_pattern(
                Some((&trusted_node).into()),
                Some(PRED_WOT_TRUST_SCORE),
                None,
                None,
            )
            .filter_map(|quad| match &quad.ok()?.object {
                Term::Literal(lit) => lit.value().parse::<f32>().ok(),
                _ => None,
            })
            .next()
            .unwrap_or(0.0);

        // remove the current score
        self.store.remove(QuadRef::new(
            &trusted_node,
            PRED_WOT_TRUST_SCORE,
            &Literal::from(cur_score),
            &GraphName::DefaultGraph,
        ))?;

        cur_score += score;

        self.store
            .insert(QuadRef::new(
                &trusted_node,
                PRED_WOT_TRUST_SCORE,
                &Literal::from(cur_score),
                &GraphName::DefaultGraph,
            ))
            .map_err(|_| RdfStoreError::QuadInsertError)?;

        Ok(())
    }

    fn wot_ring_create(
        &self,
        my_pubk: &PublicKey,
        public_key: &PublicKey,
        ring_radius: i32,
        ring_color_hex: &str,
        radius_algo: Option<TrustRingRadiusAlgo>,
        kind: Option<i32>,
    ) -> Result<(), RdfStoreError> {
        if !(0..=10).contains(&ring_radius) {
            return Err(RdfStoreError::InvalidFilterValue);
        }

        let ring_radius_lit = Literal::from(ring_radius);
        let public_key_node = public_key.named_node()?;
        let ring_node = ring_main_node(public_key)?;

        // Check if the ring already existed
        if self
            .store
            .quads_for_pattern(Some((&ring_node).into()), None, None, None)
            .count()
            != 0
        {
            // Find the previous radius
            let _previous_radius = self
                .literal_for_subject_predicate(
                    (&ring_node).into(),
                    PRED_RING_RADIUS,
                )?
                .value()
                .parse::<i32>()
                .unwrap_or(0);

            // Remove all quads for this ring
            self.rm_quads_pattern(Some((&ring_node).into()), None, None, None)?;
        }

        // Establish direct trust between the ring creator and the ring center
        self.wot_trust(my_pubk, public_key, TrustType::Direct)?;

        // Create the ring in the store
        self.store.insert(QuadRef::new(
            &ring_node,
            rdf::TYPE,
            RING_RDF_TYPE,
            &GraphName::DefaultGraph,
        ))?;

        self.store.insert(QuadRef::new(
            &ring_node,
            PRED_RING_CREATOR,
            &my_pubk.named_node()?,
            &GraphName::DefaultGraph,
        ))?;

        self.store.insert(QuadRef::new(
            &ring_node,
            PRED_RING_COLOR_HEX,
            &Literal::from(ring_color_hex),
            &GraphName::DefaultGraph,
        ))?;

        self.store.insert(QuadRef::new(
            &ring_node,
            PRED_RING_CENTER,
            &public_key_node,
            &GraphName::DefaultGraph,
        ))?;

        self.store.insert(QuadRef::new(
            &ring_node,
            PRED_RING_RADIUS,
            &ring_radius_lit,
            &GraphName::DefaultGraph,
        ))?;

        if let Some(rk) = kind {
            self.store.insert(QuadRef::new(
                &ring_node,
                PRED_RING_KIND,
                &Literal::from(rk),
                &GraphName::DefaultGraph,
            ))?;
        }

        // Create the ring's concentric circles
        for idx in 0..ring_radius {
            let ccircle_node = ring_ccircle_node(public_key, idx)?;

            // link the trustring with the circle
            self.store.insert(QuadRef::new(
                &ring_node,
                &ring_ccircle_pred(idx),
                &ccircle_node,
                &GraphName::DefaultGraph,
            ))?;

            // Compute ccircle radius based on the selected algorithm
            let cradius = match radius_algo {
                Some(TrustRingRadiusAlgo::Linear) | None => idx + 1,
                Some(TrustRingRadiusAlgo::Double) => (idx + 1) * 2,
                Some(TrustRingRadiusAlgo::Power(power)) => {
                    (idx + 1).pow(power.into())
                }
            };

            // Set the circle's virtual radius
            // The radius can be changed, and is used to calculate trust scores
            self.store.insert(QuadRef::new(
                &ccircle_node,
                PRED_CCIRCLE_RADIUS,
                &Literal::from(cradius),
                &GraphName::DefaultGraph,
            ))?;

            // Weight
            self.store.insert(QuadRef::new(
                &ccircle_node,
                PRED_CCIRCLE_WEIGHT,
                &Literal::from(ring_ccircle_weight(idx)),
                &GraphName::DefaultGraph,
            ))?;
            // index
            self.store.insert(QuadRef::new(
                &ccircle_node,
                PRED_CCIRCLE_INDEX,
                &Literal::from(idx),
                &GraphName::DefaultGraph,
            ))?;

            // Color
            self.store.insert(QuadRef::new(
                &ccircle_node,
                PRED_CCIRCLE_COLOR_HEX,
                &rand_color(),
                &GraphName::DefaultGraph,
            ))?;
        }

        Ok(())
    }

    /// Extend the trust ring for a [`PublicKey`]
    fn wot_ring_extend(
        &self,
        ring_node: NamedNodeRef,
        center_pubk: &PublicKey,
        my_pubk: &PublicKey,
        public_key: &PublicKey,
        ring_radius: i32,
        ring_ccircle_num: i32,
        contacts_set: &mut HashSet<PublicKey>,
        processed_keys: &mut Vec<String>,
        max_contacts: usize
    ) -> Result<(), RdfStoreError> {
        if !(0..=10).contains(&ring_radius) {
            return Err(RdfStoreError::InvalidFilterValue);
        }

        /*
        if ring_ccircle_num >= ring_radius {
            // ccircle index (starts at 0) >= ring's radius
            // ring complete: freeze/lock the ring
            self.store.insert(QuadRef::new(
                ring_node,
                PRED_RING_FROZEN,
                &Literal::from(1),
                &GraphName::DefaultGraph,
            ))?;
            return Ok(());
        }
        */

        let public_key_node = public_key.named_node()?;
        let ccircle_node = ring_ccircle_node(center_pubk, ring_ccircle_num)?;

        let ccircle_radius = self
            .literal_for_subject_predicate(
                (&ccircle_node).into(),
                PRED_CCIRCLE_RADIUS,
            )?
            .value()
            .parse::<i32>()
            .unwrap_or(1);

        let ccircle_weight = self
            .literal_for_subject_predicate(
                (&ccircle_node).into(),
                PRED_CCIRCLE_WEIGHT,
            )?
            .value()
            .parse::<i32>()
            .unwrap_or(1);

        // Check that another ccircle doesn't already contain this pubk
        let mut contained = false;
        for cidx in 0..ring_ccircle_num {
            if self
                .store
                .quads_for_pattern(
                    Some((&ring_ccircle_node(center_pubk, cidx)?).into()),
                    Some(PRED_RING_CONTAINS),
                    Some((&public_key_node).into()),
                    None,
                )
                .count()
                > 0
            {
                contained = true;
            }
        }

        if !contained {
            // ring#ccircle_index CONTAINS nip21
            self.store.insert(QuadRef::new(
                &ccircle_node,
                PRED_RING_CONTAINS,
                &public_key_node,
                &GraphName::DefaultGraph,
            ))?;
        }

        self.wot_score_change(
            public_key,
            comp_score(ccircle_radius, ccircle_weight, 0.5),
            Some(ring_node.into()),
        )?;

        if self
            .store
            .quads_for_pattern(
                Some((ring_node).into()),
                Some(PRED_RING_PCL),
                Some((&public_key_node).into()),
                None,
            )
            .count()
            == 0
        {
            contacts_set.insert(*public_key);
        }

        // Recursively "extend" the ring
        if ring_ccircle_num < ring_radius {
            if let Ok((_event_id, contacts)) =
                self.get_contacts_w_event_id(public_key, max_contacts)
            {
                if !contacts.is_empty() {
                    for contact in contacts {
                        // Indirect trust
                        self.wot_trust(my_pubk, &contact, TrustType::Indirect)?;

                        if processed_keys.contains(&contact.to_hex()) {
                            continue;
                        }

                        processed_keys.push(contact.to_hex());

                        sleep(Duration::from_millis(50));

                        self.wot_ring_extend(
                            ring_node,
                            center_pubk,
                            my_pubk,
                            &contact,
                            ring_radius,
                            ring_ccircle_num + 1,
                            contacts_set,
                            processed_keys,
                            max_contacts / 2
                        )?;
                    }

                    self.store.insert(QuadRef::new(
                        ring_node,
                        PRED_RING_PCL,
                        &public_key_node,
                        &GraphName::DefaultGraph,
                    ))?;
                }
            }
        }

        processed_keys.push(public_key.to_hex());

        Ok(())
    }

    fn wot_ring_radius(
        &self,
        my_pubk: &PublicKey,
        public_key: &PublicKey,
    ) -> Result<i32, RdfStoreError> {
        let subs = [
            subnn("ring_creator", my_pubk.named_node()?)?,
            subnn("ring_center", public_key.named_node()?)?,
        ];

        match self
            .run_query(&nrq_get("wot_rings").unwrap(), subs, None)?
            .rows
            .first()
        {
            Some(row) => match row.get("ring_radius") {
                Some(cell) => cell.to_int().ok_or(RdfStoreError::QueryError),
                None => Err(RdfStoreError::QueryError),
            },
            None => Err(RdfStoreError::QueryError),
        }
    }

    fn wot_ring_members(
        &self,
        ring_node: NamedNodeRef,
        depth: u32,
    ) -> Result<Vec<PublicKey>, RdfStoreError> {
        let mut subs = vec![
            subnn("ring", ring_node.into())?,
            subl("max_depth", Literal::from(depth))?,
        ];

        for idx in 0..depth {
            subs.push(subl(
                &format!("include_ccircle_{idx}"),
                Literal::from(1),
            )?);
        }

        Ok(self
            .run_query_typed(
                &nrq_get("wot_ring_web_nometa")?,
                None,
                subs,
                None,
            )?
            .rows
            .clone()
            .into_iter()
            .map(|row: TRdfResultRow<QueryRings>| {
                row.get_node("trusted_nip21")
                    .unwrap()
                    .from_named_node()
                    .unwrap()
            })
            .collect())
    }

    fn wot_ring_members_from_pubk(
        &self,
        my_pubk: &PublicKey,
        public_key: &PublicKey,
        depth: u32,
    ) -> Result<Vec<PublicKey>, RdfStoreError> {
        let mut subs = vec![
            subnn("ring_creator", my_pubk.named_node()?)?,
            subnn("ring_center", public_key.named_node()?)?,
            subl("max_depth", Literal::from(depth))?,
        ];

        for idx in 0..depth {
            subs.push(subl(
                &format!("include_ccircle_{idx}"),
                Literal::from(1),
            )?);
        }

        Ok(self
            .run_query_typed(
                &nrq_get("wot_ring_web_nometa")?,
                None,
                subs,
                None,
            )?
            .rows
            .clone()
            .into_iter()
            .map(|row: TRdfResultRow<QueryRings>| {
                row.get_node("trusted_nip21")
                    .unwrap()
                    .from_named_node()
                    .unwrap()
            })
            .collect())
    }
}

impl RdfEventsStore {
    #[allow(dead_code)]
    fn get_contacts(
        &self,
        public_key: &PublicKey,
    ) -> Result<Vec<PublicKey>, RdfStoreError> {
        let user_pk_hex = public_key.to_hex();

        let subs = [subl("pubk", Literal::from(user_pk_hex))?];
        Ok(self
            .run_query(&nrq_get("contact_list").unwrap(), subs, None)?
            .rows
            .iter()
            .filter_map(|row| {
                row.get("contact_pubk").unwrap().value.to_public_key().ok()
            })
            .collect::<Vec<_>>())
    }

    fn get_contacts_w_event_id(
        &self,
        public_key: &PublicKey,
        max_contacts: usize,
    ) -> Result<(String, Vec<PublicKey>), RdfStoreError> {
        let user_pk_hex = public_key.to_hex();

        let subs = [subl("pubk", Literal::from(user_pk_hex))?];
        let results =
            self.run_query(&nrq_get("contact_list_latest")?, subs, Some(format!("cl_{}", public_key.to_hex())))?;

        match results.first() {
            Some(row) => {
                let event_id = row.get("event_id").unwrap().to_string();

                let mut contacts = results
                    .rows
                    .iter()
                    .filter_map(|row| {
                        row.get("contact_pubk")
                            .unwrap()
                            .value
                            .to_public_key()
                            .ok()
                    })
                    .take(max_contacts)
                    .collect::<Vec<_>>();

                contacts.dedup();

                Ok((event_id, contacts))
            }
            None => Err(RdfStoreError::QueryError),
        }
    }
}