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

Implement lsps2.buy #120

Merged
merged 4 commits into from
Aug 21, 2023
Merged
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
3 changes: 2 additions & 1 deletion .github/workflows/integration_tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ jobs:
test: [
testLsps0GetProtocolVersions,
testLsps2GetVersions,
testLsps2GetInfo
testLsps2GetInfo,
testLsps2Buy
]
implementation: [
CLN
Expand Down
4 changes: 4 additions & 0 deletions itest/lspd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,8 @@ var allTestCases = []*testCase{
name: "testLsps2GetInfo",
test: testLsps2GetInfo,
},
{
name: "testLsps2Buy",
test: testLsps2Buy,
},
}
88 changes: 88 additions & 0 deletions itest/lsps2_buy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package itest

import (
"encoding/hex"
"encoding/json"
"log"
"time"

"github.com/breez/lntest"
"github.com/breez/lspd/lsps0"
)

func testLsps2Buy(p *testParams) {
SetFeeParams(p.Lsp(), []*FeeParamSetting{
{
Validity: time.Second * 3600,
MinMsat: 1000000,
Proportional: 1000,
},
})
p.BreezClient().Node().ConnectPeer(p.Lsp().LightningNode())

p.BreezClient().Node().SendCustomMessage(&lntest.CustomMsgRequest{
PeerId: hex.EncodeToString(p.Lsp().NodeId()),
Type: lsps0.Lsps0MessageType,
Data: []byte(`{
"method": "lsps2.get_info",
"jsonrpc": "2.0",
"id": "example#3cad6a54d302edba4c9ade2f7ffac098",
"params": {
"version": 1,
"token": "hello"
}
}`),
})

resp := p.BreezClient().ReceiveCustomMessage()
log.Print(string(resp.Data))

type params struct {
MinFeeMsat uint64 `json:"min_fee_msat,string"`
Proportional uint32 `json:"proportional"`
ValidUntil string `json:"valid_until"`
MinLifetime uint32 `json:"min_lifetime"`
MaxClientToSelfDelay uint32 `json:"max_client_to_self_delay"`
Promise string `json:"promise"`
}
data := new(struct {
Result struct {
Menu []params `json:"opening_fee_params_menu"`
MinPayment uint64 `json:"min_payment_size_msat,string"`
MaxPayment uint64 `json:"max_payment_size_msat,string"`
} `json:"result"`
})
err := json.Unmarshal(resp.Data[:], &data)
lntest.CheckError(p.t, err)

pr, err := json.Marshal(&data.Result.Menu[0])
lntest.CheckError(p.t, err)
p.BreezClient().Node().SendCustomMessage(&lntest.CustomMsgRequest{
PeerId: hex.EncodeToString(p.Lsp().NodeId()),
Type: lsps0.Lsps0MessageType,
Data: append(append(
[]byte(`{
"method": "lsps2.get_info",
"jsonrpc": "2.0",
"id": "example#3cad6a54d302edba4c9ade2f7ffac098",
"params": {
"version": 1,
"payment_size_msat": "42000",
"opening_fee_params":`),
pr...),
[]byte(`}}`)...,
),
})

buyResp := p.BreezClient().ReceiveCustomMessage()
log.Print(string(resp.Data))
b := new(struct {
Result struct {
Jit_channel_scid string `json:"jit_channel_scid"`
Lsp_cltv_expiry_delta uint32 `json:"lsp_cltv_expiry_delta"`
Client_trusts_lsp bool `json:"client_trusts_lsp"`
} `json:"result"`
})
err = json.Unmarshal(buyResp.Data, b)
lntest.CheckError(p.t, err)
}
9 changes: 8 additions & 1 deletion lsps0/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ var BadMessageFormatError string = "bad message format"
var InternalError string = "internal error"
var MaxSimultaneousRequests = 25

type ContextKey string

var PeerContextKey = ContextKey("peerId")

