kolo docsbeta

kolo-sync

Copia un log firmado de kolo-log de un peer a otro, solo mediante pull, o trae algunas de sus entradas sin réplica.

En esta página

kolo-sync mantiene al día una réplica del log de kolo-log de otra persona desde cualquier peer que tenga una copia, con el modelo de traer y verificar de Certificate Transparency 2.0 (RFC 9162): heads, pruebas de consistencia y pruebas de inclusión, comprobados solo con las firmas del propietario. Un Server ofrece los logs que elige la aplicación y le pregunta qué peer puede hacer pull de qué log. Pull abre un stream por log sobre una conexión, comprueba el head firmado del peer, trae las entradas que faltan con pruebas de consistencia y hace crecer una réplica de kolo-store, que verifica cada entrada antes de guardarla. Las marcas de borrado también llegan, igual que las claves de las entradas para los peers que pueden leerlas. Fetch trae un rango de entradas por separado, cada una comprobada con su prueba de inclusión frente a un head firmado, para leer parte de un log sin guardarlo. Usa una conexión que ya tienes y nunca busca peers ni se conecta a ellos. Funciona sobre conexiones directas y a través de un relay: cada llamada recibe un Conn, que cumplen tanto una conexión de kolo-secure como un enlace con un peer de kolo-swarm, directo o a través de un relay. Consulta Réplicas.

Todos los pasos

Un pull entre dos peers

Quien hace el pull pide y comprueba; el servidor solo responde. Nada se guarda hasta que está verificado.

  1. Quien hace el pull abre un stream en su conexión kolo-secure y envía HEAD_REQ con la clave del propietario y el ID del log.
  2. El servidor pregunta a su función authorize por este peer y este log. Un log que no ofrece y un peer sin acceso reciben el mismo error de no encontrado. Si no, responde HEAD: el head firmado y la cabecera del log.
  3. Quien hace el pull comprueba la firma del head. Si ya tiene un head anterior, PROOF_REQ pide una prueba de consistencia de que el nuevo lo amplía.
  4. ENTRIES_REQ pide el rango que falta. Cada respuesta ocupa como mucho 4 MiB, y Replica.Update comprueba cada registro y cada prueba antes de guardar nada.
  5. STATE_REQ pide las marcas de borrado y las claves. Quien hace el pull comprueba y aplica las marcas, y luego añade las claves.
  6. Quien hace el pull cierra el stream. El servidor nunca escribe en quien hace el pull: kolo-sync es solo pull.

Instalación

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

Compila sin cgo.

Inicio rápido

Alice escribe un log de dos entradas y se lo ofrece solo a bob. Bob se conecta por loopback, trae la cabecera firmada del log, abre una réplica y hace pull. Después trae una entrada sin réplica, comprobada frente al head firmado de alice.

main.go
package main

import (
	"context"
	"crypto/ed25519"
	"fmt"
	"log"
	"time"

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	alice, err := koloid.Generate()
	check(err)
	bob, err := koloid.Generate()
	check(err)

	// Alice writes a log and offers it, with its entry keys, to bob only.
	as := kolostore.New(kolostore.NewMemory())
	defer as.Close()
	l, err := as.Create(alice)
	check(err)
	_, err = l.Append([]byte("hello from alice"))
	check(err)
	_, err = l.Append([]byte("second entry"))
	check(err)
	srv := kolosync.NewServer(func(peer, _ ed25519.PublicKey, _ kololog.LogID) kolosync.Access {
		if peer.Equal(bob.PublicKey()) {
			return kolosync.Keys
		}
		return kolosync.NoAccess
	})
	check(srv.Offer(l))
	ln, err := kolosecure.Listen(ctx, "127.0.0.1:0", alice, nil)
	check(err)
	defer ln.Close()
	go func() {
		conn, err := ln.Accept(ctx)
		if err != nil {
			return
		}
		srv.Serve(ctx, conn)
	}()

	// Bob knows alice's key and the log ID, and keeps a replica in his own store.
	conn, err := kolosecure.Dial(ctx, ln.Addr().String(), bob, alice.PublicKey(), nil)
	check(err)
	defer conn.Close()
	bs := kolostore.New(kolostore.NewMemory())
	defer bs.Close()
	header, err := kolosync.FetchHeader(ctx, conn, alice.PublicKey(), l.ID())
	check(err)
	rep, err := bs.OpenReplica(alice.PublicKey(), l.ID(), header)
	check(err)
	check(kolosync.Pull(ctx, conn, rep))
	v, err := rep.Get(0)
	check(err)
	fmt.Printf("bob read %q from %d entries\n", v, rep.Len())

	// Without a replica, bob checks one entry against alice's signed head.
	h, err := kolosync.FetchHead(ctx, conn, alice.PublicKey(), l.ID())
	check(err)
	got, err := kolosync.Fetch(ctx, conn, h, 1, 1)
	check(err)
	fmt.Printf("bob fetched %q at index %d\n", got[0].Data, got[0].Index)
}

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

Imprime:

Texto
bob read "hello from alice" from 2 entries
bob fetched "second entry" at index 1

Una aplicación real guarda sus almacenes en disco con kolostore.OpenPebble.

Referencia de la API

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

Paquete kolosync · github.com/ciranda-dev/kolo-sync · v0.1.0

Package kolosync replicates kolo-log logs between two peers, pull only, over any authenticated Conn: a kolo-secure connection or a kolo-swarm link, direct or relayed.

A Server offers logs, and authorizes each peer per log. Pull opens one stream per log, verifies the peer's signed head, fetches the missing range with consistency proofs, and grows a kolo-store Replica, which verifies every entry before it stores it. Delete markers and, for authorized peers, entry keys follow. Fetch gets a range of entries without a replica, each checked with its inclusion proof against a head the client trusts; FetchWithKeys opens them with keys the client holds, which FetchKeys gets from a peer with Keys access, so a client can read from a peer that holds ciphertext only. Many logs share one connection.

Experimental: the API may change before v1.0.0.

Constantes

