Htlcswitch: switch all accounting and forwarding decisions to use mSAT's

This commit is contained in:
Olaoluwa Osuntokun 2017-08-21 23:36:43 -07:00
parent 39ab177567
commit 8a51b1a0c6
No known key found for this signature in database
GPG Key ID: 9CC5B105D03521A2
10 changed files with 82 additions and 78 deletions

@ -5,7 +5,6 @@ import (
"github.com/lightningnetwork/lnd/lnwallet" "github.com/lightningnetwork/lnd/lnwallet"
"github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/lnwire"
"github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/chaincfg/chainhash"
"github.com/roasbeef/btcutil"
) )
// InvoiceDatabase is an interface which represents the persistent subsystem // InvoiceDatabase is an interface which represents the persistent subsystem
@ -63,16 +62,16 @@ type ChannelLink interface {
// policy to govern if it an incoming HTLC should be forwarded or not. // policy to govern if it an incoming HTLC should be forwarded or not.
UpdateForwardingPolicy(ForwardingPolicy) UpdateForwardingPolicy(ForwardingPolicy)
// Bandwidth returns the amount of satoshis which current link might // Bandwidth returns the amount of milli-satoshis which current link
// pass through channel link. The value returned from this method // might pass through channel link. The value returned from this method
// represents the up to date available flow through the channel. This // represents the up to date available flow through the channel. This
// takes into account any forwarded but un-cleared HTLC's, and any // takes into account any forwarded but un-cleared HTLC's, and any
// HTLC's which have been set to the over flow queue. // HTLC's which have been set to the over flow queue.
Bandwidth() btcutil.Amount Bandwidth() lnwire.MilliSatoshi
// Stats return the statistics of channel link. Number of updates, // Stats return the statistics of channel link. Number of updates,
// total sent/received satoshis. // total sent/received milli-satoshis.
Stats() (uint64, btcutil.Amount, btcutil.Amount) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi)
// Peer returns the representation of remote peer with which we have // Peer returns the representation of remote peer with which we have
// the channel link opened. // the channel link opened.

@ -6,7 +6,6 @@ import (
"github.com/lightningnetwork/lightning-onion" "github.com/lightningnetwork/lightning-onion"
"github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/lnwire"
"github.com/roasbeef/btcutil"
) )
// NetworkHop indicates the blockchain network that is intended to be the next // NetworkHop indicates the blockchain network that is intended to be the next
@ -58,9 +57,9 @@ type ForwardingInfo struct {
// end-to-end route. // end-to-end route.
NextHop lnwire.ShortChannelID NextHop lnwire.ShortChannelID
// AmountToForward is the amount that the receiving node should forward // AmountToForward is the amount of milli-satoshis that the receiving
// to the next hop. // node should forward to the next hop.
AmountToForward btcutil.Amount AmountToForward lnwire.MilliSatoshi
// OutgoingCTLV is the specified value of the CTLV timelock to be used // OutgoingCTLV is the specified value of the CTLV timelock to be used
// in the outgoing HTLC. // in the outgoing HTLC.
@ -133,7 +132,7 @@ func (r *sphinxHopIterator) ForwardingInstructions() ForwardingInfo {
return ForwardingInfo{ return ForwardingInfo{
Network: BitcoinHop, Network: BitcoinHop,
NextHop: nextHop, NextHop: nextHop,
AmountToForward: btcutil.Amount(fwdInst.ForwardAmount), AmountToForward: lnwire.MilliSatoshi(fwdInst.ForwardAmount),
OutgoingCTLV: fwdInst.OutgoingCltv, OutgoingCTLV: fwdInst.OutgoingCltv,
} }
} }

