Commit Graph

113 Commits

Author SHA1 Message Date
Olaoluwa Osuntokun
f217093c00
multi: replace usage of fastsha256 with crypto/sha256
This commit removes all instances of the fastsha256 library and
replaces it with the sha256 library in the standard library. This
change should see a number of performance improvements as the standard
library has highly optimized assembly instructions with use vectorized
instructions as the platform supports.
2017-03-15 18:56:41 -07:00
Andrey Samokhvalov
ee2379775c lnd: fix golint warning which requires to add additional comments 2017-03-13 16:30:23 -07:00
Christopher Jämthagen
a6a503bf28 lnwallet: ForceCloseSummary should check if to-local output exists
If the value of the to-local output is below the dust limit, the
ForceCloseSummary should not include a sign descriptor for this output.

We also find the proper to-self output by looking for the expected public
key script and not assume that no HTLC outputs exist.
2017-03-09 15:32:31 -08:00
Christopher Jämthagen
52b56b8cf2 lnwallet+test: no dust outputs in commitment transaction + tests
Currently non-HTLC outputs will be accepted in the commitment
transaction as long as it is non-zero. We change this by not allowing
outputs with a value lower than the dust limit. The value of such
an output will go towards transaction fees.
2017-03-09 15:32:31 -08:00
Olaoluwa Osuntokun
fc54c5d8d8
lnwallet: perform sanity check on cooperative closure transacitons
This commit fixes a class of bug that currently exists within the
cooperative closure methods for the channel state machine. As an
example, due to the current hard coded fees, if one of the outputs
generated within the generated closure transaction has a negative
output, then the initiating node would gladly forward this to the
remote node. The remote node would then reject the closure as the
transaction is invalid. However, the act of completing the closure
would cause the remote node’s state machine to shift into a “closed”
state. As a result, any further closure attempts by the first node
(force or regular) would go unnoticed by the remote node.

We fix this issue by ensuring the transaction is “sane” before
initiating of completing a cooperative channel closure.

At test case has been added exercising the particular erroneous case
reported by “moli” on IRC.
2017-02-27 21:00:25 -06:00
Olaoluwa Osuntokun
8283ff2da6
lnwallet: during cooperative closure don't shift status until end
This commit avoids a class of bug wherein the state of the channel
would be marked as closing enough though an error occurred somewhere in
the function. The bug was due to the fact that the channel `status` was
shifted before any actual logic within the function(s) were executed.

We fix this bug by _only_ shifting the channel status once the function
has completed without any error.
2017-02-27 20:52:30 -06:00
Olaoluwa Osuntokun
f0c13c5a15
lnwallet: expose a NextRevocationKey method in channel state machine
This commit adds a new method to the channel’s state machine:
NextRevocationKey. This method is being added in preparation for the
upcoming change to switch to the commitment transaction format outlined
in the spec. When this comes to pass, the ExtendRevocationWindow method
will be removed, as it will no longer be needed.

The NextRevocationKey method will be needed as to conform to the spec,
we’ll need to send the next revocation key within the `fundingLocked`
message.
2017-02-24 16:31:48 -08:00
Olaoluwa Osuntokun
9adc5f6484
lnwallet+channeldb: update callers to shachain API changes 2017-02-24 16:31:45 -08:00
Andrey Samokhvalov
f86557c3e4 channeldb+lnwallet: replace elkrem with shachain
In this commit the initial implementation of revocation hash
generation 'elkrem' was replaced with 'shachain' Rusty Russel
implementation which currently enshrined in the spec. This alghoritm has
the same asymptotic characteristics but has more complex scheme
to determine wish hash we can drop and what needs to be stored
in order to be able to achive full compression.
2017-02-22 16:49:29 -08:00
Christopher Jämthagen
873211c02f Use 48-bit commitment transaction numbers
Fix SetStateNumHint and GetStateNumHint to properly
set and get the stateNumHints using the lower 24 bits
of the locktime of the commitment transaction as the
lower 24 bits of the obfuscated state number and the
lower 24 bits of the sequence field as the higher 24
bits.
2017-02-22 15:46:59 -08:00
Olaoluwa Osuntokun
75787b3e4d
lnwallet: use spew when logging logging retribution 2017-02-21 01:43:39 -08:00
Olaoluwa Osuntokun
f2e077c10c
lnwallet: account for de-sync'd channels within closeObserver
This commit adds an additional case of the closeObserver that will
properly handle the case of a channel being closed by a de-sync’d
commitment transaction from the PoV of the local node. In the case of a
minor 1-state divergence, the commitment transaction broadcast by the
remote node will be 1 state ahead of the commitment transaction we have
locally. This should be seen as a regular unilateral close as they
remote peer didn’t violate the channel contract in any way.