const (
	// DefaultInFlight is PullOptions.InFlight when it is 0.
	DefaultInFlight = 3
	// MaxInFlight is the largest PullOptions.InFlight.
	MaxInFlight = 8
)
const (
	// DefaultMaxTotalStreams is the default ServerOptions.MaxTotalStreams: 16 connections each serving MaxStreams streams.
	DefaultMaxTotalStreams = 16 * MaxStreams
	// DefaultMaxAnswerBytes is the default ServerOptions.MaxAnswerBytes, a quarter of kolo-transport's DefaultMaxMemory (1 GiB),
	// which leaves the rest of that budget to the connections themselves.
	DefaultMaxAnswerBytes = 256 << 20
)
const (
	// MaxMessageSize is the largest message, length prefix excluded, that a peer sends or accepts.
	MaxMessageSize = 4 << 20
	// MaxStreams is how many streams Serve handles at once per connection; more are answered busy.
	MaxStreams = 16
	// Timeout bounds opening a stream, the wait for the next request, and the start of each message read or write.
	// A message of n bytes may then take another n at MinRate, so a slow but moving 4 MiB answer is not cut off.
	Timeout = 60 * time.Second
	// MinRate is the slowest average speed, in bytes a second, at which a message may be read or written.
	MinRate = 16 << 10
)

Variables

var (
	// ErrInvalidArgument means a nil connection, replica, source or key, a key of the wrong size, a zero head,
	// a Fetch, FetchWithKeys or FetchKeys range that is empty or past the head (wrapping kololog.ErrOutOfRange),
	// or a PullOptions.KeysFrom past the replica's length.
	ErrInvalidArgument = errors.New("kolosync: invalid argument")
	// ErrNotFound means the peer does not serve the log to us: it does not have it, did not offer it, or did not authorize us.
	ErrNotFound = errors.New("kolosync: log not found")
	// ErrDiverged means the owner signed two histories: the peer's signed head or record conflicts with ours or with the head
	// Fetch, FetchWithKeys or FetchKeys checks against. Neither log was changed.
	ErrDiverged = errors.New("kolosync: logs diverged")
	// ErrInvalid means the peer sent a head, proof, entry, marker or key that does not verify; a kolo-log error is wrapped too.
	ErrInvalid = errors.New("kolosync: peer sent data that does not verify")
	// ErrProtocol means a malformed, truncated or unexpected message, or another protocol version.
	ErrProtocol = errors.New("kolosync: protocol error")
	// ErrTooLarge means a message over MaxMessageSize, or an entry too large to fit in one.
	ErrTooLarge = errors.New("kolosync: message too large")
	// ErrBehind means the peer's head has fewer entries than the head Fetch, FetchWithKeys or FetchKeys checks against,
	// or, for PullWith with NoMarkers, than the head the replica is filling toward (after ErrMarked); no entry or key is added.
	ErrBehind = errors.New("kolosync: peer is behind the head")
	// ErrKeyMismatch, in Fetched.Err, means a key given to FetchWithKeys does not match its entry's record.
	ErrKeyMismatch = errors.New("kolosync: held key does not match its record")
	// ErrBusy means the peer refused the stream or an answer (MaxStreams, ServerOptions) or could not read its log, or another Pull of the replica is running.
	ErrBusy = errors.New("kolosync: peer busy")
	// ErrMarked means the peer serves a deleted entry to a PullWith with NoMarkers; the replica then holds
	// only the entries before it, so its Len is that entry's index.
	ErrMarked = errors.New("kolosync: peer serves a deleted entry")
	// ErrTimeout means a message read or write took longer than Timeout.
	ErrTimeout = errors.New("kolosync: timeout")
)

Funciones

func FetchHead

func FetchHead(ctx context.Context, conn Conn, owner ed25519.PublicKey, logID kololog.LogID) (kololog.VerifiedHead, error)

FetchHead returns the signed head of the log logID that the peer on conn serves, verified against owner.

func FetchHeader

func FetchHeader(ctx context.Context, conn Conn, owner ed25519.PublicKey, logID kololog.LogID) ([]byte, error)

FetchHeader returns the signed header of the log logID that the peer on conn serves, checked against owner, for opening a new replica with kolostore.Store.OpenReplica.

func FetchKeys

func FetchKeys(ctx context.Context, conn Conn, h kololog.VerifiedHead, start, end uint64) ([]kololog.EntryKey, error)

FetchKeys gets the entry keys of the entries start to end, end included, from a peer with Keys access, without their ciphertexts; element i is the key of entry start+i, or nil where the peer gave none.

func Pull

func Pull(ctx context.Context, conn Conn, rep *kolostore.Replica) error

Pull brings rep up to date with the copy of its log that the peer on conn serves, then applies the peer's delete markers and, if the peer gives them, the keys rep lacks; a key other than one rep holds is ErrInvalid. Only rep's Update, ApplyDelete and AddKey store anything, and each verifies first. A second Pull of the same replica while one runs returns ErrBusy; pulls of different replicas may run at once on one connection.

func PullCiphertext

func PullCiphertext(ctx context.Context, conn Conn, rep *kolostore.Replica) error

PullCiphertext is Pull for a peer that must never hold entry keys: it never asks for them, never calls AddKey, and an answer that carries a key anyway is ErrProtocol, with nothing from it stored.

Tipos

type Access

type Access int

Access is what a peer may pull from one offered log.

const (
	// NoAccess gives the peer the same answer as a log we do not have.
	NoAccess Access = iota
	// Ciphertext gives records, proofs, ciphertexts and delete markers, but no entry keys.
	Ciphertext
	// Keys gives everything Ciphertext gives, and the entry keys.
	Keys
)

type Conn

type Conn interface {
	RemotePublicKey() ed25519.PublicKey
	OpenStream(ctx context.Context) (*kolotransport.Stream, error)
	AcceptStream(ctx context.Context) (*kolotransport.Stream, error)
}

Conn is an authenticated connection to one peer, direct or relayed, such as a *kolosecure.Conn or a koloswarm.Conn; RemotePublicKey must return the key the peer proved in the end-to-end handshake.

type Fetched

