Skip to content

Commit

Permalink
nit fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
aarani committed Jun 16, 2021
1 parent b54a9bc commit d0b91b7
Show file tree
Hide file tree
Showing 9 changed files with 61 additions and 56 deletions.
8 changes: 4 additions & 4 deletions src/DotNetLightning.Core/Channel/CommitmentsModule.fs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ module internal Commitments =
match cm.GetHTLCCrossSigned(Direction.Out, msg.HTLCId) with
| Some htlc when htlc.PaymentHash = msg.PaymentPreimage.Hash ->
let commitments = cm.AddRemoteProposal(msg)
let origin = cm.OriginChannels |> Map.tryFind(msg.HTLCId)
let origin = cm.OriginChannels |> Map.tryFind msg.HTLCId
[WeAcceptedFulfillHTLC(msg, origin, htlc, commitments)] |> Ok
| Some htlc ->
(htlc.PaymentHash, msg.PaymentPreimage)
Expand Down Expand Up @@ -345,10 +345,10 @@ module internal Commitments =
Transactions.checkTxFinalized signedCommitTx localCommitTx.WhichInput sigPair
|> expectTransactionError
let! finalizedCommitTx = tmp
let sortedHTLCTXs = Helpers.sortBothHTLCs htlcTimeoutTxs htlcSuccessTxs
let sortedHTLCTXs = Helpers.sortBothHTLCs htlcTimeoutTxs htlcSuccessTxs
do! checkSignatureCountMismatch sortedHTLCTXs msg

