Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/examples_build.nim
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{.used.}

import directchat, mdns
import directchat, kad_custom_store, mdns
28 changes: 28 additions & 0 deletions examples/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,31 @@ Welcome to the nim-libp2p documentation!

Here, you'll find [tutorials](tutorial_1_connect.md) to help you get started, as well as
the [full reference](https://iftech.github.io/nim-libp2p/master/libp2p.html).

## Custom Kademlia store

`KadDHT` keeps its records in a `KadStore`. The default `MemoryKadStore` loses every record when the process exits. [kad_custom_store.nim](https://github.com/iftech/nim-libp2p/blob/master/examples/kad_custom_store.nim) keeps them in a sorted byte key/value backend, so a node that restarts on the same data still serves its records.

The store needs four calls from the backend (`KvAdapter`):

| call | LevelDB | SQLite, `kv(k BLOB PRIMARY KEY, v BLOB)` | nim-datastore |
|------|---------|-------------------------------------------|---------------|
| `get` | `Get` | `SELECT v FROM kv WHERE k = ?` | `get` |
| `put` | `Put` | `INSERT OR REPLACE` | `put` |
| `del` | `Delete` | `DELETE FROM kv WHERE k = ?` | `delete` |
| `scan(prefix, after, limit)` | `Seek`, then `Next` while the key has the prefix | `SELECT k, v FROM kv WHERE k > ? AND substr(k, 1, ?) = ? ORDER BY k LIMIT ?` | `query` on hex-encoded keys, sorted |

A store method makes several backend calls. Put them in one transaction (SQLite) or one write batch (LevelDB), so each method stays atomic. `SnapshotKv` is the smallest backend: a sorted list in memory that `save` writes to a file and `SnapshotKv.load` reads back.

The first byte of a backend key names its kind:

| key | value | kind |
|-----|-------|------|
| `v`, record key | expiry, time, value | value record |
| `p`, key length (2 bytes), key, peer id | expiry, encoded `Peer` | provider record |
| `k`, provided key | stamp | provided key |
| `e`, expiry, record key | empty | values by expiry |
| `x`, expiry, key length, key, peer id | empty | providers by expiry |
| `s`, stamp, provided key | empty | provided keys by age |

Numbers are big-endian, so the backend sorts them in numeric order. An expiry has its sign bit flipped for the same reason. With the three index kinds, each eviction and each prune is a scan from the start of one prefix.
Loading
Loading