kolo docsbeta

kolo-store

Armazenamento persistente para logs do Kolo e réplicas somente leitura em uma máquina.

Nesta página

A kolo-store guarda logs da kolo-log em disco e os traz de volta depois de uma reinicialização, verificando de novo cada assinatura, hash e raiz Merkle. Ela mantém uma réplica de log como um monitor de Certificate Transparency (RFC 9162, seção 8.2) mantém um log, e apaga destruindo chaves, o apagamento criptográfico (cryptographic erase) do NIST SP 800-88 Rev. 1. Ela é o kololog.Storage do log: um log aberto mantém na memória só os hashes da sua árvore e os seus registros, e lê as entradas do disco. Um store guarda vários logs, um por ID de log: os seus e réplicas somente leitura dos logs de outras pessoas. Ele guarda dados em uma máquina e não fala com a rede.

Instalação

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

O Pebble faz link com a biblioteca C zstd quando o cgo está ativado. Compile com CGO_ENABLED=0 para ter um binário em Go puro.

Início rápido

Crie um log, feche o store, abra o diretório de novo e leia a entrada de volta.

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)
	}
}

O programa imprime 1 hello. Store.Close também fecha todos os logs abertos do store. Em um programa real, guarde me com Save e Load da kolo-id: só a identidade que criou um log consegue abri-lo de novo.

Referência da API

A referência da API é gerada a partir do código Go e está em inglês.

Pacote 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
)

Variáveis

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.

Bom saber

A kolo-store responde a uma entrada ausente com um erro que envolve kololog.ErrOutOfRange junto com ErrCorrupt, como a kolo-log exige de um Storage. A kolo-store grava cada chave de uma kololog.Change (Change.Keys) no lote da mudança. Create e OpenReplica de uma réplica nova retornam o erro do backend quando a leitura que verifica que o log novo não tem entradas falha, em vez de seguir como se ele estivesse vazio. Ler uma entrada que o log tem mas que o backend perdeu retorna ErrCorrupt envolvendo kololog.ErrStorageMismatch, nunca ErrOutOfRange.

Depois de uma reinicialização, List retorna os IDs dos logs e das réplicas guardados, e Owner informa, para cada um, a chave do dono e se é uma réplica. Assim você sabe se deve chamar Open ou OpenReplica. Open recusa uma réplica guardada com ErrReplica, e OpenReplica recusa um dos seus próprios logs com ErrNotReplica.

Log e Replica são seguros para uso concorrente. Um Log é a única forma de gravar em um log guardado. Uma Replica só cresce por Update e não tem Append nem Delete por índice. Open e OpenReplica leem as entradas e as chaves guardadas em uma única varredura cada, e a kolo-log verifica cada entrada enquanto a lê, sem guardar nenhuma. Depois disso, cada leitura busca a entrada no disco e a verifica de novo contra o seu registro.

Log.Delete(indexes...) e Replica.ApplyDelete(markers...) excluem ou aplicam várias entradas de uma vez em um único lote, tudo ou nada; um marcador inválido faz com que nenhum seja aplicado. Key e EntryInfo retornam a chave de uma entrada, e se ela está excluída ou tem chave, sem ler o seu texto cifrado.

Uma réplica muito atrasada pode se atualizar em etapas. Replica.Update aceita entradas que param antes do head e guarda, a cada etapa, o alvo pendente e a sua prova, então cada etapa é um único lote limitado. OpenReplica verifica de novo um alvo guardado reproduzindo-o com Update, então uma reinicialização no meio de uma atualização continua de onde parou, e Target retorna o head que está sendo preenchido e a sua prova. AddKey guarda uma chave que chega depois da sua entrada, verificada contra o compromisso do registro, em uma única gravação. Replica.AddKeys(start, keys) entrega as chaves de muitas entradas de uma vez, no máximo kololog.MaxAddKeys (32.768) por chamada, e guarda em um único lote cada chave que passa; as recusadas voltam em um *kololog.BadKeyError, e uma gravação que falha não guarda nenhuma. Log.Entry e Replica.Entry retornam a forma guardada de uma entrada com a sua chave, para uma camada de sincronização; limpe Key quando terminar de usá-la.

