wtdb

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2019 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const BreachHintSize = 16

BreachHintSize is the length of the txid prefix used to identify remote commitment broadcasts.

View Source
const SessionIDSize = 33

SessionIDSize is 33-bytes; it is a serialized, compressed public key.

Variables

View Source
var (
	// ErrClientSessionNotFound signals that the requested client session
	// was not found in the database.
	ErrClientSessionNotFound = errors.New("client session not found")

	// ErrUpdateAlreadyCommitted signals that the chosen sequence number has
	// already been committed to an update with a different breach hint.
	ErrUpdateAlreadyCommitted = errors.New("update already committed")

	// ErrCommitUnorderedUpdate signals the client tried to commit a
	// sequence number other than the next unallocated sequence number.
	ErrCommitUnorderedUpdate = errors.New("update seqnum not monotonic")

	// ErrCommittedUpdateNotFound signals that the tower tried to ACK a
	// sequence number that has not yet been allocated by the client.
	ErrCommittedUpdateNotFound = errors.New("committed update not found")

	// ErrUnallocatedLastApplied signals that the tower tried to provide a
	// LastApplied value greater than any allocated sequence number.
	ErrUnallocatedLastApplied = errors.New("tower echoed last appiled " +
		"greater than allocated seqnum")

	// ErrNoReservedKeyIndex signals that a client session could not be
	// created because no session key index was reserved.
	ErrNoReservedKeyIndex = errors.New("key index not reserved")

	// ErrIncorrectKeyIndex signals that the client session could not be
	// created because session key index differs from the reserved key
	// index.
	ErrIncorrectKeyIndex = errors.New("incorrect key index")
)
View Source
var (
	// ErrSessionNotFound is returned when querying by session id for a
	// session that does not exist.
	ErrSessionNotFound = errors.New("session not found in db")

	// ErrSessionAlreadyExists signals that a session creation failed
	// because a session with the same session id already exists.
	ErrSessionAlreadyExists = errors.New("session already exists")

	// ErrUpdateOutOfOrder is returned when the sequence number is not equal
	// to the server's LastApplied+1.
	ErrUpdateOutOfOrder = errors.New("update sequence number is not " +
		"sequential")

	// ErrLastAppliedReversion is returned when the client echos a
	// last-applied value that is less than it claimed in a prior update.
	ErrLastAppliedReversion = errors.New("update last applied must be " +
		"non-decreasing")

	// ErrSeqNumAlreadyApplied is returned when the client sends a sequence
	// number for which they already claim to have an ACK.
	ErrSeqNumAlreadyApplied = errors.New("update sequence number has " +
		"already been applied")

	// ErrSessionConsumed is returned if the client tries to send a sequence
	// number larger than the session's max number of updates.
	ErrSessionConsumed = errors.New("all session updates have been " +
		"consumed")
)
View Source
var (

	// ErrUninitializedDB signals that top-level buckets for the database
	// have not been initialized.
	ErrUninitializedDB = errors.New("tower db not initialized")

	// ErrNoDBVersion signals that the database contains no version info.
	ErrNoDBVersion = errors.New("tower db has no version")

	// ErrNoSessionHintIndex signals that an active session does not have an
	// initialized index for tracking its own state updates.
	ErrNoSessionHintIndex = errors.New("session hint index missing")
)
View Source
var (
	// ErrTowerNotFound signals that the target tower was not found in the
	// database.
	ErrTowerNotFound = errors.New("tower not found")
)

Functions

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func ReadElement

func ReadElement(r io.Reader, element interface{}) error

ReadElement deserializes a single element from the provided io.Reader.

func ReadElements

func ReadElements(r io.Reader, elements ...interface{}) error

ReadElements deserializes the provided io.Reader into a variadic list of target elements.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

func WriteElement

func WriteElement(w io.Writer, element interface{}) error

WriteElement serializes a single element into the provided io.Writer.

func WriteElements

func WriteElements(w io.Writer, elements ...interface{}) error

WriteElements serializes a variadic list of elements into the given io.Writer.

Types

type BackupID

type BackupID struct {
	// ChanID is the channel id of the revoked commitment.
	ChanID lnwire.ChannelID

	// CommitHeight is the commitment height of the revoked commitment.
	CommitHeight uint64
}

BackupID identifies a particular revoked, remote commitment by channel id and commitment height.

type BreachHint

type BreachHint [BreachHintSize]byte

BreachHint is the first 16-bytes of the txid belonging to a revoked commitment transaction.

func NewBreachHintFromHash

func NewBreachHintFromHash(hash *chainhash.Hash) BreachHint

NewBreachHintFromHash creates a breach hint from a transaction ID.

func (BreachHint) String

func (h BreachHint) String() string

String returns a hex encoding of the breach hint.

type ClientSession