type Fetched struct {
	Index uint64
	Data  []byte // the entry's value, as kololog.Log.Get returns it; nil when Err is set
	// Err is kololog.ErrDeleted, kololog.ErrKeyUnavailable, ErrKeyMismatch or nil (see the README).
	Err error
}

Fetched is one entry that Fetch got from the peer and verified.

func Fetch
func Fetch(ctx context.Context, conn Conn, h kololog.VerifiedHead, start, end uint64) ([]Fetched, error)

Fetch gets the entries start to end, end included, of the log of h from the peer on conn, without a replica. Each entry is checked with its inclusion proof in the tree of h's size, so the peer must hold h's entries: a peer with a smaller head is ErrBehind, one with another root at h's size ErrDiverged.

func FetchWithKeys
func FetchWithKeys(ctx context.Context, conn Conn, h kololog.VerifiedHead, start, end uint64,
	keys func(index uint64) (kololog.EntryKey, error)) ([]Fetched, error)

FetchWithKeys is Fetch for a caller that holds entry keys, such as one reading from a peer that serves ciphertext only; keys returns a copy of the key held for an entry that came without one (see the README). keys is asked after the stream is closed, so its use shows only in how long FetchWithKeys takes to return.

type PullMeter

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

PullMeter collects the statistics of a pull while it runs. Its zero value is ready to use: pass it in PullOptions.Meter and call Stats from any goroutine. A meter measures one pull at a time: starting a pull with a meter another pull is using is ErrInvalidArgument, and one that starts after the last has ended resets it.

func (PullMeter) Stats
func (m *PullMeter) Stats() PullStats

Stats returns the statistics so far, or the whole pull's once it has ended; it is safe to call at any time.

type PullOptions

type PullOptions struct {
	// NoMarkers makes the pull neither request nor store delete markers: a chunk is stored only up
	// to its first deleted entry (ErrMarked), and STATE markers are ignored.
	NoMarkers bool
	// KeysFrom is the first index the caller may hold without its key; the pull scans and asks for
	// keys only from there.
	KeysFrom uint64
	// InFlight is the most requests for entries the pull has waiting at once, 1 to MaxInFlight. A peer that streams is
	// sent credit in requests of 2 MiB and keeps from 2 up to InFlight of them waiting, as many as twice the measured
	// round trip times the speed asks for; 0 is MaxInFlight, and 1 asks again only when the credit is used up.
	// For a peer that does not stream, such as v0.1.7, it is how many answers are asked for before the first is
	// stored: 0 is DefaultInFlight, and 1 asks for each after the one before is stored. The pull holds at most 6 MiB
	// of answers not yet stored whatever it is.
	InFlight int
	// Meter, if not nil, collects the statistics of the pull while it runs; see PullMeter.
	Meter *PullMeter
}

PullOptions changes how PullWith pulls; the zero value pulls as Pull does.

type PullResult

type PullResult struct {
	// KeysFrom is the first index still held without its key after the pull.
	KeysFrom uint64
	// Stats is how the pull went, also when it failed.
	Stats PullStats
}

PullResult is what PullWith reports.

func PullWith
func PullWith(ctx context.Context, conn Conn, rep *kolostore.Replica, opts *PullOptions) (PullResult, error)

PullWith is Pull with opts (nil for none). On an error the result's KeysFrom is opts.KeysFrom, and a KeysFrom past rep.Len() is ErrInvalidArgument.

type PullStats

type PullStats struct {
	// Streamed is true when the peer served the entries as a stream (STREAM_REQ) and false when the pull asked for them one
	// answer at a time, as for a peer that predates streaming.
	Streamed bool
	// Elapsed is the time since the pull started, or its whole length once it has ended.
	Elapsed time.Duration
	// Bytes, Entries and Answers count the ENTRIES answers read: their message bytes, entries and messages.
	Bytes   uint64
	Entries uint64
	Answers uint64
	// Requests counts the requests for entries sent: ENTRIES_REQ, or STREAM_REQ and CREDIT_REQ.
	Requests uint64
	// ReaderWait is the time the reader spent waiting for the bytes of answers, not counting waits for memory.
	ReaderWait time.Duration
	// CommitBusy is the time the goroutine that stores the answers spent verifying and storing them, and CommitIdle the
	// time it spent waiting for an answer.
	CommitBusy time.Duration
	CommitIdle time.Duration
	// FirstByteMin, FirstByteAvg and FirstByteMax are the time from writing the request for entries to reading the
	// first bytes of its answer. A request sent while others wait includes the time of the answers before it; a streamed
	// pull has one sample for each fill: its STREAM_REQ.
	FirstByteMin time.Duration
	FirstByteAvg time.Duration
	FirstByteMax time.Duration
	// InFlightMax and InFlightAvg are the most requests for entries asked for and not yet answered, and their average over
	// time. For a streamed pull a request is 2 MiB of credit.
	InFlightMax int
	InFlightAvg float64
	// InFlightBlocked counts the times the limit on requests in flight, PullOptions.InFlight, held a request back.
	InFlightBlocked uint64
	// MemoryBlocked counts the times the reader had to wait for room under the 6 MiB of answers a pull holds, and
	// MemoryWait is the time it waited. HeldMax is the most bytes of answers held at once.
	MemoryBlocked uint64
	MemoryWait    time.Duration
	HeldMax       int
}

PullStats says where the time of a pull went and how full it kept the link. All durations are wall time.

func (PullStats) AvgAnswer
func (s PullStats) AvgAnswer() uint64

AvgAnswer returns the average size in bytes of an ENTRIES answer, 0 if none was read.

type Server

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

Server serves the logs the application offers to the peers it authorizes; it is safe for concurrent use. A log is named by its owner's key and its log ID, so two owners' logs with one ID are two logs.

func NewServer
func NewServer(authorize func(peer, owner ed25519.PublicKey, logID kololog.LogID) Access) *Server

NewServer returns a Server with no offered logs. authorize is asked on every request, for any owner and log ID; nil, a panic or any other value than Ciphertext or Keys means NoAccess.

func NewServerWith
func NewServerWith(authorize func(peer, owner ed25519.PublicKey, logID kololog.LogID) Access, opts *ServerOptions) (*Server, error)