Store.Adopt(id, rep, opts...) serve para um dispositivo cujo log próprio está atrasado em relação à cópia que outros têm: traga para uma réplica as entradas que faltam, com as suas chaves, adote-a, e o log passa a anexar a partir do tamanho da réplica. Ele leva o log próprio fechado de id ao nível da réplica rep dele, que pode estar em qualquer store, em um único lote, e abre o resultado como Open. O lote adiciona só as entradas depois do head guardado, com as suas chaves, e o head da réplica, então uma queda do processo deixa o log antigo ou o novo, nunca uma mistura. As exclusões são mantidas dos dois lados: uma entrada que a réplica excluiu é guardada com o seu marcador e sem a sua chave, e uma entrada que o store excluiu continua excluída mesmo que a réplica ainda a tenha, então uma exclusão guardada nunca é desfeita. Antes do lote, Adopt lê as chaves guardadas, sem o texto cifrado, e verifica o marcador de cada entrada que só o store excluiu. Ele não repara as entradas guardadas que mantém: outros danos nelas fazem a abertura final falhar, como fazem Open falhar. Um erro da abertura final, como kololog.ErrEncodingMismatch por opts ausentes, deixa o log adotado guardado, e Open o abre.

Adopt recusa:

  • uma réplica de outro dono, ou cujo header não é o guardado (kololog.ErrBadLogHeader);
  • um ID de log que o store não guarda (kololog.ErrMissingHeader), ou uma réplica guardada no lugar de um log próprio (ErrReplica);
  • um log aberto neste processo (ErrLogInUse);
  • uma réplica sem head ou com uma atualização inacabada (ErrIncomplete);
  • uma entrada viva depois do head guardado sem a sua chave (kololog.ErrKeyUnavailable);
  • uma réplica da qual o log guardado não é prefixo, mais curta ou bifurcada (kololog.ErrRollback);
  • uma entrada guardada que ele mantém e que não tem nem chave nem um marcador de exclusão válido (ErrCorrupt);
  • um lote de 2 GiB ou mais, 1 GiB em 32 bits (ErrTooLarge). Nada é gravado.

O lote retém as entradas que adiciona, e o Pebble retém uma segunda cópia enquanto confirma, então Adopt é a única chamada cuja memória cresce com o tamanho do que ela processa: adotar 256 MiB de entradas chegou a um heap máximo de 560 MB, 2,1 vezes o tamanho delas. Ele conta o seu lote como o Pebble conta, e o seu limite de 2 GiB é metade do limite de lote do Pebble, então as duas cópias cabem nele.

Limites

  • Memória: um log ou uma réplica aberta ocupa cerca de 250 bytes por entrada, seja qual for o tamanho das entradas, e uma leitura, um Append ou um Update só retém as entradas que processa. Adopt é a exceção: ele retém as entradas que adiciona cerca de duas vezes, e recusa um lote de 2 GiB ou mais (1 GiB em 32 bits) com ErrTooLarge.
  • Um lote do Pebble de 4 GiB - 1 bytes ou mais (2 GiB - 1 em 32 bits) retorna ErrTooLarge em vez de causar um pânico dentro do Pebble. Nada é gravado.
  • Um store guarda um log por ID de log, seja quem for o dono. Open ou OpenReplica de um ID que o store guarda para outro dono retorna kololog.ErrBadLogHeader e não muda nada; uma réplica do log de outro dono com o mesmo ID precisa de outro store.
  • OpenPebble cria o diretório do store com modo 0700 e retorna ErrInsecureDir para um diretório que o grupo ou outros possam acessar, que pertença a outro usuário ou que seja trocado durante a abertura.
  • OpenPebble deixa em modo 0600 todos os arquivos que o Pebble cria no diretório, e muda para 0600 os de um diretório que já existia, porque eles guardam as chaves das entradas. OpenPebbleWith(dir, PebbleOptions{MemTableSize, NoCompression}) é o OpenPebble para valores grandes, como fragmentos de 1 MiB: MemTableSize (0 para os 4 MiB do Pebble, ou de 1 MiB a 1 GiB, senão ErrInvalidOptions) faz o Pebble descarregar e compactar com menos frequência e custa até o dobro desse tamanho em memória, e NoCompression evita comprimir blocos, trabalho inútil sobre texto cifrado. Cada commit continua sincronizado. Em um Mac, gravar 1 GiB em valores de 1 MiB levou 14,9 s com os padrões e 7,4 s com 256 MiB e sem compressão.
  • Open e OpenReplica levam tempo, e fazem E/S, linear no tamanho do log: leem cada entrada guardada uma vez, então um log grande abre devagar. Depois ficam uns 250 bytes de memória por entrada.
  • Um ID de log só pode ser aberto uma vez por backend em um processo; uma segunda abertura retorna ErrLogInUse. Um segundo OpenPebble no mesmo diretório falha, mesmo por outro caminho, então outro processo não consegue gravar os mesmos logs.
  • Store.Delete retorna ErrLogInUse para um log aberto em qualquer lugar do processo. Excluir uma réplica também retorna esse erro enquanto o log gravável do dono com esse ID estiver aberto no mesmo processo.
  • Uma entrada guardada cujo registro ou marcador de exclusão passa de 1024 bytes, cuja chave existe mas não tem 32 bytes, ou que foi excluída e ainda tem chave, é recusada com ErrCorrupt. O alvo de atualização guardado de uma réplica também tem limite: o head com até 1024 bytes e a prova com até 65 hashes.
  • Os valores de entrada guardados são da versão 3, e a chave de cada entrada viva é guardada à parte, ao lado deles. As versões 1 e 2, que guardavam a chave dentro do valor da entrada, são recusadas.

