lookup_invoice_controller.go raw

   1  package controllers
   2  
   3  import (
   4  	"context"
   5  	"fmt"
   6  	"strings"
   7  
   8  	"github.com/getAlby/go-nostr"
   9  	"github.com/getAlby/hub/constants"
  10  	"github.com/getAlby/hub/logger"
  11  	"github.com/getAlby/hub/nip47/models"
  12  	decodepay "github.com/nbd-wtf/ln-decodepay"
  13  	"github.com/sirupsen/logrus"
  14  )
  15  
  16  type lookupInvoiceParams struct {
  17  	Invoice     string `json:"invoice"`
  18  	PaymentHash string `json:"payment_hash"`
  19  }
  20  
  21  type lookupInvoiceResponse struct {
  22  	models.Transaction
  23  }
  24  
  25  func (controller *nip47Controller) HandleLookupInvoiceEvent(ctx context.Context, nip47Request *models.Request, requestEventId uint, appId uint, publishResponse publishFunc) {
  26  
  27  	lookupInvoiceParams := &lookupInvoiceParams{}
  28  	resp := decodeRequest(nip47Request, lookupInvoiceParams)
  29  	if resp != nil {
  30  		publishResponse(resp, nostr.Tags{})
  31  		return
  32  	}
  33  
  34  	logger.Logger.WithFields(logrus.Fields{
  35  		"invoice":          lookupInvoiceParams.Invoice,
  36  		"payment_hash":     lookupInvoiceParams.PaymentHash,
  37  		"request_event_id": requestEventId,
  38  	}).Info("Looking up invoice")
  39  
  40  	paymentHash := lookupInvoiceParams.PaymentHash
  41  
  42  	if paymentHash == "" {
  43  		paymentRequest, err := decodepay.Decodepay(strings.ToLower(lookupInvoiceParams.Invoice))
  44  		if err != nil {
  45  			logger.Logger.WithFields(logrus.Fields{
  46  				"request_event_id": requestEventId,
  47  				"invoice":          lookupInvoiceParams.Invoice,
  48  			}).WithError(err).Error("Failed to decode bolt11 invoice")
  49  
  50  			publishResponse(&models.Response{
  51  				ResultType: nip47Request.Method,
  52  				Error: &models.Error{
  53  					Code:    constants.ERROR_BAD_REQUEST,
  54  					Message: fmt.Sprintf("Failed to decode bolt11 invoice: %s", err.Error()),
  55  				},
  56  			}, nostr.Tags{})
  57  			return
  58  		}
  59  		paymentHash = paymentRequest.PaymentHash
  60  	}
  61  
  62  	dbTransaction, err := controller.transactionsService.LookupTransaction(ctx, paymentHash, nil, controller.lnClient, &appId)
  63  	if err != nil {
  64  		logger.Logger.WithFields(logrus.Fields{
  65  			"request_event_id": requestEventId,
  66  			"invoice":          lookupInvoiceParams.Invoice,
  67  			"payment_hash":     paymentHash,
  68  		}).Infof("Failed to lookup invoice: %v", err)
  69  
  70  		publishResponse(&models.Response{
  71  			ResultType: nip47Request.Method,
  72  			Error:      mapNip47Error(err),
  73  		}, nostr.Tags{})
  74  		return
  75  	}
  76  
  77  	responsePayload := &lookupInvoiceResponse{
  78  		Transaction: *models.ToNip47Transaction(dbTransaction),
  79  	}
  80  
  81  	publishResponse(&models.Response{
  82  		ResultType: nip47Request.Method,
  83  		Result:     responsePayload,
  84  	}, nostr.Tags{})
  85  }
  86