Commit Graph

640 Commits

Author SHA1 Message Date
Olaoluwa Osuntokun
c63c7cd22f
lnwallet: update Channel[Reservation+Contribution] for new funding flow
This commit updates the channel reservation workflow in order to
properly implement the new funding workflow defined in BOLT-0002.

The workflow itself hasn’t changed significantly, but the contents of
the contributions of both sides have. The bulk of the fields within the
contribution of both sides has been boiled down into a pointer to the
ChannelConfig which houses all the data required to handle all states
of the channel, and commitment state machine.

For the two portions which are dictated by the other party, we now add
builder-like modifiers to allow specifying the constraints after the
initial portion of the workflow.
2017-07-30 17:49:37 -07:00
Olaoluwa Osuntokun
e930af4b43
lnwallet: convert interface-level tests to be run as sub-tests 2017-07-30 17:49:34 -07:00
Olaoluwa Osuntokun
9c0261206d
lnwallet: modify the Signer interface to reflect new key derivation scheme
This commit modifies the Signer interface to reflect the new key
derivation defined within BOLT-0003. This entails removing the prior
PrivateTweak field all together in favor of two new fields: SingleTweak
and DoubleTweak.

These two fields are mutually exclusive. The SingleTweak field is now
required in order to sign all regular non-delay, and also must be used
to generate signatures for the localKey, or delayKey. The DoubleTweak
field is used to generate the private key that corresponds to the
revoked revocation key.
2017-07-30 17:49:31 -07:00
Olaoluwa Osuntokun
7b002175f4
lnwallet: update state hint derivation to match BOLT-0003 2017-07-30 17:49:28 -07:00
Olaoluwa Osuntokun
ca45ae7524
lnwallet: update TestCommitmentSpendValidation due to new commitment scripts 2017-07-30 17:49:25 -07:00
Olaoluwa Osuntokun
016f56e8e3
lnwallet: update TestRevocationKeyDerivation to use new derivation 2017-07-30 17:49:22 -07:00
Olaoluwa Osuntokun
44ffcf2156
lnwallet: add new test case to exercise singly tweaked key derivation 2017-07-30 17:49:19 -07:00
Olaoluwa Osuntokun
5b6cc5e92d
lnwallet: TestHTLCSenderSpendValidation for new HTLC scripts 2017-07-30 17:49:16 -07:00
Olaoluwa Osuntokun
7c035a4729
lnwallet: update TestHTLCSenderSpendValidation for new scripts 2017-07-30 17:49:13 -07:00
Olaoluwa Osuntokun
c4866723d1
lnwallet: add redemption+spend tests for the second-level HTLC txns 2017-07-30 17:49:09 -07:00
Olaoluwa Osuntokun
1a9ada4897
lnwallet: move stateHintTests global var into TestCommitTxStateHint 2017-07-30 17:49:06 -07:00
Olaoluwa Osuntokun
4e4375513d
lnwallet: update MaxHTLCNumber to precisely match the spec 2017-07-30 17:49:03 -07:00
Olaoluwa Osuntokun
71e47283cf
lnwallet: update size.go to add the weight of the success+timeout txns
This commit updates the constants in size.go to include the weight of
the HTLC success and timeout transactions. These values are required in
order to properly compute the fee required for a particular HTLC
transaction. The fee will change depending on if the HTLC is incoming
or outgoing.
2017-07-30 17:49:00 -07:00
Olaoluwa Osuntokun
360876944e
lnwallet: add new functions to generate + claim second-level HTLC txns
This commit adds a series of new functions that can be used to generate
the second level HTLC transactions, and also to claim the output
created by the transaction after a delay. The details of the scripts
and transaction format can be found in BOLT #3.
2017-07-30 17:48:56 -07:00
Olaoluwa Osuntokun
f70697bf71
lnwallet: update all witness gen funcs for receiver's HTLC scripts 2017-07-30 17:48:53 -07:00
Olaoluwa Osuntokun
4b1a7091e6
lnwallet: update public key scripts for the HTLC receiver's outputs
This commit updates all the pkScripts used within the commitment
transaction of the party that is on the reign side of an HTLC.

The major difference in these scripts as the prior generation’s is that
the claim action is now spared into a distinct transition. This clause
is guarded by a 2-of-2 multi-sig op code, which effecting creates an
off-chain covenant forcing the party claiming the transaction to incur
a delay before the funds can be swept.
2017-07-30 17:48:50 -07:00
Olaoluwa Osuntokun
d697c6ca9a
lnwallet: update the witness generation funcs for sender's HTLC output
This commit updates all the spendHtlcSpend* functions which are used to
spend each of the possible clauses within the HTLC contract placed on
the sender’s commitment transaction.
2017-07-30 17:48:47 -07:00
Olaoluwa Osuntokun
8f5129e08f
lnwallet: update public key scripts for the HTLC sender's commitment tx 2017-07-30 17:48:44 -07:00
Olaoluwa Osuntokun
0b9c117bbd
lnwallet: update key derivation for the commitment txn scheme
This commit updates the key derivation to match the derivation required
in order to construct and validate the commitment scheme that is used
within the draft specification of the Lightning Network. The new scheme
is very similar to the prior scheme aside from the following major
differences:
  * Each key (not just the revocation key) now changes with each state.
  * A commitment point (a component of the revocation key) is used to
randomize each key, and also generate new tweaked versions of the key.
   * Base points are used along with the commitment point to generate
the keys for the commitment transaction.
   * Before the remote party would send over the fully valid revocation