NewServerWith is NewServer with the server-wide limits of opts; nil is all defaults. A negative limit, or a MaxAnswerBytes below 2 * MaxMessageSize, is ErrInvalidArgument.

func (Server) Offer
func (s *Server) Offer(src Source) error

Offer makes src available under its owner's key and log ID, replacing an earlier source with both the same. src's header must be signed by its owner and name src's log ID; past that, Offer trusts src to serve that log.

func (Server) Serve
func (s *Server) Serve(ctx context.Context, conn Conn) error

Serve answers the streams the peer opens on conn, for Pull, PullCiphertext, FetchHeader, FetchHead, Fetch, FetchWithKeys and FetchKeys, until ctx is done or conn ends, then waits for them. It must be the only caller of conn.AcceptStream.

func (Server) Stats
func (s *Server) Stats() ServerStats

Stats returns the server's totals; it is safe to call at any time.

func (Server) Withdraw
func (s *Server) Withdraw(owner ed25519.PublicKey, logID kololog.LogID)

Withdraw stops offering the log logID of owner; requests for it then get the answer of a missing log.

type ServerOptions

type ServerOptions struct {
	// MaxTotalStreams is the most streams served at once over all connections.
	MaxTotalStreams int
	// MaxAnswerBytes is the most memory the answers being built or written may hold at once; each answer counts twice its
	// size, the entries read from the log and the frame sent. At least 2 * MaxMessageSize, so one largest answer always fits.
	MaxAnswerBytes int64
}

ServerOptions are the limits a Server applies over all the connections it serves, on top of MaxStreams for each. A zero field is its default. A stream or an answer over a limit is answered busy, which a Pull or Fetch returns as ErrBusy.

type ServerStats

type ServerStats struct {
	BytesSent      uint64 // frame bytes written, every answer included
	ActiveStreams  int    // streams being served now, refused ones not included
	RefusedByLimit uint64 // streams and answers refused because MaxTotalStreams or MaxAnswerBytes was reached
	AnswerBytes    int64  // memory the answers being built or written hold now, counted as MaxAnswerBytes counts it
}

ServerStats are a Server's totals over all its connections.

type Source

type Source interface {
	ID() kololog.LogID
	Header() kololog.LogHeader
	Head() (kololog.Head, error)
	Record(index uint64) (kololog.Record, error)
	Entry(index uint64) (kololog.Entry, error)
	EntryInfo(index uint64) (kololog.EntryInfo, error)
	Key(index uint64) (kololog.EntryKey, error)
	InclusionProof(index, size uint64) (kololog.InclusionProof, error)
	ConsistencyProof(oldSize, newSize uint64) (kololog.ConsistencyProof, error)
}

Source is a log a Server can offer: a kolo-store Log or Replica, or a kolo-log Log or Replica.

Conviene saber

Todos los pasos

Leer entradas sueltas

Fetch lee unas pocas entradas de cualquier peer sin copiar el log. Cada entrada se comprueba contra un head en el que ya confías.

  1. El lector tiene un head verificado de tamaño n, de FetchHead o de un pull anterior. Fetch comprueba el rango contra él antes de enviar nada.
  2. HEAD_REQ trae el head del peer. Un peer con un log más corto no puede probar estas entradas: Fetch devuelve ErrBehind, así que pregunta a otro peer.
  3. FETCH_REQ pide desde el inicio hasta el fin, en el árbol de tamaño n.
  4. FETCH responde cada entrada con su registro, su texto cifrado o su marca de borrado, su clave si el acceso lo permite y una prueba de inclusión en ese árbol.
  5. OpenEntry comprueba el registro y la prueba contra la raíz de confianza, y luego descifra. Una entrada borrada vuelve como ErrDeleted.

La confianza solo viene de las firmas del propietario, así que cualquier peer con una copia verificada puede servirla: un Source es un *Log o una *Replica de kolo-store o de kolo-log, y una réplica sirve el último head que tiene completo. Un Source propio necesita ID, Header, Head, Record, Entry, EntryInfo, Key, InclusionProof y ConsistencyProof. Offer identifica el log por src.Header().LogKey y src.ID() y sustituye una fuente anterior con los dos iguales. Rechaza una fuente cuya cabecera no esté firmada por esa clave o nombre otro ID de log (ErrInvalidArgument envolviendo kololog.ErrBadLogHeader). Después de Withdraw, las peticiones de ese log reciben la respuesta de un log que falta.

Pull lo comprueba todo frente a la clave del propietario que hay en la cabecera de la réplica y devuelve nil cuando el peer va por detrás o está igual. Un pull que se corta a medias deja a la réplica un objetivo, que kolo-store conserva; el siguiente pull lo rellena primero y devuelve nil si el head del peer está por debajo de él. Una clave en una respuesta STATE para una entrada que la réplica ya tiene con su clave debe ser esa clave, o el pull falla con ErrInvalid. Un pull sin nada nuevo no lee ningún texto cifrado en ninguno de los dos lados: los dos extremos usan los indicadores por entrada de kolo-log y solo leen las marcas de borrado y las claves que envían o aplican.

FetchHead devuelve el head firmado del peer, verificado frente a la clave del propietario y el ID de log, para un cliente que aún no tiene ningún head. Es el head que tiene ese peer, que puede ser más antiguo que el más reciente. Fetch(ctx, conn, h, start, end) trae las entradas de start a end, end incluida, frente al head h en el que confía el cliente. Cada Fetched tiene Index, Data y Err: nil, kololog.ErrDeleted para una entrada con una marca de borrado verificada, o kololog.ErrKeyUnavailable cuando el peer no envió la clave. Cualquier otro fallo hace fallar toda la llamada y no devuelve ninguna entrada. Un peer cuyo head es menor que h da ErrBehind; pregunta a otro peer. Fetch guarda los valores del rango que pediste, así que su memoria es ese rango, como mucho un mensaje más.

Conexiones directas y a través de un relay