@ -40,19 +40,17 @@ const (
// latest policy. // latest policy.
type ForwardingPolicy struct { type ForwardingPolicy struct {
// MinHTLC is the smallest HTLC that is to be forwarded. // MinHTLC is the smallest HTLC that is to be forwarded.
MinHTLC btcutil.Amount MinHTLC lnwire.MilliSatoshi
// BaseFee is the base fee, expressed in milli-satoshi that must be // BaseFee is the base fee, expressed in milli-satoshi that must be
// paid for each incoming HTLC. This field, combined with FeeRate is // paid for each incoming HTLC. This field, combined with FeeRate is
// used to compute the required fee for a given HTLC. // used to compute the required fee for a given HTLC.
// BaseFee lnwire.MilliSatoshi
// TODO(roasbeef): need to be in mSAT
BaseFee btcutil.Amount
// FeeRate is the fee rate, expressed in milli-satoshi that must be // FeeRate is the fee rate, expressed in milli-satoshi that must be
// paid for each incoming HTLC. This field combined with BaseFee is // paid for each incoming HTLC. This field combined with BaseFee is
// used to compute the required fee for a given HTLC. // used to compute the required fee for a given HTLC.
FeeRate btcutil.Amount FeeRate lnwire.MilliSatoshi
// TimeLockDelta is the absolute time-lock value, expressed in blocks, // TimeLockDelta is the absolute time-lock value, expressed in blocks,
// that will be subtracted from an incoming HTLC's timelock value to // that will be subtracted from an incoming HTLC's timelock value to
@ -75,7 +73,9 @@ type ForwardingPolicy struct {
// //
// TODO(roasbeef): also add in current available channel bandwidth, inverse // TODO(roasbeef): also add in current available channel bandwidth, inverse
// func // func
func ExpectedFee(f ForwardingPolicy, htlcAmt btcutil.Amount) btcutil.Amount { func ExpectedFee(f ForwardingPolicy, htlcAmt lnwire.MilliSatoshi) lnwire.MilliSatoshi {
// TODO(roasbeef): write some basic table driven tests
return f.BaseFee + (htlcAmt*f.FeeRate)/1000000 return f.BaseFee + (htlcAmt*f.FeeRate)/1000000
} }
@ -300,6 +300,8 @@ func (l *channelLink) htlcManager() {
// TODO(roasbeef): fail chan in case of protocol violation // TODO(roasbeef): fail chan in case of protocol violation
// TODO(roasbeef): resend funding locked if state zero
out: out:
for { for {
select { select {
@ -820,7 +822,7 @@ func (l *channelLink) ChanID() lnwire.ChannelID {
// getBandwidthCmd is a wrapper for get bandwidth handler. // getBandwidthCmd is a wrapper for get bandwidth handler.
type getBandwidthCmd struct { type getBandwidthCmd struct {
resp chan btcutil.Amount resp chan lnwire.MilliSatoshi
} }
// Bandwidth returns the amount which current link might pass through channel // Bandwidth returns the amount which current link might pass through channel
@ -828,9 +830,9 @@ type getBandwidthCmd struct {
// will not be changed during function execution. // will not be changed during function execution.
// //
// NOTE: Part of the ChannelLink interface. // NOTE: Part of the ChannelLink interface.
func (l *channelLink) Bandwidth() btcutil.Amount { func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
command := &getBandwidthCmd{ command := &getBandwidthCmd{
resp: make(chan btcutil.Amount, 1), resp: make(chan lnwire.MilliSatoshi, 1),
} }
select { select {
@ -846,7 +848,7 @@ func (l *channelLink) Bandwidth() btcutil.Amount {
// //
// NOTE: Should be used inside main goroutine only, otherwise the result might // NOTE: Should be used inside main goroutine only, otherwise the result might
// not be accurate. // not be accurate.
func (l *channelLink) getBandwidth() btcutil.Amount { func (l *channelLink) getBandwidth() lnwire.MilliSatoshi {
return l.channel.LocalAvailableBalance() - l.overflowQueue.pendingAmount() return l.channel.LocalAvailableBalance() - l.overflowQueue.pendingAmount()
} }
@ -883,11 +885,11 @@ func (l *channelLink) UpdateForwardingPolicy(newPolicy ForwardingPolicy) {
// Stats returns the statistics of channel link. // Stats returns the statistics of channel link.
// //
// NOTE: Part of the ChannelLink interface. // NOTE: Part of the ChannelLink interface.
func (l *channelLink) Stats() (uint64, btcutil.Amount, btcutil.Amount) { func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
snapshot := l.channel.StateSnapshot() snapshot := l.channel.StateSnapshot()
return snapshot.NumUpdates, return snapshot.NumUpdates,
btcutil.Amount(snapshot.TotalSatoshisSent), snapshot.TotalMilliSatoshisSent,
btcutil.Amount(snapshot.TotalSatoshisReceived) snapshot.TotalMilliSatoshisReceived
} }
// String returns the string representation of channel link. // String returns the string representation of channel link.
@ -1070,7 +1072,7 @@ func (l *channelLink) processLockedInHtlcs(
invoiceHash := chainhash.Hash(pd.RHash) invoiceHash := chainhash.Hash(pd.RHash)
invoice, err := l.cfg.Registry.LookupInvoice(invoiceHash) invoice, err := l.cfg.Registry.LookupInvoice(invoiceHash)
if err != nil { if err != nil {
log.Errorf("unable to query to locate:"+ log.Errorf("unable to query invoice registry: "+
" %v", err) " %v", err)
failure := lnwire.FailUnknownPaymentHash{} failure := lnwire.FailUnknownPaymentHash{}
l.sendHTLCError(pd.RHash, failure, obfuscator) l.sendHTLCError(pd.RHash, failure, obfuscator)
@ -1218,7 +1220,7 @@ func (l *channelLink) processLockedInHtlcs(
// accepted. // accepted.
expectedFee := ExpectedFee( expectedFee := ExpectedFee(
l.cfg.FwrdingPolicy, l.cfg.FwrdingPolicy,
pd.Amount, fwdInfo.AmountToForward,
) )
// If the amount of the incoming HTLC, minus // If the amount of the incoming HTLC, minus
@ -1233,8 +1235,8 @@ func (l *channelLink) processLockedInHtlcs(
log.Errorf("Incoming htlc(%x) has "+ log.Errorf("Incoming htlc(%x) has "+
"insufficient fee: expected "+ "insufficient fee: expected "+
"%v, got %v", pd.RHash[:], "%v, got %v", pd.RHash[:],
btcutil.Amount(pd.Amount-fwdInfo.AmountToForward), int64(expectedFee),
btcutil.Amount(expectedFee)) int64(pd.Amount-fwdInfo.AmountToForward))
// As part of the returned error, we'll // As part of the returned error, we'll
// send our latest routing policy so // send our latest routing policy so

@ -106,7 +106,7 @@ func TestChannelLinkSingleHopPayment(t *testing.T) {
n.firstBobChannelLink.ChanID())) n.firstBobChannelLink.ChanID()))
} }
var amount btcutil.Amount = btcutil.SatoshiPerBitcoin var amount lnwire.MilliSatoshi = lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight, htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight,
n.firstBobChannelLink) n.firstBobChannelLink)
@ -173,7 +173,7 @@ func TestChannelLinkBidirectionalOneHopPayments(t *testing.T) {
n.firstBobChannelLink.ChanID())) n.firstBobChannelLink.ChanID()))
} }
const amt btcutil.Amount = 20000 amt := lnwire.NewMSatFromSatoshis(20000)
htlcAmt, totalTimelock, hopsForwards := generateHops(amt, htlcAmt, totalTimelock, hopsForwards := generateHops(amt,
testStartingHeight, n.firstBobChannelLink) testStartingHeight, n.firstBobChannelLink)
@ -305,7 +305,7 @@ func TestChannelLinkMultiHopPayment(t *testing.T) {
n.carolChannelLink.ChanID())) n.carolChannelLink.ChanID()))
} }
var amount btcutil.Amount = btcutil.SatoshiPerBitcoin amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
htlcAmt, totalTimelock, hops := generateHops(amount, htlcAmt, totalTimelock, hops := generateHops(amount,
testStartingHeight, testStartingHeight,
n.firstBobChannelLink, n.carolChannelLink) n.firstBobChannelLink, n.carolChannelLink)
@ -456,7 +456,7 @@ func TestLinkForwardTimelockPolicyMismatch(t *testing.T) {
defer n.stop() defer n.stop()
// We'll be sending 1 BTC over a 2-hop (3 vertex) route. // We'll be sending 1 BTC over a 2-hop (3 vertex) route.
var amount btcutil.Amount = btcutil.SatoshiPerBitcoin amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
// Generate the route over two hops, ignoring the total time lock that // Generate the route over two hops, ignoring the total time lock that
// we'll need to use for the first HTLC in order to have a sufficient // we'll need to use for the first HTLC in order to have a sufficient
@ -499,7 +499,7 @@ func TestLinkForwardFeePolicyMismatch(t *testing.T) {
// We'll be sending 1 BTC over a 2-hop (3 vertex) route. Given the // We'll be sending 1 BTC over a 2-hop (3 vertex) route. Given the
// current default fee of 1 SAT, if we just send a single BTC over in // current default fee of 1 SAT, if we just send a single BTC over in
// an HTLC, it should be rejected. // an HTLC, it should be rejected.
var amountNoFee btcutil.Amount = btcutil.SatoshiPerBitcoin amountNoFee := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
// Generate the route over two hops, ignoring the amount we _should_ // Generate the route over two hops, ignoring the amount we _should_
// actually send in order to be able to cover fees. // actually send in order to be able to cover fees.
@ -543,7 +543,7 @@ func TestLinkForwardMinHTLCPolicyMismatch(t *testing.T) {
// The current default global min HTLC policy set in the default config // The current default global min HTLC policy set in the default config
// for the three-hop-network is 5 SAT. So in order to trigger this // for the three-hop-network is 5 SAT. So in order to trigger this
// failure mode, we'll create an HTLC with 1 satoshi. // failure mode, we'll create an HTLC with 1 satoshi.
amountNoFee := btcutil.Amount(1) amountNoFee := lnwire.NewMSatFromSatoshis(1)
// With the amount set, we'll generate a route over 2 hops within the // With the amount set, we'll generate a route over 2 hops within the
// network that attempts to pay out our specified amount. // network that attempts to pay out our specified amount.
@ -590,7 +590,7 @@ func TestUpdateForwardingPolicy(t *testing.T) {
secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth() secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth()
aliceBandwidthBefore := n.aliceChannelLink.Bandwidth() aliceBandwidthBefore := n.aliceChannelLink.Bandwidth()
amountNoFee := btcutil.Amount(10) amountNoFee := lnwire.NewMSatFromSatoshis(10)
htlcAmt, htlcExpiry, hops := generateHops(amountNoFee, htlcAmt, htlcExpiry, hops := generateHops(amountNoFee,
testStartingHeight, testStartingHeight,
n.firstBobChannelLink, n.carolChannelLink) n.firstBobChannelLink, n.carolChannelLink)
@ -639,8 +639,10 @@ func TestUpdateForwardingPolicy(t *testing.T) {
// TODO(roasbeef): should implement grace period within link policy // TODO(roasbeef): should implement grace period within link policy
// update logic // update logic
newPolicy := n.globalPolicy newPolicy := n.globalPolicy
newPolicy.BaseFee = btcutil.Amount(1000) newPolicy.BaseFee = lnwire.NewMSatFromSatoshis(1000)
n.firstBobChannelLink.UpdateForwardingPolicy(newPolicy) n.firstBobChannelLink.UpdateForwardingPolicy(newPolicy)
// TODO(roasbeef): should send again an ensure rejected?
} }
// TestChannelLinkMultiHopInsufficientPayment checks that we receive error if // TestChannelLinkMultiHopInsufficientPayment checks that we receive error if
@ -664,7 +666,7 @@ func TestChannelLinkMultiHopInsufficientPayment(t *testing.T) {
secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth() secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth()
aliceBandwidthBefore := n.aliceChannelLink.Bandwidth() aliceBandwidthBefore := n.aliceChannelLink.Bandwidth()
var amount btcutil.Amount = 4 * btcutil.SatoshiPerBitcoin amount := lnwire.NewMSatFromSatoshis(4 * btcutil.SatoshiPerBitcoin)
htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight, htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight,
n.firstBobChannelLink, n.carolChannelLink) n.firstBobChannelLink, n.carolChannelLink)
@ -734,7 +736,7 @@ func TestChannelLinkMultiHopUnknownPaymentHash(t *testing.T) {
secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth() secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth()
aliceBandwidthBefore := n.aliceChannelLink.Bandwidth() aliceBandwidthBefore := n.aliceChannelLink.Bandwidth()
var amount btcutil.Amount = btcutil.SatoshiPerBitcoin amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight, htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight,
n.firstBobChannelLink, n.carolChannelLink) n.firstBobChannelLink, n.carolChannelLink)
@ -818,7 +820,7 @@ func TestChannelLinkMultiHopUnknownNextHop(t *testing.T) {
secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth() secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth()
aliceBandwidthBefore := n.aliceChannelLink.Bandwidth() aliceBandwidthBefore := n.aliceChannelLink.Bandwidth()
var amount btcutil.Amount = btcutil.SatoshiPerBitcoin amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight, htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight,
n.firstBobChannelLink, n.carolChannelLink) n.firstBobChannelLink, n.carolChannelLink)
@ -889,7 +891,7 @@ func TestChannelLinkMultiHopDecodeError(t *testing.T) {
secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth() secondBobBandwidthBefore := n.secondBobChannelLink.Bandwidth()
aliceBandwidthBefore := n.aliceChannelLink.Bandwidth() aliceBandwidthBefore := n.aliceChannelLink.Bandwidth()
var amount btcutil.Amount = btcutil.SatoshiPerBitcoin amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight, htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight,
n.firstBobChannelLink, n.carolChannelLink) n.firstBobChannelLink, n.carolChannelLink)
@ -950,7 +952,7 @@ func TestChannelLinkExpiryTooSoonExitNode(t *testing.T) {
} }
defer n.stop() defer n.stop()
var amount btcutil.Amount = btcutil.SatoshiPerBitcoin amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
// We'll craft an HTLC packet, but set the starting height to 10 blocks // We'll craft an HTLC packet, but set the starting height to 10 blocks
// before the current true height. // before the current true height.
@ -991,7 +993,7 @@ func TestChannelLinkExpiryTooSoonMidNode(t *testing.T) {
} }
defer n.stop() defer n.stop()
var amount btcutil.Amount = btcutil.SatoshiPerBitcoin amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
// We'll craft an HTLC packet, but set the starting height to 10 blocks // We'll craft an HTLC packet, but set the starting height to 10 blocks
// before the current true height. The final route will be three hops, // before the current true height. The final route will be three hops,
@ -1096,7 +1098,7 @@ func TestChannelLinkSingleHopMessageOrdering(t *testing.T) {
} }
defer n.stop() defer n.stop()
var amount btcutil.Amount = btcutil.SatoshiPerBitcoin amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight, htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight,
n.firstBobChannelLink) n.firstBobChannelLink)