type ClientSession struct {
	// ID is the client's public key used when authenticating with the
	// tower.
	ID SessionID

	// SeqNum is the next unallocated sequence number that can be sent to
	// the tower.
	SeqNum uint16

	// TowerLastApplied the last last-applied the tower has echoed back.
	TowerLastApplied uint16

	// TowerID is the unique, db-assigned identifier that references the
	// Tower with which the session is negotiated.
	TowerID uint64

	// Tower holds the pubkey and address of the watchtower.
	//
	// NOTE: This value is not serialized. It is recovered by looking up the
	// tower with TowerID.
	Tower *Tower

	// KeyIndex is the index of key locator used to derive the client's
	// session key so that it can authenticate with the tower to update its
	// session. In order to rederive the private key, the key locator should
	// use the keychain.KeyFamilyTowerSession key family.
	KeyIndex uint32

	// SessionPrivKey is the ephemeral secret key used to connect to the
	// watchtower.
	//
	// NOTE: This value is not serialized. It is derived using the KeyIndex
	// on startup to avoid storing private keys on disk.
	SessionPrivKey *btcec.PrivateKey

	// Policy holds the negotiated session parameters.
	Policy wtpolicy.Policy

	// RewardPkScript is the pkscript that the tower's reward will be
	// deposited to if a sweep transaction confirms and the sessions
	// specifies a reward output.
	RewardPkScript []byte

	// CommittedUpdates is a map from allocated sequence numbers to unacked
	// updates. These updates can be resent after a restart if the update
	// failed to send or receive an acknowledgment.
	CommittedUpdates map[uint16]*CommittedUpdate

	// AckedUpdates is a map from sequence number to backup id to record
	// which revoked states were uploaded via this session.
	AckedUpdates map[uint16]BackupID
}

ClientSession encapsulates a SessionInfo returned from a successful session negotiation, and also records the tower and ephemeral secret used for communicating with the tower.

type CommittedUpdate

type CommittedUpdate struct {
	BackupID BackupID

	// Hint is the 16-byte prefix of the revoked commitment transaction ID.
	Hint BreachHint

	// EncryptedBlob is a ciphertext containing the sweep information for
	// exacting justice if the commitment transaction matching the breach
	// hint is broadcast.
	EncryptedBlob []byte
}

CommittedUpdate holds a state update sent by a client along with its SessionID.

type Match

type Match struct {
	// ID is the session id of the client who uploaded the state update.
	ID SessionID

	// SeqNum is the session sequence number occupied by the client's state
	// update. Together with ID, this allows the tower to derive the
	// appropriate nonce for decryption.
	SeqNum uint16

	// Hint is the breach hint that triggered the match.
	Hint BreachHint

	// EncryptedBlob is the encrypted payload containing the justice kit
	// uploaded by the client.
	EncryptedBlob []byte

	// SessionInfo is the contract negotiated between tower and client, that
	// provides input parameters such as fee rate, reward rate, and reward
	// address when attempting to reconstruct the justice transaction.
	SessionInfo *SessionInfo
}

Match is returned in response to a database query for a breach hints contained in a particular block. The match encapsulates all data required to properly decrypt a client's encrypted blob, and pursue action on behalf of the victim by reconstructing the justice transaction and broadcasting it to the network.

NOTE: It is possible for a match to cause a false positive, since they are matched on a prefix of the txid. In such an event, the likely behavior is that the payload will fail to decrypt.

type SessionID

type SessionID [SessionIDSize]byte

SessionID is created from the remote public key of a client, and serves as a unique identifier and authentication for sending state updates.

func NewSessionIDFromPubKey

func NewSessionIDFromPubKey(pubKey *btcec.PublicKey) SessionID

NewSessionIDFromPubKey creates a new SessionID from a public key.

func (SessionID) String

func (s SessionID) String() string

String returns a hex encoding of the session id.

type SessionInfo

type SessionInfo struct {
	// ID is the remote public key of the watchtower client.
	ID SessionID

	// Policy holds the negotiated session parameters.
	Policy wtpolicy.Policy

	// LastApplied the sequence number of the last successful state update.
	LastApplied uint16

	// ClientLastApplied the last last-applied the client has echoed back.
	ClientLastApplied uint16

	// RewardAddress the address that the tower's reward will be deposited
	// to if a sweep transaction confirms.
	RewardAddress []byte
}

SessionInfo holds the negotiated session parameters for single session id, and handles the acceptance and validation of state updates sent by the client.

func (*SessionInfo) AcceptUpdateSequence

func (s *SessionInfo) AcceptUpdateSequence(seqNum, lastApplied uint16) error

AcceptUpdateSequence validates that a state update's sequence number and last applied are valid given our past history with the client. These checks ensure that clients are properly in sync and following the update protocol properly. If validation is successful, the receiver's LastApplied and ClientLastApplied are updated with the latest values presented by the client. Any errors returned from this method are converted into an appropriate wtwire.StateUpdateCode.

