From d0b91b76e7a0d35a8805b43e2e4c9cb44b0721ef Mon Sep 17 00:00:00 2001 From: Afshin Arani Date: Wed, 16 Jun 2021 12:17:53 +0430 Subject: [PATCH] nit fixes --- .../Channel/CommitmentsModule.fs | 8 +++--- .../Crypto/KeyExtensions.fs | 6 +++- src/DotNetLightning.Core/Crypto/Sphinx.fs | 9 +++--- .../DotNetLightning.Core.fsproj | 4 +-- .../Serialization/TLVs.fs | 8 +++--- .../Transactions/Transactions.fs | 4 +-- src/DotNetLightning.Core/Utils/Extensions.fs | 28 +++++++++---------- .../Utils/HTLCOfferedExtensions.fs | 25 +++++++++-------- .../Utils/HTLCReceivedExtensions.fs | 25 +++++++++-------- 9 files changed, 61 insertions(+), 56 deletions(-) diff --git a/src/DotNetLightning.Core/Channel/CommitmentsModule.fs b/src/DotNetLightning.Core/Channel/CommitmentsModule.fs index 5950e1597..90292a41a 100644 --- a/src/DotNetLightning.Core/Channel/CommitmentsModule.fs +++ b/src/DotNetLightning.Core/Channel/CommitmentsModule.fs @@ -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) @@ -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) -> @@ -371,7 +371,7 @@ module internal Commitments = | _ -> failwith "Unreachable!" let! txList = - HTLCTxsAndSignatures + htlcTxsAndSignatures |> List.map(checkHTLCSig) |> List.sequenceResultA |> expectTransactionErrors diff --git a/src/DotNetLightning.Core/Crypto/KeyExtensions.fs b/src/DotNetLightning.Core/Crypto/KeyExtensions.fs index a105fa0cb..ff534c4ff 100644 --- a/src/DotNetLightning.Core/Crypto/KeyExtensions.fs +++ b/src/DotNetLightning.Core/Crypto/KeyExtensions.fs @@ -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) diff --git a/src/DotNetLightning.Core/Crypto/Sphinx.fs b/src/DotNetLightning.Core/Crypto/Sphinx.fs index 4fc0ecc86..4c7e8b7dd 100644 --- a/src/DotNetLightning.Core/Crypto/Sphinx.fs +++ b/src/DotNetLightning.Core/Crypto/Sphinx.fs @@ -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>) (sharedSecrets: list) = let filler_size = payloads.[1..] |> List.sumBy (fun payload -> payload.Length + MacLength) @@ -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 @@ -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. [] let BlankPacketFiller _= - Array.zeroCreate 1300 + Array.zeroCreate HopDataSize type PacketAndSecrets = { Packet: OnionPacket @@ -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, payloads: list>, ad: array, initialPacketFiller: Key -> array) = let (ephemeralPubKeys, sharedSecrets) = computeEphemeralPublicKeysAndSharedSecrets (sessionKey) (pubKeys) let filler = generateFiller "rho" payloads sharedSecrets diff --git a/src/DotNetLightning.Core/DotNetLightning.Core.fsproj b/src/DotNetLightning.Core/DotNetLightning.Core.fsproj index 4b48d086d..2915773bb 100644 --- a/src/DotNetLightning.Core/DotNetLightning.Core.fsproj +++ b/src/DotNetLightning.Core/DotNetLightning.Core.fsproj @@ -46,8 +46,8 @@ - - + + diff --git a/src/DotNetLightning.Core/Serialization/TLVs.fs b/src/DotNetLightning.Core/Serialization/TLVs.fs index 881d357fa..f06bbb24e 100644 --- a/src/DotNetLightning.Core/Serialization/TLVs.fs +++ b/src/DotNetLightning.Core/Serialization/TLVs.fs @@ -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 diff --git a/src/DotNetLightning.Core/Transactions/Transactions.fs b/src/DotNetLightning.Core/Transactions/Transactions.fs index 466db2da8..8e17270c9 100644 --- a/src/DotNetLightning.Core/Transactions/Transactions.fs +++ b/src/DotNetLightning.Core/Transactions/Transactions.fs @@ -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) @@ -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) diff --git a/src/DotNetLightning.Core/Utils/Extensions.fs b/src/DotNetLightning.Core/Utils/Extensions.fs index ea8e9545b..55afa2459 100644 --- a/src/DotNetLightning.Core/Utils/Extensions.fs +++ b/src/DotNetLightning.Core/Utils/Extensions.fs @@ -60,21 +60,21 @@ 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 @@ -82,7 +82,7 @@ type System.UInt64 with 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): uint64 = @@ -114,13 +114,13 @@ 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 @@ -128,7 +128,7 @@ type System.UInt32 with 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): uint32 = diff --git a/src/DotNetLightning.Core/Utils/HTLCOfferedExtensions.fs b/src/DotNetLightning.Core/Utils/HTLCOfferedExtensions.fs index 47d45a2f4..ce8805f93 100644 --- a/src/DotNetLightning.Core/Utils/HTLCOfferedExtensions.fs +++ b/src/DotNetLightning.Core/Utils/HTLCOfferedExtensions.fs @@ -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 = + static member TryExtractParameters (scriptPubKey: Script): Option = let ops = scriptPubKey.ToOps() // we have to collect it into a list and convert back to a seq @@ -23,7 +23,6 @@ type HTLCOfferedParameters = { |> List.ofSeq |> Seq.ofList - Console.WriteLine(JsonConvert.SerializeObject(ops)) let checkOpCode(opcodeType: OpcodeType) = seqParser { let! op = SeqParser.next() if op.Code = opcodeType then @@ -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()) @@ -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 diff --git a/src/DotNetLightning.Core/Utils/HTLCReceivedExtensions.fs b/src/DotNetLightning.Core/Utils/HTLCReceivedExtensions.fs index 15a1fc645..fdb22415f 100644 --- a/src/DotNetLightning.Core/Utils/HTLCReceivedExtensions.fs +++ b/src/DotNetLightning.Core/Utils/HTLCReceivedExtensions.fs @@ -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 = + static member TryExtractParameters (scriptPubKey: Script): Option = let ops = scriptPubKey.ToOps() // we have to collect it into a list and convert back to a seq @@ -23,7 +23,6 @@ type HTLCReceivedParameters = { |> List.ofSeq |> Seq.ofList - Console.WriteLine(JsonConvert.SerializeObject(ops)) let checkOpCode(opcodeType: OpcodeType) = seqParser { let! op = SeqParser.next() if op.Code = opcodeType then @@ -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()) @@ -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