From 4b82e2ec43422e8cf802a1ee054da4eea0661c86 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Wed, 18 Oct 2017 21:57:13 -0700 Subject: [PATCH] routing: correct fee calculation when converting from path to route MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In this commit, we correct the fee calculation when converting from a path to route. Previously we would apply the “no fee” case at the _first_ hop, rather than the last hop. As a result, we needed to swap the edges during path finding, otherwise, if the incoming and outgoing edges had different fee rates, then we would create an invalid onion payload. In this commit we now properly switch fee calculation into three cases: * a single hop route, so there’s no fee * we’re at the first hop in a multi hop route, and we apply the fee for the _next_ hop * we’re at an intermediate hop and the fee calculation proceeds as normal --- routing/pathfind.go | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/routing/pathfind.go b/routing/pathfind.go index 7d8dc015c..3c2d63bb1 100644 --- a/routing/pathfind.go +++ b/routing/pathfind.go @@ -280,7 +280,28 @@ func newRoute(amtToSend lnwire.MilliSatoshi, sourceVertex vertex, // We don't pay any fees to ourselves on the first-hop channel, // so we don't tally up the running fee and amount. - if i != len(pathEdges)-1 { + switch { + // If this is a single-hop payment, there's no fee required. + case i == 0 && len(pathEdges) == 1: + nextHop.Fee = 0 + + // If this is the "first" hop in a multi-hop payment, then we + // don't pay any fee to ourselves, but we craft the payload to + // prescribe the proper fee for the _next_ hop. + case i == 0 && len(pathEdges) > 1: + // Now, we'll compute the fee that we need to path this + // hop for its downstream transit. This is the value we + // want coming into the _next_ hop, using the fees from + // the _incoming_ node. + nextFee := computeFee(route.Hops[i+1].AmtToForward, + pathEdges[i+1]) + + nextHop.AmtToForward -= nextFee + nextHop.Fee = 0 + + // Otherwise, this is an intermediate hop, and we compute the + // fees as normal. + default: // For a node to forward an HTLC, then following // inequality most hold true: amt_in - fee >= // amt_to_forward. Therefore we add the fee this node @@ -295,8 +316,6 @@ func newRoute(amtToSend lnwire.MilliSatoshi, sourceVertex vertex, // the amount of blocks it'll subtract from the // incoming time lock. route.TotalFees += nextHop.Fee - } else { - nextHop.Fee = 0 } // If this is the last hop, then for verification purposes, the