Cada llamada recibe un Conn: RemotePublicKey, OpenStream y AcceptStream, los únicos métodos que usa kolo-sync. Un *kolosecure.Conn y un koloswarm.Conn lo cumplen, así que kolo-sync funciona sobre conexiones directas y a través de un relay, y una conexión a través de un relay lleva la sincronización exactamente igual que una directa. RemotePublicKey debe devolver la clave que el peer demostró en el handshake de extremo a extremo. Un enlace a través de un relay la demuestra de la misma forma, así que authorize recibe la misma clave que en un enlace directo. Las comprobaciones de la clave del peer y el formato de red no cambian.

Un Conn nil, o uno que contiene un puntero nil, como un *kolosecure.Conn nil, es ErrInvalidArgument. Serve rechaza con ErrInvalidArgument un Conn cuyo RemotePublicKey no tiene 32 bytes, antes de aceptar ningún stream.

Pull sin marcas de borrado

PullWith(ctx, conn, rep, opts) es Pull con un *PullOptions y devuelve un PullResult. Con nil o el valor cero hace el pull y envía exactamente los mensajes que envía Pull. PullOptions tiene cuatro campos; NoMarkers y KeysFrom se describen aquí, InFlight más abajo y Meter en Estadísticas del pull.

  • NoMarkers: el pull ni pide ni guarda marcas de borrado, así que un peer que borró entradas, o dice haberlo hecho, no puede borrarlas de la réplica. Una respuesta ENTRIES se comprueba antes de guardar nada: en su primera entrada que lleva una marca, solo las entradas anteriores pasan a Replica.Update, con una petición PROOF más para ese prefijo más corto, de modo que la réplica sigue verificada, y el pull devuelve ErrMarked con el nombre de ese índice. rep.Len() es entonces ese índice, y la réplica se llena hacia el head de ese peer: haz pull del resto desde un peer cuyo head sea al menos igual de grande. Un peer por detrás de ese head no añade nada y devuelve ErrBehind (Pull devuelve nil en ese caso). La marca nunca se decodifica ni se comprueba, así que una falsificada detiene el pull de la misma manera. Las marcas de STATE se ignoran, también las incorrectas o fuera de lugar, y ninguna petición STATE pide solo marcas; las claves de las respuestas STATE se comprueban y se añaden como en Pull. Una marca que la réplica ya tiene se queda.
  • KeysFrom: el primer índice que quien llama puede tener sin su clave. El recorrido local en busca de claves que faltan y las peticiones STATE de claves empiezan ahí. Con NoMarkers, un pull cuesta entonces las entradas nuevas y las que siguen sin clave, no todo el log; sin él, las marcas de borrado se siguen pidiendo desde el índice 0. Un valor mayor que rep.Len() es ErrInvalidArgument.

PullResult.KeysFrom es el primer índice que sigue sin clave tras el pull (las entradas borradas se saltan), o rep.Len() cuando todas las entradas tienen su clave: guárdalo con la réplica y pásalo al siguiente pull. Si hay un error, vale opts.KeysFrom, así que el cursor nunca se salta una entrada. El formato de red no cambia.

Un pull que prueba con el siguiente peer cuando uno sirve una entrada borrada o va por detrás del head hacia el que se llena la réplica:

Go
func pullLive(ctx context.Context, peers []*kolosecure.Conn, rep *kolostore.Replica, keysFrom uint64) (uint64, error) {
	err := kolosync.ErrNotFound
	for _, conn := range peers {
		var res kolosync.PullResult
		res, err = kolosync.PullWith(ctx, conn, rep, &kolosync.PullOptions{NoMarkers: true, KeysFrom: keysFrom})
		if err == nil {
			return res.KeysFrom, nil
		}
		if !errors.Is(err, kolosync.ErrMarked) && !errors.Is(err, kolosync.ErrBehind) {
			return keysFrom, err
		}
		// rep holds the entries before the deleted one; the next peer goes on from rep.Len().
	}
	return keysFrom, err
}

Respuestas en vuelo

Un pull pide las entradas en respuestas de aproximadamente 1 MiB. Pedir una respuesta cada vez envía la siguiente petición solo cuando llegan los primeros bytes de la respuesta anterior, así que mueve más o menos una respuesta, 1 MiB, por cada tiempo de ida y vuelta, sea cual sea la capacidad del enlace: 10 MB/s a 100 ms. Un pull a un peer de esta versión pide las entradas una sola vez y mantiene el enlace lleno. Su primera petición de entradas, STREAM_REQ, indica dónde empezar y da crédito en bytes; el peer envía entonces cada respuesta, seguida de la prueba de dónde termina, sin esperar otra petición, mientras dure el crédito, y el pull envía más crédito (CREDIT_REQ) antes de que se agote. Una goroutine lee el stream, y la goroutine de quien llama verifica y guarda las respuestas en orden con Replica.Update, así que la réplica solo crece con respuestas verificadas, en orden.

  • Con un peer que hace streaming, InFlight limita las peticiones de crédito, de 2 MiB cada una, que esperan en el peer: de 1 a MaxInFlight (8), y 0 es MaxInFlight; cualquier otro valor es ErrInvalidArgument. El pull mantiene 2 en espera y más a medida que mide el tiempo de ida y vuelta y la velocidad a la que lee (el doble del producto ancho de banda por retardo, en peticiones), hasta InFlight, así que como mucho hay 16 MiB de respuestas en camino. Con 1 el pull vuelve a pedir solo cuando se agota el crédito anterior.
  • Un peer que no hace streaming responde a STREAM_REQ con un error y cierra el stream. El pull abre entonces otro stream y pide una petición y una prueba por respuesta, hasta InFlight peticiones por delante (0 es DefaultInFlight, 3), a costa de dos tiempos de ida y vuelta en cada pull que tiene entradas que traer. Un servidor solo hace streaming cuando se le pide, así que también sirve un pull que no hace streaming.
  • Las respuestas que ya esperan cuando se guarda una van al mismo Update, un commit y una sincronización del almacén, hasta 4 MiB de respuestas; si falla, se guardan de una en una, así que las entradas guardadas antes de una respuesta mala, y el error, son los mismos que cuando cada una se guarda sola.
  • Un fallo, una respuesta hostil o una cancelación dejan la réplica como estaba tras la última respuesta guardada entera, y rep.Len() es donde reanuda el siguiente Pull. Un peer que deja de enviar a mitad del crédito da ErrTimeout.
  • Un pull retiene como mucho 6 MiB de respuestas aún sin guardar, sea cual sea InFlight. El crédito en espera son las respuestas del peer en la red y en las ventanas del transporte, no en la memoria del pull.

