@@ -2,12 +2,15 @@ package datastore
2
2
3
3
import (
4
4
"context"
5
+ "strings"
5
6
"testing"
6
7
7
8
"github.com/ipfs/go-cid"
8
9
ds "github.com/ipfs/go-datastore"
10
+ "github.com/ipfs/go-test/random"
9
11
"github.com/libp2p/go-libp2p-kad-dht/provider/internal/keyspace"
10
12
mh "github.com/multiformats/go-multihash"
13
+ "github.com/stretchr/testify/require"
11
14
12
15
"github.com/probe-lab/go-libdht/kad/key"
13
16
"github.com/probe-lab/go-libdht/kad/key/bitstr"
@@ -85,6 +88,60 @@ func TestKeyStoreStoreAndGet(t *testing.T) {
85
88
}
86
89
}
87
90
91
+ func genMultihashesMatchingPrefix (prefix bitstr.Key , n int ) []mh.Multihash {
92
+ mhs := make ([]mh.Multihash , 0 , n )
93
+ for i := 0 ; len (mhs ) < n ; i ++ {
94
+ h := random .Multihashes (1 )[0 ]
95
+ k := keyspace .MhToBit256 (h )
96
+ if keyspace .IsPrefix (prefix , k ) {
97
+ mhs = append (mhs , h )
98
+ }
99
+ }
100
+ return mhs
101
+ }
102
+
103
+ func TestKeyStoreContainsPrefix (t * testing.T ) {
104
+ ctx := context .Background ()
105
+ store , err := NewKeyStore (ds .NewMapDatastore ())
106
+ require .NoError (t , err )
107
+
108
+ ok , err := store .ContainsPrefix (ctx , bitstr .Key ("0000" ))
109
+ require .NoError (t , err )
110
+ require .False (t , ok )
111
+
112
+ generated := genMultihashesMatchingPrefix (bitstr .Key (strings .Repeat ("0" , DefaultKeyStorePrefixBits + 4 )), 1 )
113
+ require .True (t , keyspace .IsPrefix (bitstr .Key ("0000" ), keyspace .MhToBit256 (generated [0 ])))
114
+ store .Put (ctx , generated ... )
115
+
116
+ ok , err = store .ContainsPrefix (ctx , bitstr .Key ("0" ))
117
+ require .NoError (t , err )
118
+ require .True (t , ok )
119
+
120
+ ok , err = store .ContainsPrefix (ctx , bitstr .Key ("0000" ))
121
+ require .NoError (t , err )
122
+ require .True (t , ok )
123
+
124
+ ok , err = store .ContainsPrefix (ctx , bitstr .Key (strings .Repeat ("0" , DefaultKeyStorePrefixBits )))
125
+ require .NoError (t , err )
126
+ require .True (t , ok )
127
+
128
+ ok , err = store .ContainsPrefix (ctx , bitstr .Key (strings .Repeat ("0" , DefaultKeyStorePrefixBits + 4 )))
129
+ require .NoError (t , err )
130
+ require .True (t , ok )
131
+
132
+ ok , err = store .ContainsPrefix (ctx , bitstr .Key ("1" ))
133
+ require .NoError (t , err )
134
+ require .False (t , ok )
135
+
136
+ ok , err = store .ContainsPrefix (ctx , bitstr .Key ("0001" ))
137
+ require .NoError (t , err )
138
+ require .False (t , ok )
139
+
140
+ ok , err = store .ContainsPrefix (ctx , bitstr .Key (strings .Repeat ("0" , DefaultKeyStorePrefixBits + 2 )+ "1" ))
141
+ require .NoError (t , err )
142
+ require .False (t , ok )
143
+ }
144
+
88
145
func TestKeyStoreReset (t * testing.T ) {
89
146
store , err := NewKeyStore (ds .NewMapDatastore ())
90
147
if err != nil {
0 commit comments