Skip to content

Commit

Permalink
feat: intercept self payments
Browse files Browse the repository at this point in the history
  • Loading branch information
rolznz committed Jul 9, 2024
1 parent 1b78f43 commit a133ed5
Show file tree
Hide file tree
Showing 14 changed files with 98 additions and 22 deletions.
6 changes: 4 additions & 2 deletions api/transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (api *api) ListTransactions(ctx context.Context, limit uint64, offset uint6
if api.svc.GetLNClient() == nil {
return nil, errors.New("LNClient not started")
}
transactions, err := api.svc.GetTransactionsService().ListTransactions(ctx, 0, 0, limit, offset, false, "", api.svc.GetLNClient())
transactions, err := api.svc.GetTransactionsService().ListTransactions(ctx, 0, 0, limit, offset, false, "", api.svc.GetLNClient(), nil)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -70,9 +70,11 @@ func toApiTransaction(transaction *transactions.Transaction) *Transaction {

createdAt := transaction.CreatedAt.Format(time.RFC3339)
var settledAt *string
var preimage *string
if transaction.SettledAt != nil {
settledAtValue := transaction.SettledAt.Format(time.RFC3339)
settledAt = &settledAtValue
preimage = transaction.Preimage
}

var metadata interface{}
Expand All @@ -91,7 +93,7 @@ func toApiTransaction(transaction *transactions.Transaction) *Transaction {
Invoice: transaction.PaymentRequest,
Description: transaction.Description,
DescriptionHash: transaction.DescriptionHash,
Preimage: transaction.Preimage,
Preimage: preimage,
PaymentHash: transaction.PaymentHash,
Amount: transaction.Amount,
AppId: transaction.AppId,
Expand Down
6 changes: 6 additions & 0 deletions lnclient/breez/breez.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
type BreezService struct {
listener *BreezListener
svc *breez_sdk.BlockingBreezServices
pubkey string
}
type BreezListener struct {
}
Expand Down Expand Up @@ -91,6 +92,7 @@ func NewBreezService(mnemonic, apiKey, inviteCode, workDir string) (result lncli
return &BreezService{
listener: &listener,
svc: svc,
pubkey: nodeInfo.Id,
}, nil
}

Expand Down Expand Up @@ -485,3 +487,7 @@ func (bs *BreezService) GetSupportedNIP47Methods() []string {
func (bs *BreezService) GetSupportedNIP47NotificationTypes() []string {
return []string{}
}

func (bs *BreezService) GetPubkey() string {
return bs.pubkey
}
4 changes: 4 additions & 0 deletions lnclient/cashu/cashu.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,3 +352,7 @@ func (cs *CashuService) GetSupportedNIP47Methods() []string {
func (cs *CashuService) GetSupportedNIP47NotificationTypes() []string {
return []string{}
}

func (svc *CashuService) GetPubkey() string {
return ""
}
11 changes: 9 additions & 2 deletions lnclient/greenlight/greenlight.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
type GreenlightService struct {
workdir string
client *glalby.BlockingGreenlightAlbyClient
pubkey string
}

const DEVICE_CREDENTIALS_KEY = "GreenlightCreds"
Expand Down Expand Up @@ -85,13 +86,14 @@ func NewGreenlightService(cfg config.Config, mnemonic, inviteCode, workDir, encr
log.Fatalf("unexpected response from NewBlockingGreenlightAlbyClient")
}

nodeInfo, err := client.GetInfo()

gs := GreenlightService{
workdir: newpath,
client: client,
pubkey: nodeInfo.Pubkey,
}

nodeInfo, err := client.GetInfo()

if err != nil {
return nil, err
}
Expand Down Expand Up @@ -206,6 +208,7 @@ func (gs *GreenlightService) MakeInvoice(ctx context.Context, amount int64, desc
Invoice: invoice.Bolt11,
Description: description,
DescriptionHash: descriptionHash,
Preimage: "", // TODO: set preimage to enable self-payments
PaymentHash: invoice.PaymentHash,
ExpiresAt: &expiresAt,
Amount: amount,
Expand Down Expand Up @@ -685,3 +688,7 @@ func (gs *GreenlightService) GetSupportedNIP47Methods() []string {
func (gs *GreenlightService) GetSupportedNIP47NotificationTypes() []string {
return []string{}
}

func (gs *GreenlightService) GetPubkey() string {
return gs.pubkey
}
11 changes: 10 additions & 1 deletion lnclient/ldk/ldk.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ type LDKService struct {
lastSync time.Time
cfg config.Config
lastWalletSyncRequest time.Time
pubkey string
}

const resetRouterKey = "ResetRouter"
Expand Down Expand Up @@ -122,6 +123,7 @@ func NewLDKService(ctx context.Context, cfg config.Config, eventPublisher events
ldkEventConsumer := make(chan *ldk_node.Event)
ldkCtx, cancel := context.WithCancel(ctx)
ldkEventBroadcaster := NewLDKEventBroadcaster(ldkCtx, ldkEventConsumer)
nodeId := node.NodeId()

ls := LDKService{
workdir: newpath,
Expand All @@ -131,6 +133,7 @@ func NewLDKService(ctx context.Context, cfg config.Config, eventPublisher events
network: network,
eventPublisher: eventPublisher,
cfg: cfg,
pubkey: nodeId,
}

// TODO: remove when LDK supports this
Expand Down Expand Up @@ -178,7 +181,6 @@ func NewLDKService(ctx context.Context, cfg config.Config, eventPublisher events
return nil, err
}

nodeId := node.NodeId()
logger.Logger.WithFields(logrus.Fields{
"nodeId": nodeId,
"status": node.Status(),
Expand Down Expand Up @@ -677,10 +679,13 @@ func (ls *LDKService) MakeInvoice(ctx context.Context, amount int64, description
description = paymentRequest.Description
descriptionHash = paymentRequest.DescriptionHash

payment := ls.node.Payment(paymentRequest.PaymentHash)

transaction = &lnclient.Transaction{
Type: "incoming",
Invoice: invoice,
PaymentHash: paymentRequest.PaymentHash,
Preimage: *payment.Kind.(ldk_node.PaymentKindBolt11).Preimage,
Amount: amount,
CreatedAt: int64(paymentRequest.CreatedAt),
ExpiresAt: expiresAt,
Expand Down Expand Up @@ -1494,3 +1499,7 @@ func (ls *LDKService) getChannelCloseReason(event *ldk_node.EventChannelClosed)

return reason
}

func (ls *LDKService) GetPubkey() string {
return ls.pubkey
}
12 changes: 8 additions & 4 deletions lnclient/lnd/lnd.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
// todo: drop dependency on lndhub package
type LNDService struct {
client *wrapper.LNDWrapper
pubkey string
}

func (svc *LNDService) GetBalance(ctx context.Context) (balance int64, err error) {
Expand Down Expand Up @@ -447,7 +448,7 @@ func NewLNDService(ctx context.Context, lndAddress, lndCertHex, lndMacaroonHex s
return nil, err
}

lndService := &LNDService{client: lndClient}
lndService := &LNDService{client: lndClient, pubkey: info.IdentityPubkey}

logger.Logger.Infof("Connected to LND - alias %s", info.Alias)

Expand Down Expand Up @@ -694,12 +695,11 @@ func (svc *LNDService) GetBalances(ctx context.Context) (*lnclient.BalancesRespo

func lndInvoiceToTransaction(invoice *lnrpc.Invoice) *lnclient.Transaction {
var settledAt *int64
var preimage string
preimage := hex.EncodeToString(invoice.RPreimage)
metadata := map[string]interface{}{}

if invoice.State == lnrpc.Invoice_SETTLED {
settledAt = &invoice.SettleDate
// only set preimage if invoice is settled
preimage = hex.EncodeToString(invoice.RPreimage)
}
var expiresAt *int64
if invoice.Expiry > 0 {
Expand Down Expand Up @@ -813,3 +813,7 @@ func (svc *LNDService) GetSupportedNIP47Methods() []string {
func (svc *LNDService) GetSupportedNIP47NotificationTypes() []string {
return []string{}
}

func (svc *LNDService) GetPubkey() string {
return svc.pubkey
}
1 change: 1 addition & 0 deletions lnclient/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ type LNClient interface {
SendPaymentSync(ctx context.Context, payReq string) (*PayInvoiceResponse, error)
SendKeysend(ctx context.Context, amount uint64, destination string, customRecords []TLVRecord) (paymentHash string, preimage string, fee uint64, err error)
GetBalance(ctx context.Context) (balance int64, err error)
GetPubkey() string
GetInfo(ctx context.Context) (info *NodeInfo, err error)
MakeInvoice(ctx context.Context, amount int64, description string, descriptionHash string, expiry int64) (transaction *Transaction, err error)
LookupInvoice(ctx context.Context, paymentHash string) (transaction *Transaction, err error)
Expand Down
13 changes: 12 additions & 1 deletion lnclient/phoenixd/phoenixd.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,19 @@ type BalanceResponse struct {
type PhoenixService struct {
Address string
Authorization string
pubkey string
}

func NewPhoenixService(address string, authorization string) (result lnclient.LNClient, err error) {
authorizationBase64 := b64.StdEncoding.EncodeToString([]byte(":" + authorization))
phoenixService := &PhoenixService{Address: address, Authorization: authorizationBase64}

info, err := phoenixService.GetInfo(context.Background())
if err != nil {
return nil, err
}
phoenixService.pubkey = info.Pubkey

return phoenixService, nil
}

Expand Down Expand Up @@ -328,7 +335,7 @@ func (svc *PhoenixService) MakeInvoice(ctx context.Context, amount int64, descri
tx := &lnclient.Transaction{
Type: "incoming",
Invoice: invoiceRes.Serialized,
Preimage: "",
Preimage: "", // TODO: set preimage to enable self-payments
PaymentHash: invoiceRes.PaymentHash,
FeesPaid: 0,
CreatedAt: time.Now().Unix(),
Expand Down Expand Up @@ -526,3 +533,7 @@ func (svc *PhoenixService) GetSupportedNIP47Methods() []string {
func (svc *PhoenixService) GetSupportedNIP47NotificationTypes() []string {
return []string{}
}

func (svc *PhoenixService) GetPubkey() string {
return svc.pubkey
}
4 changes: 2 additions & 2 deletions nip47/controllers/list_transactions_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type listTransactionsResponse struct {
Transactions []models.Transaction `json:"transactions"`
}

func (controller *nip47Controller) HandleListTransactionsEvent(ctx context.Context, nip47Request *models.Request, requestEventId uint, checkPermission checkPermissionFunc, publishResponse publishFunc) {
func (controller *nip47Controller) HandleListTransactionsEvent(ctx context.Context, nip47Request *models.Request, requestEventId uint, appId uint, checkPermission checkPermissionFunc, publishResponse publishFunc) {
// basic permissions check
resp := checkPermission(0)
if resp != nil {
Expand All @@ -48,7 +48,7 @@ func (controller *nip47Controller) HandleListTransactionsEvent(ctx context.Conte
// make sure a sensible limit is passed
limit = maxLimit
}
dbTransactions, err := controller.transactionsService.ListTransactions(ctx, listParams.From, listParams.Until, limit, listParams.Offset, listParams.Unpaid, listParams.Type, controller.lnClient)
dbTransactions, err := controller.transactionsService.ListTransactions(ctx, listParams.From, listParams.Until, limit, listParams.Offset, listParams.Unpaid, listParams.Type, controller.lnClient, &appId)
if err != nil {
logger.Logger.WithFields(logrus.Fields{
"params": listParams,
Expand Down
2 changes: 1 addition & 1 deletion nip47/controllers/make_invoice_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func (controller *nip47Controller) HandleMakeInvoiceEvent(ctx context.Context, n

expiry := makeInvoiceParams.Expiry

transaction, err := controller.transactionsService.MakeInvoice(ctx, makeInvoiceParams.Amount, makeInvoiceParams.Description, makeInvoiceParams.DescriptionHash, expiry, controller.lnClient, &requestEventId, &appId)
transaction, err := controller.transactionsService.MakeInvoice(ctx, makeInvoiceParams.Amount, makeInvoiceParams.Description, makeInvoiceParams.DescriptionHash, expiry, controller.lnClient, &appId, &requestEventId)
if err != nil {
logger.Logger.WithFields(logrus.Fields{
"request_event_id": requestEventId,
Expand Down
2 changes: 1 addition & 1 deletion nip47/event_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ func (svc *nip47Service) HandleEvent(ctx context.Context, sub *nostr.Subscriptio
HandleLookupInvoiceEvent(ctx, nip47Request, requestEvent.ID, app.ID, checkPermission, publishResponse)
case models.LIST_TRANSACTIONS_METHOD:
controller.
HandleListTransactionsEvent(ctx, nip47Request, requestEvent.ID, checkPermission, publishResponse)
HandleListTransactionsEvent(ctx, nip47Request, requestEvent.ID, app.ID, checkPermission, publishResponse)
case models.GET_INFO_METHOD:
controller.
HandleGetInfoEvent(ctx, nip47Request, requestEvent.ID, &app, checkPermission, publishResponse)
Expand Down
7 changes: 2 additions & 5 deletions nip47/models/transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@ import (
)

func ToNip47Transaction(transaction *transactions.Transaction) *Transaction {
preimage := ""
if transaction.Preimage != nil {
preimage = *transaction.Preimage
}

fees := int64(0)
if transaction.Fee != nil {
fees = int64(*transaction.Fee)
Expand All @@ -26,9 +21,11 @@ func ToNip47Transaction(transaction *transactions.Transaction) *Transaction {
}

var settledAt *int64
preimage := ""
if transaction.SettledAt != nil {
settledAtUnix := transaction.SettledAt.Unix()
settledAt = &settledAtUnix
preimage = *transaction.Preimage
}

var metadata interface{}
Expand Down
3 changes: 3 additions & 0 deletions tests/mock_ln_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,6 @@ func (mln *MockLn) GetSupportedNIP47Methods() []string {
func (mln *MockLn) GetSupportedNIP47NotificationTypes() []string {
return []string{"payment_received", "payment_sent"}
}
func (mln *MockLn) GetPubkey() string {
return "123pubkey"
}
38 changes: 35 additions & 3 deletions transactions/transactions_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type TransactionsService interface {
events.EventSubscriber
MakeInvoice(ctx context.Context, amount int64, description string, descriptionHash string, expiry int64, lnClient lnclient.LNClient, appId *uint, requestEventId *uint) (*Transaction, error)
LookupTransaction(ctx context.Context, paymentHash string, lnClient lnclient.LNClient, appId *uint) (*Transaction, error)
ListTransactions(ctx context.Context, from, until, limit, offset uint64, unpaid bool, invoiceType string, lnClient lnclient.LNClient) (transactions []Transaction, err error)
ListTransactions(ctx context.Context, from, until, limit, offset uint64, unpaid bool, invoiceType string, lnClient lnclient.LNClient, appId *uint) (transactions []Transaction, err error)
SendPaymentSync(ctx context.Context, payReq string, lnClient lnclient.LNClient, appId *uint, requestEventId *uint) (*Transaction, error)
SendKeysend(ctx context.Context, amount uint64, destination string, customRecords []lnclient.TLVRecord, lnClient lnclient.LNClient, appId *uint, requestEventId *uint) (*Transaction, error)
}
Expand Down Expand Up @@ -146,7 +146,31 @@ func (svc *transactionsService) SendPaymentSync(ctx context.Context, payReq stri
return nil, err
}

response, err := lnClient.SendPaymentSync(ctx, payReq)
var response *lnclient.PayInvoiceResponse
if paymentRequest.Payee != "" && paymentRequest.Payee == lnClient.GetPubkey() {
transaction := db.Transaction{}
result := svc.db.Find(&transaction, &db.Transaction{
Type: TRANSACTION_TYPE_INCOMING,
PaymentHash: dbTransaction.PaymentHash,
AppId: appId,
})
err = result.Error
if err == nil && result.RowsAffected == 0 {
err = NewNotFoundError()
}
if transaction.Preimage == nil {
err = errors.New("preimage is not set on transaction. Self payments not supported.")
}
if err == nil {
fee := uint64(0)
response = &lnclient.PayInvoiceResponse{
Preimage: *transaction.Preimage,
Fee: &fee,
}
}
} else {
response, err = lnClient.SendPaymentSync(ctx, payReq)
}

if err != nil {
logger.Logger.WithFields(logrus.Fields{
Expand Down Expand Up @@ -301,6 +325,10 @@ func (svc *transactionsService) LookupTransaction(ctx context.Context, paymentHa
}

if result.RowsAffected == 0 {
logger.Logger.WithFields(logrus.Fields{
"payment_hash": paymentHash,
"app_id": appId,
}).WithError(result.Error).Error("Failed to lookup DB transaction")
return nil, NewNotFoundError()
}

Expand All @@ -311,7 +339,7 @@ func (svc *transactionsService) LookupTransaction(ctx context.Context, paymentHa
return &transaction, nil
}

func (svc *transactionsService) ListTransactions(ctx context.Context, from, until, limit, offset uint64, unpaid bool, transactionType string, lnClient lnclient.LNClient) (transactions []Transaction, err error) {
func (svc *transactionsService) ListTransactions(ctx context.Context, from, until, limit, offset uint64, unpaid bool, transactionType string, lnClient lnclient.LNClient, appId *uint) (transactions []Transaction, err error) {
svc.checkUnsettledTransactions(ctx, lnClient)

// TODO: add other filtering and pagination
Expand All @@ -320,6 +348,10 @@ func (svc *transactionsService) ListTransactions(ctx context.Context, from, unti
tx = tx.Where("state == ?", TRANSACTION_STATE_SETTLED)
}

if appId != nil {
tx = tx.Where("app_id == ?", *appId)
}

tx = tx.Order("created_at desc")

if limit != 0 {
Expand Down

0 comments on commit a133ed5

Please sign in to comment.