Skip to content

Commit

Permalink
Merge pull request #463 from getAlby/task-out-exceeding-checks
Browse files Browse the repository at this point in the history
chore(addoutgoinginvoice): add exceeding checks for send
  • Loading branch information
kiwiidb authored Dec 1, 2023
2 parents e58e6ac + 29957ed commit c581250
Show file tree
Hide file tree
Showing 7 changed files with 90 additions and 51 deletions.
20 changes: 3 additions & 17 deletions controllers/keysend.ctrl.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,6 @@ func (controller *KeySendController) KeySend(c echo.Context) error {
Keysend: true,
}

if controller.svc.Config.MaxSendAmount > 0 {
if lnPayReq.PayReq.NumSatoshis > controller.svc.Config.MaxSendAmount {
c.Logger().Errorf("Max send amount exceeded for user_id:%v (amount:%v)", userID, lnPayReq.PayReq.NumSatoshis)
return c.JSON(http.StatusBadRequest, responses.BadArgumentsError)
}
}

if controller.svc.LndClient.IsIdentityPubkey(reqBody.Destination) && reqBody.CustomRecords[strconv.Itoa(service.TLV_WALLET_ID)] == "" {
return c.JSON(http.StatusBadRequest, &responses.ErrorResponse{
Error: true,
Expand All @@ -97,16 +90,9 @@ func (controller *KeySendController) KeySend(c echo.Context) error {
c.Logger().Errorf("User does not have enough balance user_id:%v amount:%v", userID, lnPayReq.PayReq.NumSatoshis)
return c.JSON(http.StatusBadRequest, resp)
}
invoice, err := controller.svc.AddOutgoingInvoice(c.Request().Context(), userID, "", lnPayReq)
if err != nil {
c.Logger().Errorj(
log.JSON{
"message": "failed to add invoice",
"error": err,
"lndhub_user_id": userID,
},
)
return c.JSON(http.StatusBadRequest, responses.BadArgumentsError)
invoice, errResp := controller.svc.AddOutgoingInvoice(c.Request().Context(), userID, "", lnPayReq)
if errResp != nil {
return c.JSON(errResp.HttpStatusCode, errResp)
}
if _, err := hex.DecodeString(invoice.DestinationPubkeyHex); err != nil || len(invoice.DestinationPubkeyHex) != common.DestinationPubkeyHexSize {
c.Logger().Errorf("Invalid destination pubkey hex user_id:%v pubkey:%v", userID, len(invoice.DestinationPubkeyHex))
Expand Down
20 changes: 3 additions & 17 deletions controllers/payinvoice.ctrl.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,6 @@ func (controller *PayInvoiceController) PayInvoice(c echo.Context) error {
lnPayReq.PayReq.NumSatoshis = amt
}

if controller.svc.Config.MaxSendAmount > 0 {
if lnPayReq.PayReq.NumSatoshis > controller.svc.Config.MaxSendAmount {
c.Logger().Errorf("Max send amount exceeded for user_id:%v (amount:%v)", userID, lnPayReq.PayReq.NumSatoshis)
return c.JSON(http.StatusBadRequest, responses.BadArgumentsError)
}
}

resp, err := controller.svc.CheckPaymentAllowed(c.Request().Context(), lnPayReq, userID)
if err != nil {
c.Logger().Errorj(
Expand All @@ -113,16 +106,9 @@ func (controller *PayInvoiceController) PayInvoice(c echo.Context) error {
return c.JSON(http.StatusBadRequest, resp)
}

invoice, err := controller.svc.AddOutgoingInvoice(c.Request().Context(), userID, paymentRequest, lnPayReq)
if err != nil {
c.Logger().Errorj(
log.JSON{
"message": "error adding invoice",
"error": err,
"lndhub_user_id": userID,
},
)
return c.JSON(http.StatusBadRequest, responses.GeneralServerError)
invoice, errResp := controller.svc.AddOutgoingInvoice(c.Request().Context(), userID, paymentRequest, lnPayReq)
if errResp != nil {
return c.JSON(errResp.HttpStatusCode, errResp)
}
sendPaymentResponse, err := controller.svc.PayInvoice(c.Request().Context(), invoice)
if err != nil {
Expand Down
7 changes: 3 additions & 4 deletions controllers_v2/keysend.ctrl.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,9 @@ func (controller *KeySendController) SingleKeySend(ctx context.Context, reqBody
HttpStatusCode: 400,
}
}
invoice, err := controller.svc.AddOutgoingInvoice(ctx, userID, "", lnPayReq)
if err != nil {
controller.svc.Logger.Error(err)
return nil, &responses.GeneralServerError
invoice, errResp := controller.svc.AddOutgoingInvoice(ctx, userID, "", lnPayReq)
if errResp != nil {
return nil, errResp
}
if _, err := hex.DecodeString(invoice.DestinationPubkeyHex); err != nil || len(invoice.DestinationPubkeyHex) != common.DestinationPubkeyHexSize {
controller.svc.Logger.Errorf("Invalid destination pubkey hex user_id:%v pubkey:%v", userID, len(invoice.DestinationPubkeyHex))
Expand Down
13 changes: 3 additions & 10 deletions controllers_v2/payinvoice.ctrl.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,16 +113,9 @@ func (controller *PayInvoiceController) PayInvoice(c echo.Context) error {
c.Logger().Errorf("User does not have enough balance user_id:%v amount:%v", userID, lnPayReq.PayReq.NumSatoshis)
return c.JSON(http.StatusInternalServerError, resp)
}
invoice, err := controller.svc.AddOutgoingInvoice(c.Request().Context(), userID, paymentRequest, lnPayReq)
if err != nil {
c.Logger().Errorj(
log.JSON{
"message": "error adding invoice",
"error": err,
"lndhub_user_id": userID,
},
)
return err
invoice, errResp := controller.svc.AddOutgoingInvoice(c.Request().Context(), userID, paymentRequest, lnPayReq)
if errResp != nil {
return c.JSON(errResp.HttpStatusCode, errResp)
}
sendPaymentResponse, err := controller.svc.PayInvoice(c.Request().Context(), invoice)
if err != nil {
Expand Down
59 changes: 59 additions & 0 deletions integration_tests/internal_payment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,65 @@ func (suite *PaymentTestSuite) TestIncomingExceededChecks() {
err = suite.mlnd.mockPaidInvoice(invoiceResponse, 0, false, nil)
assert.NoError(suite.T(), err)
}

func (suite *PaymentTestSuite) TestOutgoingExceededChecks() {
//this will cause the payment to fail as the account was already funded
//with 1000 sats
suite.service.Config.MaxSendAmount = 100
aliceFundingSats := 1000
//fund alice account
invoiceResponse := suite.createAddInvoiceReq(aliceFundingSats, "integration test internal payment alice", suite.aliceToken)
err := suite.mlnd.mockPaidInvoice(invoiceResponse, 0, false, nil)
assert.NoError(suite.T(), err)

//wait a bit for the payment to be processed
time.Sleep(10 * time.Millisecond)

//try to make external payment
//which should fail
//create external invoice
externalSatRequested := 500
externalInvoice := lnrpc.Invoice{
Memo: "integration tests: external pay from user",
Value: int64(externalSatRequested),
}
invoice, err := suite.externalLND.AddInvoice(context.Background(), &externalInvoice)
assert.NoError(suite.T(), err)
//pay external invoice
rec := httptest.NewRecorder()
var buf bytes.Buffer
assert.NoError(suite.T(), json.NewEncoder(&buf).Encode(&ExpectedPayInvoiceRequestBody{
Invoice: invoice.PaymentRequest,
}))
req := httptest.NewRequest(http.MethodPost, "/payinvoice", &buf)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", suite.aliceToken))
suite.echo.ServeHTTP(rec, req)
//should fail because max volume check
assert.Equal(suite.T(), http.StatusBadRequest, rec.Code)
resp := &responses.ErrorResponse{}
err = json.NewDecoder(rec.Body).Decode(resp)
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), responses.SendExceededError.Message, resp.Message)

suite.service.Config.MaxSendAmount = 2000
rec = httptest.NewRecorder()
externalInvoice = lnrpc.Invoice{
Memo: "integration tests: external pay from user",
Value: int64(externalSatRequested),
}
invoice, err = suite.externalLND.AddInvoice(context.Background(), &externalInvoice)
assert.NoError(suite.T(), err)
assert.NoError(suite.T(), json.NewEncoder(&buf).Encode(&ExpectedPayInvoiceRequestBody{
Invoice: invoice.PaymentRequest,
}))
suite.echo.ServeHTTP(rec, req)
assert.Equal(suite.T(), http.StatusOK, rec.Code)

//change the config back
suite.service.Config.MaxSendAmount = 0
}

func (suite *PaymentTestSuite) TestInternalPayment() {
aliceFundingSats := 1000
bobSatRequested := 500
Expand Down
7 changes: 7 additions & 0 deletions lib/responses/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ var TooMuchVolumeError = ErrorResponse{
HttpStatusCode: 400,
}

var SendExceededError = ErrorResponse{
Error: true,
Code: 2,
Message: "max send amount exceeded. please contact support for further assistance.",
HttpStatusCode: 400,
}

var AccountDeactivatedError = ErrorResponse{
Error: true,
Code: 1,
Expand Down
15 changes: 12 additions & 3 deletions lib/service/invoices.go
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,14 @@ func (svc *LndhubService) HandleSuccessfulPayment(ctx context.Context, invoice *
return nil
}

func (svc *LndhubService) AddOutgoingInvoice(ctx context.Context, userID int64, paymentRequest string, lnPayReq *lnd.LNPayReq) (*models.Invoice, error) {
func (svc *LndhubService) AddOutgoingInvoice(ctx context.Context, userID int64, paymentRequest string, lnPayReq *lnd.LNPayReq) (*models.Invoice, *responses.ErrorResponse) {
if svc.Config.MaxSendAmount > 0 {
if lnPayReq.PayReq.NumSatoshis > svc.Config.MaxSendAmount {
svc.Logger.Errorf("Max send amount exceeded for user_id %v (amount:%v)", userID, lnPayReq.PayReq.NumSatoshis)
return nil, &responses.SendExceededError
}
}

// Initialize new DB invoice
invoice := models.Invoice{
Type: common.InvoiceTypeOutgoing,
Expand All @@ -460,7 +467,8 @@ func (svc *LndhubService) AddOutgoingInvoice(ctx context.Context, userID int64,
if lnPayReq.Keysend {
preImage, err := makePreimageHex()
if err != nil {
return nil, err
svc.Logger.Errorf("Error adding invoice: user_id:%v error: %v", userID, err)
return nil, &responses.GeneralServerError
}
pHash := sha256.New()
pHash.Write(preImage)
Expand All @@ -472,7 +480,8 @@ func (svc *LndhubService) AddOutgoingInvoice(ctx context.Context, userID int64,
// Save invoice
_, err := svc.DB.NewInsert().Model(&invoice).Exec(ctx)
if err != nil {
return nil, err
svc.Logger.Errorf("Error adding invoice: user_id:%v error: %v", userID, err)
return nil, &responses.GeneralServerError
}
return &invoice, nil
}
Expand Down

0 comments on commit c581250

Please sign in to comment.