Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTLCs #27

Draft
wants to merge 15 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions .github/workflows/publish_master.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,4 @@ jobs:
if: startsWith(matrix.os, 'ubuntu')
run: |
dotnet pack ./src/DotNetLightning.Core -p:Configuration=Release --version-suffix date`date +%Y%m%d-%H%M`-git-`echo $GITHUB_SHA | head -c 7` -p:Portability=True
dotnet nuget push ./src/DotNetLightning.Core/bin/Release/DotNetLightning.1*.nupkg -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json

- name: Upload nuget packages (native)
run: |
bash -c "dotnet pack ./src/DotNetLightning.Core -p:Configuration=Release --version-suffix date$(date +%Y%m%d-%H%M).git-$(git rev-parse --short=7 HEAD)-${{ matrix.RID }}"
bash -c "dotnet nuget push ./src/DotNetLightning.Core/bin/Release/DotNetLightning.Core.1*.nupkg -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json"
dotnet nuget push ./src/DotNetLightning.Core/bin/Release/DotNetLightning.Kiss.1*.nupkg -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json
28 changes: 12 additions & 16 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
MIT License
AGPL License

Copyright (c) 2020 Joe Miyamoto <[email protected]>
Copyright (c) 2020 Node Effect Ltd <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
12 changes: 3 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,11 @@ The main API is in `DotNetLightning.Core` project/assembly.

## Installation

The package is compiled and published with two variants:
The package is compiled and published in nuget:

