forked from bluesky-social/indigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmst_util.go
240 lines (206 loc) · 5.17 KB
/
mst_util.go
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
// Helpers for MST implementation. Following code split between mst.ts and util.ts in upstream Typescript implementation
package mst
import (
"context"
"fmt"
"strings"
"unsafe"
"github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
sha256 "github.com/minio/sha256-simd"
)
// Used to determine the "depth" of keys in an MST.
// For atproto, repo v2, the "fanout" is always 4, so we count "zeros" in
// chunks of 2-bits. Eg, a leading 0x00 byte is 4 "zeros".
// Typescript: leadingZerosOnHash(key, fanout) -> number
func leadingZerosOnHash(key string) int {
var b []byte
if len(key) > 0 {
b = unsafe.Slice(unsafe.StringData(key), len(key))
}
return leadingZerosOnHashBytes(b)
}
func leadingZerosOnHashBytes(key []byte) (total int) {
hv := sha256.Sum256(key)
for _, b := range hv {
if b&0xC0 != 0 {
// Common case. No leading pair of zero bits.
break
}
if b == 0x00 {
total += 4
continue
}
if b&0xFC == 0x00 {
total += 3
} else if b&0xF0 == 0x00 {
total += 2
} else {
total += 1
}
break
}
return total
}
// Typescript: layerForEntries(entries, fanout) -> (number?)
func layerForEntries(entries []nodeEntry) int {
var firstLeaf nodeEntry
for _, e := range entries {
if e.isLeaf() {
firstLeaf = e
break
}
}
if firstLeaf.Kind == entryUndefined {
return -1
}
return leadingZerosOnHash(firstLeaf.Key)
}
// Typescript: deserializeNodeData(storage, data, layer)
func deserializeNodeData(ctx context.Context, cst cbor.IpldStore, nd *nodeData, layer int) ([]nodeEntry, error) {
entries := []nodeEntry{}
if nd.Left != nil {
// Note: like Typescript, this is actually a lazy load
entries = append(entries, nodeEntry{
Kind: entryTree,
Tree: createMST(cst, *nd.Left, nil, layer-1),
})
}
var lastKey string
var keyb []byte // re-used between entries
for _, e := range nd.Entries {
if keyb == nil {
keyb = make([]byte, 0, int(e.PrefixLen)+len(e.KeySuffix))
}
keyb = append(keyb[:0], lastKey[:e.PrefixLen]...)
keyb = append(keyb, e.KeySuffix...)
keyStr := string(keyb)
err := ensureValidMstKey(keyStr)
if err != nil {
return nil, err
}
entries = append(entries, nodeEntry{
Kind: entryLeaf,
Key: keyStr,
Val: e.Val,
})
if e.Tree != nil {
entries = append(entries, nodeEntry{
Kind: entryTree,
Tree: createMST(cst, *e.Tree, nil, layer-1),
Key: keyStr,
})
}
lastKey = keyStr
}
return entries, nil
}
// Typescript: serializeNodeData(entries) -> NodeData
func serializeNodeData(entries []nodeEntry) (*nodeData, error) {
var data nodeData
i := 0
if len(entries) > 0 && entries[0].isTree() {
i++
ptr, err := entries[0].Tree.GetPointer(context.TODO())
if err != nil {
return nil, err
}
data.Left = &ptr
}
var lastKey string
for i < len(entries) {
leaf := entries[i]
if !leaf.isLeaf() {
return nil, fmt.Errorf("Not a valid node: two subtrees next to each other (%d, %d)", i, len(entries))
}
i++
var subtree *cid.Cid
if i < len(entries) {
next := entries[i]
if next.isTree() {
ptr, err := next.Tree.GetPointer(context.TODO())
if err != nil {
return nil, fmt.Errorf("getting subtree pointer: %w", err)
}
subtree = &ptr
i++
}
}
err := ensureValidMstKey(leaf.Key)
if err != nil {
return nil, err
}
prefixLen := countPrefixLen(lastKey, leaf.Key)
data.Entries = append(data.Entries, treeEntry{
PrefixLen: int64(prefixLen),
KeySuffix: []byte(leaf.Key)[prefixLen:],
Val: leaf.Val,
Tree: subtree,
})
lastKey = leaf.Key
}
return &data, nil
}
// how many leading bytes are identical between the two strings?
// Typescript: countPrefixLen(a: string, b: string) -> number
func countPrefixLen(a, b string) int {
// This pattern avoids panicindex calls, as the Go compiler's prove pass can
// convince itself that neither a[i] nor b[i] are ever out of bounds.
var i int
for i = 0; i < len(a) && i < len(b); i++ {
if a[i] != b[i] {
return i
}
}
return i
}
// both computes *and* persists a tree entry; this is different from typescript
// implementation
// Typescript: cidForEntries(entries) -> CID
func cidForEntries(ctx context.Context, entries []nodeEntry, cst cbor.IpldStore) (cid.Cid, error) {
nd, err := serializeNodeData(entries)
if err != nil {
return cid.Undef, fmt.Errorf("serializing new entries: %w", err)
}
return cst.Put(ctx, nd)
}
// keyHasAllValidChars reports whether s matches
// the regexp /^[a-zA-Z0-9_:.-]+$/ without using regexp,
// which is slower.
func keyHasAllValidChars(s string) bool {
if len(s) == 0 {
return false
}
for i := 0; i < len(s); i++ {
b := s[i]
if 'a' <= b && b <= 'z' ||
'A' <= b && b <= 'Z' ||
'0' <= b && b <= '9' {
continue
}
switch b {
case '_', ':', '.', '-':
continue
default:
return false
}
}
return true
}
// Typescript: isValidMstKey(str)
func isValidMstKey(s string) bool {
if len(s) > 256 || strings.Count(s, "/") != 1 {
return false
}
a, b, _ := strings.Cut(s, "/")
return len(b) > 0 &&
keyHasAllValidChars(a) &&
keyHasAllValidChars(b)
}
// Typescript: ensureValidMstKey(str)
func ensureValidMstKey(s string) error {
if !isValidMstKey(s) {
return fmt.Errorf("Not a valid MST key: %s", s)
}
return nil
}