kolo docsbeta

kolo-store

Almacenamiento persistente para logs de Kolo y réplicas de solo lectura en una máquina.

En esta página

kolo-store guarda logs de kolo-log en disco y los recupera después de un reinicio, volviendo a comprobar cada firma, cada hash y cada raíz de Merkle. Mantiene una réplica de un log como lo hace un monitor de Certificate Transparency (RFC 9162, sección 8.2) con un log, y borra destruyendo claves, el borrado criptográfico (cryptographic erase) de NIST SP 800-88 Rev. 1. Es el kololog.Storage del log: un log abierto solo mantiene en memoria los hashes de su árbol y sus registros, y lee las entradas del disco. Un almacén guarda muchos logs, uno por ID de log: los tuyos y réplicas de solo lectura de los de otras personas. Guarda los datos en una máquina y no habla con la red.

Instalación

go get github.com/ciranda-dev/kolo-store

Pebble enlaza la biblioteca C de zstd cuando cgo está activado. Compila con CGO_ENABLED=0 para obtener un binario solo en Go.

Inicio rápido

Crea un log, cierra el almacén, vuelve a abrir el directorio y lee de nuevo la entrada.

main.go
package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	koloid "github.com/ciranda-dev/kolo-id"
	kololog "github.com/ciranda-dev/kolo-log"
	kolostore "github.com/ciranda-dev/kolo-store"
)

func main() {
	dir, err := os.MkdirTemp("", "kolostore")
	check(err)
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "db")

	me, err := koloid.Generate()
	check(err)
	b, err := kolostore.OpenPebble(path)
	check(err)
	s := kolostore.New(b)
	l, err := s.Create(me, kololog.WithValueEncoding(kololog.UTF8))
	check(err)
	_, err = l.Append("hello")
	check(err)
	logID := l.ID()
	check(s.Close())

	// Open the directory again, as a restarted process would.
	b, err = kolostore.OpenPebble(path)
	check(err)
	s = kolostore.New(b)
	defer s.Close()
	l, err = s.Open(me, logID, kololog.WithValueEncoding(kololog.UTF8))
	check(err)
	var text string
	check(l.Read(0, &text))
	fmt.Println(l.Len(), text)
}