func (*SessionInfo) Decode

func (s *SessionInfo) Decode(r io.Reader) error

Decode deserializes the session infor from the given io.Reader.

func (*SessionInfo) Encode

func (s *SessionInfo) Encode(w io.Writer) error

Encode serializes the session info to the given io.Writer.

type SessionStateUpdate

type SessionStateUpdate struct {
	// ID the session id of the client who sent the state update.
	ID SessionID

	// SeqNum the sequence number of the update within the session.
	SeqNum uint16

	// LastApplied the highest index that client has acknowledged is
	// committed
	LastApplied uint16

	// Hint is the 16-byte prefix of the revoked commitment transaction.
	Hint BreachHint

	// EncryptedBlob is a ciphertext containing the sweep information for
	// exacting justice if the commitment transaction matching the breach
	// hint is broadcast.
	EncryptedBlob []byte
}

SessionStateUpdate holds a state update sent by a client along with its SessionID.

func (*SessionStateUpdate) Decode

func (u *SessionStateUpdate) Decode(r io.Reader) error

Decode deserializes the target state update from the provided io.Reader.

func (*SessionStateUpdate) Encode

func (u *SessionStateUpdate) Encode(w io.Writer) error

Encode serializes the state update into the provided io.Writer.

type Tower

type Tower struct {
	// ID is a unique ID for this record assigned by the database.
	ID uint64

	// IdentityKey is the public key of the remote node, used to
	// authenticate the brontide transport.
	IdentityKey *btcec.PublicKey

	// Addresses is a list of possible addresses to reach the tower.
	Addresses []net.Addr
	// contains filtered or unexported fields
}

Tower holds the necessary components required to connect to a remote tower. Communication is handled by brontide, and requires both a public key and an address.

func (*Tower) AddAddress

func (t *Tower) AddAddress(addr net.Addr)

AddAddress adds the given address to the tower's in-memory list of addresses. If the address's string is already present, the Tower will be left unmodified. Otherwise, the adddress is prepended to the beginning of the Tower's addresses, on the assumption that it is fresher than the others.

func (*Tower) LNAddrs

func (t *Tower) LNAddrs() []*lnwire.NetAddress

LNAddrs generates a list of lnwire.NetAddress from a Tower instance's addresses. This can be used to have a client try multiple addresses for the same Tower.

type TowerDB

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

TowerDB is single database providing a persistent storage engine for the wtserver and lookout subsystems.

func OpenTowerDB

func OpenTowerDB(dbPath string) (*TowerDB, error)

OpenTowerDB opens the tower database given the path to the database's directory. If no such database exists, this method will initialize a fresh one using the latest version number and bucket structure. If a database exists but has a lower version number than the current version, any necessary migrations will be applied before returning. Any attempt to open a database with a version number higher that the latest version will fail to prevent accidental reversion.

func (*TowerDB) Close

func (t *TowerDB) Close() error

Close closes the underlying database.

func (*TowerDB) DeleteSession

func (t *TowerDB) DeleteSession(target SessionID) error

DeleteSession removes all data associated with a particular session id from the tower's database.

func (*TowerDB) GetLookoutTip

func (t *TowerDB) GetLookoutTip() (*chainntnfs.BlockEpoch, error)

GetLookoutTip retrieves the current lookout tip block epoch from the tower database.

func (*TowerDB) GetSessionInfo

func (t *TowerDB) GetSessionInfo(id *SessionID) (*SessionInfo, error)

GetSessionInfo retrieves the session for the passed session id. An error is returned if the session could not be found.

func (*TowerDB) InsertSessionInfo

func (t *TowerDB) InsertSessionInfo(session *SessionInfo) error

InsertSessionInfo records a negotiated session in the tower database. An error is returned if the session already exists.

func (*TowerDB) InsertStateUpdate

func (t *TowerDB) InsertStateUpdate(update *SessionStateUpdate) (uint16, error)

InsertStateUpdate stores an update sent by the client after validating that the update is well-formed in the context of other updates sent for the same session. This include verifying that the sequence number is incremented properly and the last applied values echoed by the client are sane.

func (*TowerDB) QueryMatches

func (t *TowerDB) QueryMatches(breachHints []BreachHint) ([]Match, error)

QueryMatches searches against all known state updates for any that match the passed breachHints. More than one Match will be returned for a given hint if they exist in the database.

func (*TowerDB) SetLookoutTip

func (t *TowerDB) SetLookoutTip(epoch *chainntnfs.BlockEpoch) error

SetLookoutTip stores the provided epoch as the latest lookout tip epoch in the tower database.

func (*TowerDB) Version

func (t *TowerDB) Version() (uint32, error)

Version returns the database's current version number.

type UnknownElementType

type UnknownElementType = channeldb.UnknownElementType

UnknownElementType is an alias for channeldb.UnknownElementType.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL