sphinx

package module
v0.0.0-...-48c0817 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2018 License: MIT Imports: 21 Imported by: 0

README

lightning-onion

This repository houses an implementation of the Lightning Network's onion routing protocol. The Lightning Network uses onion routing to securely, and privately route HTLC's (Hash-Time-Locked-Contracts, basically a conditional payment) within the network. (A full specification of the protocol can be found amongst the lighting-rfc repository, specifically within BOLT#04.

The Lightning Network is composed of a series of "payment channels" which are essentially tubes of money whose balances can instantaneous be reallocated between two participants. By linking these payment channels in a pair-wise manner, a network of connect payment channels are created.

Within the Lightning Network, source-routing is utilized in order to give nodes full control over the route their payment follows within the network. This level of control is highly desirable as with it, senders are able to fully specify: the total number of hops in their routes, the total cumulative fee they'll pay to send the payment, and finally the total worst-case time-lock period enforced by the conditional payment contract.

In line with Bitcoin's spirit of decentralization and censorship resistance, we employ an onion routing scheme within the Lightning protocol to prevent the ability of participants on the network to easily censor payments, as the participants are not aware of the final destination of any given payment. Additionally, by encoding payment routes within a mix-net like packet, we are able to achieve the following security and privacy features:

  • Participants in a route don't know their exact position within the route
  • Participants within a route don't know the source of the payment, nor the ultimate destination of the payment
  • Participants within a route aren't away exactly how many other participants were involved in the payment route
  • Each new payment route is computationally indistinguishable from any other payment route

Our current onion routing protocol utilizes a message format derived from Sphinx. In order to cater Sphinx's mix-format to our specification application, we've made the following modifications:

  • We've added a MAC over the entire mix-header as we have no use for SURB's (single-use-reply-blocks) in our protocol.
  • Additionally, the end-to-end payload to the destination has been removed in order to cut down on the packet-size, and also as we don't currently have a use for a large message from payment sender to recipient.
  • We've dropped usage of LIONESS (as we don't need SURB's), and instead utilize chacha20 uniformly throughout as a stream cipher.
  • Finally, the mix-header has been extended with a per-hop-payload which provides each hops with exact instructions as to how and where to forward the payment. This includes the amount to forward, the destination chain, and the time-lock value to attach to the outgoing HTLC.

For further information see these resources:

In the near future, this repository will be extended to also includes a application specific version of HORNET.

Documentation

Index

Constants

View Source
const (
	// ExitNode indicates that the node which processed the Sphinx packet
	// is the destination hop in the route.
	ExitNode = iota

	// MoreHops indicates that there are additional hops left within the
	// route. Therefore the caller should forward the packet to the node
	// denoted as the "NextHop".
	MoreHops

	// Failure indicates that a failure occurred during packet processing.
	Failure
)
View Source
const (

	// NumMaxHops is the the maximum path length. This should be set to an
	// estiamate of the upper limit of the diameter of the node graph.
	NumMaxHops = 20
)

Variables

View Source
var (
	// ErrDecayedLogInit is used to indicate a decayed log failed to create
	// the proper bucketing structure on startup.
	ErrDecayedLogInit = errors.New("unable to initialize decayed log")

	// ErrDecayedLogCorrupted signals that the anticipated bucketing
	// structure has diverged since initialization.
	ErrDecayedLogCorrupted = errors.New("decayed log structure corrupted")
)
View Source
var (
	// ErrReplayedPacket is an error returned when a packet is rejected
	// during processing due to being an attempted replay or probing
	// attempt.
	ErrReplayedPacket = fmt.Errorf("sphinx packet replay attempted")

	// ErrInvalidOnionVersion is returned during decoding of the onion
	// packet, when the received packet has an unknown version byte.
	ErrInvalidOnionVersion = fmt.Errorf("invalid onion packet version")

	// ErrInvalidOnionHMAC is returned during onion parsing process, when received
	// mac does not corresponds to the generated one.
	ErrInvalidOnionHMAC = fmt.Errorf("invalid mismathed mac")

	// ErrInvalidOnionKey is returned during onion parsing process, when
	// onion key is invalid.
	ErrInvalidOnionKey = fmt.Errorf("invalid onion key: pubkey isn't on " +
		"secp256k1 curve")
)
View Source
var ErrAlreadyCommitted = errors.New("cannot add to batch after committing")

ErrAlreadyCommitted signals that an entry could not be added to the batch because it has already been persisted.

Functions

func DisableLog

func DisableLog()

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

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.

Types

type Batch

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

Batch is an object used to incrementally construct a set of entries to add to the replay log. After construction is completed, it can be added to the log using the PutBatch method.

func NewBatch

func NewBatch(id []byte) *Batch

NewBatch initializes an object for constructing a set of entries to atomically add to a replay log. Batches are identified by byte slice, which allows the caller to safely process the same batch twice and get an idempotent result.

func (*Batch) Put

func (b *Batch) Put(seqNum uint16, hashPrefix *HashPrefix, cltv uint32) error

Put inserts a hash-prefix/CLTV pair into the current batch. This method only returns an error in the event that the batch was already committed to disk. Decisions regarding whether or not a particular sequence number is a replay is ultimately reported via the batch's ReplaySet after committing to disk.

type Circuit

type Circuit struct {
	// SessionKey is the key which have been used during generation of the
	// shared secrets.
	SessionKey *btcec.PrivateKey

	// PaymentPath is the pub keys of the nodes in the payment path.
	PaymentPath []*btcec.PublicKey
}

Circuit is used encapsulate the data which is needed for data deobfuscation.

func (*Circuit) Decode

func (c *Circuit) Decode(r io.Reader) error

Decode initializes the circuit from the byte stream.

func (*Circuit) Encode

func (c *Circuit) Encode(w io.Writer) error

Encode writes converted circuit in the byte stream.

type DecayedLog

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

DecayedLog implements the PersistLog interface. It stores the first sharedHashSize bytes of a sha256-hashed shared secret along with a node's CLTV value. It is a decaying log meaning there will be a garbage collector to collect entries which are expired according to their stored CLTV value and the current block height. DecayedLog wraps boltdb for simplicity and batches writes to the database to decrease write contention.

func NewDecayedLog

func NewDecayedLog(dbPath string,
	notifier chainntnfs.ChainNotifier) *DecayedLog

NewDecayedLog creates a new DecayedLog, which caches recently seen hash shared secrets. Entries are evicted as their cltv expires using block epochs from the given notifier.

func (*DecayedLog) Delete

func (d *DecayedLog) Delete(hash []byte) error

Delete removes a <shared secret hash, CLTV> key-pair from the sharedHashBucket.

func (*DecayedLog) Get

func (d *DecayedLog) Get(hash []byte) (uint32, error)

Get retrieves the CLTV of a processed HTLC given the first 20 bytes of the Sha-256 hash of the shared secret.

func (*DecayedLog) Put

func (d *DecayedLog) Put(hash *HashPrefix, cltv uint32) error

Put stores a shared secret hash as the key and the CLTV as the value.

func (*DecayedLog) PutBatch

func (d *DecayedLog) PutBatch(b *Batch) (*ReplaySet, error)

PutBatch accepts a pending batch of hashed secret entries to write to disk. Each hashed secret is inserted with a corresponding time value, dictating when the entry will be evicted from the log. NOTE: This method enforces idempotency by writing the replay set obtained from the first attempt for a particular batch ID, and decoding the return value to subsequent calls. For the indices of the replay set to be aligned properly, the batch MUST be constructed identically to the first attempt, pruning will cause the indices to become invalid.

func (*DecayedLog) Start

func (d *DecayedLog) Start() error

Start opens the database we will be using to store hashed shared secrets. It also starts the garbage collector in a goroutine to remove stale database entries.

func (*DecayedLog) Stop

func (d *DecayedLog) Stop() error

Stop halts the garbage collector and closes boltdb.

type Hash256

type Hash256 [sha256.Size]byte

Hash256 is a statically sized, 32-byte array, typically containing the output of a SHA256 hash.

type HashPrefix

type HashPrefix [sharedHashSize]byte

HashPrefix is a statically size, 20-byte array containing the prefix of a Hash256, and is used to detect duplicate sphinx packets.

type HopData

type HopData struct {
	// Realm denotes the "real" of target chain of the next hop. For
	// bitcoin, this value will be 0x00.
	Realm byte

	// NextAddress is the address of the next hop that this packet should
	// be forward to.
	NextAddress [addressSize]byte

	// ForwardAmount is the HTLC amount that the next hop should forward.
	// This value should take into account the fee require by this
	// particular hop, and the cumulative fee for the entire route.
	ForwardAmount uint64

	// OutgoingCltv is the value of the outgoing absolute time-lock that
	// should be included in the HTLC forwarded.
	OutgoingCltv uint32

	// HMAC is an HMAC computed over the entire per-hop payload that also
	// includes the higher-level (optional) associated data bytes.
	HMAC [hmacSize]byte
}

HopData is the information destined for individual hops. It is a fixed size 64 bytes, prefixed with a 1 byte realm that indicates how to interpret it. For now we simply assume it's the bitcoin realm (0x00) and hence the format is fixed. The last 32 bytes are always the HMAC to be passed to the next hop, or zero if this is the packet is not to be forwarded, since this is the last hop.

func (*HopData) Decode

func (hd *HopData) Decode(r io.Reader) error

Decode deserializes the encoded HopData contained int he passed io.Reader instance to the target empty HopData instance.

func (*HopData) Encode

func (hd *HopData) Encode(w io.Writer) error

Encode writes the serialized version of the target HopData into the passed io.Writer.

type OnionErrorDecrypter

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

OnionErrorDecrypter is a struct that's used to decrypt onion errors in response to failed HTLC routing attempts according to BOLT#4.

func NewOnionErrorDecrypter

func NewOnionErrorDecrypter(circuit *Circuit) *OnionErrorDecrypter

NewOnionErrorDecrypter creates new instance of onion decrypter.

func (*OnionErrorDecrypter) DecryptError

func (o *OnionErrorDecrypter) DecryptError(encryptedData []byte) (*btcec.PublicKey, []byte, error)

DecryptError attempts to decrypt the passed encrypted error response. The onion failure is encrypted in backward manner, starting from the node where error have occurred. As a result, in order to decrypt the error we need get all shared secret and apply decryption in the reverse order.

type OnionErrorEncrypter

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

OnionErrorEncrypter is a struct that's used to implement onion error encryption as defined within BOLT0004.

func NewOnionErrorEncrypter

func NewOnionErrorEncrypter(router *Router,
	ephemeralKey *btcec.PublicKey) (*OnionErrorEncrypter, error)

NewOnionErrorEncrypter creates new instance of the onion encrypter backed by the passed router, with encryption to be doing using the passed ephemeralKey.

func (*OnionErrorEncrypter) Decode

func (o *OnionErrorEncrypter) Decode(r io.Reader) error

Decode restores the encrypter's share secret from the provided io.Reader.

func (*OnionErrorEncrypter) Encode

func (o *OnionErrorEncrypter) Encode(w io.Writer) error

Encode writes the encrypter's shared secret to the provided io.Writer.

func (*OnionErrorEncrypter) EncryptError

func (o *OnionErrorEncrypter) EncryptError(initial bool, data []byte) []byte

EncryptError is used to make data obfuscation using the generated shared secret.

In context of Lightning Network is either used by the nodes in order to make initial obfuscation with the creation of the hmac or by the forwarding nodes for backward failure obfuscation of the onion failure blob. By obfuscating the onion failure on every node in the path we are adding additional step of the security and barrier for malware nodes to retrieve valuable information. The reason for using onion obfuscation is to not give away to the nodes in the payment path the information about the exact failure and its origin.

type OnionPacket

type OnionPacket struct {
	// Version denotes the version of this onion packet. The version
	// indicates how a receiver of the packet should interpret the bytes
	// following this version byte. Currently, a version of 0x00 is the
	// only defined version type.
	Version byte

	// EphemeralKey is the public key that each hop will used in
	// combination with the private key in an ECDH to derive the shared
	// secret used to check the HMAC on the packet and also decrypted the
	// routing information.
	EphemeralKey *btcec.PublicKey

	// RoutingInfo is the full routing information for this onion packet.
	// This encodes all the forwarding instructions for this current hop
	// and all the hops in the route.
	RoutingInfo [routingInfoSize]byte

	// HeaderMAC is an HMAC computed with the shared secret of the routing
	// data and the associated data for this route. Including the
	// associated data lets each hop authenticate higher-level data that is
	// critical for the forwarding of this HTLC.
	HeaderMAC [hmacSize]byte
}

OnionPacket is the onion wrapped hop-to-hop routing information necessary to propagate a message through the mix-net without intermediate nodes having knowledge of their position within the route, the source, the destination, and finally the identities of the past/future nodes in the route. At each hop the ephemeral key is used by the node to perform ECDH between itself and the source node. This derived secret key is used to check the MAC of the entire mix header, decrypt the next set of routing information, and re-randomize the ephemeral key for the next node in the path. This per-hop re-randomization allows us to only propagate a single group element through the onion route.

func NewOnionPacket

func NewOnionPacket(paymentPath []*btcec.PublicKey, sessionKey *btcec.PrivateKey,
	hopsData []HopData, assocData []byte) (*OnionPacket, error)

NewOnionPacket creates a new onion packet which is capable of obliviously routing a message through the mix-net path outline by 'paymentPath'.

func (*OnionPacket) Decode

func (f *OnionPacket) Decode(r io.Reader) error

Decode fully populates the target ForwardingMessage from the raw bytes encoded within the io.Reader. In the case of any decoding errors, an error will be returned. If the method success, then the new OnionPacket is ready to be processed by an instance of SphinxNode.

func (*OnionPacket) Encode

func (f *OnionPacket) Encode(w io.Writer) error

Encode serializes the raw bytes of the onion packet into the passed io.Writer. The form encoded within the passed io.Writer is suitable for either storing on disk, or sending over the network.

type ProcessCode

type ProcessCode int

ProcessCode is an enum-like type which describes to the high-level package user which action should be taken after processing a Sphinx packet.

func (ProcessCode) String

func (p ProcessCode) String() string

String returns a human readable string for each of the ProcessCodes.

type ProcessedPacket

type ProcessedPacket struct {
	// Action represents the action the caller should take after processing
	// the packet.
	Action ProcessCode

	// ForwardingInstructions is the per-hop payload recovered from the
	// initial encrypted onion packet. It details how the packet should be
	// forwarded and also includes information that allows the processor of
	// the packet to authenticate the information passed within the HTLC.
	//
	// NOTE: This field will only be populated iff the above Action is
	// MoreHops.
	ForwardingInstructions HopData

	// NextPacket is the onion packet that should be forwarded to the next
	// hop as denoted by the ForwardingInstructions field.
	//
	// NOTE: This field will only be populated iff the above Action is
	// MoreHops.
	NextPacket *OnionPacket
}

ProcessedPacket encapsulates the resulting state generated after processing an OnionPacket. A processed packet communicates to the caller what action should be taken after processing.

type ReplayLog

type ReplayLog interface {
	// Start starts up the on-disk persistent log. It returns an error if
	// one occurs.
	Start() error

	// Stop safely stops the on-disk persistent log.
	Stop() error

	// Get retrieves an entry from the persistent log given a []byte. It
	// returns the value stored and an error if one occurs.
	Get([]byte) (uint32, error)

	// Put stores an entry into the persistent log given a []byte and an
	// accompanying purposefully general type. It returns an error if the
	// provided hash prefix already exists in the log.
	Put(*HashPrefix, uint32) error

	// PutBatch stores
	PutBatch(*Batch) (*ReplaySet, error)

	// Delete deletes an entry from the persistent log given []byte
	Delete([]byte) error
}

ReplayLog is an interface that defines a new on-disk data structure that contains a persistent log to enable strong replay protection. The interface is general to allow implementations near-complete autonomy. All of these calls should be safe for concurrent access.

type ReplaySet

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

ReplaySet is a data structure used to efficiently record the occurrence of replays, identified by sequence number, when processing a Batch. Its primary functionality includes set construction, membership queries, and merging of replay sets.

func NewReplaySet

func NewReplaySet() *ReplaySet

NewReplaySet initializes an empty replay set.

func (*ReplaySet) Add

func (rs *ReplaySet) Add(idx uint16)

Add inserts the provided index into the replay set.

func (*ReplaySet) Contains

func (rs *ReplaySet) Contains(idx uint16) bool

Contains queries the contents of the replay set for membership of a particular index.

func (*ReplaySet) Decode

func (rs *ReplaySet) Decode(r io.Reader) error

Decode reconstructs a replay set given a io.Reader. The byte slice is assumed to be even in length, otherwise resulting in failure.

func (*ReplaySet) Encode

func (rs *ReplaySet) Encode(w io.Writer) error

Encode serializes the replay set into an io.Writer suitable for storage. The replay set can be recovered using Decode.

func (*ReplaySet) Merge

func (rs *ReplaySet) Merge(rs2 *ReplaySet)

Merge adds the contents of the provided replay set to the receiver's set.

func (*ReplaySet) Size

func (rs *ReplaySet) Size() int

Size returns the number of elements in the replay set.

type Router

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

Router is an onion router within the Sphinx network. The router is capable of processing incoming Sphinx onion packets thereby "peeling" a layer off the onion encryption which the packet is wrapped with.

func NewRouter

func NewRouter(dbPath string, nodeKey *btcec.PrivateKey, net *chaincfg.Params,
	chainNotifier chainntnfs.ChainNotifier) *Router

NewRouter creates a new instance of a Sphinx onion Router given the node's currently advertised onion private key, and the target Bitcoin network.

func (*Router) BeginTxn

func (r *Router) BeginTxn(id []byte, nels int) *Tx

BeginTxn creates a new transaction that can later be committed back to the sphinx router's replay log.

NOTE: The nels parameter should represent the maximum number of that could be added to the batch, using sequence numbers that match or exceed this value could result in an out-of-bounds panic.

func (*Router) ProcessOnionPacket

func (r *Router) ProcessOnionPacket(onionPkt *OnionPacket,
	assocData []byte, incomingCltv uint32) (*ProcessedPacket, error)

ProcessOnionPacket processes an incoming onion packet which has been forward to the target Sphinx router. If the encoded ephemeral key isn't on the target Elliptic Curve, then the packet is rejected. Similarly, if the derived shared secret has been seen before the packet is rejected. Finally if the MAC doesn't check the packet is again rejected.

In the case of a successful packet processing, and ProcessedPacket struct is returned which houses the newly parsed packet, along with instructions on what to do next.

func (*Router) ReconstructOnionPacket

func (r *Router) ReconstructOnionPacket(onionPkt *OnionPacket,
	assocData []byte) (*ProcessedPacket, error)

ReconstructOnionPacket rederives the subsequent onion packet. NOTE: This method does not do any sort of replay protection, and should only be used to reconstruct packets that were successfully processed previously.

func (*Router) Start

func (r *Router) Start() error

Start starts / opens the DecayedLog's channeldb and its accompanying garbage collector goroutine.

func (*Router) Stop

func (r *Router) Stop()

Stop stops / closes the DecayedLog's channeldb and its accompanying garbage collector goroutine.

type Tx

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

Tx is a transaction consisting of a number of sphinx packets to be atomically written to the replay log. This structure helps to coordinate construction of the underlying Batch object, and to ensure that the result of the processing is idempotent.

func (*Tx) Commit

func (t *Tx) Commit() ([]ProcessedPacket, *ReplaySet, error)

Commit writes this transaction's batch of sphinx packets to the replay log, performing a final check against the log for replays.

func (*Tx) ProcessOnionPacket

func (t *Tx) ProcessOnionPacket(seqNum uint16, onionPkt *OnionPacket,
	assocData []byte, incomingCltv uint32) error

ProcessOnionPacket processes an incoming onion packet which has been forward to the target Sphinx router. If the encoded ephemeral key isn't on the target Elliptic Curve, then the packet is rejected. Similarly, if the derived shared secret has been seen before the packet is rejected. Finally if the MAC doesn't check the packet is again rejected.

In the case of a successful packet processing, and ProcessedPacket struct is returned which houses the newly parsed packet, along with instructions on what to do next.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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