La ventana que kolo-transport da a un stream sigue limitando un stream a su ventana por tiempo de ida y vuelta, así que un pull alcanza lo menor entre eso y el enlace: una ventana de stream de 4 MiB son unos 40 MB/s a 100 ms y 20 MB/s a 200 ms. Subir los techos de ventana de kolo-transport, MaxGrownStreamReceiveWindow y MaxGrownConnReceiveWindow, es la forma de que un pull vaya más rápido (mira kolo-transport). InFlight no necesita cambiar para eso.

Estadísticas del pull

PullResult.Stats dice en qué se fue el tiempo de un PullWith, también cuando falló. Para tener las cifras mientras corre, da a PullOptions.Meter un *PullMeter (su valor cero está listo) y llama a Meter.Stats() desde cualquier goroutine. Un medidor mide un pull cada vez: un pull que empieza con un medidor que otro pull está usando devuelve ErrInvalidArgument.

  • Streamed: el peer envió las entradas en streaming; false con un peer anterior a STREAM_REQ.
  • Elapsed, Bytes, Entries, Answers y Requests: el tiempo del pull, las respuestas ENTRIES leídas y las peticiones de entradas enviadas.
  • ReaderWait, CommitBusy y CommitIdle: el tiempo que el lector esperó bytes, y el tiempo que la goroutine que verifica y guarda estuvo ocupada y ociosa.
  • FirstByteMin, FirstByteAvg y FirstByteMax: desde que se escribe una petición de entradas hasta los primeros bytes de su respuesta.
  • InFlightMax, InFlightAvg, InFlightBlocked, MemoryBlocked, MemoryWait y HeldMax: las peticiones en espera, las veces que InFlight o los 6 MiB frenaron el pull, y el máximo de bytes de respuestas retenidos.

CommitIdle y ReaderWait cerca de Elapsed quieren decir que el pull espera al peer o a la red, no a esta máquina. CommitBusy cerca de Elapsed quiere decir que la máquina verifica y guarda tan rápido como puede. FirstByteMin muy por encima del tiempo de ida y vuelta quiere decir que el peer tarda en leer su log.

Leer de un pin que sirve solo texto cifrado

Un peer de anclaje (pin) guarda una copia verificada de un log y la sirve con acceso Ciphertext, así que no tiene claves de entradas. Un Fetch contra él devuelve cada entrada viva con kololog.ErrKeyUnavailable. Usa Fetch cuando el peer envía las claves (acceso Keys) o solo necesitas saber qué entradas existen. Usa FetchWithKeys cuando las claves ya las tienes tú y el peer sirve solo texto cifrado, por ejemplo para leer mientras el propietario está desconectado.

Las claves vienen de ti, nunca del pin. Obtén un head con FetchHead y las claves del rango con FetchKeys del propietario o de otro peer con acceso Keys, y guárdalas donde tu aplicación guarda su estado. Después, FetchWithKeys(ctx, conn, h, start, end, keys) es Fetch con una función keys(index) que devuelve la clave que tienes para una entrada que llegó sin ella. Log.Key y Replica.Key sirven como keys si guardas un log o una réplica, y la función puede leer de un mapa o de un archivo igual de bien. Las dos llamadas se comprueban contra el head h, igual que Fetch.

main.go
package main

import (
	"context"
	"crypto/ed25519"
	"errors"
	"fmt"
	"log"
	"time"

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	alice, err := koloid.Generate()
	check(err)
	device, err := koloid.Generate() // another device of alice, with Keys access
	check(err)
	reader, err := koloid.Generate() // reads from the pin, with Ciphertext access
	check(err)

	// One server plays both parts here: it gives keys to the device and
	// ciphertext only to the reader, as a pin would.
	as := kolostore.New(kolostore.NewMemory())
	defer as.Close()
	l, err := as.Create(alice)
	check(err)
	_, err = l.Append([]byte("hello from alice"))
	check(err)
	_, err = l.Append([]byte("second entry"))
	check(err)
	srv := kolosync.NewServer(func(peer, _ ed25519.PublicKey, _ kololog.LogID) kolosync.Access {
		switch {
		case peer.Equal(device.PublicKey()):
			return kolosync.Keys
		case peer.Equal(reader.PublicKey()):
			return kolosync.Ciphertext
		}
		return kolosync.NoAccess
	})
	check(srv.Offer(l))
	ln, err := kolosecure.Listen(ctx, "127.0.0.1:0", alice, nil)
	check(err)
	defer ln.Close()
	go func() {
		for {
			conn, err := ln.Accept(ctx)
			if err != nil {
				return
			}
			go srv.Serve(ctx, conn)
		}
	}()

	// The device gets a head and the keys of both entries, and keeps them.
	dconn, err := kolosecure.Dial(ctx, ln.Addr().String(), device, alice.PublicKey(), nil)
	check(err)
	defer dconn.Close()
	h, err := kolosync.FetchHead(ctx, dconn, alice.PublicKey(), l.ID())
	check(err)
	keys, err := kolosync.FetchKeys(ctx, dconn, h, 0, 1)
	check(err)

	// The reader asks the pin. Fetch alone cannot open the entries.
	rconn, err := kolosecure.Dial(ctx, ln.Addr().String(), reader, alice.PublicKey(), nil)
	check(err)
	defer rconn.Close()
	got, err := kolosync.Fetch(ctx, rconn, h, 0, 1)
	check(err)
	fmt.Println("without keys:", errors.Is(got[0].Err, kololog.ErrKeyUnavailable))

	// FetchWithKeys opens them with the held keys, which never leave the reader.
	got, err = kolosync.FetchWithKeys(ctx, rconn, h, 0, 1, func(i uint64) (kololog.EntryKey, error) {
		return append(kololog.EntryKey(nil), keys[i]...), nil
	})
	check(err)
	for _, f := range got {
		if f.Err != nil { // for example kolosync.ErrKeyMismatch
			log.Fatal(f.Err)
		}
		fmt.Printf("with keys: %q at index %d\n", f.Data, f.Index)
	}
}

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