Segurança

  • A chave de cada entrada é guardada em claro ao lado do seu texto cifrado, porque o store confia no disco do próprio nó.
  • Open e OpenReplica verificam tudo de novo com a kolo-log, usando a chave que você passa. Owner verifica a chave do dono guardada só contra a assinatura do próprio cabeçalho.
  • Passe kololog.WithTrustedHead com o último head que você publicou, para que um snapshot guardado mais antigo retorne kololog.ErrRollback. Essa é a âncora contra um rollback do disco.
  • O byte que marca o tipo réplica não é assinado: uma gravação no disco que marca uma réplica que cresceu como log próprio faz Open aceitá-la com a identidade do dono.
  • OpenReplica nunca precisa de uma chave privada, e um Update recusado não muda nada na memória nem no disco.

Limites conhecidos

  • Experimental. A API pode mudar antes da v1.0.0.
  • As permissões e o dono do diretório do store não são verificados no Windows.
  • O diretório só é verificado quando é aberto. Mudar para onde o caminho aponta depois disso exige acesso de escrita a um diretório pai, e o store não se defende contra isso.
  • NewMemory mantém tudo na memória, para testes e stores de vida curta.
  • Um Backend próprio deve ser um tipo comparável, como um ponteiro, para que os stores sobre ele compartilhem os seus logs abertos.

Erros

ErroMensagem
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

Teste os erros com errors.Is. Dados guardados danificados sempre envolvem ErrCorrupt, no Open ou em uma leitura posterior: chaves que faltam ou sobram, dados que não decodificam ou não batem com o seu cabeçalho assinado, os seus heads, os seus registros e os seus marcadores de exclusão, ou uma entrada viva de um log seu que perdeu a chave. O erro também envolve o erro da kolo-log que o encontrou, então errors.Is acha os dois: kololog.ErrRestoreMismatch no Open, kololog.ErrStorageMismatch para uma mudança no disco depois do Open ou uma entrada que o backend perdeu, ou kololog.ErrInvalidHead de dados guardados. Os outros erros da kolo-log passam adiante envolvidos, sem ErrCorrupt, como kololog.ErrMissingHeader, kololog.ErrBadLogHeader, kololog.ErrRollback, kololog.ErrDiverged, kololog.ErrBadProof ou kololog.ErrBadEntry. Uma gravação que falha retorna o erro do backend. ErrIncomplete significa que Adopt recebeu uma réplica sem head ou com uma atualização inacabada, e ErrTooLarge, uma gravação grande demais para um lote: um lote de Adopt de 2 GiB ou mais, ou um lote do Pebble de 4 GiB - 1 bytes ou mais (1 GiB e 2 GiB - 1 em 32 bits).

Referências

  • RFC 9162, Certificate Transparency Version 2.0 (Experimental, December 2021).
    • Usa: a seção 8.2, o monitor que guarda todas as entradas, que uma réplica guardada segue.
    • Não implementa: os timestamps nos heads, então os heads são ordenados só pelo tamanho.
  • NIST SP 800-88 Rev. 1 (December 2014), section 2.6, Cryptographic Erase.
    • Usa: apagar destruindo uma chave.
    • Não implementa: o encapsulamento da chave por uma chave mestra (key wrapping); a chave fica em claro ao lado do texto cifrado, porque o store confia no disco do próprio nó.
  • Reardon, Basin and Capkun, SoK: Secure Data Deletion, IEEE S&P 2013.
    • Usa: por que um motor com estrutura de log guarda bytes antigos até compactar.
  • O'Neil et al., The Log-Structured Merge-Tree, Acta Informatica 1996.
    • Usa: o modelo de armazenamento do motor de armazenamento embutido, em que uma exclusão grava uma lápide (tombstone).