// ServiceDesc and is constructed from it for internal purposes.
type serviceInfo struct {
// Contains the implementation for the methods in this service.
Expand Down Expand Up @@ -139,8 +143,11 @@ func (s *Server) Serve(lis lightning.CustomMsgClient) error {
// another simultaneous request.
defer func() { <-guard }()

ctx := context.Background()
ctx = context.WithValue(ctx, PeerContextKey, msg.PeerId)

// Call the method handler for the requested method.
r, err := m.method.Handler(m.service.serviceImpl, context.TODO(), df)
r, err := m.method.Handler(m.service.serviceImpl, ctx, df)
if err != nil {
s, ok := status.FromError(err)
if !ok {
Expand Down
42 changes: 42 additions & 0 deletions lsps2/fee.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package lsps2

import "fmt"

var ErrOverflow = fmt.Errorf("integer overflow detected")

func computeOpeningFee(paymentSizeMsat uint64, proportional uint32, minFeeMsat uint64) (uint64, error) {
tmp, err := safeMultiply(paymentSizeMsat, uint64(proportional))
if err != nil {
return 0, err
}

tmp, err = safeAdd(tmp, 999_999)
if err != nil {
return 0, err
}

openingFee := tmp / 1_000_000
if openingFee < minFeeMsat {
openingFee = minFeeMsat
}

return openingFee, nil
}

func safeAdd(a uint64, b uint64) (uint64, error) {
sum := a + b
if sum < a {
return 0, ErrOverflow
}

return sum, nil
}

func safeMultiply(a uint64, b uint64) (uint64, error) {
prod := a * b
if a != 0 && ((prod / a) != b) {
return 0, ErrOverflow
}

return prod, nil
}
41 changes: 41 additions & 0 deletions lsps2/fee_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package lsps2

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

func Test_FeeVariant(t *testing.T) {
zero := uint64(0)
tests := []struct {
paymentSizeMsat uint64
proportional uint32
minFeeMsat uint64
err error
expected uint64
}{
{proportional: 0, paymentSizeMsat: 0, minFeeMsat: 0, expected: 0},
{proportional: 0, paymentSizeMsat: 0, minFeeMsat: 1, expected: 1},
{proportional: 1, paymentSizeMsat: 1, minFeeMsat: 0, expected: 1},
{proportional: 1000, paymentSizeMsat: 10_000_000, minFeeMsat: 9999, expected: 10000},
{proportional: 1000, paymentSizeMsat: 10_000_000, minFeeMsat: 10000, expected: 10000},
{proportional: 1000, paymentSizeMsat: 10_000_000, minFeeMsat: 10001, expected: 10001},
{proportional: 1, paymentSizeMsat: zero - 999_999, minFeeMsat: 0, err: ErrOverflow},
{proportional: 1, paymentSizeMsat: zero - 1_000_000, minFeeMsat: 0, expected: 18446744073709},
{proportional: 2, paymentSizeMsat: zero - 1_000_000, minFeeMsat: 0, err: ErrOverflow},
}

for _, tst := range tests {
t.Run(
fmt.Sprintf("ps%d_prop%d_min%d", tst.paymentSizeMsat, tst.proportional, tst.minFeeMsat),
func(t *testing.T) {
res, err := computeOpeningFee(tst.paymentSizeMsat, tst.proportional, tst.minFeeMsat)
assert.Equal(t, tst.expected, res)
assert.Equal(t, tst.err, err)
},
)

}
}
24 changes: 24 additions & 0 deletions lsps2/scid.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package lsps2

import (
"crypto/rand"
"math/big"

"github.com/breez/lspd/basetypes"
)

var one = big.NewInt(1)
var two = big.NewInt(2)
var sixtyfour = big.NewInt(64)
var twoPowSixtyfour = two.Exp(two, sixtyfour, nil)
var maxUint64 = twoPowSixtyfour.Sub(twoPowSixtyfour, one)

func newScid() (*basetypes.ShortChannelID, error) {
s, err := rand.Int(rand.Reader, maxUint64)
if err != nil {
return nil, err
}

scid := basetypes.ShortChannelID(s.Uint64())
return &scid, nil
}
Loading