@ -22,7 +22,6 @@ import (
"github.com/roasbeef/btcd/chaincfg/chainhash" "github.com/roasbeef/btcd/chaincfg/chainhash"
"github.com/roasbeef/btcd/txscript" "github.com/roasbeef/btcd/txscript"
"github.com/roasbeef/btcd/wire" "github.com/roasbeef/btcd/wire"
"github.com/roasbeef/btcutil"
) )
type mockServer struct { type mockServer struct {
@ -371,13 +370,13 @@ func (f *mockChannelLink) HandleChannelUpdate(lnwire.Message) {
func (f *mockChannelLink) UpdateForwardingPolicy(_ ForwardingPolicy) { func (f *mockChannelLink) UpdateForwardingPolicy(_ ForwardingPolicy) {
} }
func (f *mockChannelLink) Stats() (uint64, btcutil.Amount, btcutil.Amount) { func (f *mockChannelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
return 0, 0, 0 return 0, 0, 0
} }
func (f *mockChannelLink) ChanID() lnwire.ChannelID { return f.chanID } func (f *mockChannelLink) ChanID() lnwire.ChannelID { return f.chanID }
func (f *mockChannelLink) ShortChanID() lnwire.ShortChannelID { return f.shortChanID } func (f *mockChannelLink) ShortChanID() lnwire.ShortChannelID { return f.shortChanID }
func (f *mockChannelLink) Bandwidth() btcutil.Amount { return 99999999 } func (f *mockChannelLink) Bandwidth() lnwire.MilliSatoshi { return 99999999 }
func (f *mockChannelLink) Peer() Peer { return f.peer } func (f *mockChannelLink) Peer() Peer { return f.peer }
func (f *mockChannelLink) Start() error { return nil } func (f *mockChannelLink) Start() error { return nil }
func (f *mockChannelLink) Stop() {} func (f *mockChannelLink) Stop() {}

@ -4,7 +4,6 @@ import (
"crypto/sha256" "crypto/sha256"
"github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/lnwire"
"github.com/roasbeef/btcutil"
) )
// htlcPacket is a wrapper around htlc lnwire update, which adds additional // htlcPacket is a wrapper around htlc lnwire update, which adds additional
@ -29,8 +28,7 @@ type htlcPacket struct {
src lnwire.ShortChannelID src lnwire.ShortChannelID
// amount is the value of the HTLC that is being created or modified. // amount is the value of the HTLC that is being created or modified.
// TODO(andrew.shvv) should be removed after introducing sphinx payment. amount lnwire.MilliSatoshi
amount btcutil.Amount
// htlc lnwire message type of which depends on switch request type. // htlc lnwire message type of which depends on switch request type.
htlc lnwire.Message htlc lnwire.Message
@ -77,7 +75,7 @@ func newAddPacket(src, dest lnwire.ShortChannelID,
// settle htlc request which should be created and sent back by last hope in // settle htlc request which should be created and sent back by last hope in
// htlc path. // htlc path.
func newSettlePacket(src lnwire.ShortChannelID, htlc *lnwire.UpdateFufillHTLC, func newSettlePacket(src lnwire.ShortChannelID, htlc *lnwire.UpdateFufillHTLC,
payHash [sha256.Size]byte, amount btcutil.Amount) *htlcPacket { payHash [sha256.Size]byte, amount lnwire.MilliSatoshi) *htlcPacket {
return &htlcPacket{ return &htlcPacket{
src: src, src: src,
@ -92,7 +90,9 @@ func newSettlePacket(src lnwire.ShortChannelID, htlc *lnwire.UpdateFufillHTLC,
// add request if something wrong happened on the path to the final // add request if something wrong happened on the path to the final
// destination. // destination.
func newFailPacket(src lnwire.ShortChannelID, htlc *lnwire.UpdateFailHTLC, func newFailPacket(src lnwire.ShortChannelID, htlc *lnwire.UpdateFailHTLC,
payHash [sha256.Size]byte, amount btcutil.Amount, isObfuscated bool) *htlcPacket { payHash [sha256.Size]byte, amount lnwire.MilliSatoshi,
isObfuscated bool) *htlcPacket {
return &htlcPacket{ return &htlcPacket{
src: src, src: src,
payHash: payHash, payHash: payHash,

@ -5,7 +5,6 @@ import (
"sync" "sync"
"github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/lnwire"
"github.com/roasbeef/btcutil"
) )
// packetQueue represent the wrapper around the original queue plus the // packetQueue represent the wrapper around the original queue plus the
@ -103,11 +102,11 @@ func (q *packetQueue) length() int {
} }
// pendingAmount returns the amount of money which is stored in pending queue. // pendingAmount returns the amount of money which is stored in pending queue.
func (q *packetQueue) pendingAmount() btcutil.Amount { func (q *packetQueue) pendingAmount() lnwire.MilliSatoshi {
q.Lock() q.Lock()
defer q.Unlock() defer q.Unlock()
var amount btcutil.Amount var amount lnwire.MilliSatoshi
for e := q.Front(); e != nil; e = e.Next() { for e := q.Front(); e != nil; e = e.Next() {
packet := e.Value.(*htlcPacket) packet := e.Value.(*htlcPacket)
htlc := packet.htlc.(*lnwire.UpdateAddHTLC) htlc := packet.htlc.(*lnwire.UpdateAddHTLC)

@ -6,7 +6,6 @@ import (
"time" "time"
"github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/lnwire"
"github.com/roasbeef/btcutil"
) )
// TestWaitingQueueThreadSafety test the thread safety properties of the // TestWaitingQueueThreadSafety test the thread safety properties of the
@ -17,16 +16,16 @@ func TestWaitingQueueThreadSafety(t *testing.T) {
q := newWaitingQueue() q := newWaitingQueue()
a := make([]btcutil.Amount, 1000) a := make([]lnwire.MilliSatoshi, 1000)
for i := 0; i < len(a); i++ { for i := 0; i < len(a); i++ {
a[i] = btcutil.Amount(i) a[i] = lnwire.MilliSatoshi(i)
q.consume(&htlcPacket{ q.consume(&htlcPacket{
amount: btcutil.Amount(i), amount: lnwire.MilliSatoshi(i),
htlc: &lnwire.UpdateAddHTLC{}, htlc: &lnwire.UpdateAddHTLC{},
}) })
} }
var b []btcutil.Amount var b []lnwire.MilliSatoshi
for i := 0; i < len(a); i++ { for i := 0; i < len(a); i++ {
q.release() q.release()

@ -1,6 +1,7 @@
package htlcswitch package htlcswitch
import ( import (
"fmt"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
@ -31,7 +32,7 @@ var (
// successfully. // successfully.
type pendingPayment struct { type pendingPayment struct {
paymentHash lnwallet.PaymentHash paymentHash lnwallet.PaymentHash
amount btcutil.Amount amount lnwire.MilliSatoshi
preimage chan [sha256.Size]byte preimage chan [sha256.Size]byte
err chan error err chan error
@ -91,6 +92,8 @@ type Config struct {
// UpdateTopology sends the onion error failure topology update to router // UpdateTopology sends the onion error failure topology update to router
// subsystem. // subsystem.
//
// TODO(roasbeef): remove
UpdateTopology func(msg *lnwire.ChannelUpdate) error UpdateTopology func(msg *lnwire.ChannelUpdate) error
} }
@ -208,14 +211,14 @@ func (s *Switch) SendHTLC(nextNode [33]byte, htlc *lnwire.UpdateAddHTLC,
case e := <-payment.err: case e := <-payment.err:
err = e err = e
case <-s.quit: case <-s.quit:
return zeroPreimage, errors.New("service is shutdown") return zeroPreimage, errors.New("switch is shutting down")
} }
select { select {
case p := <-payment.preimage: case p := <-payment.preimage:
preimage = p preimage = p
case <-s.quit: case <-s.quit:
return zeroPreimage, errors.New("service is shutdown") return zeroPreimage, errors.New("switch is shutting down")
} }
return preimage, err return preimage, err
@ -348,7 +351,7 @@ func (s *Switch) handleLocalDispatch(payment *pendingPayment, packet *htlcPacket
// Will allow us more flexibility w.r.t how we handle // Will allow us more flexibility w.r.t how we handle
// the error. // the error.
if update != nil { if update != nil {
log.Info("Received payment failure(%v), "+ log.Infof("Received payment failure(%v), "+
"applying lightning network topology update", "applying lightning network topology update",
failure.Code()) failure.Code())
@ -624,7 +627,7 @@ func (s *Switch) htlcForwarder() {
case cmd := <-s.htlcPlex: case cmd := <-s.htlcPlex:
var ( var (
paymentHash lnwallet.PaymentHash paymentHash lnwallet.PaymentHash
amount btcutil.Amount amount lnwire.MilliSatoshi
) )
// Only three types of message should be forwarded: // Only three types of message should be forwarded:
@ -677,8 +680,8 @@ func (s *Switch) htlcForwarder() {
// stats printed. // stats printed.
updates, sent, recv := link.Stats() updates, sent, recv := link.Stats()
newNumUpdates += updates newNumUpdates += updates
newSatSent += sent newSatSent += sent.ToSatoshis()
newSatRecv += recv newSatRecv += recv.ToSatoshis()
} }
var ( var (
@ -958,8 +961,9 @@ func (s *Switch) getLinks(destination [33]byte) ([]ChannelLink, error) {
// removePendingPayment is the helper function which removes the pending user // removePendingPayment is the helper function which removes the pending user
// payment. // payment.
func (s *Switch) removePendingPayment(amount btcutil.Amount, func (s *Switch) removePendingPayment(amount lnwire.MilliSatoshi,
hash lnwallet.PaymentHash) error { hash lnwallet.PaymentHash) error {
s.pendingMutex.Lock() s.pendingMutex.Lock()
defer s.pendingMutex.Unlock() defer s.pendingMutex.Unlock()
@ -987,8 +991,9 @@ func (s *Switch) removePendingPayment(amount btcutil.Amount,
} }
// findPayment is the helper function which find the payment. // findPayment is the helper function which find the payment.
func (s *Switch) findPayment(amount btcutil.Amount, func (s *Switch) findPayment(amount lnwire.MilliSatoshi,
hash lnwallet.PaymentHash) (*pendingPayment, error) { hash lnwallet.PaymentHash) (*pendingPayment, error) {
s.pendingMutex.RLock() s.pendingMutex.RLock()
defer s.pendingMutex.RUnlock() defer s.pendingMutex.RUnlock()

@ -183,8 +183,8 @@ func createTestChannel(alicePrivKey, bobPrivKey []byte,
FeePerKw: feePerKw, FeePerKw: feePerKw,
IsInitiator: true, IsInitiator: true,
Capacity: channelCapacity, Capacity: channelCapacity,
LocalBalance: aliceAmount - commitFee, LocalBalance: lnwire.NewMSatFromSatoshis(aliceAmount - commitFee),
RemoteBalance: bobAmount, RemoteBalance: lnwire.NewMSatFromSatoshis(bobAmount),
CommitTx: *aliceCommitTx, CommitTx: *aliceCommitTx,
CommitSig: bytes.Repeat([]byte{1}, 71), CommitSig: bytes.Repeat([]byte{1}, 71),
RemoteCurrentRevocation: bobCommitPoint, RemoteCurrentRevocation: bobCommitPoint,
@ -202,8 +202,8 @@ func createTestChannel(alicePrivKey, bobPrivKey []byte,
ChanType: channeldb.SingleFunder, ChanType: channeldb.SingleFunder,
IsInitiator: false, IsInitiator: false,
Capacity: channelCapacity, Capacity: channelCapacity,
LocalBalance: bobAmount, LocalBalance: lnwire.NewMSatFromSatoshis(bobAmount),
RemoteBalance: aliceAmount - commitFee, RemoteBalance: lnwire.NewMSatFromSatoshis(aliceAmount - commitFee),
CommitTx: *bobCommitTx, CommitTx: *bobCommitTx,
CommitSig: bytes.Repeat([]byte{1}, 71), CommitSig: bytes.Repeat([]byte{1}, 71),
RemoteCurrentRevocation: aliceCommitPoint, RemoteCurrentRevocation: aliceCommitPoint,
@ -274,7 +274,7 @@ func getChanID(msg lnwire.Message) lnwire.ChannelID {
// generatePayment generates the htlc add request by given path blob and // generatePayment generates the htlc add request by given path blob and
// invoice which should be added by destination peer. // invoice which should be added by destination peer.
func generatePayment(invoiceAmt, htlcAmt btcutil.Amount, timelock uint32, func generatePayment(invoiceAmt, htlcAmt lnwire.MilliSatoshi, timelock uint32,
blob [lnwire.OnionPacketSize]byte) (*channeldb.Invoice, *lnwire.UpdateAddHTLC, error) { blob [lnwire.OnionPacketSize]byte) (*channeldb.Invoice, *lnwire.UpdateAddHTLC, error) {
var preimage [sha256.Size]byte var preimage [sha256.Size]byte
@ -343,8 +343,8 @@ type threeHopNetwork struct {
// generateHops creates the per hop payload, the total amount to be sent, and // generateHops creates the per hop payload, the total amount to be sent, and
// also the time lock value needed to route a HTLC with the target amount over // also the time lock value needed to route a HTLC with the target amount over
// the specified path. // the specified path.
func generateHops(payAmt btcutil.Amount, startingHeight uint32, func generateHops(payAmt lnwire.MilliSatoshi, startingHeight uint32,
path ...*channelLink) (btcutil.Amount, uint32, []ForwardingInfo) { path ...*channelLink) (lnwire.MilliSatoshi, uint32, []ForwardingInfo) {
lastHop := path[len(path)-1] lastHop := path[len(path)-1]
@ -413,7 +413,7 @@ func generateHops(payAmt btcutil.Amount, startingHeight uint32,
// * from Alice to some another peer through the Bob // * from Alice to some another peer through the Bob
func (n *threeHopNetwork) makePayment(sendingPeer, receivingPeer Peer, func (n *threeHopNetwork) makePayment(sendingPeer, receivingPeer Peer,
firstHopPub [33]byte, hops []ForwardingInfo, firstHopPub [33]byte, hops []ForwardingInfo,
invoiceAmt, htlcAmt btcutil.Amount, invoiceAmt, htlcAmt lnwire.MilliSatoshi,
timelock uint32) (*channeldb.Invoice, error) { timelock uint32) (*channeldb.Invoice, error) {
sender := sendingPeer.(*mockServer) sender := sendingPeer.(*mockServer)
@ -543,8 +543,8 @@ func newThreeHopNetwork(t *testing.T, aliceToBob,
}, },
} }
globalPolicy := ForwardingPolicy{ globalPolicy := ForwardingPolicy{
MinHTLC: 5, MinHTLC: lnwire.NewMSatFromSatoshis(5),
BaseFee: btcutil.Amount(1), BaseFee: lnwire.NewMSatFromSatoshis(1),
TimeLockDelta: 6, TimeLockDelta: 6,
} }
obfuscator := newMockObfuscator() obfuscator := newMockObfuscator()