We address this case by changing the `==` to a `>=`.
2017-02-21 01:43:27 -08:00
Olaoluwa Osuntokun
0e0e207802
lnwallet: update state machine to the version within the spec
This commit updates the internal channel state machine to the one as
described within the spec and currently implemented within the rest of
the other Lightning implementations.

At a high level the following modifications have been made:
    * When signing we no loner include the index of the remote party’s
log
      that our signature covers. Instead we include ALL of our current
      updates, but only the updates of the remote party that we’ve
ACK’d.
    * A pending change is considered ACK’d once a revocation message
      has been received, locking in the changes in the remote party’s
      commitment transaction.
   * When sending a new commitment, we remember the index of our
     log at that point so we can mark that portion of the log as ACK’d
     once we receive a revocation message from the remote party.
   * When receiving a new commitment signature, we include ALL of
     the remote party’s changes that we’ve received but only our set
     of changes that’ve been ACK’d by the remote party.
   * Implicitly a revocation message now also implicitly serves to ACK
     all the changes that were included in the CommitSig message
     received before it.

The resulting change is a rather minor diff. However, with this state
machine it’s important to note that the order to sig/revoke messages
has been swapped. A proper exchange now looks like the following:
    * Alice -> Add, Add, Add
    * Alice -> Sig
    * Revoke <- Bob
    * Sig <- Bob
    * Alice -> Revoke

One other thing that’s worth noting is that with this state machine,
since what’s included in an update is implicit, both side may need to
at times send a new commitment update in the case of a concurrent state
transition initiated by both sides.

Finally, all counters/indexes have been made 64-bit integers in order
to properly match the spec.
2017-02-21 01:43:15 -08:00
Olaoluwa Osuntokun
6cf905088c
lnwallet: create new updateLog abstraction within channel state machine
This commit adds a new struct to the channel state machine: updateLog.
updateLog encapsulates the update log linked list itself, a series of
new counters we’ll need in order to switch to the spec’s state machine
and also the index into the log itself. This new struct serves to
simplify much of the logic surrounding the update log and also
elminates a bit of code duplication within the current state machine.

This commit only adds the new struct. The rest of the state machine
will be updated in a later commit to use the new log and its new
counters.
2017-02-21 01:43:13 -08:00
Olaoluwa Osuntokun
39f0300995
lnwallet: add godoc comments to a channel's updateTypes 2017-02-21 01:43:10 -08:00
Olaoluwa Osuntokun
a9416300e5
lnwallet: ensure that total satoshi sent/received aren't counted twice
This commit fixes a bug in the LightingChannel commitment state machine
which could occasionally result in the total number of satoshis sent or
received being counted twice if a redundant state transition were
initiated.

To fix this bug, we now only increment the number of satoshi
sent/recv’d iff it’s the first time the HTLC has been processed.
2017-02-21 01:43:07 -08:00
Olaoluwa Osuntokun
fb9bf054cc
lnwallet: cancel the spend notification when a channel's closeObserver exits
This commit ensures that when a channel’s closeObserver is signaled to
exit before a channel closure has been detected, then the resources
dedicated to the pending spend notification can be freed up.
2017-02-21 01:43:04 -08:00
Christopher Jämthagen
a2403d9c07 lnwallet: optimize PaymentDescriptor lookup on HTLC state transitions
rHashMap is used to store the PaymentDescriptor belonging to a received
HTLC's revocation hash. This improves the efficiency of looking up
PaymentDescriptors from their RHash whenever we want to settle or cancel
that HTLC.
2017-02-08 18:22:01 -08:00
Olaoluwa Osuntokun
62bcd59db4
lnwallet: add ability to cancel the channel's closeObserver
This commit adds the ability to cancel a channel’s internal
closeObserver goroutine by adding a new public facing Stop method.