let HTLCTxsAndSignatures =
let htlcTxsAndSignatures =
sortedHTLCTXs
|> List.zip (msg.HTLCSignatures)
|> List.map(fun (remoteSig, htlc) ->
Expand All @@ -371,7 +371,7 @@ module internal Commitments =
| _ -> failwith "Unreachable!"

let! txList =
HTLCTxsAndSignatures
htlcTxsAndSignatures
|> List.map(checkHTLCSig)
|> List.sequenceResultA
|> expectTransactionErrors
Expand Down
6 changes: 5 additions & 1 deletion src/DotNetLightning.Core/Crypto/KeyExtensions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,11 @@ module KeyExtensions =
: TransactionSignature * PSBT =
let htlcPrivKey = perCommitmentPoint.DeriveHtlcPrivKey this.HtlcBasepointSecret
let htlcPubKey = htlcPrivKey.HtlcPubKey()
psbt.Settings.CustomBuilderExtensions <- ([new HTLCReceivedExtensions() :> BuilderExtension; new HTLCOfferedExtensions():> BuilderExtension] |> Seq.ofList)
psbt.Settings.CustomBuilderExtensions <-
[
HtlcReceivedExtensions() :> BuilderExtension
HtlcOfferedExtensions() :> BuilderExtension
] |> Seq.ofList
psbt.SignWithKeys(htlcPrivKey.RawKey()) |> ignore
match psbt.GetMatchingSig(htlcPubKey.RawPubKey()) with
| Some signature -> (signature, psbt)
Expand Down
9 changes: 4 additions & 5 deletions src/DotNetLightning.Core/Crypto/Sphinx.fs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ module Sphinx =
computeEphemeralPublicKeysAndSharedSecretsCore
(sessionKey) (pubKeys |> List.tail) ([ephemeralPK0]) ([blindingFactor0]) ([secret0])

let rec internal generateFiller (keyType: string) (payloads: byte[] list) (sharedSecrets: Key list) =
let rec internal generateFiller (keyType: string) (payloads: list<array<byte>>) (sharedSecrets: list<Key>) =
let filler_size =
payloads.[1..] |>
List.sumBy (fun payload -> payload.Length + MacLength)
Expand All @@ -106,7 +106,6 @@ module Sphinx =
payloads.[..i-1] |>
List.sumBy (fun payload -> payload.Length + MacLength)


let filler_start = HopDataSize - filler_offset
let filler_end = HopDataSize + payloads.[i].Length + MacLength
let filler_len = filler_end - filler_start
Expand Down Expand Up @@ -197,14 +196,14 @@ module Sphinx =
// set of filler bytes by using chacha20 with a key derived from the session
// key.
let DeterministicPacketFiller (sessionKey: Key) =
generateStream(generateKey("pad",sessionKey.ToBytes()), 1300)
generateStream(generateKey("pad", sessionKey.ToBytes()), HopDataSize)

// BlankPacketFiller is a packet filler that doesn't attempt to fill out the
// packet at all. It should ONLY be used for generating test vectors or other
// instances that required deterministic packet generation.
[<Obsolete("BlankPacketFiller is obsolete, see here: https://github.com/lightningnetwork/lightning-rfc/commit/8dd0b75809c9a7498bb9031a6674e5f58db509f4", false)>]
let BlankPacketFiller _=
Array.zeroCreate 1300
Array.zeroCreate HopDataSize

type PacketAndSecrets = {
Packet: OnionPacket
Expand All @@ -213,7 +212,7 @@ module Sphinx =
SharedSecrets: (Key * PubKey) list
}
with
static member Create (sessionKey: Key, pubKeys: PubKey list, payloads: byte[] list, ad: byte[], initialPacketFiller: Key -> byte[]) =
static member Create (sessionKey: Key, pubKeys: list<PubKey>, payloads: list<array<byte>>, ad: array<byte>, initialPacketFiller: Key -> array<byte>) =
let (ephemeralPubKeys, sharedSecrets) = computeEphemeralPublicKeysAndSharedSecrets (sessionKey) (pubKeys)
let filler = generateFiller "rho" payloads sharedSecrets

Expand Down
4 changes: 2 additions & 2 deletions src/DotNetLightning.Core/DotNetLightning.Core.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@
<Compile Include="Utils/Errors.fs" />
<Compile Include="Utils/RouteType.fs" />
<Compile Include="Utils/PriorityQueue.fs" />
<Compile Include="Utils/HTLCReceivedExtensions.fs" />
<Compile Include="Utils/HTLCOfferedExtensions.fs" />
<Compile Include="Utils/HtlcReceivedExtensions.fs" />
<Compile Include="Utils/HtlcOfferedExtensions.fs" />
<Compile Include="Chain/ChainInterface.fs" />
<Compile Include="Chain/KeysInterface.fs" />
<Compile Include="Serialization\GenericTLV.fs" />
Expand Down
8 changes: 4 additions & 4 deletions src/DotNetLightning.Core/Serialization/TLVs.fs
Original file line number Diff line number Diff line change
Expand Up @@ -108,18 +108,18 @@ type HopPayloadTLV =
static member FromGenericTLV(tlv: GenericTLV) =
match tlv.Type with
| 2UL ->
UInt64.FromTruncatedBytes(tlv.Value)
UInt64.FromTruncatedBytes tlv.Value
|> LNMoney.MilliSatoshis
|> AmountToForward
| 4UL ->
UInt32.FromTruncatedBytes(tlv.Value)
UInt32.FromTruncatedBytes tlv.Value
|> OutgoingCLTV
| 6UL ->
ShortChannelId.From8Bytes(tlv.Value)
ShortChannelId.From8Bytes tlv.Value
|> ShortChannelId
| 8UL ->
let secret = tlv.Value.[0..PaymentSecret.LENGTH - 1] |> PaymentSecret.FromByteArray
let totalMSat = UInt64.FromTruncatedBytes(tlv.Value.[PaymentSecret.LENGTH..]) |> LNMoney.MilliSatoshis
let totalMSat = UInt64.FromTruncatedBytes tlv.Value.[PaymentSecret.LENGTH..] |> LNMoney.MilliSatoshis
(secret, totalMSat) |> PaymentData
| _ -> Unknown tlv

Expand Down
4 changes: 2 additions & 2 deletions src/DotNetLightning.Core/Transactions/Transactions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ module Transactions =
let dest = Scripts.toLocalDelayed localRevocationPubKey toLocalDelay localDelayedPaymentPubKey
// we have already done dust limit check above
txb.DustPrevention <- false
txb.Extensions.Add (new HTLCOfferedExtensions())
txb.Extensions.Add (HtlcOfferedExtensions())
let tx = txb.AddCoins(scriptCoin)
.Send(dest.WitHash, amount)
.SendFees(fee)
Expand Down Expand Up @@ -567,7 +567,7 @@ module Transactions =
ScriptCoin(coin, redeem)
let dest = Scripts.toLocalDelayed localRevocationPubKey toLocalDelay localDelayedPaymentPubKey
// we have already done dust limit check above
txb.Extensions.Add (new HTLCReceivedExtensions())
txb.Extensions.Add (HtlcReceivedExtensions())
txb.DustPrevention <- false
let tx = txb.AddCoins(scriptCoin)
.Send(dest.WitHash, amount)
Expand Down
28 changes: 14 additions & 14 deletions src/DotNetLightning.Core/Utils/Extensions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -60,29 +60,29 @@ type System.UInt64 with
buf

member private x.GetLeadingZerosCount() =
if (x = 0UL) then
if x = 0UL then
8
else if (x &&& 0xffffffffffffff00UL = 0UL) then
elif x &&& 0xffffffffffffff00UL = 0UL then
7
else if (x &&& 0xffffffffffff0000UL = 0UL) then
elif x &&& 0xffffffffffff0000UL = 0UL then
6
else if (x &&& 0xffffffffff000000UL = 0UL) then
elif x &&& 0xffffffffff000000UL = 0UL then
5
else if (x &&& 0xffffffff00000000UL = 0UL) then
elif x &&& 0xffffffff00000000UL = 0UL then
4
else if (x &&& 0xffffff0000000000UL = 0UL) then
elif x &&& 0xffffff0000000000UL = 0UL then
3
else if (x &&& 0xffff000000000000UL = 0UL) then
elif x &&& 0xffff000000000000UL = 0UL then
2
else if (x &&& 0xff00000000000000UL = 0UL) then
elif x &&& 0xff00000000000000UL = 0UL then
1
else
0

member x.GetTruncatedBytes() =
let numZeros =
x.GetLeadingZerosCount()
x.GetBytesBigEndian() |> Array.skip(numZeros)
x.GetBytesBigEndian() |> Array.skip numZeros

//TODO: better error handling?
static member FromTruncatedBytes(bytes: array<byte>): uint64 =
Expand Down Expand Up @@ -114,21 +114,21 @@ type System.UInt32 with
BitConverter.ToUInt32(bytes, 0)

member private x.GetLeadingZerosCount() =
if (x = 0u) then
if x = 0u then
4
else if (x &&& 0xffffff00u = 0u) then
elif x &&& 0xffffff00u = 0u then
3
else if (x &&& 0xffff0000u = 0u) then
elif x &&& 0xffff0000u = 0u then
2
else if (x &&& 0xff000000u = 0u) then
elif x &&& 0xff000000u = 0u then
1
else
0

member x.GetTruncatedBytes() =
let numZeros =
x.GetLeadingZerosCount()
x.GetBytesBigEndian() |> Array.skip(numZeros)
x.GetBytesBigEndian() |> Array.skip numZeros

//TODO: better error handling?
static member FromTruncatedBytes(bytes: array<byte>): uint32 =
Expand Down
25 changes: 13 additions & 12 deletions src/DotNetLightning.Core/Utils/HTLCOfferedExtensions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ open ResultUtils
open ResultUtils.Portability
open Newtonsoft.Json

type HTLCOfferedParameters = {
type HtlcOfferedParameters = {
LocalHtlcPubKey: HtlcPubKey
RemoteHtlcPubKey: HtlcPubKey
}
with
static member TryExtractParameters (scriptPubKey: Script): Option<HTLCOfferedParameters> =
static member TryExtractParameters (scriptPubKey: Script): Option<HtlcOfferedParameters> =
let ops =
scriptPubKey.ToOps()
// we have to collect it into a list and convert back to a seq
Expand All @@ -23,7 +23,6 @@ type HTLCOfferedParameters = {
|> List.ofSeq
|> Seq.ofList

Console.WriteLine(JsonConvert.SerializeObject(ops))
let checkOpCode(opcodeType: OpcodeType) = seqParser<Op> {
let! op = SeqParser.next()
if op.Code = opcodeType then
Expand Down Expand Up @@ -88,31 +87,33 @@ type HTLCOfferedParameters = {
| Ok data -> Some data
| Error _consumeAllError -> None

type internal HTLCOfferedExtensions() =
type internal HtlcOfferedExtensions() =
inherit BuilderExtension()
override self.CanGenerateScriptSig (scriptPubKey: Script): bool =
(HTLCOfferedParameters.TryExtractParameters scriptPubKey).IsSome
(HtlcOfferedParameters.TryExtractParameters scriptPubKey).IsSome

override self.GenerateScriptSig(scriptPubKey: Script, keyRepo: IKeyRepository, signer: ISigner): Script =
let parameters =
match (HTLCOfferedParameters.TryExtractParameters scriptPubKey) with
match (HtlcOfferedParameters.TryExtractParameters scriptPubKey) with
| Some parameters -> parameters
| None ->
failwith
"NBitcoin should not call this unless CanGenerateScriptSig returns true"
let pubKey = keyRepo.FindKey scriptPubKey
let pubKeyOpt =
keyRepo.FindKey scriptPubKey
|> Option.ofObj
// FindKey will return null if it can't find a key for
// scriptPubKey. If we can't find a valid key then this method
// should return null, indicating to NBitcoin that the sigScript
// could not be generated.
match pubKey with
| null -> null
| _ when pubKey = parameters.LocalHtlcPubKey.RawPubKey() ->
match pubKeyOpt with
| None -> null
| Some pubKey when pubKey = parameters.LocalHtlcPubKey.RawPubKey() ->
let localHtlcSig = signer.Sign (parameters.LocalHtlcPubKey.RawPubKey())
Script [
Op.GetPushOp (localHtlcSig.ToBytes())
]
| _ when pubKey = parameters.RemoteHtlcPubKey.RawPubKey() ->
| Some pubKey when pubKey = parameters.RemoteHtlcPubKey.RawPubKey() ->
let remoteHtlcSig = signer.Sign (parameters.RemoteHtlcPubKey.RawPubKey())
Script [
Op.GetPushOp (remoteHtlcSig.ToBytes())
Expand All @@ -138,7 +139,7 @@ type internal HTLCOfferedExtensions() =
raise <| NotSupportedException()

override self.IsCompatibleKey(pubKey: PubKey, scriptPubKey: Script): bool =
match HTLCOfferedParameters.TryExtractParameters scriptPubKey with
match HtlcOfferedParameters.TryExtractParameters scriptPubKey with
| None -> false
| Some parameters ->
parameters.LocalHtlcPubKey.RawPubKey() = pubKey
Expand Down
25 changes: 13 additions & 12 deletions src/DotNetLightning.Core/Utils/HTLCReceivedExtensions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ open ResultUtils
open ResultUtils.Portability
open Newtonsoft.Json

type HTLCReceivedParameters = {
type HtlcReceivedParameters = {
LocalHtlcPubKey: HtlcPubKey
RemoteHtlcPubKey: HtlcPubKey
}
with
static member TryExtractParameters (scriptPubKey: Script): Option<HTLCReceivedParameters> =
static member TryExtractParameters (scriptPubKey: Script): Option<HtlcReceivedParameters> =
let ops =
scriptPubKey.ToOps()
// we have to collect it into a list and convert back to a seq
Expand All @@ -23,7 +23,6 @@ type HTLCReceivedParameters = {
|> List.ofSeq
|> Seq.ofList

Console.WriteLine(JsonConvert.SerializeObject(ops))
let checkOpCode(opcodeType: OpcodeType) = seqParser<Op> {
let! op = SeqParser.next()
if op.Code = opcodeType then
Expand Down Expand Up @@ -94,31 +93,33 @@ type HTLCReceivedParameters = {
| Ok data -> Some data
| Error _consumeAllError -> None

type internal HTLCReceivedExtensions() =
type internal HtlcReceivedExtensions() =
inherit BuilderExtension()
override self.CanGenerateScriptSig (scriptPubKey: Script): bool =
(HTLCReceivedParameters.TryExtractParameters scriptPubKey).IsSome
(HtlcReceivedParameters.TryExtractParameters scriptPubKey).IsSome

override self.GenerateScriptSig(scriptPubKey: Script, keyRepo: IKeyRepository, signer: ISigner): Script =
let parameters =
match (HTLCReceivedParameters.TryExtractParameters scriptPubKey) with
match (HtlcReceivedParameters.TryExtractParameters scriptPubKey) with
| Some parameters -> parameters
| None ->
failwith
"NBitcoin should not call this unless CanGenerateScriptSig returns true"
let pubKey = keyRepo.FindKey scriptPubKey
let pubKeyOpt =
keyRepo.FindKey scriptPubKey
|> Option.ofObj
// FindKey will return null if it can't find a key for
// scriptPubKey. If we can't find a valid key then this method
// should return null, indicating to NBitcoin that the sigScript
// could not be generated.
match pubKey with
| null -> null
| _ when pubKey = parameters.LocalHtlcPubKey.RawPubKey() ->
match pubKeyOpt with
| None -> null
| Some pubKey when pubKey = parameters.LocalHtlcPubKey.RawPubKey() ->
let localHtlcSig = signer.Sign (parameters.LocalHtlcPubKey.RawPubKey())
Script [
Op.GetPushOp (localHtlcSig.ToBytes())
]
| _ when pubKey = parameters.RemoteHtlcPubKey.RawPubKey() ->
| Some pubKey when pubKey = parameters.RemoteHtlcPubKey.RawPubKey() ->
let remoteHtlcSig = signer.Sign (parameters.RemoteHtlcPubKey.RawPubKey())
Script [
Op.GetPushOp (remoteHtlcSig.ToBytes())
Expand All @@ -144,7 +145,7 @@ type internal HTLCReceivedExtensions() =
raise <| NotSupportedException()

override self.IsCompatibleKey(pubKey: PubKey, scriptPubKey: Script): bool =
match HTLCReceivedParameters.TryExtractParameters scriptPubKey with
match HtlcReceivedParameters.TryExtractParameters scriptPubKey with
| None -> false
| Some parameters ->
parameters.LocalHtlcPubKey.RawPubKey() = pubKey
Expand Down

0 comments on commit d0b91b7

Please sign in to comment.