key. Now the remote party sends us a commitment point, which we then
use our local revocation base point to generate their revocation key.
2017-07-30 17:48:41 -07:00
Olaoluwa Osuntokun
13404243cf
lnwallet: revocation root generation is now based on a block hash + node key
This commit modifies the prior revocation root generation to a newer
version which is intended to allow for easy recovery of revocation
state. Rather than using the node’s keys (which we can’t count on NOT
to change), we instead now use the block hash as a salt. With this,
given the block hash prior to the one that funded the channel, and the
node’s identity key, we can reconstruct our revocation state.
2017-07-30 17:48:38 -07:00
Olaoluwa Osuntokun
14832d8c09
lnwallet+lnwire: minor grammatical fixes after UpdateFee merge 2017-07-14 17:10:42 -07:00
Johan T. Halseth
ebe05f6568 lnwallet: add update_fee message support.
This commit adds the possibility for the initiator of a
channel to send the update_fee message, as specified
in BOLT#2. After the message is sent and both parties
have committed to the updated fee, all new commitment
messages in the channel will use the specified fee.
2017-07-14 16:39:15 -07:00
bryanvu
7fbb1e5a37 lnwallet: refactor dust limit tests
Split up and simplified dust limit tests.
2017-07-06 18:05:43 -07:00
bryanvu
73767f8c78 lnwallet: factor createHTLC out of unit tests 2017-07-06 18:05:43 -07:00
bryanvu
5068541044 lnwallet: apply dust HTLC amounts to fees
If an HTLC’s value is below a node’s dust limit, the amount for that
HTLC should be applied to to the fee used for the channel’s commitment
transaction.
2017-07-06 18:05:43 -07:00
Andrey Samokhvalov
8fa2b95c12 lnd: remove seelog logger
The btclog package has been changed to defining its own logging
interface (rather than seelog's) and provides a default implementation
for callers to use.

There are two primary advantages to the new logger implementation.

First, all log messages are created before the call returns.  Compared
to seelog, this prevents data races when mutable variables are logged.

Second, the new logger does not implement any kind of artifical rate
limiting (what seelog refers to as "adaptive logging").  Log messages
are outputted as soon as possible and the application will appear to
perform much better when watching standard output.

Because log rotation is not a feature of the btclog logging
implementation, it is handled by the main package by importing a file
rotation package that provides an io.Reader interface for creating
output to a rotating file output.  The rotator has been configured
with the same defaults that btcd previously used in the seelog config
(10MB file limits with maximum of 3 rolls) but now compresses newly
created roll files.  Due to the high compressibility of log text, the
compressed files typically reduce to around 15-30% of the original
10MB file.
2017-06-25 14:19:56 +01:00
Olaoluwa Osuntokun
5dd7b157a0
lnwallet: fix race condition when forwarding by creating new pubkey
This commit fixes a race condition that would at times occur in the
htlcswitch.TestChannelLinkBidirectionalOneHopPayments test case. A race
condition would occur in the goroutine running ReceiveNewCommitment
compared with the grouting that would obtain the snapshot in order to
make a forwarding decision.

We fix this by creating a new public key for each new commitment
transaction such that we complete avoid the read/write race condition.
2017-06-19 17:43:57 +02:00
Olaoluwa Osuntokun
1be4d67ce4
multi: run all test instances in parallel 2017-06-17 01:00:07 +02:00
Olaoluwa Osuntokun
6937a42f2d
lnwallet: add new ShortChanID method to LightningChannel 2017-06-16 23:25:13 +02:00
Olaoluwa Osuntokun
2e05051176
lnwallet: clarify comment within commitment state sanity function 2017-06-08 22:25:06 -07:00
Olaoluwa Osuntokun
9676d476c9
lnwallet: fix race condition in channel state machine, use single mutex
This commit fixes a race condition that was discovered as a result of
the new htlcswitch package. The StateSnapshot method and all of the
other methods which mutate the state of the channel state machine were
using distinct mutexes. The fix is trivial: all methods accessing the
internal channel state variable now use the same mutex.
2017-06-08 22:24:20 -07:00
Olaoluwa Osuntokun
5e2381a64c
lnwallet: properly set FeeEstimator within integration tests 2017-06-07 17:22:46 -07:00
Olaoluwa Osuntokun
dc40662770
lnwallet/btcwallet: properly pass in FeeEstimator to btcwallet
This commit fixes a bug wherein the wallet would use the default relay
fee to craft transactions. On testnet, this might be insufficient or be
rejected all together in a mainnet setting. Therefore, we now pass in
the FeeEstimator interface and ensure that it’s consulted in order to
set the relay fee the wallet will use to craft transactions.

Note that this is a hold over until we have true dynamic fee
calculation within lnd which can then be extended to the internal
wallets.
2017-06-07 17:01:27 -07:00
Olaoluwa Osuntokun
9fd70958f4
multi: fix linter errors 2017-06-05 19:45:01 -07:00
Olaoluwa Osuntokun
91d4e6a377
lnwallet/btcwallet: fix duplicate imports 2017-06-05 19:41:12 -07:00
Olaoluwa Osuntokun
cbf7cd48f5
multi: update to latest neutrino API changes 2017-06-05 19:41:07 -07:00
Olaoluwa Osuntokun
467ccfde41
lnwallet: update interface test initiation for latest API change 2017-06-05 19:21:44 -07:00
Olaoluwa Osuntokun
3c5d856248
lnwallet: use current height as FundingBrodcastHeight during funding flow 2017-06-05 19:18:34 -07:00
Olaoluwa Osuntokun
54f849a62e
lnwallet: use the FundingBroadcastHeight as height hint for spend ntfns 2017-06-05 19:17:13 -07:00
Olaoluwa Osuntokun
7d62293d4a
lnwallet: remove GetTransaction method from BlockChainIO 2017-06-05 19:12:42 -07:00
Olaoluwa Osuntokun
0e8af209bd
lnwallet/btcwallet: update BlockChainIO implementation to be backend aware 2017-06-05 19:12:00 -07:00
Olaoluwa Osuntokun
aca729abfe
lnwallet/btcwallet: update btcwallet config to be aware of new chain interface 2017-06-05 19:10:08 -07:00
Alex
5746e764cb lnwallet: replace empty byte arrays with nils 2017-06-05 18:54:00 -07:00
Alex
b65f92abe2 lnwallet: ensure minimal OP_IF used everywhere. 2017-06-05 18:41:56 -07:00
Andrey Samokhvalov
79feebea80 channeldb: remove redudant test
After addition of the bidirectional payment test in htlcswitch packet,
which is more abstract, we may remove redudant test.
2017-05-31 11:06:08 -07:00
Andrey Samokhvalov
dbcce82d52 lnwallet: make DeriveRevocationRoot public
In order to be able to use the DeriveRevocationRoot in the createChannel
function inside the htlcswicth package we need to make it public.

NOTE: The original lnwallet.CreateChannel function haven't been
sufficient as far it not takes the private keys as input.
2017-05-31 11:06:08 -07:00
Andrey Samokhvalov
f774e3d9bf lnwallet: add missed addition of RHash
add rhash to the payment descriptor when receiving the settle htlc in
order to be able to pass it during settle htlc packet generation and
later find the user pending payment by rhash without additional hashing.
2017-05-31 11:06:08 -07:00
Andrey Samokhvalov
0e51b1d22d channeldb: add available balance function
In this commit we made state machine to be responsible for returning
proper available balance - amount of satoshi which we able to use at
current moment. This will help us in constrction channel link
abstraction.
2017-05-31 11:06:08 -07:00
Andrey Samokhvalov
fde27716d1 channeldb: add restriction to to use only half of the capacity locally
In this commit severe bug have been fixed which allows the state of the
nodes to be desychnorinesed in the moments of high htlc flow. We limit
the number of the htlc which we can add to commitment transaction
to half of the available capcity. This change fixes the bug when
commimtment transaction on the verge of being full, in this case race
condition might occures and remote htlc will be rejected, but at the
same time they will be added on remote side, the same situiation will
happen with htlc we have added, which cause the commitment transactions
to be different.
2017-05-31 11:06:08 -07:00
bryanvu
408be356fb lnwallet: update channel close to use fee estimation interface
This commit switches the channel close workflow to use the lnwallet fee
estimation interface rather than the hardcoded proposedFee.
2017-05-23 14:31:20 -07:00
bryanvu
514760f529 peer: handling for channel shutdown messages
This commit changes the cooperative channel close workflow to comply
with the latest spec. This adds steps to handle and send shutdown
messages as well as moving responsibility for sending the channel close
message from the initiator to the responder.
2017-05-23 14:31:20 -07:00
Olaoluwa Osuntokun
e689ef61dd
lnwallet: when calc'ing fee for commitment tx, use current fee-per-kw
This commit modifies the fee calculation logic when creating or
accepting a new commitment transaction to use the set FeePerKw within
the channel rather then re-query the estimator each time. The prior
behavior was benign as we currently use a static fee estimator, but the
dynamic setting this could’ve caused a state divergence.
2017-05-16 19:05:18 -07:00
Olaoluwa Osuntokun
82f591dbab
lnwallet: add TODO to properly roll dust outputs into initiator's paid fee 2017-05-16 19:02:52 -07:00
Olaoluwa Osuntokun
4ba01bb558
lnwallet: correct scaling for fee-per-byte to fee-per-weight, divide by 4
This commit corrects an error in the scaling as currently implemented
in the default static fee estimator. The spec draft has an error and
erroneously recommends multiplying by 4 to arrive at the fee-per-weight
from the fee-per-byte. This is incorrect as with the segwit block-size
increase, the ratio is 1/4 rather than 4.
2017-05-16 19:02:02 -07:00
Olaoluwa Osuntokun
c324b11b95
lnwallet: use distinct fee rate for funding transaction coin selection
This commit modifies the coin selection logic around selecting inputs
for a funding transaction to query the fee estimator directly (and use
fee-per-byte), rather than use the fee estimate which was passed into
the context.

We also use the value passed into the InitChannelReservation method
directly rather than make a call to the fee estimator. With this
change, the responder to a funding workflow will now properly adopt the
fee-per-kw suggested by the funder of the channel.
2017-05-16 19:00:27 -07:00
Olaoluwa Osuntokun
222385bf73
lnwallet: calcStaticFee now directly uses feePerKw 2017-05-16 18:56:46 -07:00
Olaoluwa Osuntokun
52942e4f13
lnwallet: NewChannelReservation now accepts target feePerKw for commitment 2017-05-16 18:55:33 -07:00
Olaoluwa Osuntokun
48850d31d6
lnwallet: simplify remote balance computation for single funder
The remote balance in the case of a single funder workflow is simply
what ever the pushSat amount is. The capacity - fundingAmt in this
scenario would always be zero, so we simply just set it directly to
pushSat.
2017-05-16 18:52:39 -07:00
Olaoluwa Osuntokun
392f6b5d8a
lnwallet: convert all references to transaction/block cost to weight 2017-05-16 18:50:55 -07:00
bryanvu
4ac7cc719f lnwallet: replace hard-coded fees and adjust tests accordingly
This commit replaces the hard-coded 5000 satoshi fees with calls to the
FeeEstimator interface. This should provide a way to cleanly plug in
additional fee calculation algorithms in the future. This change
affected quite a few tests. When possible, the tests were changed to
assert amounts sent rather than balances so that fees wouldn't need to
be taken into account. There were several tests for which this wasn't
possible, so calls to the static fee calculator were made.
2017-05-15 20:26:11 -07:00
bryanvu
abe2e502d5 lnwallet: add FeeEstimator interface, StaticFeeEstimator implementation
This commit adds the FeeEstimator interface, which can be used for
future fee calculation implementations. Currently, there is only the
StaticFeeEstimator implementation, which returns the same fee rate for
any transaction.
2017-05-15 20:26:11 -07:00
bryanvu
320bed7e6b lnwallet: add CommitFee field to OpenChannel
In order to cleanly handle shutdowns and restarts during state machine operation, the fee for the current
commitment transaction must be persisted. This allows the fee to be
reapplied when the current state is reloaded.
2017-05-15 20:26:11 -07:00
bryanvu
18f453a3e6 lnwallet: add dust limit to contribution
In order to make the node's dust limit available to the wallet during
the initial stages of the funding process, add and set a
DustLimit field in the Contribution.
2017-05-15 20:26:11 -07:00
bryanvu
74854963bf lnwallet: remove OP_CHECKSEQUENCEVERIFY variable
Primarily to avoid linting errors, the lnwallet.OP_CHECKSEQUENCEVERIFY
variable was removed and references to it replaced with
txscript.OP_CHECKSEQUENCEVERIFY.
2017-05-15 20:26:11 -07:00
bryanvu
c1769f959b lnwallet: fix failure messages, spacing in tests
This commit changes t.Fatal to t.Fatalf in TestCheckDustLimit so as to
provide more information. This commit also makes some column width
adjustments and minor spelling/formatting changes.
2017-05-15 20:26:11 -07:00
Olaoluwa Osuntokun
80598dff11
lnwallet: in closeObserver if commitment is is ours, exit early 2017-05-15 18:21:02 -07:00
Olaoluwa Osuntokun
d2585ae6e5
lnwallet: add new struct UnilateralCloseSummary to provide complete channel close details 2017-05-15 18:20:59 -07:00
Olaoluwa Osuntokun
34959e4648
peer+lnwallet: update API usage to recent channeldb changes 2017-05-14 19:23:57 -07:00
Olaoluwa Osuntokun
2486097554
discovery+lnwallet: fix tests by making mock notifiers compliant to new interface 2017-05-11 15:58:41 -07:00
Olaoluwa Osuntokun
1b4862d815
lnwallet: use new ChainNotifier API, typo fixes 2017-05-11 15:21:05 -07:00
Olaoluwa Osuntokun
a18d9b8449
lnwallet+routing: modify BlockChainIO.GetUtxo to be light client friendly
This commit modifies the GetUtxo method of the BlockChainIO interface
to be more light client friendly by introducing a height hint which
gives light clients that don’t have UTXO set commitments a way in which
they can restrict their search space. Light clients will now be able to
have a concrete cut off point in the chain as they scan backwards for
spentness of an output.
2017-05-11 15:20:29 -07:00
Olaoluwa Osuntokun
521c76d65a
lnwallet: add distinct channel to send close details over
This commit modifies the actions of the closeObserver goroutine to
utilize a _new_ channel to send channel close details over. The
original close signal channel is still used to notify observers that a
channel _has_ been closed, but this new channel will provide a single
observer with details w.r.t _how_ a channel was closed.
2017-05-04 17:39:24 -07:00
Olaoluwa Osuntokun
5e48cf1273
lnwallet: upon force close detection populate close summary 2017-05-04 17:39:22 -07:00
Olaoluwa Osuntokun
be583306ab
lnwallet: include the origin chanPoint in the ForceCloseSummary
This commit adds an additional field to the ForceCloseSummary that
allows observers of the channel that sends this struct to track _which_
channel the force close came from.
2017-05-04 17:39:20 -07:00
Olaoluwa Osuntokun
77ae9f560e
lnwallet: update DeleteState method to latest DB API change 2017-05-04 17:39:17 -07:00
bryanvu
0779ce59fe lnwallet: fix error propagation for funding messages
Previously, if an error was returned during handleSingleFunderSigs or
handleFundingCounterPartySigs, the wallet would hang waiting for
the completeChan channel to be populated. This commit adds nil returns for
the completeChan when errors are propagated.
2017-04-26 21:40:38 -07:00
Olaoluwa Osuntokun
c41d673c7b
lnwallet/btcwallet: update WalletController imp to latest btcwallet API 2017-04-23 19:19:22 -07:00
Olaoluwa Osuntokun
844cdba513
lnwallet/btcwallet: unlock wallet during startup, not creation
This commit modifies the way we go about unlocking the wallet. With the
latest changes to the API of btcwallet, we can on longer directly
access the waddrmgr struct. As a result, we’re now forced to go
_directly_ via the wallet to unlock the waddrmgr. The root
LightingWallet has been modified to not request the root key until we
finish starting the underlying wallet, so we can unlock the wallet in
the Start() method.
2017-04-23 19:17:59 -07:00
Olaoluwa Osuntokun
85b306bb48
lnwallet: fetch the root key during startup rather than on creation
This commit modifies the initialization logic of the LightningWallet to
fetch the root key during startup rather than during creation. We make
this change in order to give enough time for the underlying
WalletController to properly boot up before we ask it to do any work.
2017-04-23 19:15:30 -07:00
Olaoluwa Osuntokun
c4ea5e1e2c
lnwallet: save netParams within struct in constructor 2017-04-23 19:12:19 -07:00
Olaoluwa Osuntokun
c06894a2e6
lnwire: replace ChannelPoint with ChannelID, use new PendingChanID 2017-04-16 15:22:27 -07:00
Olaoluwa Osuntokun
4e988b228e
lnwallet/btcwallet: remove FundingSigner, implement MessageSigner
This commit removes the now deprecated FundingSigner struct as part of
the btcwallet package, and instead replaces it within an implementation
of the MessageSigner interface.
2017-04-14 11:08:24 -07:00
Olaoluwa Osuntokun
98c58ddb67
lnwallet: remove old deprecated MessageSigner struct 2017-04-14 11:00:06 -07:00
Olaoluwa Osuntokun
b226edf96e
lnwallet: introduce the MessageSigner interface
This commit introduces the MessageSigner interface which is an abstract
object capable of signing arbitrary messages with a target public key.
This interface will be used within the daemon for: signing channel
authentication proofs, signing node/channel announcements, and also to
possibly sign arbitrary messages in the future.
2017-04-14 10:59:19 -07:00
Olaoluwa Osuntokun
17d6835861
lnwallet: removed unused sync.RWMutex in PaymentDescriptor 2017-04-11 22:08:25 -07:00
Olaoluwa Osuntokun
31acace692
lnwallet: convert PendingUpdates to FullySynced
This commit improves the channel state machine by converting the
objective PendingUpdates method to a subjective FullySynced method
which is to be used in place of PendingUpdates. The new FullySynced
method is fully encompassing and replaces any upper state required by
the state machine which wraps this one.

The new FullySynced method is identical to PendingUpdates aside from
the fact that: it now also factors in the log message index of the
remote commitment chain, and also introduces a concept of an “owed
commitment”. A commitment chain owes a commitment if the height of the
local commitment chain is higher than that of the remote chain.
2017-04-11 22:02:33 -07:00
Olaoluwa Osuntokun
4cd277c8da
lnwallet: eliminate usage of LightningChannel.theirPrevPkScript
This commit removes the theirPrevPkScript field from the
LightningChannel struct all together. It’s no longer needed as the more
fundamental mutation bug has been fixed within the channel state
machine.
2017-04-11 22:02:30 -07:00
Olaoluwa Osuntokun
a3fd738491
lnwallet: fix HTLC mutation bug in commitment chain
This commit fixes a class of bug that can arise in the channel state
machine when a very high throughput workflow is attempted. Since the
PaymentDescriptor’s within a commitment pointed directly into the log,
any changes to a payment descriptor would also be reflected in all
other ones. Due to this mutation possibility, at times, the
locateOutputIndex method would fail since the HTLC’s pkScript was
modified, causing the channel to fail.

We fix this class of bug by simply ensure that once an HTLC has been
associated with a particular commitment, then it becomes immutable.
2017-04-11 22:02:26 -07:00
Olaoluwa Osuntokun
eca3a10064
lnwallet: reorder PaymentDescriptor attributes to reduce padding 2017-04-11 22:02:23 -07:00
Olaoluwa Osuntokun
0858d8a17d
lnwallet: fix constant overflow build issue on 32-bit systems
This commit fixes a build issue that appears when attempting to
cross-compile binaries to a 32-bit system from a 64-bit system. The
issue was that the defined max-state hint overflows a 32-bit integer. To
fix this issue, we now proeprly specify a type of a uint64 for the typed
constant.
2017-04-07 18:05:04 +02:00
Olaoluwa Osuntokun
a668aab478
lnwallet: couple websockets and wtxmgr logging into package logging
This commit bolsters the logging available within the lnwallet package
by include the logging from both web sockets connections, and the
wtxmgr as part of the exposed package level logging. With this, users
will gain additional avenues for obtaining debug logs from various
parts of the system.
2017-04-01 20:14:13 +02:00
Olaoluwa Osuntokun
ca053e5273
multi: minor coding style and comment clean ups post-discovery merge
This commit implements some minor coding style, commenting and naming
clean up after the recent major discovery service was merged into the
codebase.

Highlights of the naming changes:
* fundingManager.SendToDiscovery -> SendAnnouncement
* discovery.Discovery -> discovery.AuthenticatedGossiper

The rest of the changes consist primary of grammar fixes and proper
column wrapping.
2017-04-01 20:14:05 +02:00
Andrey Samokhvalov
a23715a9c7 lnwallet: add message signer
Added the signer which will be needed in the funding manager to sign
the lnwaire announcement message before sending them to discovery
package. Also in the future the message signer will be used to sign
the users data.
2017-03-29 19:49:05 -07:00
Olaoluwa Osuntokun
6b3a258e86
multi: fix formatting issues in packge README's 2017-03-27 16:25:25 -07:00
Olaoluwa Osuntokun
d6c863e2d1
lnwallet: initialize the height of both commitment chains independently
This commit fixes a slight oversight in the current state machine which
assumes that both commitment chains are always at the same height. In a
future where we move back to allowing nodes to pipeline commitment
updates, this will not always be the case.
2017-03-24 16:26:03 -07:00
Olaoluwa Osuntokun
a8671c485f
lnwallet: properly observe dust limits during cooperative chan closure
This commit fixes a lingering TODO within the wallet portion of the
codebase by properly adhering to the set dust limits when closing a
channel. With this new commit if a party’s current settled balance is
below their current dust-limit, then it will be omitted from the
commitment transaction.

The prior test that asserted negative outputs are rejected has been
removed as they’ll now be avoided by ensuring we omit dust outputs from
the commitment transaction.
2017-03-24 16:20:12 -07:00
Olaoluwa Osuntokun
2dd1c0de3d
lnwallet: adhere to project code-style in restoreStateLogs
This commit does some minor shuffling around and also adds some
additional comments to the restoreStateLogs method within the channel
state machine. After the latest merge in this area, the code has
diverged slightly from what’s considered typical within the rest of the
codebase.
2017-03-24 16:15:19 -07:00
Olaoluwa Osuntokun
c241892104
lnwallet: use full struct initialization for outputs in CreateCommitmentTx 2017-03-24 16:13:36 -07:00
Christopher Jämthagen
d958ea005f lnwallet: check for correct value in HTLC outputs in commitment transaction
It is possible that that there are multiple HTLCs with different values,
but the same public key script. As such, a check against the value should
be performed when looking for HTLC outputs in a commitment transaction.
2017-03-21 21:21:46 -07:00
Christopher Jämthagen
17d29ba62e lnwallet: properly restore public key scripts for HTLCs
Create a new helper method called genHtlcScript which will
generate the public key scripts for a supplied HTLC. This functionality
from addHTLC is removed, and addHTLC will instead call this new
method.

In restoreStateLogs we will regenerate the public key scripts for the
HTLCs with genHtlcScript and restore the proper values.
2017-03-21 21:21:46 -07:00
Christopher Jämthagen
e524b7ac81 test: change HTLC amount in persistent test to account for dust 2017-03-21 21:21:46 -07:00
Christopher Jämthagen
78e102f08d lnwallet: fix settled/cancelled HTLCs remote pkScripts + cleanup
When an HTLC is either cancelled or settled we must properly set the
pkScript for the HTLC on the remote commitment, such that we can
generate a valid ChannelDelta.
2017-03-21 21:21:46 -07:00
Christopher Jämthagen
2222df21f3 lnwallet: fix dust limit checks and toChannelDelta() handling of dust 2017-03-21 21:21:46 -07:00
Christopher Jämthagen
05a90df67a lnwallet: return error from toChannelDelta() if htlc output is not found 2017-03-21 21:21:46 -07:00
Christopher Jämthagen
9083007ece lnwallet: fix bug that retrieves incorrect pkScript in toChannelDelta()
Description of bug:
When calling ReceiveNewCommitment() we will progress through methods
fetchCommitmentView and addHTLC which will add HTLC outputs to the
commitment transaction in the local commitment chain and save the
pkScript to the relevant PaymentDescriptor which resides in the
corresponding updateLog. Finally the local commitment will be added
to the local commitment chain.

When the same user next calls SignNextCommitment we will again
progress through fetchCommitmentView and addHTLC. In addHTLC we will
now overwrite the pkScripts in the PaymentDescriptors with the
pkScript from the context of the remote commitment. When we later
call RevokeCurrentCommitment and proceed into toChannelDelta, we
will not be able to find the correct pkScript in the PaymentDescriptor
to match it against the outputs in the commitment transaction.
This will lead to the nested function locateOutputIndex returning
incorrect values.

Fixing the bug:
We introduce three new fields in PaymentDescriptor:
* ourPkScript
* theirPkScript
* theirPrevPkScript

ourPkScript will include the pkScript for the HTLC from the context
of the local commitment.

theirPkScript will take the value of the latest pkScript for the HTLC
from the context of the remote commitment.

theirPrevPkScript will take the second-latest pkScript for the HTLC
from the context of the remote commitment. This is the value we use
in toChannelDelta when we save a revoked commitment from our peer.

The appropriate value of these fields are set in the addHTLC method.

Additionally we pass a boolean value to toChannelDelta so we know
whether we are operating on a local or remote commitment and grab
the correct pkScript in locateUpdateIndex.
2017-03-21 21:21:46 -07:00
Christopher Jämthagen
4d03f60e40 lnwallet: handle duplicate payment hashes in toChannelDelta() 2017-03-21 21:21:46 -07:00
Olaoluwa Osuntokun
ec52c49b6c
lnd+lnwallet+glide: replace last lingering instances of fastsha256 2017-03-16 19:40:29 -07:00
Thomas Preindl
a1bb36730a lnd: fix typos in comments 2017-03-16 12:39:40 -07:00
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
Andrey Samokhvalov
7fcccff22a lnwallet: add TODO which asks to justifying strange import 2017-03-13 16:30:23 -07:00
Andrey Samokhvalov
fd97a4bd19 lnd: partially fix golint warnings 2017-03-13 16:30:23 -07:00
Andrey Samokhvalov
f2843dd4c9 lnd: fix gofmt warnings 2017-03-13 16:30:23 -07:00
Andrey Samokhvalov
8fb54782e2 lnd: fix gosimple warnings 2017-03-13 16:30:23 -07:00
Christopher Jämthagen
242c656fd6 lnwallet: use DefaultDustLimit() instead of hard-coded values 2017-03-09 15:32:31 -08:00
Christopher Jämthagen
810d8c286e test: add TestForceClose for lnwallet package 2017-03-09 15:32:31 -08: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
bryanvu
d911107ec6 fundingmanager: Update tests for funding manager persistence
This commit adds the FundingManagerPersistence test to ensure that the
funding process completes as expected when nodes shutdown after the the
funding transaction has been broadcast. Note that the final parts of
several wallet tests have been removed, as functionality has been moved
to the Funding Manager and should now be tested there.
2017-02-24 11:37:33 -08:00
bryanvu
e549a3f0ed fundingmanager: move final funding steps from wallet to funding manager.
Once a channel funding process has advanced to the point of broadcasting
the funding transaction, the state of the channel should be persisted
so that the nodes can disconnect or go down without having to wait for the
funding transaction to be confirmed on the blockchain.

Previously, the finalization of the funding process was handled by a
combination of the funding manager, the peer and the wallet, but if
the remote peer is no longer online or no longer connected, this flow
will no longer work. This commit moves all funding steps following
the transaction broadcast into the funding manager, which is available
as long as the daemon is running.
2017-02-24 11:37:33 -08:00
bryanvu
59763ebc7e channeldb: persist numConfsRequired in OpenChannel.
When a pending channel is persisted and then reloaded upon system startup
it's necessary to also persist the number of confirmations that will be required
before the pending channel can be opened.
2017-02-24 11:37:33 -08:00
bryanvu
3e02ea11ef channeldb: added isPending flag and queries
In order to facilitate persistence during the funding process, added
the isPending flag to channels so that when the daemon restarts, we can
properly re-initialize the chain notifier and update the state of
channels that were going through the funding process.
2017-02-24 11:37:33 -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
cf306098c5 lnwallet: extend test to check for valid locktime and sequence 2017-02-22 15:46:59 -08:00
Christopher Jämthagen
bdb38cafcc lnwallet: fix bug that makes commitment transaction unspendable
Introduce TimelockShift which is used to make sure the commitment
transaction is spendable by setting the locktime with it so that
it is larger than 500,000,000, thus interpreting it as Unix epoch
timestamp and not a block height. It is also smaller than the current
timestamp which has bit (1 << 30) set, so there is no risk of having
the commitment transaction be rejected. This way we can safely use
the lower 24 bits of the locktime field for part of the obscured
commitment transaction number.
2017-02-22 15:46:59 -08:00
Christopher Jämthagen
0410ea7374 test: Add table driven tests for script_utils
Add table-driven tests for testing GetStateHint and SetStateHint in package lnwallet.
2017-02-22 15:46:59 -08:00
Christopher Jämthagen
42b3b54e3c lnwallet: allow maximum state size to be used + tests
Add tests to assert maximum state can be used. Also test
that more than one input in the commitment transaction
will fail and that having state number larger than
maxStateHint will fail.
2017-02-22 15:46:59 -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
bd775b9bb3
lnwallet: ensure reservation state is cleaned up in case of Cancel
This commit fixes a bug in the wallet’s internal reservation manager
that prevented it from cleaning up the resources used by a reservation
after it was finished running through the workflow.

We fix this issue by ensuring the reservations context is deleted from
the funding limbo.

It is the callers responsibility to properly .Cancel() a reservation in
the case of an error during the funding workflow.
2017-02-22 14:51:41 -08:00
Olaoluwa Osuntokun
d759e05a1c
lnwallet: fix failure to exit early in openChannelAfterConfirmations 2017-02-22 14:51:35 -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
caa464f33b
lnwallet: update channel state machine tests to latest changes
This commit updates the set of channel state machine tests to properly
compile and execute with the latest set of changes to the state
machine.

Most of the changes within this commit are just renaming and field
changes as a result of the new wire messages.

The more substantial change is due to the change in semantics of the
new state machine w.r.t what has and has not been ACK’d when a new
state transition is implemented. In the case of a concurrent update
(both sides add to the log before a state transition), both sides need
to trigger  a state update in order to ensure their updates have been
included.
2017-02-21 01:43:18 -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
Olaoluwa Osuntokun
384fe61e73
multi: fix go vet warnings throughout code base 2017-02-16 19:33:19 +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
1da054625b
lnwallet/btcwallet: fix bug in non-recognition of self-funds in chan force close
This commit fixes a bug which would cause the node on the _receiving_
side of a channel force close to be blind of their immediately funds
on-chain. The root of the issue was that within the btcwallet
implementation of the WalletController method ‘NewRawKey’, the wallet
wouldn’t request notifications for the new address, as the direct
function from the waddrmgr was used which skips registration of the new
address.

To fix, this, we now ensure that btcwallet will receive notifications
for keys used within the raw p2wkh commitment output. This ensures that
the wallet is aware of funds that are made available as a result of a
channel force closure by the channel counter party.
2017-02-07 20:01:19 -08:00
Olaoluwa Osuntokun
a9078562ac
lnwallet/btcwallet: fix bug in ordering of change vs regular addresses 2017-02-07 19:55:54 -08:00
Olaoluwa Osuntokun
a393362eb8
lnwallet: ensure CSV delay witness spend uses a minimal OP_IF
This commit fixes a slight scripting related issue as a result of
default policy in Bitcoin Core 0.13.1. With this version of Bitcoin
Core, nodes will now enforce a policy that ensures the first argument
of OP_IF is either an empty vector or a 0x01 value. Our current sent of
functions to generate the witness for the delay clause of the
commitment transaction instead uses a 0x00 value rather than an empty
byte vector.

With this commit we fix the issue by ensuring that we use an empty
vector rather an 0x00 for forcing the commitment delay script pathway.
2017-02-03 15:28:19 -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
Olaoluwa Osuntokun
de70175be6
lnwallet+funding: properly propagate NewLightningChannel errors
This commit ensures that we now properly handle and propagate errors
that arise when attempting to create a new channel after the funding
transaction is believed to be confirmed.

A previous edge case would arise when a user attempted to create a new
channel, but their corresponding btcd node wasn’t yet fully synced.
2017-01-22 15:06:41 -08:00
Trevin Hofmann
40c7bac3aa multi: fix a variety of typos throughout the repo 2017-01-17 17:02:56 -08:00
Olaoluwa Osuntokun
e60f40b845
lnwallet: fix bug with funding channels with 50/50 balances
This commit fixes a prior bug in the wallet triggered by the creation
of a channel using the single funder workflow, but pushing exactly
*half* of the channel over to the other side. The prior logic to
determine who the initiator would result in a disagreement over who
created the channel initially. This wouldn’t manifest until the channel
was attempted to be closed cooperatively. As both side disagreed about
who created the channel they would apply the closing fee to different
outputs, thereby creating mismatched closing transaction. The signature
would fail to validate as the closer will create a different
transaction from that of the responder.

This commit fixes the issue by properly detecting who initially created
the channel.
2017-01-16 20:28:38 -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
Trevin Hofmann
a13ac90d46 multi: add link to LICENSE in README license badges (#100) 2017-01-12 16:31:08 -08:00
Christopher Jämthagen
95888613d0 multi: minor fixes for README's 2017-01-11 15:50:22 -08:00
Olaoluwa Osuntokun
4ccdad0d66
multi: add README's for all sub-packages 2017-01-10 15:02:37 -08:00
Olaoluwa Osuntokun
285ba711a1
lnwallet: add support for the push-during-funding workflow
This commit adds support to the wallet’s internal funding workflow for
pushing a certain amount of BTC to the responder’s side for a single
funder workflow as part of the first commitment.
2017-01-09 18:58: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
4e53cf8b49
lnwallet: correct error message in txn subscription test 2017-01-07 21:20:47 -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
5957725975
lnwallet: mine enough blocks to activate CSV+segwit in reservation tests 2017-01-05 13:20:37 -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
473f298524
lnwallet/btcwallet: fix bug in GetUtxo for BlockChainIO implementation
This commit fixes an unnoticed bug within btcwallet’s implementation of
the BlockChainIO interface, specifically the GetUtxo method. In order
to maintain compatibility with Bitcoin Core’s gettxout method, btcd
doesn’t return an error if the targeted output is actually spent.

We weren’t properly detecting this, but we do now by creating a new
error which is returned in the case of a nil error but a nil return
value.
2016-12-27 16:44:27 -08:00
Olaoluwa Osuntokun
0313dcfc89
lnwallet: thread through tx conf details in ChannelReservation.DispatchChan()
This commit slightly modifies the channel reservation workflow to
expose the new information conerning the exact confirmation location of
the channel provided by the ChainNotifier. The DispatchChan() method of
the ChannelReservation now also returns the blockHeight and txIndex
where the transaction was ultimately confirmed. This information will
be needed by the fundingManager so it can properly generate the
authenticated channel announcement proofs.
2016-12-27 16:44:03 -08:00
Olaoluwa Osuntokun
4a0a657eb0
lnwallet/btcwallet: fix bug in implementation of GetUxo
This commit fixes a bug within the btcwallet implementation of the
BlockChainIO interface. The exact nature of the bug was a rounding
error that would only manifest if the value of the UTXO was below 1
BTC.

The tests within this package currently test channels with mostly whole
values of BTC, as a result the bug went unnoticed until now.

The fix itself is trivial: convert to an int64 AFTER performing the
multiplication to convert to satoshis from Bitcoin.
2016-12-27 16:43:51 -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
Olaoluwa Osuntokun
b49d2827a2
lnwallet/btcwallet: add compile-time interface assertions for Signer+BlockChainIO 2016-12-27 16:43:31 -08:00
Olaoluwa Osuntokun
782fc61dc1
lnwallet+lnrpc: convert GetCurrentHeight to GetBestBlock in BlockChainIO
This commit expands the data returned by the current GetCurrentHeight
to also return the current best block hash, expanding the method into
GetBestBlock. Additionally, the current best BlockHash is also now
displayed within the GetInfo RPC call.
2016-12-27 16:43:26 -08:00
Olaoluwa Osuntokun
597b4ee3d3
channeldb: Open is no longer dependant on a specific set of chain params 2016-12-27 16:43:19 -08:00
Olaoluwa Osuntokun
ddc1eb4c8a
lnwallet: correct comment for logging object 2016-12-27 16:43:07 -08:00
Andrey Samokhvalov
1119d75996
lnwallet: add additional BlockChainIO methods 2016-12-27 16:43:05 -08:00
Olaoluwa Osuntokun
e3e2ba342c
lnwallet: properly set nodeAddr during channel reservation init
This commit fixes a lingering bug within the channel funding
reservation workflow that caused the address of a channel counter-party
to not be written to disk, resulting in an error on start up. To fix
this, we now properly populate the node’s TCP address when initiating
the reservation.
2016-12-14 17:49:18 -08:00
Andrey Samokhvalov
d01f1b5ff4 fundingmanager+lnwallet: add HTLC dust limit logic 2016-12-13 11:01:57 -08:00
Andrey Samokhvalov
202fce5501 channeldb: add TheirDustLimit and OurDustLimit fields in OpenChannel 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
85defc3ec3
lnwallet: add new method IsSynced to the WalletController interface
This commit adds a new method to the WalletController interface:
IsSynced. The role of the function is to query the local wallet about
if it thinks it has fully synced to the tip of the current main chain.
This function can be useful within U.I’s to block off certain
functionality until the wallet is fully synced to the main chain.
2016-12-12 15:56:33 -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
e942e70651
lnwallet: extend the SignDescriptor to include a PrivateTweak
This commit extends the SignDescriptor with a single attribute, the
‘PrivateTweak’. The duties of the Signer interface have also been
augmented to properly derive a private key using the specified tweak,
iff it’s non-nil.

As currently defined in order to generate the proper private key based
off of a PrivateTweak, the signer is to add the tweak value to the
private key for the specified public key. This generated value is to be
used for signing within the specified context.

This change paves the way for automatic revoked output sweeping with
signatures generated directly by the Signer interface, maintaining the
structure of the abstraction.

A test has been added at the interface level in order to excerise each
WalletController’s implementation of the key derivation as currently
defined.
2016-11-18 17:12:58 -08:00
Olaoluwa Osuntokun
c81e0a3ebb
lnwallet: convert CommitSpendRevoke+CommitSpendNoDelay to use Signer
This commit converts the rearming two commitment spend functions to use
the lnwallet.Signer interface directly rather than manually manage
private keys during the signing process. This commit is in preparation
for implementation of fully automated revoked uncooperative closure
detection and retribution.
2016-11-18 15:23:50 -08:00
Olaoluwa Osuntokun
22074eb737
lnwallet: integrate obfuscated state hints into funding workflow
This commit finalizes the implementation of #58 by integrating passing
around the obfuscate state hints into the funding workflow of the
wallet, and also the daemon’s funding manager.

In order to amend the tests, the functions to set and receive the state
hints are now publicly exported.
2016-11-16 12:54:39 -08:00
Olaoluwa Osuntokun
3010412bbc
lnwallet: set initiator and channel type during reservation creation 2016-11-16 12:51:27 -08: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
fef927e276
lnwallet: correct good comments on state hint helper funcs 2016-11-14 18:37:20 -08:00
Olaoluwa Osuntokun
d43ef24ed3
lnwallet: add utility functions for obfuscated commitment state hints
This commit adds two utility functions along with corresponding tests
for adding obfuscated state number hints to each commitment
transaction.

Such a feature reduces the search time to recover the necessary
material to punish a counterpaty for broadcasting an invalid state from
O(N), to O(1), where N is the number of states in the channel’s
transcript. By encoding the obsfucated state number, either side is
able to quickly obtain the ncessary state to excerise “justice”.
2016-11-14 18:35:10 -08:00
Olaoluwa Osuntokun
6e01bb72b0
lnwallet+peer: minor typo fixes 2016-11-14 15:06:17 -08:00
Olaoluwa Osuntokun
4113260f9f
lnwallet: minor comment correction 2016-11-10 17:38:59 -08:00
Olaoluwa Osuntokun
81f7efe1e0
lnwallet+funding: include node net address in reservation workflow
This commit modifies the existing channel reservation workflow slightly
to thread through the IP address that we were able to reach the node
at, or the one which the node reached us via. Additionally, rather than
using OpenChannel.FullSync() at the end of the reservation workflow, we
now use OpenChannel.FullSyncWithAddr() in order to create the
relationship in the database between the channel, and the p2p node we
created the channel with.

All tests, as well as a portion of the fundingManager have been updated
accordingly,
2016-10-26 14:56:58 -07: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
Olaoluwa Osuntokun
5d6b8e49a3
lnwallet: disallow creating a funding reservation with zero total satoshis 2016-10-23 19:27:20 -07:00
Andrey Samokhvalov
19d8abade8 config: add --pendingchannel lnd flag 2016-10-22 02:11:18 +03: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
bea555e61d
lnwallet: add tests for SubscribeTransactions and ListTransactionDetails 2016-10-15 14:12:23 -07:00
Olaoluwa Osuntokun
628224a5ee
lnwallet/btcwallet: concretely implement the new TransactionSubscription interface
This commit returns the BtcWallet wrapper struct back to conformance to
the WalletController interface by adding support for
SubscribeTransactions.

The implementation of the lnwallet.TransactionSubscription consists
simply of a proxy goroutine which forwards notifications from the
wallet’s internal NotificaitonServer.
2016-10-15 14:11:25 -07:00
Olaoluwa Osuntokun
2eb1936cce
lnwallet: extend the WalletController with a new txn pub/sub client
This commit adds a new simple interface related to the WalletController
which allows for subscribing to new notifications as transactions
relevant to the wallet are seen on at the network and/or mined. The
TransactionSubscription interface will prove useful for building higher
level UI’s on-top of the daemon which update the presentation layer in
response to received notifications.
2016-10-15 14:07:24 -07:00
Olaoluwa Osuntokun
617716ce9a
lnwallet/btcwallet: implement ListTransactionDetails
This commit implements the new ListTransactionDetails method within
btcwallet’s concrete implementation of the WalletController interface.
Both mined and unmined transactions are currently returned via the same
method. Unmined transactions are indicated by their lack of an
inclusion block hash and lack of confirmations.
2016-10-14 20:16:00 -07:00
Olaoluwa Osuntokun
78cfcc28b7
lnwallet: add method to list relevant txns to WalletController interface 2016-10-14 20:14:15 -07:00
Olaoluwa Osuntokun
85b2b52a5f
lnwallet: add concrete type for coin selection fail during funding workflow 2016-09-26 12:18:03 -07:00
Olaoluwa Osuntokun
0013b804c0
lnwallet: display target+current amount when coin selection fails for funding txns 2016-09-26 11:52:56 -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
7310d0a0f7
lnwallet: remove extraneous logging messages 2016-09-21 19:48:46 -07:00
Olaoluwa Osuntokun
49ce1040d4
lnwallet: adopt simple fee structure for commitment transactions
This commit modifies the prior funding workflow to account for fees
when creating the funding output. As a stop gap, the current fee for
the commitment transaction is now hard-coded at 5k satoshis. Once the
fee models are in place this should instead be some high multiple of
the current “average” fee rate within the network, continuing, the
proper fee should be adjusted from the commitment transaction has
outputs are added/removed.
2016-09-12 19:08:01 -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
024deb93f3
lnwallet: modify btcwallet's SignOutputRaw method to get proper pubkey
This commit slightly modifies btcwallet’s SignOutputRaw method to work
properly in the case that the pkScript of the output being spent isn’t
one of the template pkScripts (p2pkh, multi-sig, etc). Rather than
examining the address, we now attempt to find the private key which
matches the public key passed within the sign descriptor.
2016-09-12 19:07:24 -07:00
Olaoluwa Osuntokun
f972378140
lnwallet: modify CommitSpendTimeout to expect proper input sequence num and tx version 2016-09-12 19:07:20 -07:00
Olaoluwa Osuntokun
e858bb5ca2
lnwallet: convert CommitSpendTimeout to user the Signer interface 2016-09-12 19:07:12 -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
6684f6aedf
channeldb: implement commitment state update log
This commit implements a state update log which is intended the record
the relevant information for each state transition on disk. For each
state transition a delta should be written recording the new state. A
new method is also provided which is able to retrieve a previous
channel state based on a state update #.

At the moment no measures has been taken to optimize the space
utilization of each update on disk. There are several low-hanging
fruits which can be addressed at a later point. Ultimately the update
log itself should be implemented with an append-only flat file at the
storage level. In any case, the high level abstraction should be able
to maintained independent of differences in the on-disk format itself.
2016-09-12 19:06:44 -07:00
Olaoluwa Osuntokun
e536e1afb1
lnwallet: eliminate flaky assert within integration tests
This commit removes a flaky assertion within the interaction tests. Due
to differences in final coin selection across tests due to the
pseudo-random nature of map iterations, a single output might be
selected rather than two as we previously expected.

Additionally a duplicate test has been removed, and the locked output tests
simplified a bit.
2016-09-08 13:10:51 -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
Olaoluwa Osuntokun
99fdb3a3a9
lnwallet: modify elkrem root derivation, derive from root HD seed
This commit modifies the elkrem root derivation for each newly created
channel. First a master elkrem root is derived from the rood HD seed
generated from private wallet data. Next, a HKDF is used with the
secret being the master elkrem root.
2016-09-08 12:25:49 -07:00
Olaoluwa Osuntokun
564316a846
lnwallet: publicly export several functions within script_utils.go 2016-09-08 12:25:44 -07:00
Olaoluwa Osuntokun
044b65317a
lnwallet: remove setup.go
This file is no longer needed as each implementation of the
WalletController is expected to handle its own set up via an instance
of the WalletDriver factory struct.
2016-09-08 12:25:40 -07:00
Olaoluwa Osuntokun
773c831561
lnwallet: replace naive coin selection a size+fee aware version 2016-09-08 12:25:36 -07:00
Olaoluwa Osuntokun
6a1d8d0682
lnwallet: add a BtcWallet implementation of WalletController
This commit adds the first concrete implementation of the
WalletController interface: BtcWallet. This implementation is simply a
series of wrapper functions are the base btcwallet struct.

Additionally, for ease of use both the BlockChain IO and Signer
interface are also implemented by BtcWallet. Finally a new WalletDriver
implementation has been implemented, and will be register by the init()
method within this new package.
2016-09-08 12:25:32 -07:00
Olaoluwa Osuntokun
5449ba2b34
lnwallet: revamp interfaces, add BlockChainIO and Singer
This commit revamps the previous WalletController interface, edging it
closer to a more complete version.

Additionally, this commit also introduces two new interfaces:
BlockchainIO, and Singer along with a new factor driver struct, the
WalletDriver.

This BlockChainIO abstracts read-only access to the blockchain, while
the Singer interface abstracts the signing of inputs from the base
wallet paving the way to hardware wallets, air-gapped signing, etc.

Finally, in order to provide an easy method for selecting a particular
concrete implementation of a WalletController interface, the concept of
registering “WalletDriver”s has been introduced. A wallet driver is
essentially the encapsulation of a factory function capable of create a
new instance of a Wallet Controller.
2016-09-08 12:25:28 -07:00
Olaoluwa Osuntokun
a87ddeabdc
lnwallet: remove interaction with the btcutil.coinset package
This commit removes the wrapper functions used to rely on the coinset
package for coin selection. In a future commit the prior behavior will
be replaced by a custom coin selection implementation which estimates
the size of the funding transaction.
2016-09-08 12:25:24 -07:00
Olaoluwa Osuntokun
8bbd010f74
lnwallet: use the ChainNotifier interface throughout instead of BtcdNotifier
This commit refactors the code within lnwallet interacting with the
ChainNotifier to accept, and call against the implementation rather
than a single concrete implementation.

LightningWallet no longer creates it’s own BtcdNotifier implementation
doing construction, now instead accepting a pre-started `ChainNotifier`
interface.  All imports have been updated to reflect the new naming
scheme.
2016-09-01 19:13:19 -07:00
Olaoluwa Osuntokun
04e7a88a83
lnwallet: fix bug in lockTimeToSequence function
This commit fixes a bug in the lockTimeToSequence function when mapping
a block-based relative lock time to the proper sequence number.

Applying the mask isn’t necessary since the values are expected to be
blow 65K blocks.
2016-08-25 16:25:32 -07:00
Olaoluwa Osuntokun
4104a9bcde
lnwallet: never create zero-value outputs within the commitment transaction 2016-07-27 12:15:50 -07:00
Olaoluwa Osuntokun
c0614c0478
lnwallet: add basic tests for cooperative channel closure
This commit adds a basic test for cooperative channel closure. The
current test ensures correctness of the cooperative closure procedure
initiated by either the channel initiator, or the channel responder.
2016-07-27 11:32:35 -07:00
Olaoluwa Osuntokun
e01dd7f18d
lnwallet: properly make channelState an enum by using iota 2016-07-27 11:29:49 -07:00
Olaoluwa Osuntokun
8a56fbf196
lnwallet: switch name of package logger to avoid module collision 2016-07-27 11:29:07 -07:00
Olaoluwa Osuntokun
c8e58147b6
add glide dependency management for fully reproducible builds
This commit adds glide integration in order to make lnd builds fully
reproducible. Rather than using “go get” users should now manually pull down
the repo, use glide to fetch+install the dependancies, then manually install
all related binaries.

With this change we no longer have to chase dependancies making breaking API
changes under us. We can manually update the managed dependancies once a new
stable release of a defendant package is released.

Additionally, reproducible builds are a strong requirement in order to securely
distribute future major releases of lnd.
2016-07-22 18:53:35 -07:00
Olaoluwa Osuntokun
2bb65a3fb8
lnwallet: add PendingUpdates method to channel state machine
This commit adds a new method, “PendingUpdates” to the channel state
machine which is intended to be a source to give callers a hint as to
when an additional commitment signature should be sent independent of
any request/response book keeping.
2016-07-21 16:52:18 -07:00
Olaoluwa Osuntokun
4063171918
lnwallet: partition state update logs within channel state machine
This commit patrons the state update logs properly within the channel
state machine. This change fixes a number of bugs caused by treating a
central log as two logically distinct logs. Rather than having a bit
indicating if the entry is incoming/outgoing, an entry is added to a
remote or local log depending on which modification method is used.

As a result the code is much easier to follow due to separation of
concerts.

Finally, when attempting to sign a new update with an exhausted
renovation window a distinct error is returned in order to allow higher
level callers to properly back-off and handle the protocol event.
2016-07-21 16:50:38 -07:00
Olaoluwa Osuntokun
b60270f3f7
lnwallet: include htlcs to settle in returned set of htlc's to forward
This commit fixes a slight bug in the channel state machine’s code
executed when processing a revocation messages. With this commit after
processing a revocation, log entries which we should forward to the
downstream or upstream peer for settling/adding HTLC’s are now properly
returned.

The testa have also been updated to ensure to correct htlc’s are
returned “for forwarding”.
2016-07-16 18:12:49 -07:00
Olaoluwa Osuntokun
2c303a1879
lnwallet: AddHTLC now returns log index of created log entry 2016-07-16 18:02:09 -07:00
Olaoluwa Osuntokun
a14246c5bb
lnwallet: use two-value read from conf channel to detect closure 2016-07-14 16:17:10 -07:00
Olaoluwa Osuntokun
7dea354711
lnwallet: properly handle HTLC settles in channel state-machine
We no longer track HTLC’s by their r-hash within the log into the
index, as we may have multiple HTLC’s that can be redeemed by the same
pre-image. Instead we now use a separate index which is keyed by a
log-index.

Additionally, the SettleHTLC method now also returns the index of the
HTLC being settled which allows the remote party to quickly locate the
HTLC within their log.

This commit also introduces a few trace/debug log messages which will
likely be pruned in the near future
2016-07-12 17:35:57 -07:00
Olaoluwa Osuntokun
06f062e678
lnwallet: sync revocation state after receiving a revocation 2016-07-12 17:32:42 -07:00
Olaoluwa Osuntokun
14d669dfd1
lnwallet: decrease initial revocation window to 4 2016-07-12 17:31:01 -07:00
Olaoluwa Osuntokun
94c242073a
lnwallet: finish initial draft of LightningChannel state machine
This commit finishes the initial draft of the commitment state machine.
A full re-write of the prior protocol which combines aspects of the
former ‘lnstate’ package has replaced the prior un-finished
stop-and-wait protocol.

This new protocol is designed to operate in an asynchronous environment
and to facilitate non-blocking batched and pipelined updates to the
committed channel states. The protocol is also de-synchronized meaning
that either side can propose new commitment states independent of the
actions of the other party.

The state machine implemented is very similar to that of c-lightning,
however we allow multiple unrevoked commentates in order to minimize
blocking, and also to reduce latency across several hops in a
bi-directional setting.

The current implementation consists of 3 main data structures: a
commitment chain which consist of unrevoked commitment transactions
(one for each side), and a (mostly) append-only log of HTLC updates
shared between both sides. New commitments proposed index into the log
denoting which updates they include, this allows both parties to
progress chains independent of one another. Revoked commitments, reduce
the length of the chain by one, and free up space within the revocation
window.

At this point only basic tests are in place for the state machine,
however more extensive testing infrastructure along with formal proofs
using PlusCall are planned.
2016-07-05 17:02:03 -07:00
Olaoluwa Osuntokun
8775107454
lnwallet: keep commitments cold at all times, store sig instead
This commit changes prior behavior which stored a “hot” commitment
transaction, meaning one which all the sigScript fully assembled and
able to be broadcast.

Instead, we now store the current signature for our commitment
transaction as a separate field within the database and within memory.
As a result, this eliminates a class of bugs which would erroneously
broadcast a fully loaded commitment transaction, either leading to a
loss of funds, or suspending availability to funds for a period of
time.
2016-07-05 16:55:47 -07:00
Olaoluwa Osuntokun
f03122e697
lnwallet: correct comment in revoke derivation explanation 2016-07-05 16:49:27 -07:00
Olaoluwa Osuntokun
2c187209eb
lnwallet: update internal wallet reservations to use revoke keys
This update the wallet to implement the new single funder workflow
which uses revocation keys rather than revocation hashes for the
commitment transactions.
2016-06-30 12:13:50 -07:00
Olaoluwa Osuntokun
1b490c52ed
lnwallet: createCommitTx now a revocation key 2016-06-30 12:12:19 -07:00
Olaoluwa Osuntokun
d85719b5a7
lnwallet: add elkrem root derivation function
The derivation is current bed on an HKDF invocation using our private
key as the secret, and the node’s channel multi-sig key as the salt.
This scheme allows us to derive the key on the fly given data known to
only us and the remote node.

The current derivation is just a place-holder and will be re-visited at
a later time.
2016-06-30 12:09:42 -07:00
Olaoluwa Osuntokun
78346c81e7
lnwallet: update reservation workflow to revoke keys
With this commit, the reservation workflow for the single funder use
case is now aware of the usage of revocation keys.

The changes are relatively minor:
  * contributions now have RevocationKeys instead of RevocationHashes
  * CompleteReservationSingle now takes the initiators revocation key
2016-06-30 12:02:51 -07:00
Olaoluwa Osuntokun
f3a6f8ffe6
lnd: implement the sendcoins RPC request
This commit implements the “send coins” RPC request which was
introduced at both the lnrpc and command line level in a prior commit.

A small refactoring has taken place w.r.t to sendmany+sendcoins in
order to eliminate some code duplication.
2016-06-29 11:31:34 -07:00
Olaoluwa Osuntokun
e22734f9cf
lnwallet: update HTLC+commitment scripts
This commit updates the previous HTLC and commitment scripts to their
current latest evolution.

The HTLC scripts have been optimized for space savings, the
functionality itself has remained relatively unchanged. A trade off was
made to add additional bytes into the sigScript in order to avoid
extraneous CHECKSIG’s. The rationale is that an extra 1-2 bytes in the
sigScript to guide execution, are worthwhile since they’re in the
witness, and witness data may be pruned in the near future.

The primary change is within the commitment transaction itself. Instead
of using revocation hashes, we now use signature based revocation. This
saves space in the Script, and optimizes away an extra hashing
operation. Elkrem/shachain is still used but, we now use the pre-images
to homomorphically derive a public key which the other party will be
able to sign with, once we disclose the pre-image itself.

Finally, we have switched to using SHA-256 everywhere uniformly for
both revocation hashes, and payment hashes. The rationale is that the
output of ripemd160 is too small for modern security margins, and that
other coins/chains are more likely to have SHA-256 implemented, than
ripemd160.

A set of tests has also been included which contain (mostly) exhaustive
tests of all possible redemption paths for both commitment and HTLC.
2016-06-27 11:35:32 -07:00
Olaoluwa Osuntokun
ac8736ff99
lnwallet: convert commitment no-delay output to p2wsh 2016-06-27 11:21:13 -07:00
Olaoluwa Osuntokun
05fb9b5a6d
lnwallet: payment and revocation hashes are now 32 bytes
This unifies some inconstancies across the code-base with hashes being
32 vs 20 bytes. All hashes, whether payment or revocation are now
uniformly 32 bytes everywhere. As a result, only OP_SHA256 will be used
within commitment and HTLC scripts. The rationale for using sha256
instead of hash160 for the HTLC payment pre-image is that alternative
chains are more likely to have sha256 implemented, rather than
ripemd160.

A forthcoming commit will update the current commitment, and HTLC
scripts.
2016-06-26 23:04:14 -07:00
Olaoluwa Osuntokun
77a006f03b
lnwallet: ChannelPoint() now returns a pointer to outpoint 2016-06-22 22:15:13 -07:00
Olaoluwa Osuntokun
e17bdf08ea
lnwallet: expose db channel deletion+snapshotting 2016-06-22 22:12:37 -07:00
Olaoluwa Osuntokun
31e5466692
lnd: introduce the fundingManager
This commit introduces the fundingManger which is used as a bridge
between the wallet’s internal ‘ChannelReservation’ workflow, and the
wire protocol’s funding messages.

 The funding manger is responsible for progressing the workflow, and
communicating any errors generated during the workflow back to the
source peer.
2016-06-21 13:13:49 -07:00
Olaoluwa Osuntokun
25577b6cd5
lnwallet: add test cases for single funder workflow
This commit adds additional test cases to test both cases (initiator vs
responder) for a single funder channel workflow. Additionally, the
previous dual funder tests have been extended in order to detect proper
funding channel broadcast, and the ChainNotifier’s role in notifying
upstream callers that a funding transaction has been embedded in the
chain at a sufficient depth.

At this point the tests certainly need to be cleaned up. bobNode should
be replaced with a second instance of the wallet modeling a remote
peer.
2016-06-21 13:13:45 -07:00
Olaoluwa Osuntokun
3a14fe8ba5
lnwallet: add support for single funder workflow
This commit modifies the existing workflow to add additional paths to
be used when on the responding side of a single funder workflow.

Additionally, several bugs encountered within the existing dual funder
workflow logic have been fixed, and modified to account for the wallet
being on the igniting side of a single funder workflow.
2016-06-21 13:13:41 -07:00
Olaoluwa Osuntokun
4a6a2d6cd4
lnwallet: correct inputs scripts for nested P2SH spend
The previous logic incorrectly assumed the returned address was already
a p2wkh address. Instead, a p2sh address was returned. So we now
correctly craft both the sigScript and witness stack for a nested p2sh
spend.
2016-06-21 13:13:33 -07:00
Olaoluwa Osuntokun
d52955b146
lnwallet: extract coin selection to distinct method
This is required since for single funder channels, we don’t contribute
any funds so we don’t need to select any change or coins for input into
the funding transaction.
2016-06-21 13:13:29 -07:00
Olaoluwa Osuntokun
e62fc414cb
lnwallet: add single funder workflow to ChannelReservation
This commit adds 3 methods to lnwallet.ChannelReservation intended to
facilitating a single funder channel workflow between two nodes. A
single funder workflow is characterized as the initiator committing all
the funds to a channel, with the responder only providing public keys,
and a revocation hash.

The workflow remains the same for the initiator of the funding
transaction, however for the responder, the following methods are
instead called in order:
  * .ProcessSingleConribution()
  * .CompleteSingleContribution()
  * .FinalizeReservation()

These methods are required for the responder as they are never able to
construct the full funding transaction, and only receive the out point
of the funding transaction once available.
2016-06-21 13:13:26 -07:00
Olaoluwa Osuntokun
45236fa092
lnwallet: implement cooperative closure for LightningChannel
A cooperative closure of a LightningChannel proceeds in two steps.
First, the party who wishes to close the channel sends a signature for
the closing transaction. Next, the responder reconstructs the closing
transaction identically as the initiator did using a canonical
input/output ordering, and the currently settled balance within the
channel. At this point, the responder then broadcasts the closure
transaction. It is the responsibility of the initiator to watch for
this transaction broadcast within the network to clean up any resources
they committed to the active channel.
2016-06-21 13:13:22 -07:00
Olaoluwa Osuntokun
27e6839060
lnwallet: publicly export constructor for LightningChannel 2016-06-21 13:13:18 -07:00
Olaoluwa Osuntokun
507520cda9
lnwallet: move channelState from channeldb to channel.go 2016-06-21 13:13:14 -07:00
Olaoluwa Osuntokun
fcff17c336
multi: change all imports to roasbeef's forks
This commit will allow the general public to build lnd without jumping
through hoops setting up their local git branches nicely with all of
our forks.
2016-05-15 17:22:37 +03:00
Olaoluwa Osuntokun
c6eedafb9a
lnwallet: update reservation workflow to be segwitty
Only nested p2sh or pure witness outputs are used when selecting coins
for inputs to a funding transaction.

The funding transaction output now uses p2wsh rather than regular p2sh.

All tests have been updated accordingly.
2016-05-03 20:06:58 -07:00
Olaoluwa Osuntokun
4b4c0f73b0
lnwallet: add ListUnspentWitness for funding tx coin selection 2016-05-03 20:06:49 -07:00
Olaoluwa Osuntokun
0e74672797
lnwallet: use InputScripts struct within ChannelReservation
This allows the reservation workflow to support pure witness program
outputs, as well as witness programs nested within p2sh.
2016-05-03 20:06:44 -07:00
Olaoluwa Osuntokun
eeb2887fe9
lnwallet: segwit-ify all scripts and signing utils 2016-05-03 20:06:39 -07:00
Olaoluwa Osuntokun
163eb8dcb8
lnwallet: remove FundingType enum
Removing as segwit is now the path forward.
2016-05-03 20:06:30 -07:00
Tadge Dryja
71231c477c make imports lowercase 2016-04-30 20:24:57 -07:00
Olaoluwa Osuntokun
1a96e4f7a6 lnwallet: default to p2wkh address for generated change+delivery addresses 2016-04-24 20:27:56 -07:00
Olaoluwa Osuntokun
0e607c1939 lnwallet: during shutdown properly wait for all goroutines to exit 2016-04-24 12:39:43 -07:00
Olaoluwa Osuntokun
1e35018e89 lnwallet: fix compile errors against btcd's segwit branch 2016-04-12 21:37:08 -07:00
Olaoluwa Osuntokun
f9a8dcbc9c lnwallet: add ListUnspentWitness to WalletController
This method has been added in order to allow lnd to collect eligible
unspent witness programs outputs from the wallet controller for use as
inputs to the funding transaction.

Additionally, the change address functions now also specify whether the
generated change address should be payable to a witness program or not.
2016-04-12 21:36:41 -07:00
Olaoluwa Osuntokun
10d52611cd lnwallet: introduce WalletController interface as a "base wallet"
The WalletController will serve as a layer of separation between “base”
Bitcoin wallet logic, and the higher level Lightning Network logic. As
a result LightningWallet will no behave as an overly wallet, relying on
the lower wallet for basic services such as new address, signing etc.

Within this higher level lies the awareness of channel types, chain
monitoring, HTLCs, and so on.
2016-03-24 16:19:57 -07:00
Olaoluwa Osuntokun
7420503c7a lnwallet: publicly export WaddrmgrEncryptorDecryptor 2016-03-24 14:32:44 -07:00
Olaoluwa Osuntokun
082a8a34e3 lnwallet: update tests and workflow to new OpenChannel struct 2016-03-24 00:01:35 -07:00
Olaoluwa Osuntokun
983294c444 lnwallet: set OpenChannel's internal db pointer 2016-03-24 00:01:17 -07:00
Olaoluwa Osuntokun
4b16763f4d lnwallet: update channel.go to new OpenChannel fields
Simply to compile, channel.go will be replaced with lnstate soon
enough.
2016-03-24 00:00:59 -07:00
Olaoluwa Osuntokun
fe6d71e95e lnwallet: accept channeldb as a param in constructor
lnwallet is no longer responsible for creating/opening channeldb. The
call is now expected to do so.
2016-03-22 18:48:18 -07:00
Olaoluwa Osuntokun
8feb86c4aa multi: create lnd's logging infrastructure 2016-03-22 18:43:10 -07:00
mkl
e07086a523 Integrate basic configuration functionality 2016-03-22 13:28:56 -07:00
Olaoluwa Osuntokun
1944003fde lnwallet: update to use new btcdnotify.NewBtcdNotifier API 2016-02-26 17:38:31 -08:00
Olaoluwa Osuntokun
25c1b7a491 lnwallet: update chainNotifier assignment to new BtcdNotifier constructor 2016-02-26 17:38:31 -08:00
Tadge Dryja
0d3639435f can sync with segnet in hard mode
lots of changes but they seem to work
2016-02-15 22:13:17 -08:00
Olaoluwa Osuntokun
ab16933575 lnwallet: commit tx should have final sequence num 2016-02-05 20:24:32 -08:00
Olaoluwa Osuntokun
81a4887d11 lnwallet: move lockTimeToSequence to script_utils.go 2016-02-05 20:24:17 -08:00
Olaoluwa Osuntokun
fa05ee9a22 lnwallet: move pubKey comparison for funding output spend into spendMultiSig func
* This change makes the spendMultiSig function testable independent of
the reservation workflow.
2016-02-05 12:33:22 -08:00
Olaoluwa Osuntokun
4632894562 lnwallet: move teardown of rpctest before setup to ensure proper cleanup
* Previously, if the call to SetUp(..) returned an error, then the test
harness would fail to stop the running bcd process, and clean up the
test directories. This would cause any subsequent tests to fail. This
commit remedies this scenario.
2016-02-05 12:32:23 -08:00
Olaoluwa Osuntokun
1a8ae48807 lnwallet: point rpctest at my in-progress fork+branch
Fixes compilation issues for those not using my laptop :)
2016-02-03 12:05:53 -08:00
Olaoluwa Osuntokun
daeecd5fc0 lnwallet: nuke most of setup.go, no longer needed w/ wallet.Loader 2016-02-03 12:01:45 -08:00
Olaoluwa Osuntokun
b3cdc6167f lnwallet: switch over to using btcwallet's new Loader type
Allows us to remove a lot of duplicated code pertaining to wallet
setup. We also gain hooks into the wallet to trigger callbacks once the
wallet is created/opened.
2016-02-03 12:01:45 -08:00
Olaoluwa Osuntokun
92c14c99c3 lnwallet: update tests to utilize the in-progress btcsuite/btcd/rpctest package
Instead of creating “fake” utxos for bob, and alice. We now employ a
dedicated mining node to hand out utxos, and generate blocks with hand
picked transactions.
2016-02-03 12:01:44 -08:00
Olaoluwa Osuntokun
7bebefbd8f lnwallet: fix script bug, ensure sigScript is set before verification 2016-02-03 12:01:44 -08:00
Olaoluwa Osuntokun
74ee5334f4 lnwallet: allow configurable net param for wallet create/open 2016-02-03 12:01:44 -08:00
Olaoluwa Osuntokun
98bbd314a7 lnwallet: add active Bitcoin network to config 2016-02-03 12:01:44 -08:00
Olaoluwa Osuntokun
80ce49a883 lnwallet: update btcwallet and chain.Client to new upstream API's
A major change for btcwallet adding a new RPC wallet, refactoring parts
of the wallet, and introducing new functionality has been introduced.
This commit updates lnwallet to the API changes. A future commit will
change lnwallet to use some of the new functionality such as the
notification server, etc.
2016-02-03 12:01:44 -08:00