Additionally, we now make passing a ChainNotifier interface completely
optional. If the ChainNotifier isn’t passed in as a constructor, then
the closeObserver goroutine will never be launched. This new feature
lets the caller ensure that only a single closeObsever for any given
channels exists.
2017-02-02 17:11:03 -08:00
Olaoluwa Osuntokun
f4b403679b
lnwallet: remove BlockChainIO as a dependency to LightningChannel
This commit removes the BlockChainIO interface as a dependency to the
LightningChannel struct as the interface is no longer used within the
operation of the LightningChannel.
2017-02-02 17:05:40 -08:00
Trevin Hofmann
40c7bac3aa multi: fix a variety of typos throughout the repo 2017-01-17 17:02:56 -08:00
Olaoluwa Osuntokun
55f89be10f
lnwallet+lnd: ensure curve parameters are set to avoid panics
This commit fixes a bug introduced by the past attempt to Make Logging
Great Again. Since we unset the curve parameters when reading/writing
the messages, if we have a lingering reference that’s active elsewhere
in the daemon, then we’ll modify that reference. To fix this, we now
explicitly set the Curve parameters in two areas.

A similar commit has been pushed to lightning-onion.
2017-01-14 19:44:37 -08:00
Olaoluwa Osuntokun
ae72475612
lnwallet: create channel close summary when commitment broadcast detected
This commit modifies the closeObserver goroutine to ensure that a close
summary has been inserted into the database before signalling any
observers that a unilateral channel closure was detected. This fixes a
slight bug where a peer would force close a channel, but we wouldn’t
properly detect that and clean up the channel state if had a failed
cooperative channel closure.
2017-01-14 18:01:28 -08:00
Olaoluwa Osuntokun
c451258fd2
lnwallet: properly detect initiator cooperative close in closeObserver
This commit modifies the logic of the closeObserver slightly to not
incorrectly mark the broadcast of the commitment transaction triggered
by a cooperative channel closure as an unprompted broadcast.
2017-01-12 18:30:07 -08:00
Olaoluwa Osuntokun
c9dbaa1403
lnwallet: include r-hash of canceled htlc in log entry for cancel
This commit modifies the logic around adding cancel entries to the
update log for the commitment state machine slightly by also including
the r-hash of the HTLC that’s been cancelled in the entry for the
cancellation. With this change, we can accurately track which HTLC is
being cancelled within outer sub-systems.
2017-01-07 21:22:01 -08:00
Olaoluwa Osuntokun
9bb5a45f89
lnwallet: the canceller of an HTLC targets by payment hash not index
This commit alters the new HTLC cancellation logic to instead allow the
canceller of an HTLC to cancel the HTLC by the payment hash rather than
the index of the HTLC.
2017-01-07 21:20:57 -08:00
Olaoluwa Osuntokun
fd0c0574e6
lnwallet: add send/recv of HTLC cancellations to state machine
This commit adds the ability to send/recv HTLC cancellation to the
commitment state machine. Previously this feature had been
unimplemented within the state machine, with only adds/settles working.

With this change, there’s now now no concept of “timing” out HTLC’s,
only the cancellation of HTLC’s which may be triggered for various
reasons.
2017-01-07 21:20:51 -08:00
Olaoluwa Osuntokun
5affed38fc
multi: update btcsuite API's to latest upstream changes
This commit makes a large number of minor changes concerning API usage
within the deamon to match the latest version on the upstream btcsuite
libraries.

The major changes are the switch from wire.ShaHash to chainhash.Hash,
and that wire.NewMsgTx() now takes a paramter indicating the version of
the transaction to be created.
2017-01-05 13:56:34 -08:00
Olaoluwa Osuntokun
0585ed93be
lnwallet: use in-memory height within channel's closeObserver
This commit partially rectifies a quick hack that was previously thrown
in to address an issue discovered due to possible state inconsistencies
between an active channel object and the daemon’s breachAbrbiter.