Imprime:

Texto
without keys: true
with keys: "hello from alice" at index 0
with keys: "second entry" at index 1

Lo que se queda en el cliente: las claves, y cuáles de ellas tiene. El pin recibe las mismas peticiones que con Fetch y no necesita material de claves. Se le pregunta a keys solo cuando llegó la última respuesta y el stream está cerrado, así que ni el ritmo ni el final del stream le dicen al pin si tienes claves. FetchWithKeys borra cada clave después de usarla, así que keys devuelve una copia.

Una clave nil o vacía, o un error que envuelve kololog.ErrKeyUnavailable, significa que no tienes ninguna y la entrada se informa con kololog.ErrKeyUnavailable. El kololog.ErrOutOfRange de Log.Key y Replica.Key cuenta como ninguna, y su kololog.ErrDeleted informa la entrada como borrada. Una clave guardada que no coincide con el registro firmado de la entrada se informa solo para esa entrada con ErrKeyMismatch, y las demás se abren. Cualquier otro error de keys hace fallar la llamada. Cuando ctx termina no se piden más claves, y ante cualquier error no se devuelve ninguna entrada y se borran los valores ya abiertos.

El tiempo que tarda FetchWithKeys en volver depende de las claves guardadas: abre las entradas después de que termine el stream, así que un peer que ve tu siguiente petición en la misma conexión puede saber por la demora si tenías claves y si coincidían. Lo mismo vale para lo que haga tu aplicación a continuación, como parar tras un ErrKeyMismatch. Nada cambia en la red con las claves. Si eso importa, abre el siguiente stream tras una espera fija, o en otra conexión.

FetchKeys(ctx, conn, h, start, end) devuelve un elemento por entrada pedida: el elemento i es la clave de la entrada start+i, o nil donde el peer no dio ninguna (una entrada borrada, una clave que no tiene o falta de acceso Keys: las tres se ven igual). No comprueba la clave, porque kolo-log no tiene una comprobación de una clave sin su texto cifrado; FetchWithKeys sí, contra el registro firmado. Borra las claves cuando termines.

Ejecuta un Serve por conexión, como único llamante de conn.AcceptStream, y un solo Pull a la vez por réplica (un segundo devuelve ErrBusy). Los pulls de réplicas distintas y muchos fetch pueden compartir una conexión, cada uno en su propio stream, y los dos extremos pueden servir y hacer pull en la misma conexión.

Límites

  • MaxMessageSize: 4 MiB por mensaje, con el prefijo de longitud comprobado antes de reservar memoria. Una entrada cuyo texto cifrado con relleno no cabe en un mensaje no se puede sincronizar ni traer con Fetch (ErrTooLarge), consulta Límites conocidos.
  • MaxStreams: 16 streams servidos a la vez por conexión, sean de pull o de fetch, igual que el límite de streams por defecto de kolo-transport. A los demás se les responde «ocupado», y el cliente recibe ErrBusy.
  • ServerOptions.MaxTotalStreams: 256 streams servidos a la vez en todas las conexiones (DefaultMaxTotalStreams, 16 conexiones de MaxStreams). ServerOptions.MaxAnswerBytes: 256 MiB de respuestas en construcción o en escritura en todas las conexiones (DefaultMaxAnswerBytes), al menos 2 x MaxMessageSize; una respuesta cuenta el doble de su tamaño. Se fijan con NewServerWith. A un stream o una respuesta que pasa de cualquiera de los dos se le responde «ocupado», el cliente recibe ErrBusy y ServerStats.RefusedByLimit lo cuenta.
  • Timeout: 60s para abrir un stream, para el inicio de cada lectura o escritura de un mensaje y para la espera de la siguiente petición. Un mensaje de n bytes puede tardar Timeout más n a MinRate (16 KiB/s), así que un mensaje completo de 4 MiB solo se corta por debajo de 16 KiB/s. Un peer callado retiene un stream como mucho Timeout; un cliente que espera demasiado recibe ErrTimeout.
  • Una respuesta a una petición de entradas se llena hasta aproximadamente 1 MiB cuando ya contiene una entrada; una entrada mayor va sola, hasta MaxMessageSize.
  • PullOptions.InFlight: de 1 a 8 (MaxInFlight); cualquier otro valor es ErrInvalidArgument. Con un peer que hace streaming es el máximo de peticiones de crédito, de 2 MiB cada una, en espera (0 es 8); con un peer más antiguo, las respuestas en vuelo (0 es DefaultInFlight, 3). Un pull retiene como mucho 6 MiB de respuestas aún sin guardar, y un commit guarda las respuestas que esperan, hasta 4 MiB.
  • Crédito de un pull en streaming: el peer acepta como mucho 64 MiB de crédito por stream y rechaza una petición de más.
  • Una respuesta STATE mira como máximo 32.768 entradas (MaxMessageSize / 128); después se detiene antes de tiempo y quien hace pull pide el resto. Solo lee las marcas de borrado y las claves que envía, nunca un texto cifrado.
  • En la red, los heads, las cabeceras, los registros, las marcas y las pruebas ocupan como máximo 4 KiB cada uno, y una clave de entrada tiene 0 o 32 bytes.
  • Los límites son constantes fijas, salvo los dos de ServerOptions. Las conexiones vienen de kolo-secure, así que kolo-sync solo funciona con IPv4.

