working on test refactoring

This commit is contained in:
kiwiidb
2022-06-15 11:39:54 +02:00
parent 9e9fc4fbf0
commit 9574b41a08
12 changed files with 299 additions and 324 deletions

View File

@@ -15,7 +15,6 @@ import (
"github.com/getAlby/lndhub.go/lib/responses" "github.com/getAlby/lndhub.go/lib/responses"
"github.com/getAlby/lndhub.go/lib/service" "github.com/getAlby/lndhub.go/lib/service"
"github.com/getAlby/lndhub.go/lib/tokens" "github.com/getAlby/lndhub.go/lib/tokens"
"github.com/getAlby/lndhub.go/lnd"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/lightningnetwork/lnd/lnrpc" "github.com/lightningnetwork/lnd/lnrpc"
@@ -25,7 +24,6 @@ import (
type CheckPaymentTestSuite struct { type CheckPaymentTestSuite struct {
TestSuite TestSuite
fundingClient *lnd.LNDWrapper
service *service.LndhubService service *service.LndhubService
userLogin ExpectedCreateUserResponseBody userLogin ExpectedCreateUserResponseBody
userToken string userToken string
@@ -33,15 +31,6 @@ type CheckPaymentTestSuite struct {
} }
func (suite *CheckPaymentTestSuite) SetupSuite() { func (suite *CheckPaymentTestSuite) SetupSuite() {
lndClient, err := lnd.NewLNDclient(lnd.LNDoptions{
Address: lnd2RegtestAddress,
MacaroonHex: lnd2RegtestMacaroonHex,
})
if err != nil {
log.Fatalf("Error setting up funding client: %v", err)
}
suite.fundingClient = lndClient
svc, err := LndHubTestServiceInit(nil) svc, err := LndHubTestServiceInit(nil)
if err != nil { if err != nil {
log.Fatalf("Error initializing test service: %v", err) log.Fatalf("Error initializing test service: %v", err)
@@ -85,12 +74,11 @@ func (suite *CheckPaymentTestSuite) TestCheckPaymentNotFound() {
func (suite *CheckPaymentTestSuite) TestCheckPaymentProperIsPaidResponse() { func (suite *CheckPaymentTestSuite) TestCheckPaymentProperIsPaidResponse() {
// create incoming invoice and fund account // create incoming invoice and fund account
invoice := suite.createAddInvoiceReq(1000, "integration test check payments for user", suite.userToken) invoice := suite.createAddInvoiceReq(1000, "integration test check payments for user", suite.userToken)
sendPaymentRequest := lnrpc.SendRequest{ //TODO fund
_ = lnrpc.SendRequest{
PaymentRequest: invoice.PayReq, PaymentRequest: invoice.PayReq,
FeeLimit: nil, FeeLimit: nil,
} }
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err)
// wait a bit for the callback event to hit // wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)

View File

@@ -15,7 +15,6 @@ import (
"github.com/getAlby/lndhub.go/lib/responses" "github.com/getAlby/lndhub.go/lib/responses"
"github.com/getAlby/lndhub.go/lib/service" "github.com/getAlby/lndhub.go/lib/service"
"github.com/getAlby/lndhub.go/lib/tokens" "github.com/getAlby/lndhub.go/lib/tokens"
"github.com/getAlby/lndhub.go/lnd"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/lightningnetwork/lnd/lnrpc" "github.com/lightningnetwork/lnd/lnrpc"
@@ -26,23 +25,21 @@ import (
type GetTxTestSuite struct { type GetTxTestSuite struct {
TestSuite TestSuite
Service *service.LndhubService Service *service.LndhubService
fundingClient *lnd.LNDWrapper
userLogin ExpectedCreateUserResponseBody userLogin ExpectedCreateUserResponseBody
userToken string userToken string
mockLND *MockLND
invoiceUpdateSubCancelFn context.CancelFunc invoiceUpdateSubCancelFn context.CancelFunc
} }
func (suite *GetTxTestSuite) SetupSuite() { func (suite *GetTxTestSuite) SetupSuite() {
lndClient, err := lnd.NewLNDclient(lnd.LNDoptions{ mockLND := &MockLND{
Address: lnd2RegtestAddress, Sub: &MockSubscribeInvoices{
MacaroonHex: lnd2RegtestMacaroonHex, invoiceChan: make(chan (*lnrpc.Invoice)),
}) },
if err != nil { fee: 0,
log.Fatalf("Error setting up funding client: %v", err) addIndexCounter: 0,
} }
suite.fundingClient = lndClient svc, err := LndHubTestServiceInit(mockLND)
svc, err := LndHubTestServiceInit(nil)
if err != nil { if err != nil {
log.Fatalf("Error initializing test service: %v", err) log.Fatalf("Error initializing test service: %v", err)
} }
@@ -56,6 +53,7 @@ func (suite *GetTxTestSuite) SetupSuite() {
suite.invoiceUpdateSubCancelFn = cancel suite.invoiceUpdateSubCancelFn = cancel
go svc.InvoiceUpdateSubscription(ctx) go svc.InvoiceUpdateSubscription(ctx)
suite.Service = svc suite.Service = svc
suite.mockLND = mockLND
e := echo.New() e := echo.New()
e.HTTPErrorHandler = responses.HTTPErrorHandler e.HTTPErrorHandler = responses.HTTPErrorHandler
@@ -88,17 +86,14 @@ func (suite *GetTxTestSuite) TestGetOutgoingInvoices() {
assert.Equal(suite.T(), http.StatusOK, rec.Code) assert.Equal(suite.T(), http.StatusOK, rec.Code)
assert.NoError(suite.T(), json.NewDecoder(rec.Body).Decode(&responseBody)) assert.NoError(suite.T(), json.NewDecoder(rec.Body).Decode(&responseBody))
assert.Empty(suite.T(), responseBody) assert.Empty(suite.T(), responseBody)
// create incoming invoice and fund account // fund account
invoice := suite.createAddInvoiceReq(1000, "integration test internal payment alice", suite.userToken) invoice := suite.createAddInvoiceReq(1000, "integration test internal payment alice", suite.userToken)
sendPaymentRequest := lnrpc.SendRequest{ err := suite.mockLND.mockPaidInvoice(invoice)
PaymentRequest: invoice.PayReq,
FeeLimit: nil,
}
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait for a short time to allow the payment to be processed asynchronously
time.Sleep(100 * time.Millisecond) time.Sleep(10 * time.Millisecond)
// create invoice // create invoice
invoice = suite.createAddInvoiceReq(500, "integration test internal payment alice", suite.userToken) invoice = suite.createAddInvoiceReq(500, "integration test internal payment alice", suite.userToken)
// pay invoice, this will create outgoing invoice and settle it // pay invoice, this will create outgoing invoice and settle it

View File

@@ -5,7 +5,6 @@ import (
"context" "context"
"crypto/rand" "crypto/rand"
"crypto/sha256" "crypto/sha256"
"encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
@@ -20,18 +19,15 @@ import (
"github.com/getAlby/lndhub.go/lib/responses" "github.com/getAlby/lndhub.go/lib/responses"
"github.com/getAlby/lndhub.go/lib/service" "github.com/getAlby/lndhub.go/lib/service"
"github.com/getAlby/lndhub.go/lib/tokens" "github.com/getAlby/lndhub.go/lib/tokens"
"github.com/getAlby/lndhub.go/lnd"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/labstack/gommon/random" "github.com/labstack/gommon/random"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
) )
type IncomingPaymentTestSuite struct { type IncomingPaymentTestSuite struct {
TestSuite TestSuite
fundingClient *lnd.LNDWrapper
service *service.LndhubService service *service.LndhubService
userLogin ExpectedCreateUserResponseBody userLogin ExpectedCreateUserResponseBody
userToken string userToken string
@@ -39,15 +35,6 @@ type IncomingPaymentTestSuite struct {
} }
func (suite *IncomingPaymentTestSuite) SetupSuite() { func (suite *IncomingPaymentTestSuite) SetupSuite() {
lndClient, err := lnd.NewLNDclient(lnd.LNDoptions{
Address: lnd2RegtestAddress,
MacaroonHex: lnd2RegtestMacaroonHex,
})
if err != nil {
log.Fatalf("Error setting up funding client: %v", err)
}
suite.fundingClient = lndClient
svc, err := LndHubTestServiceInit(nil) svc, err := LndHubTestServiceInit(nil)
if err != nil { if err != nil {
log.Fatalf("Error initializing test service: %v", err) log.Fatalf("Error initializing test service: %v", err)
@@ -92,15 +79,16 @@ func (suite *IncomingPaymentTestSuite) TestIncomingPayment() {
//assert the user has no balance to start with //assert the user has no balance to start with
assert.Equal(suite.T(), int64(0), balance.BTC.AvailableBalance) assert.Equal(suite.T(), int64(0), balance.BTC.AvailableBalance)
fundingSatAmt := 10 fundingSatAmt := 10
invoiceResponse := suite.createAddInvoiceReq(fundingSatAmt, "integration test IncomingPaymentTestSuite", suite.userToken) //TODO fund
//invoiceResponse := suite.createAddInvoiceReq(fundingSatAmt, "integration test IncomingPaymentTestSuite", suite.userToken)
//try to pay invoice with external node //try to pay invoice with external node
// Prepare the LNRPC call // Prepare the LNRPC call
sendPaymentRequest := lnrpc.SendRequest{ //sendPaymentRequest := lnrpc.SendRequest{
PaymentRequest: invoiceResponse.PayReq, // PaymentRequest: invoiceResponse.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
@@ -129,18 +117,19 @@ func (suite *IncomingPaymentTestSuite) TestIncomingPaymentZeroAmt() {
assert.Equal(suite.T(), http.StatusOK, rec.Code) assert.Equal(suite.T(), http.StatusOK, rec.Code)
assert.NoError(suite.T(), json.NewDecoder(rec.Body).Decode(&balance)) assert.NoError(suite.T(), json.NewDecoder(rec.Body).Decode(&balance))
initialBalance := balance.BTC.AvailableBalance initialBalance := balance.BTC.AvailableBalance
fundingSatAmt := 0 //fundingSatAmt := 0
sendSatAmt := 10 sendSatAmt := 10
invoiceResponse := suite.createAddInvoiceReq(fundingSatAmt, "integration test IncomingPaymentTestSuite", suite.userToken) //todo fund
//invoiceResponse := suite.createAddInvoiceReq(fundingSatAmt, "integration test IncomingPaymentTestSuite", suite.userToken)
//try to pay invoice with external node //try to pay invoice with external node
// Prepare the LNRPC call // Prepare the LNRPC call
sendPaymentRequest := lnrpc.SendRequest{ //sendPaymentRequest := lnrpc.SendRequest{
PaymentRequest: invoiceResponse.PayReq, // PaymentRequest: invoiceResponse.PayReq,
Amt: int64(sendSatAmt), // Amt: int64(sendSatAmt),
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
@@ -175,21 +164,20 @@ func (suite *IncomingPaymentTestSuite) TestIncomingPaymentKeysend() {
preImage, err := randBytesFromStr(32, random.Hex) preImage, err := randBytesFromStr(32, random.Hex)
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
pHash.Write(preImage) pHash.Write(preImage)
destBytes, err := hex.DecodeString(suite.service.IdentityPubkey) //todo fund
assert.NoError(suite.T(), err) //jsendPaymentRequest := lnrpc.SendRequest{
sendPaymentRequest := lnrpc.SendRequest{ //j Dest: destBytes,
Dest: destBytes, //j Amt: int64(keysendSatAmt),
Amt: int64(keysendSatAmt), //j PaymentHash: pHash.Sum(nil),
PaymentHash: pHash.Sum(nil), //j DestFeatures: []lnrpc.FeatureBit{lnrpc.FeatureBit_TLV_ONION_REQ},
DestFeatures: []lnrpc.FeatureBit{lnrpc.FeatureBit_TLV_ONION_REQ}, //j DestCustomRecords: map[uint64][]byte{
DestCustomRecords: map[uint64][]byte{ //j service.TLV_WALLET_ID: []byte(suite.userLogin.Login),
service.TLV_WALLET_ID: []byte(suite.userLogin.Login), //j service.KEYSEND_CUSTOM_RECORD: preImage,
service.KEYSEND_CUSTOM_RECORD: preImage, //j },
}, //j FeeLimit: nil,
FeeLimit: nil, //j}
} //_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //assert.NoError(suite.T(), err)
assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)

View File

@@ -20,7 +20,6 @@ import (
"github.com/getAlby/lndhub.go/lnd" "github.com/getAlby/lndhub.go/lnd"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
) )
@@ -37,15 +36,6 @@ type PaymentTestSuite struct {
} }
func (suite *PaymentTestSuite) SetupSuite() { func (suite *PaymentTestSuite) SetupSuite() {
lndClient, err := lnd.NewLNDclient(lnd.LNDoptions{
Address: lnd3RegtestAddress,
MacaroonHex: lnd3RegtestMacaroonHex,
})
if err != nil {
log.Fatalf("Error setting up funding client: %v", err)
}
suite.fundingClient = lndClient
svc, err := LndHubTestServiceInit(nil) svc, err := LndHubTestServiceInit(nil)
if err != nil { if err != nil {
log.Fatalf("Error initializing test service: %v", err) log.Fatalf("Error initializing test service: %v", err)
@@ -93,14 +83,15 @@ func (suite *PaymentTestSuite) TestInternalPayment() {
bobSatRequested := 500 bobSatRequested := 500
// currently fee is 0 for internal payments // currently fee is 0 for internal payments
fee := 0 fee := 0
//todo fund
//fund alice account //fund alice account
invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test internal payment alice", suite.aliceToken) //invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test internal payment alice", suite.aliceToken)
sendPaymentRequest := lnrpc.SendRequest{ //sendPaymentRequest := lnrpc.SendRequest{
PaymentRequest: invoiceResponse.PayReq, // PaymentRequest: invoiceResponse.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
@@ -145,13 +136,14 @@ func (suite *PaymentTestSuite) TestInternalPaymentFail() {
// currently fee is 0 for internal payments // currently fee is 0 for internal payments
fee := 0 fee := 0
//fund alice account //fund alice account
invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test internal payment alice", suite.aliceToken) //todo
sendPaymentRequest := lnrpc.SendRequest{ //invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test internal payment alice", suite.aliceToken)
PaymentRequest: invoiceResponse.PayReq, //sendPaymentRequest := lnrpc.SendRequest{
FeeLimit: nil, // PaymentRequest: invoiceResponse.PayReq,
} // FeeLimit: nil,
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //}
assert.NoError(suite.T(), err) //_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
//assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
@@ -199,17 +191,18 @@ func (suite *PaymentTestSuite) TestInternalPaymentFail() {
assert.Equal(suite.T(), int64(aliceFundingSats)-int64(bobSatRequested+fee), int64(aliceBalance)) assert.Equal(suite.T(), int64(aliceFundingSats)-int64(bobSatRequested+fee), int64(aliceBalance))
} }
func (suite *PaymentTestSuite) TestInternalPaymentKeysend() { func (suite *PaymentTestSuite) TestInternalPaymentKeysend() {
aliceFundingSats := 1000 //aliceFundingSats := 1000
bobAmt := 100 bobAmt := 100
memo := "integration test internal keysend from alice" memo := "integration test internal keysend from alice"
//todo
//fund alice account //fund alice account
invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test internal keysend alice", suite.aliceToken) //invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test internal keysend alice", suite.aliceToken)
sendPaymentRequest := lnrpc.SendRequest{ //sendPaymentRequest := lnrpc.SendRequest{
PaymentRequest: invoiceResponse.PayReq, // PaymentRequest: invoiceResponse.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)

View File

@@ -12,17 +12,14 @@ import (
"github.com/getAlby/lndhub.go/lib/responses" "github.com/getAlby/lndhub.go/lib/responses"
"github.com/getAlby/lndhub.go/lib/service" "github.com/getAlby/lndhub.go/lib/service"
"github.com/getAlby/lndhub.go/lib/tokens" "github.com/getAlby/lndhub.go/lib/tokens"
"github.com/getAlby/lndhub.go/lnd"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
) )
type KeySendTestSuite struct { type KeySendTestSuite struct {
TestSuite TestSuite
fundingClient *lnd.LNDWrapper
service *service.LndhubService service *service.LndhubService
aliceLogin ExpectedCreateUserResponseBody aliceLogin ExpectedCreateUserResponseBody
aliceToken string aliceToken string
@@ -30,14 +27,6 @@ type KeySendTestSuite struct {
} }
func (suite *KeySendTestSuite) SetupSuite() { func (suite *KeySendTestSuite) SetupSuite() {
lndClient, err := lnd.NewLNDclient(lnd.LNDoptions{
Address: lnd2RegtestAddress,
MacaroonHex: lnd2RegtestMacaroonHex,
})
if err != nil {
log.Fatalf("Error setting up funding client: %v", err)
}
suite.fundingClient = lndClient
svc, err := LndHubTestServiceInit(nil) svc, err := LndHubTestServiceInit(nil)
if err != nil { if err != nil {
@@ -84,18 +73,20 @@ func (suite *KeySendTestSuite) TestKeysendPayment() {
// 1 sat + 1 ppm // 1 sat + 1 ppm
fee := 1 fee := 1
//fund alice account //fund alice account
invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test external payment alice", suite.aliceToken) //todo
sendPaymentRequest := lnrpc.SendRequest{ // invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test external payment alice", suite.aliceToken)
PaymentRequest: invoiceResponse.PayReq, // sendPaymentRequest := lnrpc.SendRequest{
FeeLimit: nil, // PaymentRequest: invoiceResponse.PayReq,
} // FeeLimit: nil,
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) // }
assert.NoError(suite.T(), err) // _, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
// assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
suite.createKeySendReq(int64(externalSatRequested), "key send test", simnetLnd3PubKey, suite.aliceToken) //todo
//suite.createKeySendReq(int64(externalSatRequested), "key send test", simnetLnd3PubKey, suite.aliceToken)
// check that balance was reduced // check that balance was reduced
userId := getUserIdFromToken(suite.aliceToken) userId := getUserIdFromToken(suite.aliceToken)
@@ -107,16 +98,17 @@ func (suite *KeySendTestSuite) TestKeysendPayment() {
} }
func (suite *KeySendTestSuite) TestKeysendPaymentNonExistentDestination() { func (suite *KeySendTestSuite) TestKeysendPaymentNonExistentDestination() {
aliceFundingSats := 1000 //aliceFundingSats := 1000
externalSatRequested := 500 externalSatRequested := 500
//fund alice account //fund alice account
invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test external payment alice", suite.aliceToken) //todo
sendPaymentRequest := lnrpc.SendRequest{ //invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test external payment alice", suite.aliceToken)
PaymentRequest: invoiceResponse.PayReq, //sendPaymentRequest := lnrpc.SendRequest{
FeeLimit: nil, // PaymentRequest: invoiceResponse.PayReq,
} // FeeLimit: nil,
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //}
assert.NoError(suite.T(), err) //_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
//assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)

View File

@@ -2,6 +2,10 @@ package integration_tests
import ( import (
"context" "context"
"crypto/ecdsa"
"crypto/sha256"
"encoding/hex"
"math/big"
"time" "time"
"github.com/btcsuite/btcd/btcec" "github.com/btcsuite/btcd/btcec"
@@ -23,6 +27,31 @@ type MockSubscribeInvoices struct {
invoiceChan chan (*lnrpc.Invoice) invoiceChan chan (*lnrpc.Invoice)
} }
const privkey = "0123456789abcdef"
func getPubkey() ecdsa.PublicKey {
privKeyBytes, _ := hex.DecodeString(privkey)
x, y := btcec.S256().ScalarBaseMult(privKeyBytes)
return ecdsa.PublicKey{
Curve: btcec.S256(),
X: x,
Y: y,
}
}
func signMsg(msg []byte) ([]byte, error) {
privKeyBytes, err := hex.DecodeString(privkey)
if err != nil {
return nil, err
}
ecdsaPrivKey := &ecdsa.PrivateKey{
PublicKey: getPubkey(),
D: new(big.Int).SetBytes(privKeyBytes),
}
return btcec.SignCompact(btcec.S256(), (*btcec.PrivateKey)(ecdsaPrivKey),
msg, true)
}
func (mockSub *MockSubscribeInvoices) Recv() (*lnrpc.Invoice, error) { func (mockSub *MockSubscribeInvoices) Recv() (*lnrpc.Invoice, error) {
inv := <-mockSub.invoiceChan inv := <-mockSub.invoiceChan
return inv, nil return inv, nil
@@ -51,38 +80,76 @@ func (mlnd *MockLND) SendPaymentSync(ctx context.Context, req *lnrpc.SendRequest
} }
func (mlnd *MockLND) AddInvoice(ctx context.Context, req *lnrpc.Invoice, options ...grpc.CallOption) (*lnrpc.AddInvoiceResponse, error) { func (mlnd *MockLND) AddInvoice(ctx context.Context, req *lnrpc.Invoice, options ...grpc.CallOption) (*lnrpc.AddInvoiceResponse, error) {
msat := lnwire.MilliSatoshi(req.ValueMsat) pHash := sha256.New()
pHash.Write(req.RPreimage)
pHash.Sum(nil)
msat := lnwire.MilliSatoshi(1000 * req.Value)
invoice := &zpay32.Invoice{ invoice := &zpay32.Invoice{
Net: &chaincfg.Params{}, Net: &chaincfg.RegressionNetParams,
MilliSat: &msat, MilliSat: &msat,
Timestamp: time.Now(), Timestamp: time.Now(),
PaymentHash: &[32]byte{}, PaymentHash: &[32]byte{},
PaymentAddr: &[32]byte{}, PaymentAddr: &[32]byte{},
Destination: &btcec.PublicKey{}, Features: &lnwire.FeatureVector{
Description: new(string), RawFeatureVector: &lnwire.RawFeatureVector{},
DescriptionHash: &[32]byte{},
FallbackAddr: nil,
}
copy(req.RHash, invoice.PaymentHash[:])
copy(req.PaymentAddr, invoice.PaymentAddr[:])
copy(req.DescriptionHash, invoice.DescriptionHash[:])
pr, err := invoice.Encode(zpay32.MessageSigner{
SignCompact: func(msg []byte) ([]byte, error) {
return []byte{}, nil
}, },
FallbackAddr: nil,
}
copy(invoice.PaymentHash[:], pHash.Sum(nil))
copy(invoice.PaymentAddr[:], req.PaymentAddr)
if len(req.DescriptionHash) != 0 {
invoice.DescriptionHash = &[32]byte{}
copy(req.DescriptionHash, invoice.DescriptionHash[:])
}
if req.Memo != "" {
invoice.Description = &req.Memo
}
pr, err := invoice.Encode(zpay32.MessageSigner{
SignCompact: signMsg,
}) })
if err != nil { if err != nil {
return nil, err return nil, err
} }
mlnd.addIndexCounter += 1 mlnd.addIndexCounter += 1
return &lnrpc.AddInvoiceResponse{ return &lnrpc.AddInvoiceResponse{
RHash: req.RHash, RHash: invoice.PaymentHash[:],
PaymentRequest: pr, PaymentRequest: pr,
AddIndex: mlnd.addIndexCounter, AddIndex: mlnd.addIndexCounter,
PaymentAddr: []byte{},
}, nil }, nil
} }
func (mlnd *MockLND) mockPaidInvoice(added *ExpectedAddInvoiceResponseBody) error {
inv, err := mlnd.DecodeBolt11(context.Background(), added.PayReq)
if err != nil {
return err
}
rhash, err := hex.DecodeString(added.RHash)
if err != nil {
return err
}
mlnd.Sub.invoiceChan <- &lnrpc.Invoice{
Memo: inv.Description,
RPreimage: []byte("123preimage"),
RHash: rhash,
Value: inv.NumSatoshis,
ValueMsat: inv.NumMsat,
Settled: true,
CreationDate: time.Now().Unix(),
SettleDate: time.Now().Unix(),
PaymentRequest: added.PayReq,
DescriptionHash: []byte(inv.DescriptionHash),
FallbackAddr: inv.FallbackAddr,
CltvExpiry: uint64(inv.CltvExpiry),
AmtPaid: inv.NumSatoshis,
AmtPaidSat: inv.NumSatoshis,
AmtPaidMsat: inv.NumMsat,
State: lnrpc.Invoice_SETTLED,
Htlcs: []*lnrpc.InvoiceHTLC{},
IsKeysend: false,
}
return nil
}
func (mlnd *MockLND) SubscribeInvoices(ctx context.Context, req *lnrpc.InvoiceSubscription, options ...grpc.CallOption) (lnd.SubscribeInvoicesWrapper, error) { func (mlnd *MockLND) SubscribeInvoices(ctx context.Context, req *lnrpc.InvoiceSubscription, options ...grpc.CallOption) (lnd.SubscribeInvoicesWrapper, error) {
return mlnd.Sub, nil return mlnd.Sub, nil
} }
@@ -106,7 +173,7 @@ func (mlnd *MockLND) GetInfo(ctx context.Context, req *lnrpc.GetInfoRequest, opt
Testnet: false, Testnet: false,
Chains: []*lnrpc.Chain{{ Chains: []*lnrpc.Chain{{
Chain: "BTC", Chain: "BTC",
Network: "mainnet", Network: "regtest",
}}, }},
Uris: []string{"https://mocky.mcmockface.com"}, Uris: []string{"https://mocky.mcmockface.com"},
Features: map[uint32]*lnrpc.Feature{}, Features: map[uint32]*lnrpc.Feature{},
@@ -114,23 +181,25 @@ func (mlnd *MockLND) GetInfo(ctx context.Context, req *lnrpc.GetInfoRequest, opt
} }
func (mlnd *MockLND) DecodeBolt11(ctx context.Context, bolt11 string, options ...grpc.CallOption) (*lnrpc.PayReq, error) { func (mlnd *MockLND) DecodeBolt11(ctx context.Context, bolt11 string, options ...grpc.CallOption) (*lnrpc.PayReq, error) {
inv, err := zpay32.Decode(bolt11, &chaincfg.MainNetParams) inv, err := zpay32.Decode(bolt11, &chaincfg.RegressionNetParams)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &lnrpc.PayReq{ result := &lnrpc.PayReq{
Destination: string(inv.Destination.SerializeCompressed()), Destination: string(inv.Destination.SerializeCompressed()),
PaymentHash: string(inv.PaymentHash[:]), PaymentHash: string(inv.PaymentHash[:]),
NumSatoshis: int64(*inv.MilliSat) / 1000, NumSatoshis: int64(*inv.MilliSat) / 1000,
Timestamp: inv.Timestamp.Unix(), Timestamp: inv.Timestamp.Unix(),
Expiry: int64(inv.Expiry()), Expiry: int64(inv.Expiry()),
Description: *inv.Description, Description: *inv.Description,
DescriptionHash: string(inv.DescriptionHash[:]), CltvExpiry: int64(inv.MinFinalCLTVExpiry()),
FallbackAddr: inv.FallbackAddr.EncodeAddress(), RouteHints: []*lnrpc.RouteHint{},
CltvExpiry: int64(inv.MinFinalCLTVExpiry()), PaymentAddr: []byte{},
RouteHints: []*lnrpc.RouteHint{}, NumMsat: int64(*inv.MilliSat),
PaymentAddr: []byte{}, Features: map[uint32]*lnrpc.Feature{},
NumMsat: int64(*inv.MilliSat), }
Features: map[uint32]*lnrpc.Feature{}, if inv.DescriptionHash != nil {
}, nil result.DescriptionHash = string(inv.DescriptionHash[:])
}
return result, nil
} }

View File

@@ -15,6 +15,7 @@ import (
func (suite *PaymentTestSuite) TestOutGoingPayment() { func (suite *PaymentTestSuite) TestOutGoingPayment() {
aliceFundingSats := 1000 aliceFundingSats := 1000
//todo
externalSatRequested := 500 externalSatRequested := 500
// 1 sat + 1 ppm // 1 sat + 1 ppm
fee := 1 fee := 1

View File

@@ -16,14 +16,12 @@ import (
"github.com/getAlby/lndhub.go/lnd" "github.com/getAlby/lndhub.go/lnd"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
) )
type PaymentTestAsyncErrorsSuite struct { type PaymentTestAsyncErrorsSuite struct {
TestSuite TestSuite
fundingClient *lnd.LNDWrapper
service *service.LndhubService service *service.LndhubService
userLogin ExpectedCreateUserResponseBody userLogin ExpectedCreateUserResponseBody
userToken string userToken string
@@ -32,25 +30,15 @@ type PaymentTestAsyncErrorsSuite struct {
} }
func (suite *PaymentTestAsyncErrorsSuite) SetupSuite() { func (suite *PaymentTestAsyncErrorsSuite) SetupSuite() {
// use real client for funding only
fundingClient, err := lnd.NewLNDclient(lnd.LNDoptions{
Address: lnd2RegtestAddress,
MacaroonHex: lnd2RegtestMacaroonHex,
})
if err != nil {
log.Fatalf("Error setting up funding client: %v", err)
}
// inject fake lnd client with failing send payment sync into service // inject fake lnd client with failing send payment sync into service
lndClient, err := NewLNDMockWrapperAsync(lnd.LNDoptions{ lndClient, err := NewLNDMockWrapperAsync(lnd.LNDoptions{
Address: lnd1RegtestAddress, Address: mockLNDAddress,
MacaroonHex: lnd1RegtestMacaroonHex, MacaroonHex: mockLNDMacaroonHex,
}) })
suite.serviceClient = lndClient suite.serviceClient = lndClient
if err != nil { if err != nil {
log.Fatalf("Error setting up test client: %v", err) log.Fatalf("Error setting up test client: %v", err)
} }
suite.fundingClient = fundingClient
svc, err := LndHubTestServiceInit(lndClient) svc, err := LndHubTestServiceInit(lndClient)
if err != nil { if err != nil {
@@ -85,26 +73,26 @@ func (suite *PaymentTestAsyncErrorsSuite) TestExternalAsyncFailingInvoice() {
userFundingSats := 1000 userFundingSats := 1000
externalSatRequested := 500 externalSatRequested := 500
// fund user account // fund user account
invoiceResponse := suite.createAddInvoiceReq(userFundingSats, "integration test external payment user", suite.userToken) //invoiceResponse := suite.createAddInvoiceReq(userFundingSats, "integration test external payment user", suite.userToken)
sendPaymentRequest := lnrpc.SendRequest{ //sendPaymentRequest := lnrpc.SendRequest{
PaymentRequest: invoiceResponse.PayReq, // PaymentRequest: invoiceResponse.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
// wait a bit for the callback event to hit // wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
// create external invoice // create external invoice
externalInvoice := lnrpc.Invoice{ //externalInvoice := lnrpc.Invoice{
Memo: "integration tests: external pay from user", // Memo: "integration tests: external pay from user",
Value: int64(externalSatRequested), // Value: int64(externalSatRequested),
} //}
invoice, err := suite.fundingClient.AddInvoice(context.Background(), &externalInvoice) //invoice, err := suite.fundingClient.AddInvoice(context.Background(), &externalInvoice)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
// pay external from user, req will be canceled after 2 sec // pay external from user, req will be canceled after 2 sec
go suite.createPayInvoiceReqWithCancel(invoice.PaymentRequest, suite.userToken) //go suite.createPayInvoiceReqWithCancel(invoice.PaymentRequest, suite.userToken)
// wait for request to fail // wait for request to fail
time.Sleep(5 * time.Second) time.Sleep(5 * time.Second)

View File

@@ -16,14 +16,12 @@ import (
"github.com/getAlby/lndhub.go/lnd" "github.com/getAlby/lndhub.go/lnd"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
) )
type PaymentTestErrorsSuite struct { type PaymentTestErrorsSuite struct {
TestSuite TestSuite
fundingClient *lnd.LNDWrapper
service *service.LndhubService service *service.LndhubService
userLogin ExpectedCreateUserResponseBody userLogin ExpectedCreateUserResponseBody
userToken string userToken string
@@ -31,24 +29,14 @@ type PaymentTestErrorsSuite struct {
} }
func (suite *PaymentTestErrorsSuite) SetupSuite() { func (suite *PaymentTestErrorsSuite) SetupSuite() {
// use real client for funding only
fundingClient, err := lnd.NewLNDclient(lnd.LNDoptions{
Address: lnd2RegtestAddress,
MacaroonHex: lnd2RegtestMacaroonHex,
})
if err != nil {
log.Fatalf("Error setting up funding client: %v", err)
}
// inject fake lnd client with failing send payment sync into service // inject fake lnd client with failing send payment sync into service
lndClient, err := NewLNDMockWrapper(lnd.LNDoptions{ lndClient, err := NewLNDMockWrapper(lnd.LNDoptions{
Address: lnd1RegtestAddress, Address: mockLNDAddress,
MacaroonHex: lnd1RegtestMacaroonHex, MacaroonHex: mockLNDMacaroonHex,
}) })
if err != nil { if err != nil {
log.Fatalf("Error setting up test client: %v", err) log.Fatalf("Error setting up test client: %v", err)
} }
suite.fundingClient = fundingClient
svc, err := LndHubTestServiceInit(lndClient) svc, err := LndHubTestServiceInit(lndClient)
if err != nil { if err != nil {
@@ -83,26 +71,26 @@ func (suite *PaymentTestErrorsSuite) TestExternalFailingInvoice() {
userFundingSats := 1000 userFundingSats := 1000
externalSatRequested := 500 externalSatRequested := 500
//fund user account //fund user account
invoiceResponse := suite.createAddInvoiceReq(userFundingSats, "integration test external payment user", suite.userToken) //invoiceResponse := suite.createAddInvoiceReq(userFundingSats, "integration test external payment user", suite.userToken)
sendPaymentRequest := lnrpc.SendRequest{ //sendPaymentRequest := lnrpc.SendRequest{
PaymentRequest: invoiceResponse.PayReq, // PaymentRequest: invoiceResponse.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
//wait a bit for the callback event to hit //wait a bit for the callback event to hit
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
//create external invoice //create external invoice
externalInvoice := lnrpc.Invoice{ //externalInvoice := lnrpc.Invoice{
Memo: "integration tests: external pay from user", // Memo: "integration tests: external pay from user",
Value: int64(externalSatRequested), // Value: int64(externalSatRequested),
} //}
invoice, err := suite.fundingClient.AddInvoice(context.Background(), &externalInvoice) //invoice, err := suite.fundingClient.AddInvoice(context.Background(), &externalInvoice)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
//pay external from user, mock will fail immediately //pay external from user, mock will fail immediately
_ = suite.createPayInvoiceReqError(invoice.PaymentRequest, suite.userToken) //_ = suite.createPayInvoiceReqError(invoice.PaymentRequest, suite.userToken)
userId := getUserIdFromToken(suite.userToken) userId := getUserIdFromToken(suite.userToken)

View File

@@ -23,18 +23,24 @@ import (
"github.com/uptrace/bun/migrate" "github.com/uptrace/bun/migrate"
) )
//not used anymore
// const (
// lnd1RegtestAddress = "rpc.lnd1.regtest.getalby.com:443"
// lnd1RegtestMacaroonHex = "0201036c6e6402f801030a10e2133a1cac2c5b4d56e44e32dc64c8551201301a160a0761646472657373120472656164120577726974651a130a04696e666f120472656164120577726974651a170a08696e766f69636573120472656164120577726974651a210a086d616361726f6f6e120867656e6572617465120472656164120577726974651a160a076d657373616765120472656164120577726974651a170a086f6666636861696e120472656164120577726974651a160a076f6e636861696e120472656164120577726974651a140a057065657273120472656164120577726974651a180a067369676e6572120867656e657261746512047265616400000620c4f9783e0873fa50a2091806f5ebb919c5dc432e33800b401463ada6485df0ed"
// lnd2RegtestAddress = "rpc.lnd2.regtest.getalby.com:443"
// lnd2RegtestMacaroonHex = "0201036C6E6402F801030A101782922F4358E80655920FC7A7C3E9291201301A160A0761646472657373120472656164120577726974651A130A04696E666F120472656164120577726974651A170A08696E766F69636573120472656164120577726974651A210A086D616361726F6F6E120867656E6572617465120472656164120577726974651A160A076D657373616765120472656164120577726974651A170A086F6666636861696E120472656164120577726974651A160A076F6E636861696E120472656164120577726974651A140A057065657273120472656164120577726974651A180A067369676E6572120867656E657261746512047265616400000620628FFB2938C8540DD3AA5E578D9B43456835FAA176E175FFD4F9FBAE540E3BE9"
// // Use lnd3 for a funding client when testing out fee handling for payments done by lnd-1, since lnd3 doesn't have a direct channel to lnd1.
// // This will cause payment to be routed through lnd2, which will charge a fee (lnd default fee 1 sat base + 1 ppm).
// lnd3RegtestAddress = "rpc.lnd3.regtest.getalby.com:443"
// lnd3RegtestMacaroonHex = "0201036c6e6402f801030a102a5aa69a5efdf4b4a55a5304b164641f1201301a160a0761646472657373120472656164120577726974651a130a04696e666f120472656164120577726974651a170a08696e766f69636573120472656164120577726974651a210a086d616361726f6f6e120867656e6572617465120472656164120577726974651a160a076d657373616765120472656164120577726974651a170a086f6666636861696e120472656164120577726974651a160a076f6e636861696e120472656164120577726974651a140a057065657273120472656164120577726974651a180a067369676e6572120867656e657261746512047265616400000620defbb5a809262297fd661a9ab6d3deb4b7acca4f1309c79addb952f0dc2d8c82"
// simnetLnd1PubKey = "0242898f86064c2fd72de22059c947a83ba23e9d97aedeae7b6dba647123f1d71b"
// simnetLnd2PubKey = "025c1d5d1b4c983cc6350fc2d756fbb59b4dc365e45e87f8e3afe07e24013e8220"
// simnetLnd3PubKey = "03c7092d076f799ab18806743634b4c9bb34e351bdebc91d5b35963f3dc63ec5aa"
// )
const ( const (
lnd1RegtestAddress = "rpc.lnd1.regtest.getalby.com:443" mockLNDAddress = "mock.lnd.local"
lnd1RegtestMacaroonHex = "0201036c6e6402f801030a10e2133a1cac2c5b4d56e44e32dc64c8551201301a160a0761646472657373120472656164120577726974651a130a04696e666f120472656164120577726974651a170a08696e766f69636573120472656164120577726974651a210a086d616361726f6f6e120867656e6572617465120472656164120577726974651a160a076d657373616765120472656164120577726974651a170a086f6666636861696e120472656164120577726974651a160a076f6e636861696e120472656164120577726974651a140a057065657273120472656164120577726974651a180a067369676e6572120867656e657261746512047265616400000620c4f9783e0873fa50a2091806f5ebb919c5dc432e33800b401463ada6485df0ed" mockLNDMacaroonHex = "omnomnom"
lnd2RegtestAddress = "rpc.lnd2.regtest.getalby.com:443"
lnd2RegtestMacaroonHex = "0201036C6E6402F801030A101782922F4358E80655920FC7A7C3E9291201301A160A0761646472657373120472656164120577726974651A130A04696E666F120472656164120577726974651A170A08696E766F69636573120472656164120577726974651A210A086D616361726F6F6E120867656E6572617465120472656164120577726974651A160A076D657373616765120472656164120577726974651A170A086F6666636861696E120472656164120577726974651A160A076F6E636861696E120472656164120577726974651A140A057065657273120472656164120577726974651A180A067369676E6572120867656E657261746512047265616400000620628FFB2938C8540DD3AA5E578D9B43456835FAA176E175FFD4F9FBAE540E3BE9"
// Use lnd3 for a funding client when testing out fee handling for payments done by lnd-1, since lnd3 doesn't have a direct channel to lnd1.
// This will cause payment to be routed through lnd2, which will charge a fee (lnd default fee 1 sat base + 1 ppm).
lnd3RegtestAddress = "rpc.lnd3.regtest.getalby.com:443"
lnd3RegtestMacaroonHex = "0201036c6e6402f801030a102a5aa69a5efdf4b4a55a5304b164641f1201301a160a0761646472657373120472656164120577726974651a130a04696e666f120472656164120577726974651a170a08696e766f69636573120472656164120577726974651a210a086d616361726f6f6e120867656e6572617465120472656164120577726974651a160a076d657373616765120472656164120577726974651a170a086f6666636861696e120472656164120577726974651a160a076f6e636861696e120472656164120577726974651a140a057065657273120472656164120577726974651a180a067369676e6572120867656e657261746512047265616400000620defbb5a809262297fd661a9ab6d3deb4b7acca4f1309c79addb952f0dc2d8c82"
simnetLnd1PubKey = "0242898f86064c2fd72de22059c947a83ba23e9d97aedeae7b6dba647123f1d71b"
simnetLnd2PubKey = "025c1d5d1b4c983cc6350fc2d756fbb59b4dc365e45e87f8e3afe07e24013e8220"
simnetLnd3PubKey = "03c7092d076f799ab18806743634b4c9bb34e351bdebc91d5b35963f3dc63ec5aa"
) )
func LndHubTestServiceInit(lndClientMock lnd.LightningClientWrapper) (svc *service.LndhubService, err error) { func LndHubTestServiceInit(lndClientMock lnd.LightningClientWrapper) (svc *service.LndhubService, err error) {
@@ -47,8 +53,8 @@ func LndHubTestServiceInit(lndClientMock lnd.LightningClientWrapper) (svc *servi
JWTSecret: []byte("SECRET"), JWTSecret: []byte("SECRET"),
JWTAccessTokenExpiry: 3600, JWTAccessTokenExpiry: 3600,
JWTRefreshTokenExpiry: 3600, JWTRefreshTokenExpiry: 3600,
LNDAddress: lnd1RegtestAddress, LNDAddress: mockLNDAddress,
LNDMacaroonHex: lnd1RegtestMacaroonHex, LNDMacaroonHex: mockLNDMacaroonHex,
} }
dbConn, err := db.Open(c.DatabaseUri) dbConn, err := db.Open(c.DatabaseUri)
if err != nil { if err != nil {
@@ -66,27 +72,14 @@ func LndHubTestServiceInit(lndClientMock lnd.LightningClientWrapper) (svc *servi
return nil, fmt.Errorf("failed to migrate: %w", err) return nil, fmt.Errorf("failed to migrate: %w", err)
} }
var lndClient lnd.LightningClientWrapper
if lndClientMock == nil {
lndClient, err = lnd.NewLNDclient(lnd.LNDoptions{
Address: c.LNDAddress,
MacaroonHex: c.LNDMacaroonHex,
})
if err != nil {
return nil, fmt.Errorf("failed to initialize lnd service client: %w", err)
}
} else {
lndClient = lndClientMock
}
logger := lib.Logger(c.LogFilePath) logger := lib.Logger(c.LogFilePath)
svc = &service.LndhubService{ svc = &service.LndhubService{
Config: c, Config: c,
DB: dbConn, DB: dbConn,
LndClient: lndClient, LndClient: lndClientMock,
Logger: logger, Logger: logger,
} }
getInfo, err := lndClient.GetInfo(ctx, &lnrpc.GetInfoRequest{}) getInfo, err := lndClientMock.GetInfo(ctx, &lnrpc.GetInfoRequest{})
if err != nil { if err != nil {
logger.Fatalf("Error getting node info: %v", err) logger.Fatalf("Error getting node info: %v", err)
} }

View File

@@ -35,19 +35,10 @@ type WebHookTestSuite struct {
} }
func (suite *WebHookTestSuite) SetupSuite() { func (suite *WebHookTestSuite) SetupSuite() {
lndClient, err := lnd.NewLNDclient(lnd.LNDoptions{
Address: lnd2RegtestAddress,
MacaroonHex: lnd2RegtestMacaroonHex,
})
if err != nil {
log.Fatalf("Error setting up funding client: %v", err)
}
suite.fundingClient = lndClient
suite.invoiceChan = make(chan models.Invoice) suite.invoiceChan = make(chan models.Invoice)
webhookServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { webhookServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
invoice := models.Invoice{} invoice := models.Invoice{}
err = json.NewDecoder(r.Body).Decode(&invoice) err := json.NewDecoder(r.Body).Decode(&invoice)
if err != nil { if err != nil {
suite.echo.Logger.Error(err) suite.echo.Logger.Error(err)
close(suite.invoiceChan) close(suite.invoiceChan)

View File

@@ -15,11 +15,9 @@ import (
"github.com/getAlby/lndhub.go/lib/responses" "github.com/getAlby/lndhub.go/lib/responses"
"github.com/getAlby/lndhub.go/lib/service" "github.com/getAlby/lndhub.go/lib/service"
"github.com/getAlby/lndhub.go/lib/tokens" "github.com/getAlby/lndhub.go/lib/tokens"
"github.com/getAlby/lndhub.go/lnd"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
) )
@@ -30,7 +28,6 @@ type KeepAlive struct {
type WebSocketTestSuite struct { type WebSocketTestSuite struct {
TestSuite TestSuite
fundingClient *lnd.LNDWrapper
service *service.LndhubService service *service.LndhubService
userLogin ExpectedCreateUserResponseBody userLogin ExpectedCreateUserResponseBody
userToken string userToken string
@@ -55,14 +52,6 @@ func (h *WsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
func (suite *WebSocketTestSuite) SetupSuite() { func (suite *WebSocketTestSuite) SetupSuite() {
lndClient, err := lnd.NewLNDclient(lnd.LNDoptions{
Address: lnd2RegtestAddress,
MacaroonHex: lnd2RegtestMacaroonHex,
})
if err != nil {
log.Fatalf("Error setting up funding client: %v", err)
}
suite.fundingClient = lndClient
svc, err := LndHubTestServiceInit(nil) svc, err := LndHubTestServiceInit(nil)
if err != nil { if err != nil {
@@ -111,13 +100,13 @@ func (suite *WebSocketTestSuite) TestWebSocket() {
assert.Equal(suite.T(), "keepalive", keepAlive.Type) assert.Equal(suite.T(), "keepalive", keepAlive.Type)
// create incoming invoice and fund account // create incoming invoice and fund account
invoice := suite.createAddInvoiceReq(1000, "integration test websocket 1", suite.userToken) //invoice := suite.createAddInvoiceReq(1000, "integration test websocket 1", suite.userToken)
sendPaymentRequest := lnrpc.SendRequest{ //sendPaymentRequest := lnrpc.SendRequest{
PaymentRequest: invoice.PayReq, // PaymentRequest: invoice.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
_, msg, err = ws.ReadMessage() _, msg, err = ws.ReadMessage()
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
@@ -142,12 +131,12 @@ func (suite *WebSocketTestSuite) TestWebSocketDoubeSubscription() {
//read keepalive msg //read keepalive msg
_, _, err = ws2.ReadMessage() _, _, err = ws2.ReadMessage()
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
invoice := suite.createAddInvoiceReq(1000, "integration test websocket 2", suite.userToken) //invoice := suite.createAddInvoiceReq(1000, "integration test websocket 2", suite.userToken)
sendPaymentRequest := lnrpc.SendRequest{ //sendPaymentRequest := lnrpc.SendRequest{
PaymentRequest: invoice.PayReq, // PaymentRequest: invoice.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
_, msg1, err := ws1.ReadMessage() _, msg1, err := ws1.ReadMessage()
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
@@ -164,12 +153,12 @@ func (suite *WebSocketTestSuite) TestWebSocketDoubeSubscription() {
assert.Equal(suite.T(), "integration test websocket 2", event2.Invoice.Description) assert.Equal(suite.T(), "integration test websocket 2", event2.Invoice.Description)
//close 1 subscription, assert that the existing sub still receives their invoices //close 1 subscription, assert that the existing sub still receives their invoices
ws1.Close() ws1.Close()
invoice = suite.createAddInvoiceReq(1000, "integration test websocket 3", suite.userToken) //invoice = suite.createAddInvoiceReq(1000, "integration test websocket 3", suite.userToken)
sendPaymentRequest = lnrpc.SendRequest{ //sendPaymentRequest = lnrpc.SendRequest{
PaymentRequest: invoice.PayReq, // PaymentRequest: invoice.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
_, msg3, err := ws2.ReadMessage() _, msg3, err := ws2.ReadMessage()
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
@@ -194,21 +183,21 @@ func (suite *WebSocketTestSuite) TestWebSocketDoubleUser() {
_, _, err = user2Ws.ReadMessage() _, _, err = user2Ws.ReadMessage()
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
// add invoice for user 1 // add invoice for user 1
user1Invoice := suite.createAddInvoiceReq(1000, "integration test websocket user 1", suite.userToken) //user1Invoice := suite.createAddInvoiceReq(1000, "integration test websocket user 1", suite.userToken)
sendPaymentRequestUser1 := lnrpc.SendRequest{ //sendPaymentRequestUser1 := lnrpc.SendRequest{
PaymentRequest: user1Invoice.PayReq, // PaymentRequest: user1Invoice.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
// add invoice for user 2 //// add invoice for user 2
user2Invoice := suite.createAddInvoiceReq(1000, "integration test websocket user 2", suite.userToken2) //user2Invoice := suite.createAddInvoiceReq(1000, "integration test websocket user 2", suite.userToken2)
sendPaymentRequestUser2 := lnrpc.SendRequest{ //sendPaymentRequestUser2 := lnrpc.SendRequest{
PaymentRequest: user2Invoice.PayReq, // PaymentRequest: user2Invoice.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
//pay invoices //pay invoices
_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequestUser1) //_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequestUser1)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequestUser2) //_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequestUser2)
assert.NoError(suite.T(), err) assert.NoError(suite.T(), err)
//read user 1 received msg //read user 1 received msg
_, user1Msg, err := user1Ws.ReadMessage() _, user1Msg, err := user1Ws.ReadMessage()
@@ -231,21 +220,21 @@ func (suite *WebSocketTestSuite) TestWebSocketDoubleUser() {
func (suite *WebSocketTestSuite) TestWebSocketMissingInvoice() { func (suite *WebSocketTestSuite) TestWebSocketMissingInvoice() {
// create incoming invoice and fund account // create incoming invoice and fund account
invoice1 := suite.createAddInvoiceReq(1000, "integration test websocket missing invoices", suite.userToken) invoice1 := suite.createAddInvoiceReq(1000, "integration test websocket missing invoices", suite.userToken)
sendPaymentRequest := lnrpc.SendRequest{ //sendPaymentRequest := lnrpc.SendRequest{
PaymentRequest: invoice1.PayReq, // PaymentRequest: invoice1.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err := suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
// create 2nd invoice and pay it as well //// create 2nd invoice and pay it as well
invoice2 := suite.createAddInvoiceReq(1000, "integration test websocket missing invoices 2nd", suite.userToken) //invoice2 := suite.createAddInvoiceReq(1000, "integration test websocket missing invoices 2nd", suite.userToken)
sendPaymentRequest = lnrpc.SendRequest{ //sendPaymentRequest = lnrpc.SendRequest{
PaymentRequest: invoice2.PayReq, // PaymentRequest: invoice2.PayReq,
FeeLimit: nil, // FeeLimit: nil,
} //}
_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest) //_, err = suite.fundingClient.SendPaymentSync(context.Background(), &sendPaymentRequest)
assert.NoError(suite.T(), err) //assert.NoError(suite.T(), err)
//start listening to websocket after 2nd invoice has been paid //start listening to websocket after 2nd invoice has been paid
//we should get an event for the 2nd invoice if we specify the hash as the query parameter //we should get an event for the 2nd invoice if we specify the hash as the query parameter