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

Add get_budget implementation #726

Merged
merged 5 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ nostr-wallet-connect
nwc.db
.breez
.data
.idea

frontend/dist
frontend/node_modules
Expand Down
1 change: 1 addition & 0 deletions constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const (
const (
PAY_INVOICE_SCOPE = "pay_invoice" // also covers pay_keysend and multi_* payment methods
GET_BALANCE_SCOPE = "get_balance"
GET_BUDGET_SCOPE = "get_budget"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am wondering if we should not have a scope for this one - instead it chould always be callable. Is there any benefit of having a scope? (also, an extra scope requires including an extra checkbox in the UI that the user has to understand when configuring permissions)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed having it always be callable makes sense. Is there another method which has that behavior right now that I could copy? If not, I'll just dig a bit deeper to make that work.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added an always granted scope with some tests for this. That way, if there are other "always allowed" methods, they can just be added there.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the get_info method also bypasses the check here: https://github.com/getAlby/hub/blob/master/nip47/event_handler.go#L272

We need to come up with a better solution, but for now to see if it works you could try adding an && nip47Request.Method != models.GET_BUDGET_METHOD

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh cool, should I just add get_info to my new ALWAYS_GRANTED scope instead?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about the ALWAYS_GRANTED scope. This seems to have some side effects (for example, the new scope is now returned and the frontend does not know how to display it)
image

Also the scope is now included in only new apps in the database (there is a new app_permissions row for always_granted), but only new ones. The older app connections will not have it.

image

And it seems a bit hacky to even call HasPermission explicitly with the always_granted scope which actually just always returns true anyway.

I know my original suggestion is not the best, but on the plus side it's isolated to a single line of code and simply skips the permission check for that request method.

@bumi @im-adithya any thoughts on this one?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, thanks for catching the UI issue, I hadn't noticed that! FWIW, my intent here was actually to not store this scope in the DB or show it in the UI at all. Instead, I was hoping to just have it be implicitly granted to all requests. I'll try to make that the case now, but can definitely switch to a specific GET_BUDGET_SCOPE if you prefer. I just think it's a bit weird to show that in the UI in general.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adjusted to avoid always_granted in the db and UI. Let me know if you'd still prefer an explicit budget scope though.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! I also don't think we should have a GET_BUDGET_SCOPE. I was just wondering if a single line check like I suggested would be simpler than having this ALWAYS_GRANTED scope, and in the end we just bypass the logic anyway.

GET_INFO_SCOPE = "get_info"
MAKE_INVOICE_SCOPE = "make_invoice"
LOOKUP_INVOICE_SCOPE = "lookup_invoice"
Expand Down
17 changes: 17 additions & 0 deletions db/queries/get_budget_usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,20 @@ func getStartOfBudget(budget_type string) time.Time {
return time.Time{}
}
}

func GetBudgetRenewsAt(budgetRenewal string) int64 {
now := time.Now()
budgetStart := getStartOfBudget(budgetRenewal)
switch budgetRenewal {
case constants.BUDGET_RENEWAL_DAILY:
return budgetStart.AddDate(0, 0, 1).Unix()
case constants.BUDGET_RENEWAL_WEEKLY:
return budgetStart.AddDate(0, 0, 7).Unix()
case constants.BUDGET_RENEWAL_MONTHLY:
return budgetStart.AddDate(0, 1, 0).Unix()
case constants.BUDGET_RENEWAL_YEARLY:
return budgetStart.AddDate(1, 0, 0).Unix()
default: //"never"
return now.Unix()
}
}
2 changes: 2 additions & 0 deletions frontend/src/components/Scopes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const Scopes: React.FC<ScopesProps> = ({
const readOnlyScopes: Scope[] = React.useMemo(() => {
const readOnlyScopes: Scope[] = [
"get_balance",
"get_budget",
"get_info",
"make_invoice",
"lookup_invoice",
Expand All @@ -79,6 +80,7 @@ const Scopes: React.FC<ScopesProps> = ({
const isolatedScopes: Scope[] = [
"pay_invoice",
"get_balance",
"get_budget",
"make_invoice",
"lookup_invoice",
"list_transactions",
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/screens/apps/NewApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ const NewAppInternal = ({ capabilities }: NewAppInternalProps) => {
if (requestMethodsSet.has("get_balance")) {
scopes.push("get_balance");
}
if (requestMethodsSet.has("get_budget")) {
scopes.push("get_budget");
}
if (requestMethodsSet.has("make_invoice")) {
scopes.push("make_invoice");
}
Expand Down
1 change: 1 addition & 0 deletions frontend/src/screens/internal-apps/UncleJim.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export function UncleJim() {
name,
scopes: [
"get_balance",
"get_budget",
"get_info",
"list_transactions",
"lookup_invoice",
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export type BackendType =
export type Nip47RequestMethod =
| "get_info"
| "get_balance"
| "get_budget"
| "make_invoice"
| "pay_invoice"
| "pay_keysend"
Expand All @@ -41,6 +42,7 @@ export type BudgetRenewalType =
export type Scope =
| "pay_invoice" // also used for pay_keysend, multi_pay_invoice, multi_pay_keysend
| "get_balance"
| "get_budget"
| "get_info"
| "make_invoice"
| "lookup_invoice"
Expand All @@ -56,6 +58,7 @@ export type ScopeIconMap = {

export const scopeIconMap: ScopeIconMap = {
get_balance: WalletMinimal,
get_budget: WalletMinimal,
jklein24 marked this conversation as resolved.
Show resolved Hide resolved
get_info: Info,
list_transactions: NotebookTabs,
lookup_invoice: Search,
Expand All @@ -81,6 +84,7 @@ export const validBudgetRenewals: BudgetRenewalType[] = [

export const scopeDescriptions: Record<Scope, string> = {
get_balance: "Read your balance",
get_budget: "See its remaining budget",
get_info: "Read your node info",
list_transactions: "Read transaction history",
lookup_invoice: "Lookup status of invoices",
Expand Down
2 changes: 1 addition & 1 deletion lnclient/breez/breez.go
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ func (bs *BreezService) DisconnectPeer(ctx context.Context, peerId string) error
}

func (bs *BreezService) GetSupportedNIP47Methods() []string {
return []string{"pay_invoice" /*"pay_keysend",*/, "get_balance", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice", "multi_pay_keysend", "sign_message"}
return []string{"pay_invoice" /*"pay_keysend",*/, "get_balance", "get_budget", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice", "multi_pay_keysend", "sign_message"}
}

func (bs *BreezService) GetSupportedNIP47NotificationTypes() []string {
Expand Down
2 changes: 1 addition & 1 deletion lnclient/cashu/cashu.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ func (cs *CashuService) checkInvoice(cashuInvoice *storage.Invoice) {
}

func (cs *CashuService) GetSupportedNIP47Methods() []string {
return []string{"pay_invoice", "get_balance", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice"}
return []string{"pay_invoice", "get_balance", "get_budget", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice"}
}

func (cs *CashuService) GetSupportedNIP47NotificationTypes() []string {
Expand Down
2 changes: 1 addition & 1 deletion lnclient/greenlight/greenlight.go
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,7 @@ func (gs *GreenlightService) DisconnectPeer(ctx context.Context, peerId string)
}

func (gs *GreenlightService) GetSupportedNIP47Methods() []string {
return []string{"pay_invoice" /*"pay_keysend",*/, "get_balance", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice", "multi_pay_keysend", "sign_message"}
return []string{"pay_invoice" /*"pay_keysend",*/, "get_balance", "get_budget", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice", "multi_pay_keysend", "sign_message"}
}

func (gs *GreenlightService) GetSupportedNIP47NotificationTypes() []string {
Expand Down
2 changes: 1 addition & 1 deletion lnclient/ldk/ldk.go
Original file line number Diff line number Diff line change
Expand Up @@ -1631,7 +1631,7 @@ func (ls *LDKService) UpdateLastWalletSyncRequest() {
}

func (ls *LDKService) GetSupportedNIP47Methods() []string {
return []string{"pay_invoice", "pay_keysend", "get_balance", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice", "multi_pay_keysend", "sign_message"}
return []string{"pay_invoice", "pay_keysend", "get_balance", "get_budget", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice", "multi_pay_keysend", "sign_message"}
}

func (ls *LDKService) GetSupportedNIP47NotificationTypes() []string {
Expand Down
2 changes: 1 addition & 1 deletion lnclient/lnd/lnd.go
Original file line number Diff line number Diff line change
Expand Up @@ -1084,7 +1084,7 @@ func (svc *LNDService) DisconnectPeer(ctx context.Context, peerId string) error

func (svc *LNDService) GetSupportedNIP47Methods() []string {
return []string{
"pay_invoice", "pay_keysend", "get_balance", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice", "multi_pay_keysend", "sign_message",
"pay_invoice", "pay_keysend", "get_balance", "get_budget", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice", "multi_pay_keysend", "sign_message",
}
}

Expand Down
2 changes: 1 addition & 1 deletion lnclient/phoenixd/phoenixd.go
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ func (svc *PhoenixService) UpdateChannel(ctx context.Context, updateChannelReque
}

func (svc *PhoenixService) GetSupportedNIP47Methods() []string {
return []string{"pay_invoice", "get_balance", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice"}
return []string{"pay_invoice", "get_balance", "get_budget", "get_info", "make_invoice", "lookup_invoice", "list_transactions", "multi_pay_invoice"}
}

func (svc *PhoenixService) GetSupportedNIP47NotificationTypes() []string {
Expand Down
51 changes: 51 additions & 0 deletions nip47/controllers/get_budget_controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package controllers

import (
"context"
"github.com/getAlby/hub/db/queries"
"github.com/nbd-wtf/go-nostr"

"github.com/getAlby/hub/db"
"github.com/getAlby/hub/logger"
"github.com/getAlby/hub/nip47/models"
"github.com/sirupsen/logrus"
)

type getBudgetResponse struct {
UsedBudget uint64 `json:"used_budget"`
TotalBudget uint64 `json:"total_budget"`
RenewsAt uint64 `json:"renews_at"`
RenewalPeriod string `json:"renewal_period"`
}

func (controller *nip47Controller) HandleGetBudgetEvent(ctx context.Context, nip47Request *models.Request, requestEventId uint, app *db.App, publishResponse publishFunc) {

logger.Logger.WithFields(logrus.Fields{
"request_event_id": requestEventId,
}).Debug("Getting budget")

appPermission := db.AppPermission{}
controller.db.Where("app_id = ? AND scope = ?", app.ID, models.PAY_INVOICE_METHOD).First(&appPermission)

maxAmount := appPermission.MaxAmountSat
if maxAmount == 0 {
publishResponse(&models.Response{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We actually did not catch this in your proposal. I am not sure an empty result makes sense. Maybe the connection should not support this method and return an error instead if the app tries to call this method when a budget is not set?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm that's a good alternative too. Maybe we should discuss on the NIP PR. There are some tradeoffs to think through for sure.

ResultType: nip47Request.Method,
Result: struct{}{},
}, nostr.Tags{})
return
}

usedBudget := queries.GetBudgetUsageSat(controller.db, &appPermission)
responsePayload := &getBudgetResponse{
TotalBudget: uint64(maxAmount * 1000),
UsedBudget: usedBudget * 1000,
RenewalPeriod: appPermission.BudgetRenewal,
RenewsAt: uint64(queries.GetBudgetRenewsAt(appPermission.BudgetRenewal)),
}

publishResponse(&models.Response{
ResultType: nip47Request.Method,
Result: responsePayload,
}, nostr.Tags{})
}
172 changes: 172 additions & 0 deletions nip47/controllers/get_budget_controller_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
package controllers

import (
"context"
"encoding/json"
"testing"
"time"

"github.com/nbd-wtf/go-nostr"
"github.com/stretchr/testify/assert"

"github.com/getAlby/hub/constants"
"github.com/getAlby/hub/db"
"github.com/getAlby/hub/nip47/models"
"github.com/getAlby/hub/nip47/permissions"
"github.com/getAlby/hub/tests"
"github.com/getAlby/hub/transactions"
)

const nip47GetBudgetJson = `
{
"method": "get_budget"
}
`

func TestHandleGetBudgetEvent_noneUsed(t *testing.T) {
ctx := context.TODO()
defer tests.RemoveTestService()
svc, err := tests.CreateTestService()
assert.NoError(t, err)

nip47Request := &models.Request{}
err = json.Unmarshal([]byte(nip47GetBudgetJson), nip47Request)
assert.NoError(t, err)

app, _, err := tests.CreateApp(svc)
assert.NoError(t, err)
now := time.Now()

appPermission := &db.AppPermission{
AppId: app.ID,
App: *app,
Scope: constants.PAY_INVOICE_SCOPE,
MaxAmountSat: 400,
BudgetRenewal: constants.BUDGET_RENEWAL_MONTHLY,
}
err = svc.DB.Create(appPermission).Error
assert.NoError(t, err)

dbRequestEvent := &db.RequestEvent{}
err = svc.DB.Create(&dbRequestEvent).Error
assert.NoError(t, err)

var publishedResponse *models.Response

publishResponse := func(response *models.Response, tags nostr.Tags) {
publishedResponse = response
}

permissionsSvc := permissions.NewPermissionsService(svc.DB, svc.EventPublisher)
transactionsSvc := transactions.NewTransactionsService(svc.DB, svc.EventPublisher)
NewNip47Controller(svc.LNClient, svc.DB, svc.EventPublisher, permissionsSvc, transactionsSvc).
HandleGetBudgetEvent(ctx, nip47Request, dbRequestEvent.ID, app, publishResponse)

assert.Equal(t, uint64(400000), publishedResponse.Result.(*getBudgetResponse).TotalBudget)
assert.Equal(t, uint64(0), publishedResponse.Result.(*getBudgetResponse).UsedBudget)
renewsAt := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()).AddDate(0, 1, 0).Unix()
assert.Equal(t, uint64(renewsAt), publishedResponse.Result.(*getBudgetResponse).RenewsAt)
assert.Equal(t, constants.BUDGET_RENEWAL_MONTHLY, publishedResponse.Result.(*getBudgetResponse).RenewalPeriod)
assert.Nil(t, publishedResponse.Error)
}

func TestHandleGetBudgetEvent_halfUsed(t *testing.T) {
ctx := context.TODO()
defer tests.RemoveTestService()
svc, err := tests.CreateTestService()
assert.NoError(t, err)

nip47Request := &models.Request{}
err = json.Unmarshal([]byte(nip47GetBudgetJson), nip47Request)
assert.NoError(t, err)

app, _, err := tests.CreateApp(svc)
assert.NoError(t, err)
now := time.Now()

appPermission := &db.AppPermission{
AppId: app.ID,
App: *app,
Scope: constants.PAY_INVOICE_SCOPE,
MaxAmountSat: 400,
BudgetRenewal: constants.BUDGET_RENEWAL_MONTHLY,
}
err = svc.DB.Create(appPermission).Error
assert.NoError(t, err)

svc.DB.Create(&db.Transaction{
AppId: &app.ID,
State: constants.TRANSACTION_STATE_SETTLED,
Type: constants.TRANSACTION_TYPE_OUTGOING,
AmountMsat: 200000,
})

dbRequestEvent := &db.RequestEvent{}
err = svc.DB.Create(&dbRequestEvent).Error
assert.NoError(t, err)

var publishedResponse *models.Response

publishResponse := func(response *models.Response, tags nostr.Tags) {
publishedResponse = response
}

permissionsSvc := permissions.NewPermissionsService(svc.DB, svc.EventPublisher)
transactionsSvc := transactions.NewTransactionsService(svc.DB, svc.EventPublisher)
NewNip47Controller(svc.LNClient, svc.DB, svc.EventPublisher, permissionsSvc, transactionsSvc).
HandleGetBudgetEvent(ctx, nip47Request, dbRequestEvent.ID, app, publishResponse)

assert.Equal(t, uint64(400000), publishedResponse.Result.(*getBudgetResponse).TotalBudget)
assert.Equal(t, uint64(200000), publishedResponse.Result.(*getBudgetResponse).UsedBudget)
renewsAt := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()).AddDate(0, 1, 0).Unix()
assert.Equal(t, uint64(renewsAt), publishedResponse.Result.(*getBudgetResponse).RenewsAt)
assert.Equal(t, constants.BUDGET_RENEWAL_MONTHLY, publishedResponse.Result.(*getBudgetResponse).RenewalPeriod)
assert.Nil(t, publishedResponse.Error)
}

func TestHandleGetBudgetEvent_noBudget(t *testing.T) {
ctx := context.TODO()
defer tests.RemoveTestService()
svc, err := tests.CreateTestService()
assert.NoError(t, err)

nip47Request := &models.Request{}
err = json.Unmarshal([]byte(nip47GetBudgetJson), nip47Request)
assert.NoError(t, err)

app, _, err := tests.CreateApp(svc)
assert.NoError(t, err)

appPermission := &db.AppPermission{
AppId: app.ID,
App: *app,
Scope: constants.PAY_INVOICE_SCOPE,
}
err = svc.DB.Create(appPermission).Error
assert.NoError(t, err)

svc.DB.Create(&db.Transaction{
AppId: &app.ID,
State: constants.TRANSACTION_STATE_SETTLED,
Type: constants.TRANSACTION_TYPE_OUTGOING,
AmountMsat: 200000,
})

dbRequestEvent := &db.RequestEvent{}
err = svc.DB.Create(&dbRequestEvent).Error
assert.NoError(t, err)

var publishedResponse *models.Response

publishResponse := func(response *models.Response, tags nostr.Tags) {
publishedResponse = response
}

permissionsSvc := permissions.NewPermissionsService(svc.DB, svc.EventPublisher)
transactionsSvc := transactions.NewTransactionsService(svc.DB, svc.EventPublisher)
NewNip47Controller(svc.LNClient, svc.DB, svc.EventPublisher, permissionsSvc, transactionsSvc).
HandleGetBudgetEvent(ctx, nip47Request, dbRequestEvent.ID, app, publishResponse)

assert.Equal(t, struct{}{}, publishedResponse.Result)
assert.Nil(t, publishedResponse.Error)
}
3 changes: 3 additions & 0 deletions nip47/event_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,9 @@ func (svc *nip47Service) HandleEvent(ctx context.Context, relay nostrmodels.Rela
case models.GET_BALANCE_METHOD:
controller.
HandleGetBalanceEvent(ctx, nip47Request, requestEvent.ID, &app, publishResponse)
case models.GET_BUDGET_METHOD:
controller.
HandleGetBudgetEvent(ctx, nip47Request, requestEvent.ID, &app, publishResponse)
case models.MAKE_INVOICE_METHOD:
controller.
HandleMakeInvoiceEvent(ctx, nip47Request, requestEvent.ID, app.ID, publishResponse)
Expand Down
1 change: 1 addition & 0 deletions nip47/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const (
// request methods
PAY_INVOICE_METHOD = "pay_invoice"
GET_BALANCE_METHOD = "get_balance"
GET_BUDGET_METHOD = "get_budget"
GET_INFO_METHOD = "get_info"
MAKE_INVOICE_METHOD = "make_invoice"
LOOKUP_INVOICE_METHOD = "lookup_invoice"
Expand Down
Loading