Seguridad

  • Las claves de las entradas solo viajan por la conexión que das, nunca en un error ni en una línea de log. Ningún error lleva bytes que haya enviado un peer, solo números como tamaños e índices.
  • El head del peer se verifica (firma bajo kolo-log/tree-head/v0, clave del propietario, ID de log) antes de leer ningún otro mensaje, y las pruebas solo se comprueban frente a heads verificados. kolo-sync no firma nada.
  • Cada bloque traído pasa a Replica.Update, que comprueba la firma de cada registro, el hash de cada texto cifrado, cada compromiso de clave y la raíz reconstruida antes de guardar nada. Replica.AddKey comprueba una clave que llega tarde frente a su compromiso de clave. Ante ErrInvalid, la réplica conserva lo que tenía.
  • Las marcas de borrado de una respuesta STATE van a un solo Replica.ApplyDelete, en un solo commit, después de comprobar todos los elementos de la respuesta: una marca incorrecta o fuera de sitio, o cualquier elemento mal formado, no aplica ninguna.
  • Fetch lo comprueba todo frente al head h que le das, nunca frente a la palabra del peer. Cada entrada pasa por kololog.OpenEntry, que comprueba su prueba de inclusión en el árbol del tamaño de h, la firma y el índice del registro, el texto cifrado o la marca de borrado y la clave frente a su compromiso antes de descifrar. Cada prueba debe ser del índice pedido.
  • ErrDiverged necesita evidencias: un head de un tamaño que tenemos, o del tamaño de h en Fetch, con otra raíz, o un registro firmado por el propietario, recibido del peer, que difiere del nuestro en el último índice que tenemos. Una prueba incorrecta sin esas evidencias es ErrInvalid, porque cualquier peer puede enviar una. Ninguna de las dos copias cambia.
  • Quien hace pull indica lo que tiene mediante lo que pide y nunca envía su propio head. El servidor nunca escribe.
  • authorize se ejecuta antes de mirar los logs ofrecidos, así que un log que falta, uno no ofrecido, uno no autorizado y un ID de log ofrecido solo con otro propietario siguen el mismo camino y dan los mismos bytes. Un log guardado pero no ofrecido nunca se lee.
  • Un servidor solo acepta peticiones y un cliente solo acepta respuestas, y eso se comprueba antes que los campos. Otra versión, varints no mínimos o bytes sobrantes terminan el stream.

Límites conocidos

  • Experimental. La API puede cambiar antes de v1.0.0.
  • Formato de red versión 1. Un peer que habla otra versión recibe un error de protocolo.
  • Solo pull: un peer no puede enviarle un log a otro por su cuenta.
  • Una entrada cuyo texto cifrado con relleno supera MaxMessageSize no se puede sincronizar ni traer, esté borrada o no, y el log no se sincroniza más allá de ella. El servidor comprueba primero el tamaño del registro y nunca lee esa entrada.
  • Una bifurcación que empieza después de las entradas que tenemos no deja evidencias: sus pruebas fallan y el pull devuelve ErrInvalid, no ErrDiverged.
  • Fetch no distingue un peer sin acceso Keys de uno que no tiene la clave o que decidió no enviarla: todos dan kololog.ErrKeyUnavailable.
  • Los heads no llevan marca de tiempo, así que un head más nuevo es uno más grande. Para leer las entradas más recientes, consigue antes un head más nuevo con FetchHead o un Pull.
  • El formato de red no tiene forma JSON.

Errores

ErrorMensaje
ErrBehindkolosync: peer is behind the head
ErrBusykolosync: peer busy
ErrDivergedkolosync: logs diverged
ErrInvalidkolosync: peer sent data that does not verify
ErrInvalidArgumentkolosync: invalid argument
ErrKeyMismatchkolosync: held key does not match its record
ErrMarkedkolosync: peer serves a deleted entry
ErrNotFoundkolosync: log not found
ErrProtocolkolosync: protocol error
ErrTimeoutkolosync: timeout
ErrTooLargekolosync: message too large

Comprueba los errores con errors.Is. ErrInvalid también envuelve el error de kolo-log (como kololog.ErrBadEntry, kololog.ErrInvalidHead o kololog.ErrBadProof), ErrDiverged puede envolver kololog.ErrDiverged, ErrInvalidArgument envuelve kololog.ErrOutOfRange para un rango de Fetch vacío o que pasa del head, y un ErrTimeout en la lectura o escritura de un mensaje envuelve os.ErrDeadlineExceeded. ErrKeyMismatch llega en Fetched.Err y envuelve kololog.ErrBadEntry. Cuando ctx termina, Pull, FetchHeader, FetchHead, Fetch, FetchWithKeys, FetchKeys y Serve devuelven ctx.Err().

ErrMarked solo viene de PullWith con NoMarkers: el peer sirve una entrada borrada, o con una marca, donde la réplica necesita una viva. La réplica tiene las entradas anteriores, así que rep.Len() es su índice, que el mensaje del error también nombra; haz pull del resto desde otro peer cuyo head llegue hasta el head de ese peer. PullWith con NoMarkers también devuelve ErrBehind cuando el head del peer tiene menos entradas que el head hacia el que se llena la réplica, así que no se añade ninguna entrada ni clave: pregunta a otro peer, o a uno posterior.

Referencias

  • RFC 9162, Certificate Transparency Version 2.0 (Experimental, December 2021).
    • Toma: los heads firmados del árbol (4.10), las pruebas de consistencia (2.1.4), las pruebas de inclusión (2.1.3), get-sth (5.2), get-sth-consistency (5.3), get-entries (5.6) y el monitor que guarda un log entero (8.2).
    • No implementa: HTTPS y JSON (en su lugar, mensajes de kolo-codec sobre un stream de kolo-secure) y get-proof-by-hash como petición, porque una réplica tiene todas las entradas y reconstruye la raíz.
  • RFC 6962, Certificate Transparency (Experimental, June 2013, obsoleted by RFC 9162).
    • Toma: get-entry-and-proof (4.8), una entrada con su prueba de inclusión por índice y tamaño de árbol.
  • RFC 8032, Edwards-Curve Digital Signature Algorithm (EdDSA) (Informational, January 2017).
    • Toma: Ed25519ctx (5.1, 8.3), a través de los contextos de kolo-log.
    • No implementa: kolo-sync no firma nada.
  • RFC 9113, HTTP/2 (Proposed Standard, June 2022).
    • Toma: el límite de concurrencia de streams y los streams rechazados (5.1.2, 6.5.2).
    • No implementa: HTTP/2 en sí.