* [`DotNetLightning`](https://www.nuget.org/packages/DotNetLightning/)
* This does not use native bindings for cryptographic operations.
* This is the one you want to use if you run your code everywhere, but possibly slower than below.
* [`DotNetLightning.Core`](https://www.nuget.org/packages/DotNetLightning.Core/)
* This uses a pre-compiled `libsodium` for cryptographic operations.
* It only supports `windows`, `mac` and `linux` environments.
* This is what you want if you need performance and the environments above are the only ones you are planning to support.
* [`DotNetLightning.Kiss`](https://www.nuget.org/packages/DotNetLightning.Kiss/)

Run `dotnet add package` with the one you want.
It does not use native bindings for cryptographic operations.

Currently it is in alpha, so you probably want to install a latest version by specifying it with `--version`.
The version is prefixed with git commit hash and date. Please take a look at the nuget page.
Expand Down
46 changes: 38 additions & 8 deletions src/DotNetLightning.Core/Channel/Channel.fs
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,10 @@ module Channel =
((localClosingFee.Satoshi + remoteClosingFee.Satoshi) / 4L) * 2L
|> Money.Satoshis

let handleMutualClose (closingTx: FinalizedTx, d: NegotiatingData) =
let handleMutualClose (closingTx: FinalizedTx, d: NegotiatingData, nextMessage: Option<ClosingSignedMsg>) =
let nextData =
ClosingData.Create (d.ChannelId, d.Commitments, None, DateTime.Now, (d.ClosingTxProposed |> List.collect id |> List.map (fun tx -> tx.UnsignedTx)), closingTx)
[ MutualClosePerformed (closingTx, nextData) ]
[ MutualClosePerformed (closingTx, nextData, nextMessage) ]
|> Ok

let claimCurrentLocalCommitTxOutputs (channelPrivKeys: ChannelPrivKeys,
Expand Down Expand Up @@ -446,6 +446,32 @@ module Channel =
[] |> Ok

// ---------- normal operation ---------
| ChannelState.Normal state, MonoHopUnidirectionalPayment op when state.LocalShutdown.IsSome || state.RemoteShutdown.IsSome ->
sprintf "Could not send mono-hop unidirectional payment %A since shutdown is already in progress." op
|> apiMisuse
| ChannelState.Normal state, MonoHopUnidirectionalPayment op ->
result {
let payment: MonoHopUnidirectionalPaymentMsg = {
ChannelId = state.Commitments.ChannelId
Amount = op.Amount
}
let commitments1 = state.Commitments.AddLocalProposal(payment)

let remoteCommit1 =
match commitments1.RemoteNextCommitInfo with
| RemoteNextCommitInfo.Waiting info -> info.NextRemoteCommit
| RemoteNextCommitInfo.Revoked _info -> commitments1.RemoteCommit
let! reduced = remoteCommit1.Spec.Reduce(commitments1.RemoteChanges.ACKed, commitments1.LocalChanges.Proposed) |> expectTransactionError
do! Validation.checkOurMonoHopUnidirectionalPaymentIsAcceptableWithCurrentSpec reduced commitments1 payment
return [ WeAcceptedOperationMonoHopUnidirectionalPayment(payment, commitments1) ]
}
| ChannelState.Normal state, ApplyMonoHopUnidirectionalPayment msg ->
result {
let commitments1 = state.Commitments.AddRemoteProposal(msg)
let! reduced = commitments1.LocalCommit.Spec.Reduce (commitments1.LocalChanges.ACKed, commitments1.RemoteChanges.Proposed) |> expectTransactionError
do! Validation.checkTheirMonoHopUnidirectionalPaymentIsAcceptableWithCurrentSpec reduced commitments1 msg
return [ WeAcceptedMonoHopUnidirectionalPayment commitments1 ]
}
| ChannelState.Normal state, AddHTLC op when state.LocalShutdown.IsSome || state.RemoteShutdown.IsSome ->
sprintf "Could not add new HTLC %A since shutdown is already in progress." op
|> apiMisuse
Expand Down Expand Up @@ -551,8 +577,8 @@ module Channel =
RemoteCommit = theirNextCommit
RemoteNextCommitInfo = RemoteNextCommitInfo.Revoked msg.NextPerCommitmentPoint
RemotePerCommitmentSecrets = remotePerCommitmentSecrets }
let _result = Ok [ WeAcceptedRevokeAndACK commitments1 ]
failwith "needs update"
Console.WriteLine("WARNING: revocation is not implemented yet")
Ok [ WeAcceptedRevokeAndACK(commitments1) ]

| ChannelState.Normal state, ChannelCommand.Close cmd ->
let localSPK = cmd.ScriptPubKey |> Option.defaultValue (state.Commitments.LocalParams.DefaultFinalScriptPubKey)
Expand Down Expand Up @@ -713,7 +739,7 @@ module Channel =
let hasTooManyNegotiationDone =
(state.ClosingTxProposed |> List.collect (id) |> List.length) >= cs.Config.PeerChannelConfigLimits.MaxClosingNegotiationIterations
if (areWeInDeal || hasTooManyNegotiationDone) then
return! Closing.handleMutualClose (finalizedTx, { state with MaybeBestUnpublishedTx = Some(finalizedTx) })
return! Closing.handleMutualClose (finalizedTx, { state with MaybeBestUnpublishedTx = Some(finalizedTx) }, None)
else
let lastLocalClosingFee = state.ClosingTxProposed |> List.tryHead |> Option.bind (List.tryHead) |> Option.map (fun txp -> txp.LocalClosingSigned.FeeSatoshis)
let! localF =
Expand All @@ -729,7 +755,7 @@ module Channel =
let nextClosingFee =
Closing.nextClosingFee (localF, msg.FeeSatoshis)
if (Some nextClosingFee = lastLocalClosingFee) then
return! Closing.handleMutualClose (finalizedTx, { state with MaybeBestUnpublishedTx = Some(finalizedTx) })
return! Closing.handleMutualClose (finalizedTx, { state with MaybeBestUnpublishedTx = Some(finalizedTx) }, None)
else if (nextClosingFee = msg.FeeSatoshis) then
// we have reached on agreement!
let closingTxProposed1 =
Expand All @@ -738,7 +764,7 @@ module Channel =
newProposed :: state.ClosingTxProposed
let negoData = { state with ClosingTxProposed = closingTxProposed1
MaybeBestUnpublishedTx = Some(finalizedTx) }
return! Closing.handleMutualClose (finalizedTx, negoData)
return! Closing.handleMutualClose (finalizedTx, negoData, Some closingSignedMsg)
else
let! closingTx, closingSignedMsg =
Closing.makeClosingTx (
Expand Down Expand Up @@ -832,8 +858,12 @@ module Channel =
{ c with State = ChannelState.Normal data }

// ----- normal operation --------
| WeAcceptedOperationMonoHopUnidirectionalPayment(_, newCommitments), ChannelState.Normal normalData ->
{ c with State = ChannelState.Normal({ normalData with Commitments = newCommitments }) }
| WeAcceptedOperationAddHTLC(_, newCommitments), ChannelState.Normal d ->
{ c with State = ChannelState.Normal({ d with Commitments = newCommitments }) }
| WeAcceptedMonoHopUnidirectionalPayment(newCommitments), ChannelState.Normal normalData ->
{ c with State = ChannelState.Normal({ normalData with Commitments = newCommitments }) }
| WeAcceptedUpdateAddHTLC(newCommitments), ChannelState.Normal d ->
{ c with State = ChannelState.Normal({ d with Commitments = newCommitments }) }

Expand Down Expand Up @@ -874,7 +904,7 @@ module Channel =
{ c with State = Negotiating nextState }
| AcceptedShutdownWhenWeHavePendingHTLCs(nextState), ChannelState.Normal _d ->
{ c with State = Shutdown nextState }
| MutualClosePerformed (_txToPublish, nextState), ChannelState.Negotiating _d ->
| MutualClosePerformed (_txToPublish, nextState, _), ChannelState.Negotiating _d ->
{ c with State = Closing nextState }
| WeProposedNewClosingSigned(_msg, nextState), ChannelState.Negotiating _d ->
{ c with State = Negotiating(nextState) }
Expand Down
52 changes: 50 additions & 2 deletions src/DotNetLightning.Core/Channel/ChannelError.fs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type ChannelError =
// --- case they sent unacceptable msg ---
| InvalidOpenChannel of InvalidOpenChannelError
| InvalidAcceptChannel of InvalidAcceptChannelError
| InvalidMonoHopUnidirectionalPayment of InvalidMonoHopUnidirectionalPaymentError
| InvalidUpdateAddHTLC of InvalidUpdateAddHTLCError
| InvalidRevokeAndACK of InvalidRevokeAndACKError
| InvalidUpdateFee of InvalidUpdateFeeError
Expand Down Expand Up @@ -71,6 +72,7 @@ type ChannelError =
| TheyCannotAffordFee (_, _, _) -> Close
| InvalidOpenChannel _ -> DistrustPeer
| InvalidAcceptChannel _ -> DistrustPeer
| InvalidMonoHopUnidirectionalPayment _ -> Close
| InvalidUpdateAddHTLC _ -> Close
| InvalidRevokeAndACK _ -> Close
| InvalidUpdateFee _ -> Close
Expand Down Expand Up @@ -141,6 +143,8 @@ type ChannelError =
sprintf "Cannot close channel: %s" msg
| InvalidOperationAddHTLC invalidOperationAddHTLCError ->
sprintf "Invalid operation (add htlc): %s" invalidOperationAddHTLCError.Message
| InvalidMonoHopUnidirectionalPayment invalidMonoHopUnidirectionalPaymentError ->
sprintf "Invalid monohop-unidirectional payment: %s" invalidMonoHopUnidirectionalPaymentError.Message

and ChannelConsumerAction =
/// The error which should never happen.
Expand Down Expand Up @@ -181,6 +185,18 @@ and InvalidAcceptChannelError = {
member this.Message =
String.concat "; " this.Errors

and InvalidMonoHopUnidirectionalPaymentError = {
NetworkMsg: MonoHopUnidirectionalPaymentMsg
Errors: string list
}
with
static member Create msg e = {
NetworkMsg = msg
Errors = e
}
member this.Message =
String.concat "; " this.Errors

and InvalidUpdateAddHTLCError = {
NetworkMsg: UpdateAddHTLCMsg
Errors: string list
Expand Down Expand Up @@ -256,7 +272,7 @@ module internal ChannelError =
let inline unknownHTLCId x =
x |> UnknownHTLCId |> Error

let inline htlcOriginNowKnown x =
let inline htlcOriginNotKnown x =
x |> HTLCOriginNotKnown |> Error
let inline invalidFailureCode x =
x |> InvalidFailureCode |> Error
Expand Down Expand Up @@ -504,6 +520,22 @@ module internal AcceptChannelMsgValidation =

(check1 |> Validation.ofResult) *^> check2 *^> check3 *^> check4 *^> check5 *^> check6 *^> check7

module UpdateMonoHopUnidirectionalPaymentWithContext =
let internal checkWeHaveSufficientFunds (state: Commitments) (currentSpec) =
let fees =
if state.LocalParams.IsFunder then
Transactions.commitTxFee state.RemoteParams.DustLimitSatoshis currentSpec
else
Money.Zero
let missing = currentSpec.ToRemote.ToMoney() - state.RemoteParams.ChannelReserveSatoshis - fees
if missing < Money.Zero then
sprintf "We don't have sufficient funds to send mono-hop unidirectional payment. current to_remote amount is: %A. Remote Channel Reserve is: %A. and fee is %A"
(currentSpec.ToRemote.ToMoney())
state.RemoteParams.ChannelReserveSatoshis
fees
|> Error
else
Ok()

module UpdateAddHTLCValidation =
let internal checkExpiryIsNotPast (current: BlockHeight) (expiry) =
Expand All @@ -518,7 +550,23 @@ module UpdateAddHTLCValidation =
let internal checkAmountIsLargerThanMinimum (htlcMinimum: LNMoney) (amount) =
check (amount) (<) (htlcMinimum) "htlc value (%A) is too small. must be greater or equal to %A"


module internal MonoHopUnidirectionalPaymentValidationWithContext =
let checkWeHaveSufficientFunds (state: Commitments) (currentSpec) =
let fees =
if state.LocalParams.IsFunder then
Transactions.commitTxFee state.RemoteParams.DustLimitSatoshis currentSpec
else
Money.Zero
let missing = currentSpec.ToRemote.ToMoney() - state.RemoteParams.ChannelReserveSatoshis - fees
if missing < Money.Zero then
sprintf "We don't have sufficient funds to send mono-hop unidirectional payment. current to_remote amount is: %A. Remote Channel Reserve is: %A. and fee is %A"
(currentSpec.ToRemote.ToMoney())
state.RemoteParams.ChannelReserveSatoshis
fees
|> Error
else
Ok()

module internal UpdateAddHTLCValidationWithContext =
let checkLessThanHTLCValueInFlightLimit (currentSpec: CommitmentSpec) (limit) (add: UpdateAddHTLCMsg) =
let htlcValueInFlight = currentSpec.HTLCs |> Map.toSeq |> Seq.sumBy (fun (_, v) -> v.Add.Amount)
Expand Down
6 changes: 6 additions & 0 deletions src/DotNetLightning.Core/Channel/ChannelOperations.fs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ open NBitcoin
open ResultUtils
open ResultUtils.Portability

type OperationMonoHopUnidirectionalPayment = {
Amount: LNMoney
}

type OperationAddHTLC = {
Amount: LNMoney
PaymentHash: PaymentHash
Expand Down Expand Up @@ -203,6 +207,8 @@ type ChannelCommand =
| CreateChannelReestablish

// normal
| MonoHopUnidirectionalPayment of OperationMonoHopUnidirectionalPayment
| ApplyMonoHopUnidirectionalPayment of msg: MonoHopUnidirectionalPaymentMsg
| AddHTLC of OperationAddHTLC
| ApplyUpdateAddHTLC of msg: UpdateAddHTLCMsg * currentHeight: BlockHeight
| FulfillHTLC of OperationFulfillHTLC
Expand Down
Loading