func check(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

Imprime 1 hello. Store.Close también cierra todos los logs abiertos del almacén. En un programa real, conserva me con Save y Load de kolo-id: solo la identidad que creó un log puede volver a abrirlo.

Referencia de la API

La referencia de la API se genera a partir del código Go y está en inglés.

Paquete kolostore · github.com/ciranda-dev/kolo-store · v0.1.0

Package kolostore persists kolo-log logs in an ordered key-value backend. Many logs share one store; each write is one atomic, durable batch.

This package is experimental and its API may change before v1.0.0.

Constantes

const (
	// MinMemTableSize is the smallest [PebbleOptions.MemTableSize], 1 MiB.
	MinMemTableSize = 1 << 20
	// MaxMemTableSize is the largest [PebbleOptions.MemTableSize], 1 GiB.
	MaxMemTableSize = 1 << 30
)

Variables

var (
	// ErrNotFound is returned by [Backend.Get] for a key that is not stored.
	ErrNotFound = errors.New("kolostore: not found")
	// ErrClosed is returned after Close by a backend, a store or a log.
	ErrClosed = errors.New("kolostore: closed")
	// ErrTooLarge is returned for a write too large for one batch: a Pebble batch of 4 GiB - 1 bytes or more (2 GiB - 1 on 32-bit), or a [Store.Adopt] batch of 2 GiB or more (1 GiB).
	ErrTooLarge = errors.New("kolostore: batch too large")
)
var (
	// ErrReplica is returned by [Store.Open] for a stored read-only replica, which only [Store.OpenReplica] opens.
	ErrReplica = errors.New("kolostore: log is a read-only replica")
	// ErrNotReplica is returned by [Store.OpenReplica] for a stored log that is not a replica, such as one of your own.
	ErrNotReplica = errors.New("kolostore: log is not a replica")
	// ErrLogInUse is returned when a log is already open on the same backend in this process.
	ErrLogInUse = errors.New("kolostore: log already open")
)
var ErrCorrupt = errors.New("kolostore: corrupt data")

ErrCorrupt is returned when stored data is missing, extra, cannot be decoded or does not verify.

var ErrIncomplete = errors.New("kolostore: replica is not complete")

ErrIncomplete is returned by Store.Adopt for a replica that has no head yet or an unfinished catch-up.

var ErrInsecureDir = errors.New("kolostore: insecure directory")

ErrInsecureDir is returned by OpenPebble for a directory that group or others can access, that another user owns or that changed while opening.

var ErrInvalidOptions = errors.New("kolostore: invalid pebble options")

ErrInvalidOptions is returned by OpenPebbleWith for a PebbleOptions value out of bounds.

Tipos

type Backend

type Backend interface {
	// Get returns the value of key, or [ErrNotFound].
	Get(key []byte) ([]byte, error)
	// Put durably stores value under key.
	Put(key, value []byte) error
	// Delete durably removes key; deleting a missing key is not an error.
	Delete(key []byte) error
	// Scan calls fn for each key in [start, end) in order until fn returns false.
	// A nil end means no upper bound and limit <= 0 means no limit; fn must not call the backend.
	Scan(start, end []byte, reverse bool, limit int, fn func(key, value []byte) bool) error
	// NewBatch returns an empty batch of writes.
	NewBatch() Batch
	// Close releases the backend; later calls return [ErrClosed] and a second Close returns nil.
	Close() error
}

Backend is the ordered key-value storage that a Store runs on; returned slices are copies. Use a comparable type, such as a pointer, so that Stores on one backend share their open logs.

func NewMemory
func NewMemory() Backend

NewMemory returns an empty in-memory Backend, for tests and short-lived stores.

func OpenPebble
func OpenPebble(dir string) (Backend, error)

OpenPebble opens or creates a Pebble Backend in dir; another open of the same dir fails until Close. It creates dir with mode 0700 and returns ErrInsecureDir for a dir open to group or others, owned by another user or swapped while opening. Permissions and owner are not checked on Windows. The directory is checked only when it is opened; changing what dir points to afterwards needs write access to a parent directory, and the store does not defend against that.

func OpenPebbleWith
func OpenPebbleWith(dir string, o PebbleOptions) (Backend, error)

OpenPebbleWith is OpenPebble with tuning for large values; it returns ErrInvalidOptions before touching dir for a MemTableSize out of bounds. Every commit is still synced to disk, whatever the options.

type Batch

type Batch interface {
	// Put adds a write of value under key; the batch keeps its own copy, so the caller may clear value after Commit.
	Put(key, value []byte)
	// Delete adds a removal of key.
	Delete(key []byte)
	// DeleteRange adds a removal of every key in [start, end); an empty range does nothing.
	DeleteRange(start, end []byte)
	// Commit applies every write or none; a batch can be committed once.
	Commit() error
}

Batch collects writes that Batch.Commit applies atomically and durably.

type Log

type Log struct {
	// contains filtered or unexported fields
}

Log is an open log of a Store; it is safe for concurrent use and is the only way to write to the log. Every change is one atomic batch that kolo-log commits before it shows the change, so a failed write changes nothing.

func (Log) Append
func (l *Log) Append(v any) (uint64, error)

Append appends v and durably stores the entry, its key and the new head in one batch, then returns its index. If the write fails, the log is unchanged and returns the error.

func (Log) Close
func (l *Log) Close() error

Close releases the log so it can be opened again; a second Close returns nil.

func (Log) ConsistencyProof
func (l *Log) ConsistencyProof(oldSize, newSize uint64) (kololog.ConsistencyProof, error)

ConsistencyProof returns a proof that the tree of oldSize entries is a prefix of the tree of newSize entries.

func (Log) Delete
func (l *Log) Delete(indexes ...uint64) error

Delete replaces the entries at indexes with delete markers signed by the log key and removes their keys, in one synced batch. An index out of range deletes nothing and deleted entries are skipped; if the write fails, every entry stays as it was. A backup, snapshot, write-ahead log or freed block from before keeps a working key, and after a reopen an old entry value put back reads as live.

func (Log) Entry
func (l *Log) Entry(index uint64) (kololog.Entry, error)

Entry returns the stored form of the entry at index, its key included; clear Key when done with it.

func (Log) EntryInfo
func (l *Log) EntryInfo(index uint64) (kololog.EntryInfo, error)

EntryInfo returns whether the entry at index is deleted and whether its key is stored, without reading the backend.

func (Log) Get
func (l *Log) Get(index uint64) ([]byte, error)

Get returns the stored bytes of the entry at index.

func (Log) Head
func (l *Log) Head() (kololog.Head, error)

Head returns a signed head for the stored tree.

func (Log) Header
func (l *Log) Header() kololog.LogHeader

Header returns a copy of the signed log header; it also works after Close.

func (Log) ID
func (l *Log) ID() kololog.LogID

ID returns the log ID; it also works after Close.

func (Log) InclusionProof
func (l *Log) InclusionProof(index, size uint64) (kololog.InclusionProof, error)

InclusionProof returns a proof that the entry at index is in the tree of the first size entries.

func (Log) Key
func (l *Log) Key(index uint64) (kololog.EntryKey, error)

Key returns the key of the entry at index without reading its ciphertext; clear it when done.

func (Log) Len
func (l *Log) Len() uint64

Len returns the number of stored entries, deleted ones included; after Close it returns the last length.

func (Log) Read
func (l *Log) Read(index uint64, out any) error

Read decodes the entry at index into out.

func (Log) Record
func (l *Log) Record(index uint64) (kololog.Record, error)

Record returns the public record of the entry at index.

type PebbleOptions

type PebbleOptions struct {
	// MemTableSize is the size in bytes of Pebble's memtable, between [MinMemTableSize] and [MaxMemTableSize]; zero keeps Pebble's default of 4 MiB.
	// A larger memtable flushes less often, which speeds up writes of large values, and costs up to twice its size in memory.
	MemTableSize int64
	// NoCompression stores blocks uncompressed. Use it when the values are ciphertext, which does not compress.
	// A directory written with it opens with or without it.
	NoCompression bool
}

PebbleOptions tunes OpenPebbleWith; the zero value is what OpenPebble uses. Neither field changes durability: every commit is still synced.

type Replica

type Replica struct {
	// contains filtered or unexported fields
}

Replica is an open read-only replica of a Store; it is safe for concurrent use. Every change is one atomic batch that kolo-log commits before it shows the change, so a failed write changes nothing.

func (Replica) AddKey
func (r *Replica) AddKey(index uint64, key []byte) error

AddKey gives an entry that came without its key the key with kololog.Replica.AddKey and stores it in one write; the key it already has writes nothing.

func (Replica) AddKeys
func (r *Replica) AddKeys(start uint64, keys []kololog.EntryKey) error

AddKeys gives the entries from start on that came without their keys the keys with kololog.Replica.AddKeys and stores every key that passes in one batch; a failed write stores none.

func (Replica) ApplyDelete
func (r *Replica) ApplyDelete(markers ...[]byte) error

ApplyDelete applies delete markers with kololog.Replica.ApplyDelete, storing each in place of its entry's ciphertext and removing its key, all in one batch; one bad marker applies none. As with Log.Delete, old copies of the disk keep a working key.

func (Replica) Close
func (r *Replica) Close() error

Close releases the replica so it can be opened again; a second Close returns nil.

func (Replica) ConsistencyProof
func (r *Replica) ConsistencyProof(oldSize, newSize uint64) (kololog.ConsistencyProof, error)

ConsistencyProof returns a proof that the tree of oldSize entries is a prefix of the tree of newSize entries.

func (Replica) Entry
func (r *Replica) Entry(index uint64) (kololog.Entry, error)

Entry returns the stored form of the entry at index, its key included; clear Key when done with it.

func (Replica) EntryInfo
func (r *Replica) EntryInfo(index uint64) (kololog.EntryInfo, error)

EntryInfo returns whether the entry at index is deleted and whether its key is stored, without reading the backend.

func (Replica) Get
func (r *Replica) Get(index uint64) ([]byte, error)

Get returns the stored bytes of the entry at index.

func (Replica) Head
func (r *Replica) Head() (kololog.Head, error)

Head returns the last verified head, as received, or kololog.ErrNoHead.

func (Replica) Header
func (r *Replica) Header() kololog.LogHeader

Header returns a copy of the signed log header; it also works after Close.

func (Replica) ID
func (r *Replica) ID() kololog.LogID

ID returns the log ID; it also works after Close.

func (Replica) InclusionProof
func (r *Replica) InclusionProof(index, size uint64) (kololog.InclusionProof, error)

InclusionProof returns a proof that the entry at index is in the tree of the first size entries.

func (Replica) Key
func (r *Replica) Key(index uint64) (kololog.EntryKey, error)

Key returns the key of the entry at index without reading its ciphertext; clear it when done.

func (Replica) Len
func (r *Replica) Len() uint64

Len returns the number of stored entries, deleted ones included; after Close it returns the last length.

func (Replica) Read
func (r *Replica) Read(index uint64, out any) error

Read decodes the entry at index into out.

func (Replica) Record
func (r *Replica) Record(index uint64) (kololog.Record, error)

Record returns the public record of the entry at index.

func (Replica) Target
func (r *Replica) Target() (h kololog.Head, p kololog.ConsistencyProof, ok bool)

Target returns the head an unfinished catch-up is filling and the proof from Len to it, or ok false; see kololog.Replica.Target.

func (Replica) Update
func (r *Replica) Update(h kololog.Head, p kololog.ConsistencyProof, entries []kololog.Entry) error

Update grows the replica with kololog.Replica.Update, which stores the new entries and keys, the head and any unfinished target with its proof in one batch. The entries may be a chunk that stops short of h; OpenReplica replays a stored target. A refused update or a failed write changes nothing.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store persists many kolo-log logs in one Backend.

func New
func New(b Backend) *Store

New returns a Store on b; Store.Close closes b. With a nil b, also a nil pointer, every method returns an error and Close returns nil. Stores on one comparable backend value share their open logs; a non-comparable backend only guards its own Store.

func (Store) Adopt
func (s *Store) Adopt(id *koloid.Identity, rep *Replica, opts ...kololog.Option) (*Log, error)

Adopt brings the closed own log of id stored here up to rep, a replica of it with the same header in any store, and opens it with opts like Store.Open. rep needs a head, no pending catch-up (ErrIncomplete) and the keys of its live entries past the stored head, which must be a prefix of its head (kololog.ErrRollback). One batch adds those entries and rep's head and keeps every deletion of either side, so a crash leaves the old log or the new one; a batch of 2 GiB or more (1 GiB on 32-bit) returns ErrTooLarge. An error from the final open leaves the adopted log stored, and Store.Open opens it.

func (Store) Close
func (s *Store) Close() error

Close waits for running writes, closes every open Log and Replica of the store, then closes the backend. Every Close waits for the first one to finish and returns its error, also when the backend's Close panicked.

func (Store) Create
func (s *Store) Create(id *koloid.Identity, opts ...kololog.Option) (*Log, error)

Create makes a new log with kololog.New and durably stores its header and empty head in one batch.

func (Store) Delete
func (s *Store) Delete(logID kololog.LogID) error

Delete removes a closed log or replica, its header, head, entries and list key, in one atomic batch. Deleting a log that is not stored does nothing; a log open anywhere in this process returns ErrLogInUse. The stored header is not trusted, so Delete holds a reservation of the log ID: deleting a replica also returns ErrLogInUse while the owner's writable log with that ID is open in this process.

func (Store) List
func (s *Store) List() ([]kololog.LogID, error)

List returns the IDs of the stored logs and replicas in byte order; Store.Owner tells them apart.

func (Store) Open
func (s *Store) Open(id *koloid.Identity, logID kololog.LogID, opts ...kololog.Option) (*Log, error)

Open loads a log from the backend and restores it with kololog.Restore, which verifies every entry. Pass kololog.WithTrustedHead with the last head you published to reject an older snapshot (kololog.ErrRollback); the storage is trusted to be the node's own disk, so that head is the only defense against a rollback. Damaged data returns an error wrapping ErrCorrupt or a kololog error, and a stored replica returns ErrReplica.

func (Store) OpenReplica
func (s *Store) OpenReplica(pub ed25519.PublicKey, logID kololog.LogID, header []byte) (*Replica, error)

OpenReplica opens the stored read-only replica of the log logID owned by pub, or creates it from the signed header if the log is not stored. An opened replica is verified like Store.Open; a non-empty header must then equal the stored one. An own log returns ErrNotReplica.

func (Store) Owner
func (s *Store) Owner(logID kololog.LogID) (pub ed25519.PublicKey, replica bool, err error)

Owner returns the owner key named in a stored log's header and whether the log is a read-only replica, for example to reopen it after a restart. The key is checked only against the header's own signature; Open and OpenReplica verify everything against the key you pass them.

Conviene saber

kolo-store responde a una entrada ausente con un error que envuelve kololog.ErrOutOfRange junto a ErrCorrupt, como kolo-log exige a un Storage. kolo-store escribe todas las claves de un kololog.Change (Change.Keys) en el lote del cambio. Create y OpenReplica de una réplica nueva devuelven el error del backend cuando falla la lectura que comprueba que el log nuevo no tiene entradas, en vez de seguir como si estuviera vacío. Leer una entrada que el log tiene pero que el backend ha perdido devuelve ErrCorrupt envolviendo kololog.ErrStorageMismatch, nunca ErrOutOfRange.

Después de un reinicio, List devuelve los IDs de los logs y réplicas guardados, y Owner te dice, para cada uno, la clave del propietario y si es una réplica, para que sepas si llamar a Open o a OpenReplica. Open rechaza una réplica guardada con ErrReplica, y OpenReplica rechaza uno de tus propios logs con ErrNotReplica.

Log y Replica son seguros para uso concurrente. Un Log es la única forma de escribir en un log guardado. Una Replica solo crece con Update, y no tiene Append ni Delete por índice. Open y OpenReplica leen las entradas y las claves guardadas en un solo recorrido cada una, y kolo-log verifica cada entrada al leerla, sin quedarse con ninguna. Después, cada lectura trae la entrada del disco y la vuelve a comprobar frente a su registro.

Log.Delete(indexes...) y Replica.ApplyDelete(markers...) borran o aplican muchas entradas a la vez en un solo lote, todo o nada; una marca incorrecta hace que no se aplique ninguna. Key y EntryInfo devuelven la clave de una entrada, y si está borrada o tiene clave, sin leer su texto cifrado.

Una réplica muy atrasada puede ponerse al día por pasos. Replica.Update acepta entradas que se quedan antes del head y guarda con cada paso el objetivo pendiente y su prueba, así que cada paso es un único lote acotado. OpenReplica vuelve a comprobar un objetivo guardado reproduciéndolo con Update, así que un reinicio en mitad de una puesta al día continúa donde se quedó, y Target devuelve el head que se está completando y su prueba. AddKey guarda una clave que llega después de su entrada, comprobada frente al compromiso del registro, en una sola escritura. Replica.AddKeys(start, keys) da sus claves a muchas entradas a la vez, como máximo kololog.MaxAddKeys (32.768) por llamada, y guarda en un solo lote cada clave que pasa; las rechazadas vuelven en un *kololog.BadKeyError, y una escritura fallida no guarda ninguna. Log.Entry y Replica.Entry devuelven la forma guardada de una entrada con su clave, para una capa de sincronización; borra Key cuando termines con ella.

Store.Adopt(id, rep, opts...) es para un dispositivo cuyo log propio va por detrás de la copia que tienen otros: trae a una réplica las entradas que faltan con sus claves, adóptala, y el log añade a partir de la longitud de la réplica. Pone el log propio cerrado de id al nivel de la réplica rep de él, que puede estar en cualquier almacén, en un solo lote, y abre el resultado como Open. El lote añade solo las entradas posteriores al head guardado, con sus claves, y el head de la réplica, así que un fallo del proceso deja el log antiguo o el nuevo, nunca una mezcla. Los borrados se conservan de ambos lados: una entrada que la réplica borró se guarda con su marca y sin su clave, y una entrada que el almacén borró sigue borrada aunque la réplica aún la tenga, así que un borrado guardado nunca se deshace. Antes del lote, Adopt lee las claves guardadas, sin texto cifrado, y comprueba la marca de cada entrada que solo borró el almacén. No repara las entradas guardadas que conserva: otros daños en ellas hacen fallar la apertura final, igual que fallan Open. Un error de la apertura final, como kololog.ErrEncodingMismatch por unas opts ausentes, deja el log adoptado guardado, y Open lo abre.

Adopt rechaza:

  • una réplica de otro propietario, o cuyo header no es el guardado (kololog.ErrBadLogHeader);
  • un ID de log que el almacén no guarda (kololog.ErrMissingHeader), o una réplica guardada en lugar de un log propio (ErrReplica);
  • un log abierto en este proceso (ErrLogInUse);
  • una réplica sin head o con una puesta al día sin terminar (ErrIncomplete);
  • una entrada viva posterior al head guardado sin su clave (kololog.ErrKeyUnavailable);
  • una réplica de la que el log guardado no es prefijo, más corta o bifurcada (kololog.ErrRollback);
  • una entrada guardada que conserva y que no tiene ni clave ni una marca de borrado válida (ErrCorrupt);
  • un lote de 2 GiB o más, 1 GiB en 32 bits (ErrTooLarge). No se escribe nada.

El lote retiene las entradas que añade, y Pebble retiene una segunda copia mientras confirma, así que Adopt es la única llamada cuya memoria crece con el tamaño de lo que maneja: adoptar 256 MiB de entradas llegó a un heap máximo de 560 MB, 2,1 veces su tamaño. Cuenta su lote como lo hace Pebble, y su límite de 2 GiB es la mitad del límite de lote de Pebble, así que ambas copias caben en él.

Límites

  • Memoria: un log o una réplica abiertos ocupan unos 250 bytes por entrada, sea cual sea el tamaño de las entradas, y una lectura, un Append o un Update solo retienen las entradas que manejan. Adopt es la excepción: retiene las entradas que añade cerca de dos veces, y rechaza un lote de 2 GiB o más (1 GiB en 32 bits) con ErrTooLarge.
  • Un lote de Pebble de 4 GiB - 1 bytes o más (2 GiB - 1 en 32 bits) devuelve ErrTooLarge en lugar de provocar un pánico dentro de Pebble. No se escribe nada.
  • Un almacén guarda un log por ID de log, sea quien sea su propietario. Open u OpenReplica de un ID que el almacén guarda para otro propietario devuelve kololog.ErrBadLogHeader y no cambia nada; una réplica del log de otro propietario con el mismo ID necesita otro almacén.
  • OpenPebble crea el directorio del almacén con modo 0700 y devuelve ErrInsecureDir si el grupo u otros pueden acceder a él, si pertenece a otro usuario o si se sustituye mientras se abre.
  • OpenPebble deja en modo 0600 todos los archivos que Pebble crea en el directorio, y cambia a 0600 los de un directorio que ya existía, porque guardan las claves de las entradas. OpenPebbleWith(dir, PebbleOptions{MemTableSize, NoCompression}) es OpenPebble para valores grandes, como fragmentos de 1 MiB: MemTableSize (0 para los 4 MiB de Pebble, o de 1 MiB a 1 GiB, y en otro caso ErrInvalidOptions) hace que Pebble vuelque y compacte con menos frecuencia y cuesta hasta el doble de ese tamaño en memoria, y NoCompression evita comprimir bloques, un trabajo inútil sobre texto cifrado. Cada commit sigue sincronizado. En un Mac, escribir 1 GiB en valores de 1 MiB tardó 14,9 s con los valores por defecto y 7,4 s con 256 MiB y sin compresión.
  • Open y OpenReplica tardan, y hacen E/S, de forma lineal en el tamaño del log: leen una vez cada entrada guardada, así que un log grande se abre despacio. Después quedan unos 250 bytes de memoria por entrada.
  • Un ID de log solo puede abrirse una vez por backend en cada proceso; una segunda apertura devuelve ErrLogInUse. Un segundo OpenPebble sobre el mismo directorio falla, también a través de otra ruta, así que otro proceso no puede escribir los mismos logs.
  • Store.Delete devuelve ErrLogInUse para un log abierto en cualquier parte del proceso. Borrar una réplica también lo devuelve mientras el log de escritura del propietario con ese ID esté abierto en el mismo proceso.
  • Una entrada guardada cuyo registro o marca de borrado supere los 1024 bytes, cuya clave esté presente pero no tenga 32 bytes, o que esté borrada y aún tenga clave, se rechaza con ErrCorrupt. El objetivo de puesta al día guardado de una réplica también está acotado: su head, hasta 1024 bytes; su prueba, hasta 65 hashes.
  • Los valores de entrada guardados son de la versión 3, y la clave de cada entrada viva se guarda aparte, junto a ellos. Las versiones 1 y 2, que guardaban la clave dentro del valor de la entrada, se rechazan.

Seguridad

  • La clave de cada entrada se guarda en claro junto a su texto cifrado, porque el almacén confía en el propio disco del nodo.
  • Open y OpenReplica vuelven a verificarlo todo con kolo-log, frente a la clave que les pasas. Owner solo comprueba la clave del propietario guardada frente a la propia firma de la cabecera.
  • Pasa kololog.WithTrustedHead con el último head que publicaste, para que una instantánea guardada más antigua devuelva kololog.ErrRollback. Ese es el ancla frente a una vuelta atrás del disco.
  • El byte que indica el tipo de réplica no está firmado: una escritura en el disco que marque una réplica crecida como log propio hace que Open la acepte con la identidad del propietario.
  • OpenReplica nunca necesita una clave privada, y un Update rechazado no cambia nada ni en memoria ni en disco.

Límites conocidos

  • Experimental. La API puede cambiar antes de v1.0.0.
  • En Windows no se comprueban los permisos ni el propietario del directorio del almacén.
  • El directorio solo se comprueba al abrirlo. Cambiar después a qué apunta la ruta requiere permiso de escritura en un directorio padre, y el almacén no se defiende frente a eso.
  • NewMemory lo guarda todo en memoria, para tests y almacenes de vida corta.
  • Un Backend propio debería ser un tipo comparable, como un puntero, para que los almacenes que lo usan compartan sus logs abiertos.

Errores

ErrorMensaje
ErrClosedkolostore: closed
ErrCorruptkolostore: corrupt data
ErrIncompletekolostore: replica is not complete
ErrInsecureDirkolostore: insecure directory
ErrInvalidOptionskolostore: invalid pebble options
ErrLogInUsekolostore: log already open
ErrNotFoundkolostore: not found
ErrNotReplicakolostore: log is not a replica
ErrReplicakolostore: log is a read-only replica
ErrTooLargekolostore: batch too large

Comprueba los errores con errors.Is. Los datos guardados dañados siempre envuelven ErrCorrupt, en Open o en una lectura posterior: claves que faltan o sobran, datos que no se decodifican o no coinciden con su cabecera firmada, sus heads, sus registros y sus marcas de borrado, o una entrada viva de tu propio log que perdió su clave. El error también envuelve el error de kolo-log que lo detectó, así que errors.Is encuentra los dos: kololog.ErrRestoreMismatch en Open, kololog.ErrStorageMismatch para un cambio en el disco después de Open o una entrada que el backend ha perdido, o kololog.ErrInvalidHead de datos guardados. Los demás errores de kolo-log se transmiten envueltos, sin ErrCorrupt, como kololog.ErrMissingHeader, kololog.ErrBadLogHeader, kololog.ErrRollback, kololog.ErrDiverged, kololog.ErrBadProof o kololog.ErrBadEntry. Una escritura fallida devuelve el error del backend. ErrIncomplete significa que Adopt recibió una réplica sin head o con una puesta al día sin terminar, y ErrTooLarge, una escritura demasiado grande para un lote: un lote de Adopt de 2 GiB o más, o un lote de Pebble de 4 GiB - 1 bytes o más (1 GiB y 2 GiB - 1 en 32 bits).

Referencias

  • RFC 9162, Certificate Transparency Version 2.0 (Experimental, December 2021).
    • Toma: la sección 8.2, el monitor que conserva todas las entradas, que sigue una réplica guardada.
    • No implementa: las marcas de tiempo en los heads, por lo que los heads se ordenan solo por tamaño.
  • NIST SP 800-88 Rev. 1 (December 2014), section 2.6, Cryptographic Erase.
    • Toma: borrar destruyendo una clave.
    • No implementa: el cifrado de la clave con una clave maestra (key wrapping); la clave se guarda en claro junto al texto cifrado, porque el almacén confía en el propio disco del nodo.
  • Reardon, Basin and Capkun, SoK: Secure Data Deletion, IEEE S&P 2013.
    • Toma: por qué un motor con estructura de log conserva bytes antiguos hasta que compacta.
  • O'Neil et al., The Log-Structured Merge-Tree, Acta Informatica 1996.
    • Toma: el modelo de almacenamiento del motor de almacenamiento embebido, donde un borrado escribe una lápida (tombstone).