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
use std::{borrow::Cow, sync::Arc};
use dashmap::DashMap;
use ethnum::U256;
use genawaiter::rc::Gen;
use replace_with::replace_with_or_abort;
use crate::{
lowlevel::{ExplodedHexary, RawNode},
singleton_smt_root, FullProof, Hashed,
};
pub trait ContentAddrStore: Send + Sync {
fn get<'a>(&'a self, key: &[u8]) -> Option<Cow<'a, [u8]>>;
fn insert(&self, key: &[u8], value: &[u8]);
fn realize<'a>(&'a self, hash: Hashed) -> Option<RawNode<'a>> {
if hash == [0; 32] {
None
} else {
let gotten = self.get(&hash).expect("dangling pointer");
let view = match gotten {
Cow::Borrowed(gotten) => RawNode::try_from_slice(gotten).expect("corrupt node"),
Cow::Owned(gotten) => RawNode::try_from_slice(&gotten)
.expect("corrupt node")
.into_owned(),
};
Some(view)
}
}
}
#[derive(Default, Debug)]
pub struct InMemoryCas(DashMap<Vec<u8>, Vec<Vec<u8>>>);
impl ContentAddrStore for InMemoryCas {
fn get(&self, key: &[u8]) -> Option<Cow<'_, [u8]>> {
let r = self.0.get(key)?;
let r: &[u8] = r.last()?.as_slice();
Some(Cow::Borrowed(unsafe { std::mem::transmute(r) }))
}
fn insert(&self, key: &[u8], value: &[u8]) {
let mut r = self.0.entry(key.to_owned()).or_default();
r.push(value.to_owned());
}
}
#[derive(Debug)]
pub struct Database<C: ContentAddrStore> {
cas: Arc<C>,
}
impl<C: ContentAddrStore> Database<C> {
pub fn new(cas: C) -> Self {
Self { cas: cas.into() }
}
pub fn get_tree(&self, hash: Hashed) -> Option<Tree<C>> {
Some(Tree {
cas: self.cas.clone(),
ptr: hash,
})
}
pub fn storage(&self) -> &C {
&self.cas
}
}
#[derive(Debug)]
pub struct Tree<C: ContentAddrStore> {
cas: Arc<C>,
ptr: Hashed,
}
impl<C: ContentAddrStore> Clone for Tree<C> {
fn clone(&self) -> Self {
Self {
cas: self.cas.clone(),
ptr: self.ptr,
}
}
}
impl<C: ContentAddrStore> Tree<C> {
pub fn clear(&mut self) {
self.ptr = Hashed::default()
}
pub fn get<'a>(&'a self, key: Hashed) -> Cow<'a, [u8]> {
self.get_value(key, None)
}
pub fn root_hash(&self) -> Hashed {
self.ptr
}
pub fn get_with_proof<'a>(&'a self, key: Hashed) -> (Cow<'a, [u8]>, FullProof) {
let mut p = Vec::new();
let res = self.get_value(key, Some(&mut |h| p.push(h)));
log::trace!("proof: {:?}", p);
p.resize(256, Default::default());
let p = FullProof(p);
assert!(p.verify(self.ptr, key, &res));
(res, p)
}
pub fn iter(&'_ self) -> impl Iterator<Item = (Hashed, Cow<'_, [u8]>)> + '_ {
let gen = Gen::new(|co| async move {
let mut dfs_stack: Vec<Hashed> = vec![self.ptr];
while let Some(top) = dfs_stack.pop() {
if top == [0; 32] {
continue;
}
match self.cas.realize(top).unwrap() {
RawNode::Single(_, k, v) => co.yield_((k, v)).await,
RawNode::Hexary(_, _, gggc) => {
for gggc in gggc {
dfs_stack.push(*gggc)
}
}
}
}
});
gen.into_iter()
}
fn get_value<'a>(
&'a self,
key: Hashed,
mut on_proof_frag: Option<&mut dyn FnMut(Hashed)>,
) -> Cow<'a, [u8]> {
let mut ptr = self.ptr;
let mut ikey = U256::from_be_bytes(key);
loop {
match self.cas.realize(ptr) {
Some(RawNode::Single(height, single_key, data)) => {
if key == single_key {
return data;
} else {
if let Some(opf) = on_proof_frag.as_mut() {
let mut diverging_height = (height as usize) * 4;
let mut single_ikey = truncate_shl(
U256::from_be_bytes(single_key),
(64 - (height as u32)) * 4,
);
while (single_ikey & (U256::ONE << 255)) == (ikey & (U256::ONE << 255))
{
single_ikey = truncate_shl(single_ikey, 1);
ikey = truncate_shl(ikey, 1);
diverging_height -= 1;
opf(Hashed::default());
}
assert!(high4(single_ikey) != high4(ikey));
opf(singleton_smt_root(diverging_height, single_key, &data));
}
return Cow::Owned(Vec::new());
}
}
Some(RawNode::Hexary(_, _, gggc)) => {
let key_frag = (ikey.wrapping_shr(252)).as_usize();
if let Some(opf) = on_proof_frag.as_mut() {
for frag in ExplodedHexary::new(&gggc).proof_frag(key_frag) {
opf(frag)
}
}
log::trace!("key frag {} for key {}", key_frag, hex::encode(key));
ptr = *gggc[key_frag];
}
None => return Cow::Owned(Vec::new()),
}
ikey = rm4(ikey)
}
}
pub fn insert(&mut self, key: Hashed, value: &[u8]) {
replace_with_or_abort(self, |t| t.with(key, value))
}
#[must_use]
pub fn with(self, key: Hashed, value: &[u8]) -> Self {
self.with_binding(key, U256::from_be_bytes(key), value, 64)
}
fn debug_graphviz(&self) {
match self.cas.realize(self.ptr) {
Some(RawNode::Single(_, single_key, _)) => {
eprintln!(
"{:?} [label=\"key {}\"];",
hex::encode(&self.ptr),
hex::encode(&single_key[..10])
);
}
Some(RawNode::Hexary(_, _, gggc)) => {
for (i, child) in gggc.iter().enumerate() {
if **child != [0u8; 32] {
Self {
cas: self.cas.clone(),
ptr: **child,
}
.debug_graphviz();
eprintln!(
"{:?} -> {:?} [label=\"{}\"];",
hex::encode(&self.ptr),
hex::encode(&child.as_ref()),
i
);
eprintln!(
"{:?} [label=\"{}\"];",
hex::encode(&self.ptr),
hex::encode(&self.ptr[..10]),
);
}
}
}
None => todo!(),
}
}
fn with_binding(self, key: Hashed, ikey: U256, value: &[u8], rec_height: u8) -> Self {
log::trace!("RECURSE DOWN {} {}", hex::encode(&key), ikey);
let new_node = match self.cas.realize(self.ptr) {
Some(RawNode::Single(height, single_key, node_value)) => {
assert!(height == rec_height);
if key == single_key {
if value.len() == 0 {
return Self {
cas: self.cas,
ptr: Hashed::default(),
};
}
RawNode::Single(height, key, Cow::Borrowed(value))
} else {
let single_ikey = truncate_shl(
U256::from_be_bytes(single_key),
(64 - (rec_height as u32)) * 4,
);
let single_ifrag = single_ikey.wrapping_shr(252).as_usize();
let key_ifrag = ikey.wrapping_shr(252).as_usize();
if single_ifrag != key_ifrag {
let key_foo = Self {
cas: self.cas.clone(),
ptr: Hashed::default(),
}
.with_binding(
key,
rm4(ikey),
value,
rec_height - 1,
);
let single_foo = Self {
cas: self.cas.clone(),
ptr: Hashed::default(),
}
.with_binding(
single_key,
rm4(single_ikey),
&node_value,
rec_height - 1,
);
let mut gggc: [Cow<'static, Hashed>; 16] = Default::default();
gggc[single_ifrag] = Cow::Owned(single_foo.ptr);
gggc[key_ifrag] = Cow::Owned(key_foo.ptr);
RawNode::Hexary(height, 2, gggc)
} else {
let lower = RawNode::Single(height - 1, single_key, node_value);
let lower_ptr = lower.hash();
self.cas.insert(&lower_ptr, &lower.to_bytes());
let lower = Self {
cas: self.cas.clone(),
ptr: lower_ptr,
}
.with_binding(
key,
rm4(ikey),
value,
rec_height - 1,
);
let mut gggc: [Cow<'static, Hashed>; 16] = Default::default();
gggc[single_ifrag] = Cow::Owned(lower.ptr);
RawNode::Hexary(height, 2, gggc)
}
}
}
Some(RawNode::Hexary(height, count, mut gggc)) => {
assert!(height == rec_height);
let key_frag = (ikey.wrapping_shr(252)).as_usize();
let to_change = &mut gggc[key_frag];
let sub_tree = Self {
cas: self.cas.clone(),
ptr: **to_change,
};
let pre_count = sub_tree.count();
let sub_tree = sub_tree.with_binding(key, rm4(ikey), value, rec_height - 1);
*to_change = Cow::Owned(sub_tree.ptr);
RawNode::Hexary(
height,
if sub_tree.count() > pre_count {
count + (sub_tree.count() - pre_count)
} else {
count - (pre_count - sub_tree.count())
},
gggc,
)
}
None => RawNode::Single(rec_height, key, Cow::Owned(value.to_vec())),
};
let ptr = new_node.hash();
self.cas.insert(&ptr, &new_node.to_bytes());
Self { cas: self.cas, ptr }
}
pub fn count(&self) -> u64 {
self.cas
.realize(self.ptr)
.map(|r| r.count())
.unwrap_or_default()
}
pub fn storage(&self) -> &C {
&self.cas
}
}
fn rm4(i: U256) -> U256 {
(i & !(U256::from(0b1111u32) << U256::from(252u32))) << 4
}
fn truncate_shl(i: U256, offset: u32) -> U256 {
i.reverse_bits().wrapping_shr(offset).reverse_bits()
}
fn high4(i: U256) -> usize {
i.wrapping_shr(252).as_usize()
}
#[cfg(test)]
mod tests {
use dashmap::DashMap;
use ethnum::U256;
use quickcheck_macros::quickcheck;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use crate::Hashed;
use super::*;
#[quickcheck]
fn rmhigh(a: u128, b: u128) -> bool {
let t = U256::from(a) * U256::from(b);
(rm4(t) >> 4) | U256::from(high4(t) as u8) << 252 == t
}
#[quickcheck]
fn trushl(a: u128, b: u128) -> bool {
let t = U256::from(a) * U256::from(b);
truncate_shl(t, 4) == rm4(t)
}
#[test]
fn rmhigh_one() {
let t = 1u8.into();
assert_eq!((rm4(t) >> 4) | U256::from(high4(t) as u8) << 252, t);
}
#[test]
fn trushl_one() {
let t = 1u8.into();
assert_eq!(truncate_shl(t, 4), rm4(t));
}
#[test]
fn simple_insertion() {
let count = 100u64;
let bindings = (0..count)
.map(|i| {
(
*blake3::hash(format!("key-{}", i).as_bytes()).as_bytes(),
format!("key-{}", i).as_bytes().to_vec(),
)
})
.collect::<Vec<_>>();
let db = Database::new(InMemoryCas::default());
let mut empty = db.get_tree(Hashed::default()).unwrap();
for (k, v) in bindings.iter() {
empty = empty.with(*k, &v);
}
assert_eq!(empty.count(), count);
let _ = empty.get_with_proof([0; 32]);
empty.insert([0; 32], b"hello world");
let _ = empty.get_with_proof([0; 32]);
eprintln!("{} elements in database", db.storage().0.len());
bindings
.par_iter()
.for_each(|(k, v)| assert_eq!(empty.get_with_proof(*k).0, v.as_slice()));
for (i, (k, _)) in bindings.into_iter().enumerate() {
assert_eq!(empty.count(), count - (i as u64));
empty = empty.with(k, &[]);
}
}
}