A prior commit has modified the interaction between the peer and the
breachArbiter to eliminate the state in consistency. Therefore, we no
longer need to access the database to ensure that we’re observing the
latest channel state in order to correctly make a decision about
whether a broadcast commitment transaction is a breach or not.
2016-12-27 16:45:10 -08:00
Olaoluwa Osuntokun
4790ce96a8
lnwallet: public expose funding keys in channel state machine
This commit modifies the attributes of the LightningChannel struct to
publicly expose the funding keys used within the channel for the local
and remote party. Exposing these keys publicly will allow callers to
use the keys involved to generate authenticated channel advertisements
for the routing layer.
2016-12-27 16:43:34 -08:00
Andrey Samokhvalov
d01f1b5ff4 fundingmanager+lnwallet: add HTLC dust limit logic 2016-12-13 11:01:57 -08:00
Andrey Samokhvalov
5a82240c6a lnwire+lnwallet+fundingmanager: general improvements 2016-12-13 11:01:57 -08:00
Olaoluwa Osuntokun
e0c09a016b
lnwallet: use stored initiator bool to properly construct close tx
This commit modifies the channel closing logic to remove the hard coded
bools indicating which side is attempting the closure. With the recent
changes, the initiator must always pay the channel closure fees.

This information is recently stored on disk, therefore we can use the
boolean to ensure that the closure transaction is created properly no
matter who initiates the close.

This fixes a bug.
2016-12-07 22:39:33 -08:00
Olaoluwa Osuntokun
494fcec874
breacharbiter: introduce new sub-system to watch for breaches
This commit introduces a new sub-system into the daemon whose job it is
to vigilantly watch for any potential channel breaches throughout the
up-time of the daemon. The logic which was moved from the utxoNursery
in a prior commit now resides within the breachArbiter.

Upon start-up the breachArbiter will query the database for all active
channels, launching a goroutine for each channel in order to be able to
take action if a channel breach is detected. The breachArbiter is also
responsible for notifying the htlcSwitch about channel breaches in
order to black-list the breached linked during any multi-hop forwarding
decisions.
2016-11-28 19:44:09 -08:00
Andrey Samokhvalov
da3028e10c lnwallet: add HTLC count validation 2016-11-23 20:02:29 -06:00
Andrey Samokhvalov
391d5cd401 lnwallet: add commitment transaction estimation 2016-11-23 20:02:29 -06:00
Andrey Samokhvalov
5b9e4ae61e general: fix typos, rename variables, add comments 2016-11-23 20:02:29 -06:00
bryanvu
faf9daddf6 lnwallet: calculate channel's total satoshis sent and received
When HTLCs are settled, the channel’s TotalSatoshisSent and
TotalSatoshisReceived fields are updated.
2016-11-22 14:57:03 -06:00
Olaoluwa Osuntokun
cc63db0aee
lnwallet: add detection+handling of contract breaches in channel
This commit adds detection of contract breaches within the commitment
state-machine for a channel. A contract breach is defined as the event
wherein a channel counter-party broadcasts a previously revoked
commitment transaction. Such an event immediately closes a channel as
the funds are now in a state of dispute.

Once a breach is detected, a snapshot of the breached state is
retrieved from the database’s revocation log. This snapshot is then
used to generate the revocation leaf used within this particular state
along with all the other information ncessary to sweep ALL active funds
within the channel. This information is encapsulated within the
BreachRetribution struct which is sent over a new channel dedicated to
sending/receiving BreachRetributions.
2016-11-21 00:54:45 -06:00
Olaoluwa Osuntokun
188811cf05
lnwallet: populate the output index of an HTLC in ChannelDeltas
This commit modifies the logic within the state machine to properly
populate the new field of `OutputIndex` which the HTLC stored within a
channel delta.

With this change, in the future we’ll be able to quickly locate a
particular HTLC output in the scenario that the commitment transaction
has been broadcast on-chain and we need to sweep it. Allocating a few
extra bytes on-disk saves us from the guess-and-check logic+code
required otherwise.
2016-11-20 23:54:24 -06:00
Olaoluwa Osuntokun
2d884618aa
lnwallet: ensure all channel state machine methods are thread-safe
This commit adds some necessary locking to ensure that all updates to
the internal state of the commitment state machine are fully serial and
thread-safe. This change is required to ensure future actions w.r.t
taking action once a revoked commitment transaction has been broadcast
are not carried out while the channel’s state is being updated.
2016-11-20 23:33:27 -06:00
Olaoluwa Osuntokun
74122a0901
lnwallet: encode obfuscated state hints in the commitment tx
This commit modifies the channel state machine slightly to encode the
current state number using 30-bits of the sequence number within the
commitment transaction’s only input.

