From 70dc928f1b421d47f536b50a9fb15b7896953cb6 Mon Sep 17 00:00:00 2001 From: boufni95 Date: Wed, 6 Nov 2024 19:55:10 +0000 Subject: [PATCH] admin channels --- proto/autogenerated/client.md | 58 ++++++-- proto/autogenerated/go/http_client.go | 59 +++++++- proto/autogenerated/go/types.go | 28 +++- proto/autogenerated/ts/express_server.ts | 60 ++++++-- proto/autogenerated/ts/http_client.ts | 31 +++- proto/autogenerated/ts/nostr_client.ts | 31 +++- proto/autogenerated/ts/nostr_transport.ts | 46 ++++-- proto/autogenerated/ts/types.ts | 165 ++++++++++++++++++---- proto/service/methods.proto | 28 +++- proto/service/structs.proto | 46 ++++-- src/services/lnd/lnd.ts | 58 +++++++- src/services/lnd/openChannelReq.ts | 4 +- src/services/main/adminManager.ts | 28 ++++ src/services/main/paymentManager.ts | 2 - src/services/serverMethods/index.ts | 35 +++-- src/tests/adminChannels.spec.ts | 20 +++ 16 files changed, 590 insertions(+), 109 deletions(-) create mode 100644 src/tests/adminChannels.spec.ts diff --git a/proto/autogenerated/client.md b/proto/autogenerated/client.md index ac9aa9b1..2e8afe67 100644 --- a/proto/autogenerated/client.md +++ b/proto/autogenerated/client.md @@ -18,6 +18,11 @@ The nostr server will send back a message response, and inside the body there wi - input: [AddAppRequest](#AddAppRequest) - output: [AuthApp](#AuthApp) +- AddPeer + - auth type: __Admin__ + - input: [AddPeerRequest](#AddPeerRequest) + - This methods has an __empty__ __response__ body + - AddProduct - auth type: __User__ - input: [AddProductRequest](#AddProductRequest) @@ -48,6 +53,11 @@ The nostr server will send back a message response, and inside the body there wi - This methods has an __empty__ __request__ body - This methods has an __empty__ __response__ body +- CloseChannel + - auth type: __Admin__ + - input: [CloseChannelRequest](#CloseChannelRequest) + - output: [CloseChannelResponse](#CloseChannelResponse) + - CreateOneTimeInviteLink - auth type: __Admin__ - input: [CreateOneTimeInviteLinkRequest](#CreateOneTimeInviteLinkRequest) @@ -181,7 +191,7 @@ The nostr server will send back a message response, and inside the body there wi - output: [NewInvoiceResponse](#NewInvoiceResponse) - OpenChannel - - auth type: __User__ + - auth type: __Admin__ - input: [OpenChannelRequest](#OpenChannelRequest) - output: [OpenChannelResponse](#OpenChannelResponse) @@ -282,6 +292,13 @@ The nostr server will send back a message response, and inside the body there wi - input: [AddAppUserInvoiceRequest](#AddAppUserInvoiceRequest) - output: [NewInvoiceResponse](#NewInvoiceResponse) +- AddPeer + - auth type: __Admin__ + - http method: __post__ + - http route: __/api/admin/peer__ + - input: [AddPeerRequest](#AddPeerRequest) + - This methods has an __empty__ __response__ body + - AddProduct - auth type: __User__ - http method: __post__ @@ -324,6 +341,13 @@ The nostr server will send back a message response, and inside the body there wi - This methods has an __empty__ __request__ body - This methods has an __empty__ __response__ body +- CloseChannel + - auth type: __Admin__ + - http method: __post__ + - http route: __/api/admin/channel/close__ + - input: [CloseChannelRequest](#CloseChannelRequest) + - output: [CloseChannelResponse](#CloseChannelResponse) + - CreateOneTimeInviteLink - auth type: __Admin__ - http method: __post__ @@ -600,9 +624,9 @@ The nostr server will send back a message response, and inside the body there wi - output: [NewInvoiceResponse](#NewInvoiceResponse) - OpenChannel - - auth type: __User__ + - auth type: __Admin__ - http method: __post__ - - http route: __/api/user/open/channel__ + - http route: __/api/admin/channel/open__ - input: [OpenChannelRequest](#OpenChannelRequest) - output: [OpenChannelResponse](#OpenChannelResponse) @@ -736,6 +760,11 @@ The nostr server will send back a message response, and inside the body there wi - __fail_if_exists__: _boolean_ - __identifier__: _string_ +### AddPeerRequest + - __host__: _string_ + - __port__: _number_ + - __pubkey__: _string_ + ### AddProductRequest - __name__: _string_ - __price_sats__: _number_ @@ -794,6 +823,15 @@ The nostr server will send back a message response, and inside the body there wi ### CallbackUrl - __url__: _string_ +### CloseChannelRequest + - __force__: _boolean_ + - __funding_txid__: _string_ + - __output_index__: _number_ + - __sat_per_v_byte__: _number_ + +### CloseChannelResponse + - __closing_txid__: _string_ + ### ClosedChannel - __capacity__: _number_ - __channel_id__: _string_ @@ -863,6 +901,9 @@ The nostr server will send back a message response, and inside the body there wi ### GetAppUserRequest - __user_identifier__: _string_ +### GetChannelPolicyRequest + - __channel_id__: _string_ + ### GetInviteTokenStateRequest - __invite_token__: _string_ @@ -1004,13 +1045,14 @@ The nostr server will send back a message response, and inside the body there wi - __remote_balance__: _number_ ### OpenChannelRequest - - __closeAddress__: _string_ - - __destination__: _string_ - - __fundingAmount__: _number_ - - __pushAmount__: _number_ + - __close_address__: _string_ *this field is optional + - __local_funding_amount__: _number_ + - __node_pubkey__: _string_ + - __push_sat__: _number_ *this field is optional + - __sat_per_v_byte__: _number_ ### OpenChannelResponse - - __channelId__: _string_ + - __channel_id__: _string_ ### PayAddressRequest - __address__: _string_ diff --git a/proto/autogenerated/go/http_client.go b/proto/autogenerated/go/http_client.go index 67935d5b..6c64e3ff 100644 --- a/proto/autogenerated/go/http_client.go +++ b/proto/autogenerated/go/http_client.go @@ -58,12 +58,14 @@ type Client struct { AddAppInvoice func(req AddAppInvoiceRequest) (*NewInvoiceResponse, error) AddAppUser func(req AddAppUserRequest) (*AppUser, error) AddAppUserInvoice func(req AddAppUserInvoiceRequest) (*NewInvoiceResponse, error) + AddPeer func(req AddPeerRequest) error AddProduct func(req AddProductRequest) (*Product, error) AuthApp func(req AuthAppRequest) (*AuthApp, error) AuthorizeDebit func(req DebitAuthorizationRequest) (*DebitAuthorization, error) BanDebit func(req DebitOperation) error BanUser func(req BanUserRequest) (*BanUserResponse, error) // batching method: BatchUser not implemented + CloseChannel func(req CloseChannelRequest) (*CloseChannelResponse, error) CreateOneTimeInviteLink func(req CreateOneTimeInviteLinkRequest) (*CreateOneTimeInviteLinkResponse, error) DecodeInvoice func(req DecodeInvoiceRequest) (*DecodeInvoiceResponse, error) EditDebit func(req DebitAuthorizationRequest) error @@ -237,6 +239,30 @@ func NewClient(params ClientParams) *Client { } return &res, nil }, + AddPeer: func(req AddPeerRequest) error { + auth, err := params.RetrieveAdminAuth() + if err != nil { + return err + } + finalRoute := "/api/admin/peer" + body, err := json.Marshal(req) + if err != nil { + return err + } + resBody, err := doPostRequest(params.BaseURL+finalRoute, body, auth) + if err != nil { + return err + } + result := ResultError{} + err = json.Unmarshal(resBody, &result) + if err != nil { + return err + } + if result.Status == "ERROR" { + return fmt.Errorf(result.Reason) + } + return nil + }, AddProduct: func(req AddProductRequest) (*Product, error) { auth, err := params.RetrieveUserAuth() if err != nil { @@ -378,6 +404,35 @@ func NewClient(params ClientParams) *Client { return &res, nil }, // batching method: BatchUser not implemented + CloseChannel: func(req CloseChannelRequest) (*CloseChannelResponse, error) { + auth, err := params.RetrieveAdminAuth() + if err != nil { + return nil, err + } + finalRoute := "/api/admin/channel/close" + body, err := json.Marshal(req) + if err != nil { + return nil, err + } + resBody, err := doPostRequest(params.BaseURL+finalRoute, body, auth) + if err != nil { + return nil, err + } + result := ResultError{} + err = json.Unmarshal(resBody, &result) + if err != nil { + return nil, err + } + if result.Status == "ERROR" { + return nil, fmt.Errorf(result.Reason) + } + res := CloseChannelResponse{} + err = json.Unmarshal(resBody, &res) + if err != nil { + return nil, err + } + return &res, nil + }, CreateOneTimeInviteLink: func(req CreateOneTimeInviteLinkRequest) (*CreateOneTimeInviteLinkResponse, error) { auth, err := params.RetrieveAdminAuth() if err != nil { @@ -1267,11 +1322,11 @@ func NewClient(params ClientParams) *Client { return &res, nil }, OpenChannel: func(req OpenChannelRequest) (*OpenChannelResponse, error) { - auth, err := params.RetrieveUserAuth() + auth, err := params.RetrieveAdminAuth() if err != nil { return nil, err } - finalRoute := "/api/user/open/channel" + finalRoute := "/api/admin/channel/open" body, err := json.Marshal(req) if err != nil { return nil, err diff --git a/proto/autogenerated/go/types.go b/proto/autogenerated/go/types.go index 3cfb405a..e3a550fa 100644 --- a/proto/autogenerated/go/types.go +++ b/proto/autogenerated/go/types.go @@ -95,6 +95,11 @@ type AddAppUserRequest struct { Fail_if_exists bool `json:"fail_if_exists"` Identifier string `json:"identifier"` } +type AddPeerRequest struct { + Host string `json:"host"` + Port int64 `json:"port"` + Pubkey string `json:"pubkey"` +} type AddProductRequest struct { Name string `json:"name"` Price_sats int64 `json:"price_sats"` @@ -153,6 +158,15 @@ type BannedAppUser struct { type CallbackUrl struct { Url string `json:"url"` } +type CloseChannelRequest struct { + Force bool `json:"force"` + Funding_txid string `json:"funding_txid"` + Output_index int64 `json:"output_index"` + Sat_per_v_byte int64 `json:"sat_per_v_byte"` +} +type CloseChannelResponse struct { + Closing_txid string `json:"closing_txid"` +} type ClosedChannel struct { Capacity int64 `json:"capacity"` Channel_id string `json:"channel_id"` @@ -222,6 +236,9 @@ type GetAppUserLNURLInfoRequest struct { type GetAppUserRequest struct { User_identifier string `json:"user_identifier"` } +type GetChannelPolicyRequest struct { + Channel_id string `json:"channel_id"` +} type GetInviteTokenStateRequest struct { Invite_token string `json:"invite_token"` } @@ -363,13 +380,14 @@ type OpenChannel struct { Remote_balance int64 `json:"remote_balance"` } type OpenChannelRequest struct { - Closeaddress string `json:"closeAddress"` - Destination string `json:"destination"` - Fundingamount int64 `json:"fundingAmount"` - Pushamount int64 `json:"pushAmount"` + Close_address string `json:"close_address"` + Local_funding_amount int64 `json:"local_funding_amount"` + Node_pubkey string `json:"node_pubkey"` + Push_sat int64 `json:"push_sat"` + Sat_per_v_byte int64 `json:"sat_per_v_byte"` } type OpenChannelResponse struct { - Channelid string `json:"channelId"` + Channel_id string `json:"channel_id"` } type PayAddressRequest struct { Address string `json:"address"` diff --git a/proto/autogenerated/ts/express_server.ts b/proto/autogenerated/ts/express_server.ts index a103e9fd..14e598ce 100644 --- a/proto/autogenerated/ts/express_server.ts +++ b/proto/autogenerated/ts/express_server.ts @@ -122,6 +122,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } }) + if (!opts.allowNotImplementedMethods && !methods.AddPeer) throw new Error('method: AddPeer is not implemented') + app.post('/api/admin/peer', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'AddPeer', batch: false, nostr: false, batchSize: 0} + const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } + let authCtx: Types.AuthContext = {} + try { + if (!methods.AddPeer) throw new Error('method: AddPeer is not implemented') + const authContext = await opts.AdminAuthGuard(req.headers['authorization']) + authCtx = authContext + stats.guard = process.hrtime.bigint() + const request = req.body + const error = Types.AddPeerRequestValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) + const query = req.query + const params = req.params + await methods.AddPeer({rpcName:'AddPeer', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res.json({status: 'OK'}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + }) if (!opts.allowNotImplementedMethods && !methods.AddProduct) throw new Error('method: AddProduct is not implemented') app.post('/api/user/product/add', async (req, res) => { const info: Types.RequestInfo = { rpcName: 'AddProduct', batch: false, nostr: false, batchSize: 0} @@ -433,18 +455,6 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break - case 'OpenChannel': - if (!methods.OpenChannel) { - throw new Error('method OpenChannel not found' ) - } else { - const error = Types.OpenChannelRequestValidate(operation.req) - opStats.validate = process.hrtime.bigint() - if (error !== null) throw error - const res = await methods.OpenChannel({...operation, ctx}); responses.push({ status: 'OK', ...res }) - opStats.handle = process.hrtime.bigint() - callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) - } - break case 'PayAddress': if (!methods.PayAddress) { throw new Error('method PayAddress not found' ) @@ -525,6 +535,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { opts.metricsCallback([{ ...info, ...stats, ...ctx }, ...callsMetrics]) } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } }) + if (!opts.allowNotImplementedMethods && !methods.CloseChannel) throw new Error('method: CloseChannel is not implemented') + app.post('/api/admin/channel/close', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'CloseChannel', batch: false, nostr: false, batchSize: 0} + const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } + let authCtx: Types.AuthContext = {} + try { + if (!methods.CloseChannel) throw new Error('method: CloseChannel is not implemented') + const authContext = await opts.AdminAuthGuard(req.headers['authorization']) + authCtx = authContext + stats.guard = process.hrtime.bigint() + const request = req.body + const error = Types.CloseChannelRequestValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback) + const query = req.query + const params = req.params + const response = await methods.CloseChannel({rpcName:'CloseChannel', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res.json({status: 'OK', ...response}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + }) if (!opts.allowNotImplementedMethods && !methods.CreateOneTimeInviteLink) throw new Error('method: CreateOneTimeInviteLink is not implemented') app.post('/api/admin/app/invite/create', async (req, res) => { const info: Types.RequestInfo = { rpcName: 'CreateOneTimeInviteLink', batch: false, nostr: false, batchSize: 0} @@ -1204,13 +1236,13 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { } catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } }) if (!opts.allowNotImplementedMethods && !methods.OpenChannel) throw new Error('method: OpenChannel is not implemented') - app.post('/api/user/open/channel', async (req, res) => { + app.post('/api/admin/channel/open', async (req, res) => { const info: Types.RequestInfo = { rpcName: 'OpenChannel', batch: false, nostr: false, batchSize: 0} const stats: Types.RequestStats = { startMs:req.startTimeMs || 0, start:req.startTime || 0n, parse: process.hrtime.bigint(), guard: 0n, validate: 0n, handle: 0n } let authCtx: Types.AuthContext = {} try { if (!methods.OpenChannel) throw new Error('method: OpenChannel is not implemented') - const authContext = await opts.UserAuthGuard(req.headers['authorization']) + const authContext = await opts.AdminAuthGuard(req.headers['authorization']) authCtx = authContext stats.guard = process.hrtime.bigint() const request = req.body diff --git a/proto/autogenerated/ts/http_client.ts b/proto/autogenerated/ts/http_client.ts index 5fc32cbb..8da21cfb 100644 --- a/proto/autogenerated/ts/http_client.ts +++ b/proto/autogenerated/ts/http_client.ts @@ -73,6 +73,17 @@ export default (params: ClientParams) => ({ } return { status: 'ERROR', reason: 'invalid response' } }, + AddPeer: async (request: Types.AddPeerRequest): Promise => { + const auth = await params.retrieveAdminAuth() + if (auth === null) throw new Error('retrieveAdminAuth() returned null') + let finalRoute = '/api/admin/peer' + const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + return data + } + return { status: 'ERROR', reason: 'invalid response' } + }, AddProduct: async (request: Types.AddProductRequest): Promise => { const auth = await params.retrieveUserAuth() if (auth === null) throw new Error('retrieveUserAuth() returned null') @@ -151,6 +162,20 @@ export default (params: ClientParams) => ({ } return { status: 'ERROR', reason: 'invalid response' } }, + CloseChannel: async (request: Types.CloseChannelRequest): Promise => { + const auth = await params.retrieveAdminAuth() + if (auth === null) throw new Error('retrieveAdminAuth() returned null') + let finalRoute = '/api/admin/channel/close' + const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return { status: 'OK', ...result } + const error = Types.CloseChannelResponseValidate(result) + if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message } + } + return { status: 'ERROR', reason: 'invalid response' } + }, CreateOneTimeInviteLink: async (request: Types.CreateOneTimeInviteLinkRequest): Promise => { const auth = await params.retrieveAdminAuth() if (auth === null) throw new Error('retrieveAdminAuth() returned null') @@ -611,9 +636,9 @@ export default (params: ClientParams) => ({ return { status: 'ERROR', reason: 'invalid response' } }, OpenChannel: async (request: Types.OpenChannelRequest): Promise => { - const auth = await params.retrieveUserAuth() - if (auth === null) throw new Error('retrieveUserAuth() returned null') - let finalRoute = '/api/user/open/channel' + const auth = await params.retrieveAdminAuth() + if (auth === null) throw new Error('retrieveAdminAuth() returned null') + let finalRoute = '/api/admin/channel/open' const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } }) if (data.status === 'ERROR' && typeof data.reason === 'string') return data if (data.status === 'OK') { diff --git a/proto/autogenerated/ts/nostr_client.ts b/proto/autogenerated/ts/nostr_client.ts index 10a7141f..a67e87a7 100644 --- a/proto/autogenerated/ts/nostr_client.ts +++ b/proto/autogenerated/ts/nostr_client.ts @@ -27,6 +27,18 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ } return { status: 'ERROR', reason: 'invalid response' } }, + AddPeer: async (request: Types.AddPeerRequest): Promise => { + const auth = await params.retrieveNostrAdminAuth() + if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null') + const nostrRequest: NostrRequest = {} + nostrRequest.body = request + const data = await send(params.pubDestination, {rpcName:'AddPeer',authIdentifier:auth, ...nostrRequest }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + return data + } + return { status: 'ERROR', reason: 'invalid response' } + }, AddProduct: async (request: Types.AddProductRequest): Promise => { const auth = await params.retrieveNostrUserAuth() if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') @@ -110,6 +122,21 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ } return { status: 'ERROR', reason: 'invalid response' } }, + CloseChannel: async (request: Types.CloseChannelRequest): Promise => { + const auth = await params.retrieveNostrAdminAuth() + if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null') + const nostrRequest: NostrRequest = {} + nostrRequest.body = request + const data = await send(params.pubDestination, {rpcName:'CloseChannel',authIdentifier:auth, ...nostrRequest }) + if (data.status === 'ERROR' && typeof data.reason === 'string') return data + if (data.status === 'OK') { + const result = data + if(!params.checkResult) return { status: 'OK', ...result } + const error = Types.CloseChannelResponseValidate(result) + if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message } + } + return { status: 'ERROR', reason: 'invalid response' } + }, CreateOneTimeInviteLink: async (request: Types.CreateOneTimeInviteLinkRequest): Promise => { const auth = await params.retrieveNostrAdminAuth() if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null') @@ -484,8 +511,8 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ return { status: 'ERROR', reason: 'invalid response' } }, OpenChannel: async (request: Types.OpenChannelRequest): Promise => { - const auth = await params.retrieveNostrUserAuth() - if (auth === null) throw new Error('retrieveNostrUserAuth() returned null') + const auth = await params.retrieveNostrAdminAuth() + if (auth === null) throw new Error('retrieveNostrAdminAuth() returned null') const nostrRequest: NostrRequest = {} nostrRequest.body = request const data = await send(params.pubDestination, {rpcName:'OpenChannel',authIdentifier:auth, ...nostrRequest }) diff --git a/proto/autogenerated/ts/nostr_transport.ts b/proto/autogenerated/ts/nostr_transport.ts index 4b38912a..29f47829 100644 --- a/proto/autogenerated/ts/nostr_transport.ts +++ b/proto/autogenerated/ts/nostr_transport.ts @@ -48,6 +48,22 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { opts.metricsCallback([{ ...info, ...stats, ...authContext }]) }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } break + case 'AddPeer': + try { + if (!methods.AddPeer) throw new Error('method: AddPeer is not implemented') + const authContext = await opts.NostrAdminAuthGuard(req.appId, req.authIdentifier) + stats.guard = process.hrtime.bigint() + authCtx = authContext + const request = req.body + const error = Types.AddPeerRequestValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback) + await methods.AddPeer({rpcName:'AddPeer', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res({status: 'OK'}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + break case 'AddProduct': try { if (!methods.AddProduct) throw new Error('method: AddProduct is not implemented') @@ -327,18 +343,6 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break - case 'OpenChannel': - if (!methods.OpenChannel) { - throw new Error('method not defined: OpenChannel') - } else { - const error = Types.OpenChannelRequestValidate(operation.req) - opStats.validate = process.hrtime.bigint() - if (error !== null) throw error - const res = await methods.OpenChannel({...operation, ctx}); responses.push({ status: 'OK', ...res }) - opStats.handle = process.hrtime.bigint() - callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) - } - break case 'PayAddress': if (!methods.PayAddress) { throw new Error('method not defined: PayAddress') @@ -419,6 +423,22 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { opts.metricsCallback([{ ...info, ...stats, ...ctx }, ...callsMetrics]) }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } break + case 'CloseChannel': + try { + if (!methods.CloseChannel) throw new Error('method: CloseChannel is not implemented') + const authContext = await opts.NostrAdminAuthGuard(req.appId, req.authIdentifier) + stats.guard = process.hrtime.bigint() + authCtx = authContext + const request = req.body + const error = Types.CloseChannelRequestValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback) + const response = await methods.CloseChannel({rpcName:'CloseChannel', ctx:authContext , req: request}) + stats.handle = process.hrtime.bigint() + res({status: 'OK', ...response}) + opts.metricsCallback([{ ...info, ...stats, ...authContext }]) + }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } + break case 'CreateOneTimeInviteLink': try { if (!methods.CreateOneTimeInviteLink) throw new Error('method: CreateOneTimeInviteLink is not implemented') @@ -799,7 +819,7 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { case 'OpenChannel': try { if (!methods.OpenChannel) throw new Error('method: OpenChannel is not implemented') - const authContext = await opts.NostrUserAuthGuard(req.appId, req.authIdentifier) + const authContext = await opts.NostrAdminAuthGuard(req.appId, req.authIdentifier) stats.guard = process.hrtime.bigint() authCtx = authContext const request = req.body diff --git a/proto/autogenerated/ts/types.ts b/proto/autogenerated/ts/types.ts index 1c6a52e4..bece0ac0 100644 --- a/proto/autogenerated/ts/types.ts +++ b/proto/autogenerated/ts/types.ts @@ -7,8 +7,8 @@ export type RequestMetric = AuthContext & RequestInfo & RequestStats & { error?: export type AdminContext = { admin_id: string } -export type AdminMethodInputs = AddApp_Input | AuthApp_Input | BanUser_Input | CreateOneTimeInviteLink_Input | GetInviteLinkState_Input | GetSeed_Input | ListChannels_Input | LndGetInfo_Input -export type AdminMethodOutputs = AddApp_Output | AuthApp_Output | BanUser_Output | CreateOneTimeInviteLink_Output | GetInviteLinkState_Output | GetSeed_Output | ListChannels_Output | LndGetInfo_Output +export type AdminMethodInputs = AddApp_Input | AddPeer_Input | AuthApp_Input | BanUser_Input | CloseChannel_Input | CreateOneTimeInviteLink_Input | GetInviteLinkState_Input | GetSeed_Input | ListChannels_Input | LndGetInfo_Input | OpenChannel_Input +export type AdminMethodOutputs = AddApp_Output | AddPeer_Output | AuthApp_Output | BanUser_Output | CloseChannel_Output | CreateOneTimeInviteLink_Output | GetInviteLinkState_Output | GetSeed_Output | ListChannels_Output | LndGetInfo_Output | OpenChannel_Output export type AppContext = { app_id: string } @@ -34,8 +34,8 @@ export type UserContext = { app_user_id: string user_id: string } -export type UserMethodInputs = AddProduct_Input | AuthorizeDebit_Input | BanDebit_Input | DecodeInvoice_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | OpenChannel_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UserHealth_Input -export type UserMethodOutputs = AddProduct_Output | AuthorizeDebit_Output | BanDebit_Output | DecodeInvoice_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | OpenChannel_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UserHealth_Output +export type UserMethodInputs = AddProduct_Input | AuthorizeDebit_Input | BanDebit_Input | DecodeInvoice_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UserHealth_Input +export type UserMethodOutputs = AddProduct_Output | AuthorizeDebit_Output | BanDebit_Output | DecodeInvoice_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UserHealth_Output export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest} @@ -50,6 +50,9 @@ export type AddAppUser_Output = ResultError | ({ status: 'OK' } & AppUser) export type AddAppUserInvoice_Input = {rpcName:'AddAppUserInvoice', req: AddAppUserInvoiceRequest} export type AddAppUserInvoice_Output = ResultError | ({ status: 'OK' } & NewInvoiceResponse) +export type AddPeer_Input = {rpcName:'AddPeer', req: AddPeerRequest} +export type AddPeer_Output = ResultError | { status: 'OK' } + export type AddProduct_Input = {rpcName:'AddProduct', req: AddProductRequest} export type AddProduct_Output = ResultError | ({ status: 'OK' } & Product) @@ -68,6 +71,9 @@ export type BanUser_Output = ResultError | ({ status: 'OK' } & BanUserResponse) export type BatchUser_Input = UserMethodInputs export type BatchUser_Output = UserMethodOutputs +export type CloseChannel_Input = {rpcName:'CloseChannel', req: CloseChannelRequest} +export type CloseChannel_Output = ResultError | ({ status: 'OK' } & CloseChannelResponse) + export type CreateOneTimeInviteLink_Input = {rpcName:'CreateOneTimeInviteLink', req: CreateOneTimeInviteLinkRequest} export type CreateOneTimeInviteLink_Output = ResultError | ({ status: 'OK' } & CreateOneTimeInviteLinkResponse) @@ -254,11 +260,13 @@ export type ServerMethods = { AddAppInvoice?: (req: AddAppInvoice_Input & {ctx: AppContext }) => Promise AddAppUser?: (req: AddAppUser_Input & {ctx: AppContext }) => Promise AddAppUserInvoice?: (req: AddAppUserInvoice_Input & {ctx: AppContext }) => Promise + AddPeer?: (req: AddPeer_Input & {ctx: AdminContext }) => Promise AddProduct?: (req: AddProduct_Input & {ctx: UserContext }) => Promise AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise BanDebit?: (req: BanDebit_Input & {ctx: UserContext }) => Promise BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise + CloseChannel?: (req: CloseChannel_Input & {ctx: AdminContext }) => Promise CreateOneTimeInviteLink?: (req: CreateOneTimeInviteLink_Input & {ctx: AdminContext }) => Promise DecodeInvoice?: (req: DecodeInvoice_Input & {ctx: UserContext }) => Promise EditDebit?: (req: EditDebit_Input & {ctx: UserContext }) => Promise @@ -296,7 +304,7 @@ export type ServerMethods = { NewAddress?: (req: NewAddress_Input & {ctx: UserContext }) => Promise NewInvoice?: (req: NewInvoice_Input & {ctx: UserContext }) => Promise NewProductInvoice?: (req: NewProductInvoice_Input & {ctx: UserContext }) => Promise - OpenChannel?: (req: OpenChannel_Input & {ctx: UserContext }) => Promise + OpenChannel?: (req: OpenChannel_Input & {ctx: AdminContext }) => Promise PayAddress?: (req: PayAddress_Input & {ctx: UserContext }) => Promise PayAppUserInvoice?: (req: PayAppUserInvoice_Input & {ctx: AppContext }) => Promise PayInvoice?: (req: PayInvoice_Input & {ctx: UserContext }) => Promise @@ -463,6 +471,34 @@ export const AddAppUserRequestValidate = (o?: AddAppUserRequest, opts: AddAppUse return null } +export type AddPeerRequest = { + host: string + port: number + pubkey: string +} +export const AddPeerRequestOptionalFields: [] = [] +export type AddPeerRequestOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + host_CustomCheck?: (v: string) => boolean + port_CustomCheck?: (v: number) => boolean + pubkey_CustomCheck?: (v: string) => boolean +} +export const AddPeerRequestValidate = (o?: AddPeerRequest, opts: AddPeerRequestOptions = {}, path: string = 'AddPeerRequest::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.host !== 'string') return new Error(`${path}.host: is not a string`) + if (opts.host_CustomCheck && !opts.host_CustomCheck(o.host)) return new Error(`${path}.host: custom check failed`) + + if (typeof o.port !== 'number') return new Error(`${path}.port: is not a number`) + if (opts.port_CustomCheck && !opts.port_CustomCheck(o.port)) return new Error(`${path}.port: custom check failed`) + + if (typeof o.pubkey !== 'string') return new Error(`${path}.pubkey: is not a string`) + if (opts.pubkey_CustomCheck && !opts.pubkey_CustomCheck(o.pubkey)) return new Error(`${path}.pubkey: custom check failed`) + + return null +} + export type AddProductRequest = { name: string price_sats: number @@ -810,6 +846,57 @@ export const CallbackUrlValidate = (o?: CallbackUrl, opts: CallbackUrlOptions = return null } +export type CloseChannelRequest = { + force: boolean + funding_txid: string + output_index: number + sat_per_v_byte: number +} +export const CloseChannelRequestOptionalFields: [] = [] +export type CloseChannelRequestOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + force_CustomCheck?: (v: boolean) => boolean + funding_txid_CustomCheck?: (v: string) => boolean + output_index_CustomCheck?: (v: number) => boolean + sat_per_v_byte_CustomCheck?: (v: number) => boolean +} +export const CloseChannelRequestValidate = (o?: CloseChannelRequest, opts: CloseChannelRequestOptions = {}, path: string = 'CloseChannelRequest::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.force !== 'boolean') return new Error(`${path}.force: is not a boolean`) + if (opts.force_CustomCheck && !opts.force_CustomCheck(o.force)) return new Error(`${path}.force: custom check failed`) + + if (typeof o.funding_txid !== 'string') return new Error(`${path}.funding_txid: is not a string`) + if (opts.funding_txid_CustomCheck && !opts.funding_txid_CustomCheck(o.funding_txid)) return new Error(`${path}.funding_txid: custom check failed`) + + if (typeof o.output_index !== 'number') return new Error(`${path}.output_index: is not a number`) + if (opts.output_index_CustomCheck && !opts.output_index_CustomCheck(o.output_index)) return new Error(`${path}.output_index: custom check failed`) + + if (typeof o.sat_per_v_byte !== 'number') return new Error(`${path}.sat_per_v_byte: is not a number`) + if (opts.sat_per_v_byte_CustomCheck && !opts.sat_per_v_byte_CustomCheck(o.sat_per_v_byte)) return new Error(`${path}.sat_per_v_byte: custom check failed`) + + return null +} + +export type CloseChannelResponse = { + closing_txid: string +} +export const CloseChannelResponseOptionalFields: [] = [] +export type CloseChannelResponseOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + closing_txid_CustomCheck?: (v: string) => boolean +} +export const CloseChannelResponseValidate = (o?: CloseChannelResponse, opts: CloseChannelResponseOptions = {}, path: string = 'CloseChannelResponse::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.closing_txid !== 'string') return new Error(`${path}.closing_txid: is not a string`) + if (opts.closing_txid_CustomCheck && !opts.closing_txid_CustomCheck(o.closing_txid)) return new Error(`${path}.closing_txid: custom check failed`) + + return null +} + export type ClosedChannel = { capacity: number channel_id: string @@ -1231,6 +1318,24 @@ export const GetAppUserRequestValidate = (o?: GetAppUserRequest, opts: GetAppUse return null } +export type GetChannelPolicyRequest = { + channel_id: string +} +export const GetChannelPolicyRequestOptionalFields: [] = [] +export type GetChannelPolicyRequestOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + channel_id_CustomCheck?: (v: string) => boolean +} +export const GetChannelPolicyRequestValidate = (o?: GetChannelPolicyRequest, opts: GetChannelPolicyRequestOptions = {}, path: string = 'GetChannelPolicyRequest::root.'): Error | null => { + if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + + if (typeof o.channel_id !== 'string') return new Error(`${path}.channel_id: is not a string`) + if (opts.channel_id_CustomCheck && !opts.channel_id_CustomCheck(o.channel_id)) return new Error(`${path}.channel_id: custom check failed`) + + return null +} + export type GetInviteTokenStateRequest = { invite_token: string } @@ -2083,52 +2188,58 @@ export const OpenChannelValidate = (o?: OpenChannel, opts: OpenChannelOptions = } export type OpenChannelRequest = { - closeAddress: string - destination: string - fundingAmount: number - pushAmount: number + close_address?: string + local_funding_amount: number + node_pubkey: string + push_sat?: number + sat_per_v_byte: number } -export const OpenChannelRequestOptionalFields: [] = [] +export type OpenChannelRequestOptionalField = 'close_address' | 'push_sat' +export const OpenChannelRequestOptionalFields: OpenChannelRequestOptionalField[] = ['close_address', 'push_sat'] export type OpenChannelRequestOptions = OptionsBaseMessage & { - checkOptionalsAreSet?: [] - closeAddress_CustomCheck?: (v: string) => boolean - destination_CustomCheck?: (v: string) => boolean - fundingAmount_CustomCheck?: (v: number) => boolean - pushAmount_CustomCheck?: (v: number) => boolean + checkOptionalsAreSet?: OpenChannelRequestOptionalField[] + close_address_CustomCheck?: (v?: string) => boolean + local_funding_amount_CustomCheck?: (v: number) => boolean + node_pubkey_CustomCheck?: (v: string) => boolean + push_sat_CustomCheck?: (v?: number) => boolean + sat_per_v_byte_CustomCheck?: (v: number) => boolean } export const OpenChannelRequestValidate = (o?: OpenChannelRequest, opts: OpenChannelRequestOptions = {}, path: string = 'OpenChannelRequest::root.'): Error | null => { if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') - if (typeof o.closeAddress !== 'string') return new Error(`${path}.closeAddress: is not a string`) - if (opts.closeAddress_CustomCheck && !opts.closeAddress_CustomCheck(o.closeAddress)) return new Error(`${path}.closeAddress: custom check failed`) + if ((o.close_address || opts.allOptionalsAreSet || opts.checkOptionalsAreSet?.includes('close_address')) && typeof o.close_address !== 'string') return new Error(`${path}.close_address: is not a string`) + if (opts.close_address_CustomCheck && !opts.close_address_CustomCheck(o.close_address)) return new Error(`${path}.close_address: custom check failed`) - if (typeof o.destination !== 'string') return new Error(`${path}.destination: is not a string`) - if (opts.destination_CustomCheck && !opts.destination_CustomCheck(o.destination)) return new Error(`${path}.destination: custom check failed`) + if (typeof o.local_funding_amount !== 'number') return new Error(`${path}.local_funding_amount: is not a number`) + if (opts.local_funding_amount_CustomCheck && !opts.local_funding_amount_CustomCheck(o.local_funding_amount)) return new Error(`${path}.local_funding_amount: custom check failed`) - if (typeof o.fundingAmount !== 'number') return new Error(`${path}.fundingAmount: is not a number`) - if (opts.fundingAmount_CustomCheck && !opts.fundingAmount_CustomCheck(o.fundingAmount)) return new Error(`${path}.fundingAmount: custom check failed`) + if (typeof o.node_pubkey !== 'string') return new Error(`${path}.node_pubkey: is not a string`) + if (opts.node_pubkey_CustomCheck && !opts.node_pubkey_CustomCheck(o.node_pubkey)) return new Error(`${path}.node_pubkey: custom check failed`) - if (typeof o.pushAmount !== 'number') return new Error(`${path}.pushAmount: is not a number`) - if (opts.pushAmount_CustomCheck && !opts.pushAmount_CustomCheck(o.pushAmount)) return new Error(`${path}.pushAmount: custom check failed`) + if ((o.push_sat || opts.allOptionalsAreSet || opts.checkOptionalsAreSet?.includes('push_sat')) && typeof o.push_sat !== 'number') return new Error(`${path}.push_sat: is not a number`) + if (opts.push_sat_CustomCheck && !opts.push_sat_CustomCheck(o.push_sat)) return new Error(`${path}.push_sat: custom check failed`) + + if (typeof o.sat_per_v_byte !== 'number') return new Error(`${path}.sat_per_v_byte: is not a number`) + if (opts.sat_per_v_byte_CustomCheck && !opts.sat_per_v_byte_CustomCheck(o.sat_per_v_byte)) return new Error(`${path}.sat_per_v_byte: custom check failed`) return null } export type OpenChannelResponse = { - channelId: string + channel_id: string } export const OpenChannelResponseOptionalFields: [] = [] export type OpenChannelResponseOptions = OptionsBaseMessage & { checkOptionalsAreSet?: [] - channelId_CustomCheck?: (v: string) => boolean + channel_id_CustomCheck?: (v: string) => boolean } export const OpenChannelResponseValidate = (o?: OpenChannelResponse, opts: OpenChannelResponseOptions = {}, path: string = 'OpenChannelResponse::root.'): Error | null => { if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') - if (typeof o.channelId !== 'string') return new Error(`${path}.channelId: is not a string`) - if (opts.channelId_CustomCheck && !opts.channelId_CustomCheck(o.channelId)) return new Error(`${path}.channelId: custom check failed`) + if (typeof o.channel_id !== 'string') return new Error(`${path}.channel_id: is not a string`) + if (opts.channel_id_CustomCheck && !opts.channel_id_CustomCheck(o.channel_id)) return new Error(`${path}.channel_id: custom check failed`) return null } diff --git a/proto/service/methods.proto b/proto/service/methods.proto index 87f502c5..e13bbc91 100644 --- a/proto/service/methods.proto +++ b/proto/service/methods.proto @@ -144,6 +144,27 @@ service LightningPub { option (nostr) = true; } + rpc AddPeer(structs.AddPeerRequest) returns (structs.Empty) { + option (auth_type) = "Admin"; + option (http_method) = "post"; + option (http_route) = "/api/admin/peer"; + option (nostr) = true; + } + + rpc OpenChannel(structs.OpenChannelRequest) returns (structs.OpenChannelResponse) { + option (auth_type) = "Admin"; + option (http_method) = "post"; + option (http_route) = "/api/admin/channel/open"; + option (nostr) = true; + } + + rpc CloseChannel(structs.CloseChannelRequest) returns (structs.CloseChannelResponse) { + option (auth_type) = "Admin"; + option (http_method) = "post"; + option (http_route) = "/api/admin/channel/close"; + option (nostr) = true; + } + rpc GetUsageMetrics(structs.Empty) returns (structs.UsageMetrics) { option (auth_type) = "Metrics"; option (http_method) = "post"; @@ -419,13 +440,6 @@ service LightningPub { option (nostr) = true; } - rpc OpenChannel(structs.OpenChannelRequest) returns (structs.OpenChannelResponse){ - option (auth_type) = "User"; - option (http_method) = "post"; - option (http_route) = "/api/user/open/channel"; - option (nostr) = true; - } - rpc GetLnurlWithdrawLink(structs.Empty) returns (structs.LnurlLinkResponse){ option (auth_type) = "User"; option (http_method) = "get"; diff --git a/proto/service/structs.proto b/proto/service/structs.proto index d8a6e188..39e97743 100644 --- a/proto/service/structs.proto +++ b/proto/service/structs.proto @@ -131,6 +131,41 @@ message LndChannels { repeated OpenChannel open_channels = 1; } +message GetChannelPolicyRequest { + string channel_id = 1; +} + + + +message OpenChannelRequest{ + string node_pubkey = 1; + int64 local_funding_amount = 2; + int64 sat_per_v_byte = 3; + optional int64 push_sat = 5; + optional string close_address = 6; +} + +message OpenChannelResponse{ + string channel_id = 1; +} + +message CloseChannelRequest{ + bool force = 2; + int64 sat_per_v_byte = 3; + string funding_txid = 4; + int64 output_index = 5; +} + +message CloseChannelResponse{ + string closing_txid = 1; +} + +message AddPeerRequest { + string pubkey = 1; + string host = 2; + int64 port = 3; +} + message LndGetInfoRequest { int64 nodeId = 1; } @@ -308,17 +343,6 @@ message PaymentState{ int64 network_fee = 4; } -message OpenChannelRequest{ - string destination = 1; - int64 fundingAmount = 2; - int64 pushAmount = 3; - string closeAddress = 4; -} - -message OpenChannelResponse{ - string channelId = 1; -} - message LnurlLinkResponse{ string lnurl = 1; string k1 = 2; diff --git a/src/services/lnd/lnd.ts b/src/services/lnd/lnd.ts index ed4f7c62..f362f26d 100644 --- a/src/services/lnd/lnd.ts +++ b/src/services/lnd/lnd.ts @@ -8,7 +8,7 @@ import { LightningClient } from '../../../proto/lnd/lightning.client.js' import { InvoicesClient } from '../../../proto/lnd/invoices.client.js' import { RouterClient } from '../../../proto/lnd/router.client.js' import { ChainNotifierClient } from '../../../proto/lnd/chainnotifier.client.js' -import { GetInfoResponse, AddressType, NewAddressResponse, AddInvoiceResponse, Invoice_InvoiceState, PayReq, Payment_PaymentStatus, Payment, PaymentFailureReason, SendCoinsResponse, EstimateFeeResponse, ChannelBalanceResponse, TransactionDetails, ListChannelsResponse, ClosedChannelsResponse, PendingChannelsResponse, ForwardingHistoryResponse, CoinSelectionStrategy } from '../../../proto/lnd/lightning.js' +import { GetInfoResponse, AddressType, NewAddressResponse, AddInvoiceResponse, Invoice_InvoiceState, PayReq, Payment_PaymentStatus, Payment, PaymentFailureReason, SendCoinsResponse, EstimateFeeResponse, ChannelBalanceResponse, TransactionDetails, ListChannelsResponse, ClosedChannelsResponse, PendingChannelsResponse, ForwardingHistoryResponse, CoinSelectionStrategy, OpenStatusUpdate, CloseStatusUpdate, PendingUpdate } from '../../../proto/lnd/lightning.js' import { OpenChannelReq } from './openChannelReq.js'; import { AddInvoiceReq } from './addInvoiceReq.js'; import { PayInvoiceReq } from './payInvoiceReq.js'; @@ -380,6 +380,11 @@ export default class { return res.response } + async GetChannelInfo(chanId: string) { + const res = await this.lightning.getChanInfo({ chanId, chanPoint: "" }, DeadLineMetadata()) + return res.response + } + async GetChannelBalance() { const res = await this.lightning.channelBalance({}, DeadLineMetadata()) return res.response @@ -485,21 +490,66 @@ export default class { } + async AddPeer(pub: string, host: string, port: number) { + const res = await this.lightning.connectPeer({ + addr: { + pubkey: pub, + host: host + ":" + port, + }, + perm: true, + timeout: 0n + }) + return res.response + } + async ListPeers() { const res = await this.lightning.listPeers({ latestError: true }, DeadLineMetadata()) return res.response } - async OpenChannel(destination: string, closeAddress: string, fundingAmount: number, pushSats: number) { + async OpenChannel(destination: string, closeAddress: string, fundingAmount: number, pushSats: number, satsPerVByte: number): Promise { const abortController = new AbortController() - const req = OpenChannelReq(destination, closeAddress, fundingAmount, pushSats) + const req = OpenChannelReq(destination, closeAddress, fundingAmount, pushSats, satsPerVByte) const stream = this.lightning.openChannel(req, { abort: abortController.signal }) return new Promise((res, rej) => { stream.responses.onMessage(message => { console.log("message", message) switch (message.update.oneofKind) { case 'chanPending': - res(Buffer.from(message.pendingChanId).toString('base64')) + res(message) + break + } + }) + stream.responses.onError(error => { + console.log("error", error) + rej(error) + }) + }) + } + + async CloseChannel(fundingTx: string, outputIndex: number, force: boolean, satPerVByte: number): Promise { + const stream = this.lightning.closeChannel({ + deliveryAddress: "", + force: force, + satPerByte: 0n, + satPerVbyte: BigInt(satPerVByte), + noWait: false, + maxFeePerVbyte: 0n, + targetConf: 0, + channelPoint: { + fundingTxid: { + fundingTxidStr: fundingTx, + oneofKind: "fundingTxidStr" + }, + outputIndex: outputIndex + }, + }, DeadLineMetadata()) + return new Promise((res, rej) => { + stream.responses.onMessage(message => { + console.log("message", message) + switch (message.update.oneofKind) { + case 'closePending': + res(message.update.closePending) break } }) diff --git a/src/services/lnd/openChannelReq.ts b/src/services/lnd/openChannelReq.ts index ecd3cbc1..ec0d32f8 100644 --- a/src/services/lnd/openChannelReq.ts +++ b/src/services/lnd/openChannelReq.ts @@ -1,12 +1,12 @@ import { CommitmentType, OpenChannelRequest } from "../../../proto/lnd/lightning.js"; -export const OpenChannelReq = (destination: string, closeAddress: string, fundingAmount: number, pushSats: number): OpenChannelRequest => ({ +export const OpenChannelReq = (destination: string, closeAddress: string, fundingAmount: number, pushSats: number, satsPerVByte: number): OpenChannelRequest => ({ nodePubkey: Buffer.from(destination, 'hex'), closeAddress: closeAddress, localFundingAmount: BigInt(fundingAmount), pushSat: BigInt(pushSats), - satPerVbyte: 0n, // TBD + satPerVbyte: BigInt(satsPerVByte), // TBD private: false, minConfs: 0, // TBD baseFee: 1n, // TBD diff --git a/src/services/main/adminManager.ts b/src/services/main/adminManager.ts index aa3b0f46..5c1fcf06 100644 --- a/src/services/main/adminManager.ts +++ b/src/services/main/adminManager.ts @@ -7,6 +7,9 @@ import * as Types from '../../../proto/autogenerated/ts/types.js' import LND from "../lnd/lnd.js"; export class AdminManager { + + + storage: Storage log = getLogger({ component: "adminManager" }) adminNpub = "" @@ -144,6 +147,7 @@ export class AdminManager { ListChannels = async (): Promise => { const channels = await this.lnd.ListChannels(true) + return { open_channels: channels.channels.map(c => ({ active: c.active, @@ -156,4 +160,28 @@ export class AdminManager { })) } } + + + async AddPeer(req: Types.AddPeerRequest) { + await this.lnd.AddPeer(req.pubkey, req.host, req.port) + } + + async OpenChannel(req: Types.OpenChannelRequest): Promise { + let closeAddr = req.close_address + if (!closeAddr) { + const addr = await this.lnd.NewAddress(Types.AddressType.WITNESS_PUBKEY_HASH, { useProvider: false, from: 'system' }) + closeAddr = addr.address + } + const res = await this.lnd.OpenChannel(req.node_pubkey, closeAddr, req.local_funding_amount, req.push_sat || 0, req.sat_per_v_byte) + return { + channel_id: Buffer.from(res.pendingChanId).toString('hex') + } + } + + async CloseChannel(req: Types.CloseChannelRequest): Promise { + const res = await this.lnd.CloseChannel(req.funding_txid, req.output_index, req.force, req.sat_per_v_byte) + return { + closing_txid: Buffer.from(res.txid).toString('hex') + } + } } \ No newline at end of file diff --git a/src/services/main/paymentManager.ts b/src/services/main/paymentManager.ts index 51c7fec1..4c120f18 100644 --- a/src/services/main/paymentManager.ts +++ b/src/services/main/paymentManager.ts @@ -626,8 +626,6 @@ export default class { return this.GetLnurlPayInfoFromUser(linkedUser.user.user_id, linkedUser.application, { metadata: defaultLnAddressMetadata(this.settings.lnurlMetaText, addressName) }) } - async OpenChannel(userId: string, req: Types.OpenChannelRequest): Promise { throw new Error("WIP") } - mapOperations(operations: UserOperationInfo[], type: Types.UserOperationType, inbound: boolean): Types.UserOperations { if (operations.length === 0) { return { diff --git a/src/services/serverMethods/index.ts b/src/services/serverMethods/index.ts index 0e2465aa..6fec8c16 100644 --- a/src/services/serverMethods/index.ts +++ b/src/services/serverMethods/index.ts @@ -16,6 +16,32 @@ export default (mainHandler: Main): Types.ServerMethods => { ListChannels: async ({ ctx }) => { return mainHandler.adminManager.ListChannels() }, + AddPeer: async ({ ctx, req }) => { + const err = Types.AddPeerRequestValidate(req, { + pubkey_CustomCheck: pubkey => pubkey !== '', + host_CustomCheck: host => host !== '', + port_CustomCheck: port => port > 0 + }) + if (err != null) throw new Error(err.message) + return mainHandler.adminManager.AddPeer(req) + }, + OpenChannel: async ({ ctx, req }) => { + const err = Types.OpenChannelRequestValidate(req, { + node_pubkey_CustomCheck: pubkey => pubkey !== '', + local_funding_amount_CustomCheck: amt => amt > 0, + sat_per_v_byte_CustomCheck: spv => spv > 0, + }) + if (err != null) throw new Error(err.message) + return mainHandler.adminManager.OpenChannel(req) + }, + CloseChannel: async ({ ctx, req }) => { + const err = Types.CloseChannelRequestValidate(req, { + funding_txid_CustomCheck: chanId => chanId !== '', + sat_per_v_byte_CustomCheck: spv => spv > 0 + }) + if (err != null) throw new Error(err.message) + return mainHandler.adminManager.CloseChannel(req) + }, EncryptionExchange: async () => { }, Health: async () => { await mainHandler.lnd.Health() }, LndGetInfo: async ({ ctx }) => { @@ -54,15 +80,6 @@ export default (mainHandler: Main): Types.ServerMethods => { if (err != null) throw new Error(err.message) return mainHandler.paymentManager.GetPaymentState(ctx.user_id, req) }, - OpenChannel: async ({ ctx, req }) => { - const err = Types.OpenChannelRequestValidate(req, { - fundingAmount_CustomCheck: amt => amt > 0, - pushAmount_CustomCheck: amt => amt > 0, - destination_CustomCheck: dest => dest !== "" - }) - if (err != null) throw new Error(err.message) - return mainHandler.paymentManager.OpenChannel(ctx.user_id, req) - }, NewAddress: ({ ctx, req }) => mainHandler.paymentManager.NewAddress(ctx, req), PayAddress: async ({ ctx, req }) => { const err = Types.PayAddressRequestValidate(req, { diff --git a/src/tests/adminChannels.spec.ts b/src/tests/adminChannels.spec.ts new file mode 100644 index 00000000..5faf1bb9 --- /dev/null +++ b/src/tests/adminChannels.spec.ts @@ -0,0 +1,20 @@ +import { defaultInvoiceExpiry } from '../services/storage/paymentStorage.js' +import { runSanityCheck, safelySetUserBalance, TestBase } from './testBase.js' +export const ignore = false +export const dev = false + +export default async (T: TestBase) => { + await safelySetUserBalance(T, T.user1, 2000) + await openAdminChannel(T) + await runSanityCheck(T) +} + +const openAdminChannel = async (T: TestBase) => { + T.d("starting openAdminChannel") + const otherPub = (await T.externalAccessToOtherLnd.GetInfo()).identityPubkey + const openChannel = await T.main.adminManager.OpenChannel({ + node_pubkey: otherPub, local_funding_amount: 100000, sat_per_v_byte: 1 + }) + console.log(openChannel) + T.d("opened admin channel") +} \ No newline at end of file