Such a modification reduces up the processing time required to punish
the counter party for breaching the contract established within the
channel by broadcasting an older revoked state.

This fixes #58 with a minor modification to what was originally
suggested.
2016-11-16 12:49:44 -08:00
Olaoluwa Osuntokun
4113260f9f
lnwallet: minor comment correction 2016-11-10 17:38:59 -08:00
Olaoluwa Osuntokun
e1d9d9c8d2
lnwallet: update to adhere to new channeldb API change
This commit modifies the lnwallet code and related tests in order to
adhere to the recent field-name change to channeldb.OpenChannel.
Instead of having the field ‘TheirLNID’ which is the sha256 of the
node’s public key, we now instead use the public key directly in all
contexts.
2016-10-25 16:41:22 -07:00
Andrey Samokhvalov
14c6770b76 general: fix typos 2016-10-22 01:48:05 +03:00
andrew.shvv
e515710a7d multi: use witnessScript everywhere instead of redeemScript
This commit consists of a mass variable renaming to call the pkScript being executed for segwit outputs the `witnessScript` instead of `redeemScript`. The latter naming convention is generally considered to be reserved for the context of BIP 16 execution. With segwit to be deployed soon, we should be using the correct terminology uniformly through the codebase. 

In addition some minor typos throughout the codebase has been fixed.
2016-10-15 16:02:09 -07:00
Olaoluwa Osuntokun
9d5b0885d4
lnwallet/channel: add r-preimages to the PaymentDescriptor for settles 2016-09-21 19:49:07 -07:00
Olaoluwa Osuntokun
d0353b2864
lnwallet: add ability to trigger a force closure within channel state machine
This commit introduces the concept of a manually initiated “force”
closer within the channel state machine. A force closure is a closure
initiated by a  local subsystem which broadcasts the current commitment
state directly on-chain rather than attempting to cooperatively
negotiate a closure with the remote party.

A force closure returns a ForceCloseSummary which includes all the
details required for claiming all rightfully owned outputs within the
broadcast commitment transaction.

Additionally two new publicly exported channels are introduced, one
which is closed due a locally initiated force closure, and the other
which is closed once we detect that the remote party has executed a
unilateral closure by broadcasting their version of the commitment
transaction.
2016-09-12 19:07:35 -07:00
Olaoluwa Osuntokun
affd7793b3
lnwallet: add htlc persistence, state log restoration to channel state machine
This commit adds full persistence logic of the current lowest
un-revoked height within each commitment chain. The newly added
channeldb methods for record state transitions within both commitment
chains are now utilized. This un-settled HTLC state is now read upon
initialization, with the proper log entries inserted into the state
update log which reflect the garbage collected log right before the
restart.

A new set of tests have been added to exercise a few edge cases around
HTLC persistence to ensure the in-memory log is properly restored based
on the on-disk snapshot.
2016-09-12 19:07:04 -07:00
Olaoluwa Osuntokun
671098325d
lnwallet: refactor all wallet/channel interaction to use the WalletController.
This commit performs a major refactor of the current wallet,
reservation, and channel code in order to call into a WalletController
implementation rather than directly into btcwallet.

The current set of wallets tests have been modified in order to test
against *all* registered WalletController implementations rather than
only btcwallet. As a result, all future WalletControllers primary need
to ensure that their implementation passes the current set of tests
(which will be expanded into the future), providing an easy path of
integration assurance.

Rather than directly holding the private keys throughout funding and
channel creation, the burden of securing keys has been shifted to the
specified WalletController and Signer interfaces. All signing is done
via the Signer interface rather than directly, increasing flexibility
dramatically.

During channel funding, rather than creating a txscript.Engine to
verify commitment signatures, regular ECDSA sig verification is now
used instead. This is faster and more efficient.

Finally certain fields/methods within ChannelReservation and
LightningChannel have been exposed publicly in order to restrict the
amount of modifications the prior tests needed to undergo in order to
support testing directly agains the WalletController interface.
2016-09-08 12:25:54 -07:00