Browse Source

Merge pull request #109 from stakwork/boosts

Boosts
dependabot/npm_and_yarn/ini-1.3.7
Evan Feenstra 4 years ago
committed by GitHub
parent
commit
758b406e08
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 152
      app.ts
  2. 104
      dist/app.js
  3. 2
      dist/app.js.map
  4. 136
      dist/src/auth.js
  5. 1
      dist/src/auth.js.map
  6. 5
      dist/src/constants.js
  7. 2
      dist/src/constants.js.map
  8. 2
      dist/src/controllers/bots.js
  9. 2
      dist/src/controllers/bots.js.map
  10. 20
      dist/src/controllers/chatTribes.js
  11. 2
      dist/src/controllers/chatTribes.js.map
  12. 13
      dist/src/controllers/chats.js
  13. 2
      dist/src/controllers/chats.js.map
  14. 1
      dist/src/controllers/index.js
  15. 2
      dist/src/controllers/index.js.map
  16. 4
      dist/src/controllers/invoices.js
  17. 2
      dist/src/controllers/invoices.js.map
  18. 24
      dist/src/controllers/media.js
  19. 2
      dist/src/controllers/media.js.map
  20. 84
      dist/src/controllers/messages.js
  21. 2
      dist/src/controllers/messages.js.map
  22. 37
      dist/src/controllers/payment.js
  23. 2
      dist/src/controllers/payment.js.map
  24. 19
      dist/src/grpc/index.js
  25. 2
      dist/src/grpc/index.js.map
  26. 3
      dist/src/helpers.js
  27. 2
      dist/src/helpers.js.map
  28. 4
      dist/src/models/ts/message.js
  29. 2
      dist/src/models/ts/message.js.map
  30. 2
      dist/src/network/modify.js
  31. 2
      dist/src/network/modify.js.map
  32. 56
      dist/src/network/receive.js
  33. 2
      dist/src/network/receive.js.map
  34. 5
      dist/src/network/send.js
  35. 2
      dist/src/network/send.js.map
  36. 23
      dist/src/utils/lightning.js
  37. 2
      dist/src/utils/lightning.js.map
  38. 22
      dist/src/utils/macaroon.js
  39. 1
      dist/src/utils/macaroon.js.map
  40. 1
      dist/src/utils/nodeinfo.js
  41. 2
      dist/src/utils/nodeinfo.js.map
  42. 11
      dist/src/utils/setup.js
  43. 2
      dist/src/utils/setup.js.map
  44. 2
      dist/src/utils/signer.js
  45. 2
      dist/src/utils/signer.js.map
  46. 55
      dist/src/utils/unlock.js
  47. 1
      dist/src/utils/unlock.js.map
  48. 5
      package-lock.json
  49. 1
      package.json
  50. 661
      proto/router.proto
  51. 623
      proto/rpc.proto
  52. 0
      proto/signer.proto
  53. 238
      proto/walletunlocker.proto
  54. 132
      src/auth.ts
  55. 5
      src/constants.ts
  56. 3
      src/controllers/bots.ts
  57. 20
      src/controllers/chatTribes.ts
  58. 13
      src/controllers/chats.ts
  59. 1
      src/controllers/index.ts
  60. 4
      src/controllers/invoices.ts
  61. 24
      src/controllers/media.ts
  62. 88
      src/controllers/messages.ts
  63. 37
      src/controllers/payment.ts
  64. 17
      src/grpc/index.ts
  65. 3
      src/helpers.ts
  66. 3
      src/models/ts/message.ts
  67. 2
      src/network/modify.ts
  68. 58
      src/network/receive.ts
  69. 7
      src/network/send.ts
  70. 25
      src/utils/lightning.ts
  71. 20
      src/utils/macaroon.ts
  72. 2
      src/utils/nodeinfo.ts
  73. 13
      src/utils/setup.ts
  74. 2
      src/utils/signer.ts
  75. 46
      src/utils/unlock.ts

152
app.ts

@ -3,17 +3,16 @@ import * as bodyParser from 'body-parser'
import * as helmet from 'helmet'
import * as cookieParser from 'cookie-parser'
import * as cors from 'cors'
import * as crypto from 'crypto'
import * as path from 'path'
import {models} from './src/models'
import logger from './src/utils/logger'
import {pingHubInterval, checkInvitesHubInterval} from './src/hub'
import {setupDatabase, setupDone} from './src/utils/setup'
import * as controllers from './src/controllers'
import * as socket from './src/utils/socket'
import * as network from './src/network'
import {authModule, unlocker} from './src/auth'
import * as grpc from './src/grpc'
let server: any = null
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, 'config/app.json'))[env];
const port = process.env.PORT || config.node_http_port || 3001
@ -24,115 +23,74 @@ console.log('=> config.node_http_port:',config.node_http_port)
process.env.GRPC_SSL_CIPHER_SUITES = 'HIGH+ECDSA'
var i = 0
// START SETUP!
async function start(){
await setupDatabase()
connectToLND()
pingHubInterval(15000)
mainSetup()
if (config.hub_api_url) {
pingHubInterval(15000)
}
}
start()
async function connectToLND(){
i++
console.log(`=> [lnd] connecting... attempt #${i}`)
try {
await network.initGrpcSubscriptions() // LND
await mainSetup() // DB + express
await network.initTribesSubscriptions() // MQTT
} catch(e) {
if(e.details) {
console.log(`=> [lnd] error details: ${e.details}`)
} else {
console.log(`=> [lnd] error: ${e.message}`)
}
setTimeout(async()=>{ // retry each 2 secs
await connectToLND()
},2000)
}
async function mainSetup(){
await setupApp() // setup routes
grpc.reconnectToLND(Math.random(), function(){
console.log(">> FINISH SETUP")
finishSetup()
}) // recursive
}
async function mainSetup(){
async function finishSetup(){
await network.initTribesSubscriptions()
if (config.hub_api_url) {
// pingHubInterval(15000)
checkInvitesHubInterval(5000)
}
await setupApp()
setupDone()
}
async function setupApp(){
const app = express();
const server = require("http").Server(app);
app.use(helmet());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(logger)
app.use(cors({
allowedHeaders:['X-Requested-With','Content-Type','Accept','x-user-token']
}))
app.use(cookieParser())
if (env != 'development') {
app.use(authModule);
}
app.use('/static', express.static('public'));
app.get('/app', (req, res) => res.send('INDEX'))
server.listen(port, (err) => {
if (err) throw err;
/* eslint-disable no-console */
console.log(`Node listening on ${port}.`);
});
controllers.set(app);
socket.connect(server)
}
async function authModule(req, res, next) {
if (
req.path == '/app' ||
req.path == '/' ||
req.path == '/info' ||
req.path == '/action' ||
req.path == '/contacts/tokens' ||
req.path == '/latest' ||
req.path.startsWith('/static') ||
req.path == '/contacts/set_dev'
) {
next()
return
}
if (process.env.HOSTING_PROVIDER==='true'){
// const domain = process.env.INVITE_SERVER
const host = req.headers.origin
console.log('=> host:', host)
const referer = req.headers.referer
console.log('=> referer:', referer)
if (req.path === '/invoices') {
next()
return
function setupApp(){
return new Promise(resolve=>{
const app = express();
const server = require("http").Server(app);
app.use(helmet());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(logger)
app.use(cors({
allowedHeaders:['X-Requested-With','Content-Type','Accept','x-user-token']
}))
app.use(cookieParser())
if (env != 'development') {
app.use(authModule);
}
}
const token = req.headers['x-user-token'] || req.cookies['x-user-token']
if (token == null) {
res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
res.end('Invalid credentials');
} else {
const user = await models.Contact.findOne({ where: { isOwner: true }})
const hashedToken = crypto.createHash('sha256').update(token).digest('base64');
if (user.authToken == null || user.authToken != hashedToken) {
res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
res.end('Invalid credentials');
app.use('/static', express.static('public'));
app.get('/app', (req, res) => res.send('INDEX'))
server.listen(port, (err) => {
if (err) throw err;
/* eslint-disable no-console */
console.log(`Node listening on ${port}.`);
});
// start all routes!
if(!config.unlock) {
controllers.set(app);
socket.connect(server)
resolve()
} else {
next();
app.post('/unlock', async function(req,res){
const ok = await unlocker(req,res)
if(ok) {
console.log('=> relay unlocked!')
controllers.set(app);
socket.connect(server)
resolve()
}
})
}
}
}
export default server
})
}

104
dist/app.js

@ -14,16 +14,15 @@ const bodyParser = require("body-parser");
const helmet = require("helmet");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const crypto = require("crypto");
const path = require("path");
const models_1 = require("./src/models");
const logger_1 = require("./src/utils/logger");
const hub_1 = require("./src/hub");
const setup_1 = require("./src/utils/setup");
const controllers = require("./src/controllers");
const socket = require("./src/utils/socket");
const network = require("./src/network");
let server = null;
const auth_1 = require("./src/auth");
const grpc = require("./src/grpc");
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, 'config/app.json'))[env];
const port = process.env.PORT || config.node_http_port || 3001;
@ -31,50 +30,37 @@ console.log("=> env:", env);
console.log('=> process.env.PORT:', process.env.PORT);
console.log('=> config.node_http_port:', config.node_http_port);
process.env.GRPC_SSL_CIPHER_SUITES = 'HIGH+ECDSA';
var i = 0;
// START SETUP!
function start() {
return __awaiter(this, void 0, void 0, function* () {
yield setup_1.setupDatabase();
connectToLND();
hub_1.pingHubInterval(15000);
mainSetup();
if (config.hub_api_url) {
hub_1.pingHubInterval(15000);
}
});
}
start();
function connectToLND() {
function mainSetup() {
return __awaiter(this, void 0, void 0, function* () {
i++;
console.log(`=> [lnd] connecting... attempt #${i}`);
try {
yield network.initGrpcSubscriptions(); // LND
yield mainSetup(); // DB + express
yield network.initTribesSubscriptions(); // MQTT
}
catch (e) {
if (e.details) {
console.log(`=> [lnd] error details: ${e.details}`);
}
else {
console.log(`=> [lnd] error: ${e.message}`);
}
setTimeout(() => __awaiter(this, void 0, void 0, function* () {
yield connectToLND();
}), 2000);
}
yield setupApp(); // setup routes
grpc.reconnectToLND(Math.random(), function () {
console.log(">> FINISH SETUP");
finishSetup();
}); // recursive
});
}
function mainSetup() {
function finishSetup() {
return __awaiter(this, void 0, void 0, function* () {
yield network.initTribesSubscriptions();
if (config.hub_api_url) {
// pingHubInterval(15000)
hub_1.checkInvitesHubInterval(5000);
}
yield setupApp();
setup_1.setupDone();
});
}
function setupApp() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => {
const app = express();
const server = require("http").Server(app);
app.use(helmet());
@ -86,7 +72,7 @@ function setupApp() {
}));
app.use(cookieParser());
if (env != 'development') {
app.use(authModule);
app.use(auth_1.authModule);
}
app.use('/static', express.static('public'));
app.get('/app', (req, res) => res.send('INDEX'));
@ -96,51 +82,25 @@ function setupApp() {
/* eslint-disable no-console */
console.log(`Node listening on ${port}.`);
});
controllers.set(app);
socket.connect(server);
});
}
function authModule(req, res, next) {
return __awaiter(this, void 0, void 0, function* () {
if (req.path == '/app' ||
req.path == '/' ||
req.path == '/info' ||
req.path == '/action' ||
req.path == '/contacts/tokens' ||
req.path == '/latest' ||
req.path.startsWith('/static') ||
req.path == '/contacts/set_dev') {
next();
return;
}
if (process.env.HOSTING_PROVIDER === 'true') {
// const domain = process.env.INVITE_SERVER
const host = req.headers.origin;
console.log('=> host:', host);
const referer = req.headers.referer;
console.log('=> referer:', referer);
if (req.path === '/invoices') {
next();
return;
}
}
const token = req.headers['x-user-token'] || req.cookies['x-user-token'];
if (token == null) {
res.writeHead(401, 'Access invalid for user', { 'Content-Type': 'text/plain' });
res.end('Invalid credentials');
// start all routes!
if (!config.unlock) {
controllers.set(app);
socket.connect(server);
resolve();
}
else {
const user = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
const hashedToken = crypto.createHash('sha256').update(token).digest('base64');
if (user.authToken == null || user.authToken != hashedToken) {
res.writeHead(401, 'Access invalid for user', { 'Content-Type': 'text/plain' });
res.end('Invalid credentials');
}
else {
next();
}
app.post('/unlock', function (req, res) {
return __awaiter(this, void 0, void 0, function* () {
const ok = yield auth_1.unlocker(req, res);
if (ok) {
console.log('=> relay unlocked!');
controllers.set(app);
socket.connect(server);
resolve();
}
});
});
}
});
}
exports.default = server;
//# sourceMappingURL=app.js.map

2
dist/app.js.map

@ -1 +1 @@
{"version":3,"file":"app.js","sourceRoot":"","sources":["../app.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,mCAAkC;AAClC,0CAAyC;AACzC,iCAAgC;AAChC,8CAA6C;AAC7C,6BAA4B;AAC5B,iCAAgC;AAChC,6BAA4B;AAC5B,yCAAmC;AACnC,+CAAuC;AACvC,mCAAkE;AAClE,6CAA0D;AAC1D,iDAAgD;AAChD,6CAA4C;AAC5C,yCAAwC;AAExC,IAAI,MAAM,GAAQ,IAAI,CAAA;AACtB,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,aAAa,CAAC;AAClD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AACrE,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,MAAM,CAAC,cAAc,IAAI,IAAI,CAAA;AAE9D,OAAO,CAAC,GAAG,CAAC,SAAS,EAAC,GAAG,CAAC,CAAA;AAC1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AM,CAAC,CAAA;wBACtB,OAAO,EAAE,CAAA;qBACT;gBACF,CAAC;aAAA,CAAC,CAAA;SACF;IAEF,CAAC,CAAC,CAAA;AACH,CAAC"}

136
dist/src/auth.js

@ -0,0 +1,136 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const crypto = require("crypto");
const models_1 = require("./models");
const cryptoJS = require("crypto-js");
const path = require("path");
const res_1 = require("./utils/res");
const macaroon_1 = require("./utils/macaroon");
const fs = require('fs');
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../config/app.json'))[env];
/*
"unlock": true,
"encrypted_macaroon_path": "/relay/.lnd/admin.macaroon.enc"
*/
function unlocker(req, res) {
return __awaiter(this, void 0, void 0, function* () {
const { password } = req.body;
if (!password) {
res_1.failure(res, 'no password');
return false;
}
const encMacPath = config.encrypted_macaroon_path;
if (!encMacPath) {
res_1.failure(res, 'no macaroon path');
return false;
}
let hexMac;
try {
var encMac = fs.readFileSync(config.encrypted_macaroon_path, "utf8");
if (!encMac) {
res_1.failure(res, 'no macaroon');
return false;
}
console.log("PWD", password, typeof password);
console.log("ENCMAC", encMac, typeof encMac);
const decMac = decryptMacaroon(password, encMac);
if (!decMac) {
res_1.failure(res, 'failed to decrypt macaroon');
return false;
}
hexMac = base64ToHex(decMac);
}
catch (e) {
res_1.failure(res, e);
return false;
}
if (hexMac) {
macaroon_1.setInMemoryMacaroon(hexMac);
res_1.success(res, 'success!');
return true;
}
else {
res_1.failure(res, 'failed to set macaroon in memory');
return false;
}
});
}
exports.unlocker = unlocker;
function authModule(req, res, next) {
return __awaiter(this, void 0, void 0, function* () {
if (req.path == '/app' ||
req.path == '/' ||
req.path == '/unlock' ||
req.path == '/info' ||
req.path == '/action' ||
req.path == '/contacts/tokens' ||
req.path == '/latest' ||
req.path.startsWith('/static') ||
req.path == '/contacts/set_dev') {
next();
return;
}
if (process.env.HOSTING_PROVIDER === 'true') {
// const domain = process.env.INVITE_SERVER
const host = req.headers.origin;
console.log('=> host:', host);
const referer = req.headers.referer;
console.log('=> referer:', referer);
if (req.path === '/invoices') {
next();
return;
}
}
const token = req.headers['x-user-token'] || req.cookies['x-user-token'];
if (token == null) {
res.writeHead(401, 'Access invalid for user', { 'Content-Type': 'text/plain' });
res.end('Invalid credentials');
}
else {
const user = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
const hashedToken = crypto.createHash('sha256').update(token).digest('base64');
if (user.authToken == null || user.authToken != hashedToken) {
res.writeHead(401, 'Access invalid for user', { 'Content-Type': 'text/plain' });
res.end('Invalid credentials');
}
else {
next();
}
}
});
}
exports.authModule = authModule;
function decryptMacaroon(password, macaroon) {
try {
const decrypted = cryptoJS.AES.decrypt(macaroon || '', password).toString(cryptoJS.enc.Base64);
const decryptResult = atob(decrypted);
return decryptResult;
}
catch (e) {
console.error('cipher mismatch, macaroon decryption failed');
console.error(e);
return '';
}
}
function base64ToHex(str) {
const raw = atob(str);
let result = '';
for (let i = 0; i < raw.length; i++) {
const hex = raw.charCodeAt(i).toString(16);
result += (hex.length === 2 ? hex : '0' + hex);
}
return result.toUpperCase();
}
exports.base64ToHex = base64ToHex;
const atob = a => Buffer.from(a, 'base64').toString('binary');
//# sourceMappingURL=auth.js.map

1
dist/src/auth.js.map

@ -0,0 +1 @@
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/auth.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,iCAAgC;AAChC,qCAAiC;AACjC,sCAAqC;AACrC,6BAA4B;AAC5B,qCAA8C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IAAC,OAAO,CAAC,EAAE;QACV,OAAO,CAAC,KAAK,CAAC,6CAA6C,CAAC,CAAA;QAC5D,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QAChB,OAAO,EAAE,CAAA;KACV;AACH,CAAC;AAED,SAAgB,WAAW,CAAE,GAAG;IAC9B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAA;IACrB,IAAI,MAAM,GAAG,EAAE,CAAA;IACf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,MAAM,GAAG,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;QAC1C,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,CAAC,CAAA;KAC/C;IACD,OAAO,MAAM,CAAC,WAAW,EAAE,CAAA;AAC7B,CAAC;AARD,kCAQC;AAED,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA"}

5
dist/src/constants.js

@ -58,6 +58,11 @@ const constants = {
"heartbeat": 26,
"heartbeat_confirmation": 27,
"keysend": 28,
"boost": 29,
},
network_types: {
"lightning": 0,
"mqtt": 1,
},
payment_errors: {
"timeout": "Timed Out",

2
dist/src/constants.js.map

@ -1 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";;AAAA,MAAM,SAAS,GAAG;IAChB,cAAc,EAAE,CAAC;IACjB,eAAe,EAAE;QACf,SAAS,EAAE,CAAC;QACZ,OAAO,EAAE,CAAC;QACV,WAAW,EAAE,CAAC;QACd,aAAa,EAAE,CAAC;QAChB,UAAU,EA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BAA2B;QACxD,SAAS,EAAE,SAAS;KACrB;IACD,UAAU,EAAE;QACV,cAAc,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;QACV,OAAO,EAAE,CAAC;KACX;IACD,SAAS,EAAE;QACT,SAAS,EAAE,CAAC;QACZ,OAAO,EAAE,CAAC;QACV,QAAQ,EAAE,CAAC;KACZ;IACD,UAAU,EAAE;QACV,GAAG,EAAE,CAAC;QACN,OAAO,EAAE,CAAC;QACV,OAAO,EAAE,CAAC;QACV,KAAK,EAAE,CAAC;QACR,QAAQ,EAAE,CAAC;QACX,QAAQ,EAAE,CAAC;KACZ;CACF,CAAA;AAED,kBAAe,SAAS,CAAA"}
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";;AAAA,MAAM,SAAS,GAAG;IAChB,cAAc,EAAE,CAAC;IACjB,eAAe,EAAE;QACf,SAAS,EAAE,CAAC;QACZ,OAAO,EAAE,CAAC;QACV,WAAW,EAAE,CAAC;QACd,aAAa,EAAE,CAAC;QAChB,UAAU,EAAE,CAAC;QACb,SAAS,EAAE,CAAC;QACZ,iBAAiB,EAAE,CAAC;KACrB;IACD,gBAAgB,EAAE;QAChB,SAAS,EAAE,CAAC;QACZ,WAAW,EAAE,CAAC;KACf;IACD,QAAQ,EAAE;QACR,SAAS,EAAE,CAAC;QACZ,WAAW,EAAE,CAAC;QACd,WAAW,EAAE,CAAC;QACd,UAAU,EAAE,CAAC;QACb,QAAQ,EAAE,CAAC;QACX,SAAS,EAAE,CAAC;KACb;IACD,aAAa,EAAE;QACb,UAAU,EAAE,CAAC;QACb,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;KACd;IACD,aAAa,EAAE;QACb,SAAS,EAAE,CAAC;QACZ,cAAc,EAAE,CAAC;QACjB,SAAS,EAAE,CAAC;QACZ,SAAS,EAAE,CAAC;QACZ,cAAc,EAAE,CAAC;QACjB,gBAAgB,EAAE,CAAC;QACnB,YAAY,EAAE,CAA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dat.bot_name;
const sender_alias = dat.sender.alias;
const date_string = dat.message.date;
const network_type = dat.network_type || 0;
if (!chat_uuid)
return console.log('=> receiveBotRes Error no chat_uuid');
const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } });
@ -349,6 +350,7 @@ function receiveBotRes(payload) {
createdAt: date,
updatedAt: date,
senderAlias: sender_alias || 'Bot',
network_type
};
const message = yield models_1.models.Message.create(msg);
socket.sendJson({

2
dist/src/controllers/bots.js.map

File diff suppressed because one or more lines are too long

20
dist/src/controllers/chatTribes.js

@ -119,7 +119,7 @@ exports.joinTribe = joinTribe;
function receiveMemberRequest(payload) {
return __awaiter(this, void 0, void 0, function* () {
console.log('=> receiveMemberRequest');
const { sender_pub_key, sender_alias, chat_uuid, chat_members, chat_type, isTribeOwner } = yield helpers.parseReceiveParams(payload);
const { sender_pub_key, sender_alias, chat_uuid, chat_members, chat_type, isTribeOwner, network_type } = yield helpers.parseReceiveParams(payload);
const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } });
if (!chat)
return console.log('no chat');
@ -173,7 +173,8 @@ function receiveMemberRequest(payload) {
sender: (theSender && theSender.id) || 0,
messageContent: '', remoteMessageContent: '',
status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
};
if (isTribe) {
msg.senderAlias = sender_alias;
@ -314,7 +315,7 @@ exports.approveOrRejectMember = approveOrRejectMember;
function receiveMemberApprove(payload) {
return __awaiter(this, void 0, void 0, function* () {
console.log('=> receiveMemberApprove');
const { owner, chat, chat_name, sender } = yield helpers.parseReceiveParams(payload);
const { owner, chat, chat_name, sender, network_type } = yield helpers.parseReceiveParams(payload);
if (!chat)
return console.log('no chat');
yield chat.update({ status: constants_1.default.chat_statuses.approved });
@ -326,7 +327,8 @@ function receiveMemberApprove(payload) {
sender: (sender && sender.id) || 0,
messageContent: '', remoteMessageContent: '',
status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
};
const message = yield models_1.models.Message.create(msg);
socket.sendJson({
@ -358,7 +360,7 @@ exports.receiveMemberApprove = receiveMemberApprove;
function receiveMemberReject(payload) {
return __awaiter(this, void 0, void 0, function* () {
console.log('=> receiveMemberReject');
const { chat, sender, chat_name } = yield helpers.parseReceiveParams(payload);
const { chat, sender, chat_name, network_type } = yield helpers.parseReceiveParams(payload);
if (!chat)
return console.log('no chat');
yield chat.update({ status: constants_1.default.chat_statuses.rejected });
@ -371,7 +373,8 @@ function receiveMemberReject(payload) {
sender: (sender && sender.id) || 0,
messageContent: '', remoteMessageContent: '',
status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
};
const message = yield models_1.models.Message.create(msg);
socket.sendJson({
@ -388,7 +391,7 @@ exports.receiveMemberReject = receiveMemberReject;
function receiveTribeDelete(payload) {
return __awaiter(this, void 0, void 0, function* () {
console.log('=> receiveTribeDelete');
const { chat, sender } = yield helpers.parseReceiveParams(payload);
const { chat, sender, network_type } = yield helpers.parseReceiveParams(payload);
if (!chat)
return console.log('no chat');
// await chat.update({status: constants.chat_statuses.rejected})
@ -401,7 +404,8 @@ function receiveTribeDelete(payload) {
sender: (sender && sender.id) || 0,
messageContent: '', remoteMessageContent: '',
status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
};
const message = yield models_1.models.Message.create(msg);
socket.sendJson({

2
dist/src/controllers/chatTribes.js.map

File diff suppressed because one or more lines are too long

13
dist/src/controllers/chats.js

@ -79,7 +79,7 @@ exports.kickChatMember = kickChatMember;
function receiveGroupKick(payload) {
return __awaiter(this, void 0, void 0, function* () {
console.log('=> receiveGroupKick');
const { chat, sender, date_string } = yield helpers.parseReceiveParams(payload);
const { chat, sender, date_string, network_type } = yield helpers.parseReceiveParams(payload);
if (!chat)
return;
// const owner = await models.Contact.findOne({where:{isOwner:true}})
@ -104,6 +104,7 @@ function receiveGroupKick(payload) {
messageContent: '', remoteMessageContent: '',
status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date,
network_type
};
const message = yield models_1.models.Message.create(msg);
socket.sendJson({
@ -318,7 +319,7 @@ exports.deleteChat = (req, res) => __awaiter(void 0, void 0, void 0, function* (
function receiveGroupJoin(payload) {
return __awaiter(this, void 0, void 0, function* () {
console.log('=> receiveGroupJoin');
const { sender_pub_key, sender_alias, chat_uuid, chat_members, chat_type, isTribeOwner, date_string } = yield helpers.parseReceiveParams(payload);
const { sender_pub_key, sender_alias, chat_uuid, chat_members, chat_type, isTribeOwner, date_string, network_type } = yield helpers.parseReceiveParams(payload);
const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } });
if (!chat)
return;
@ -386,7 +387,8 @@ function receiveGroupJoin(payload) {
sender: (theSender && theSender.id) || 0,
messageContent: '', remoteMessageContent: '',
status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
};
if (isTribe) {
msg.senderAlias = sender_alias;
@ -407,7 +409,7 @@ exports.receiveGroupJoin = receiveGroupJoin;
function receiveGroupLeave(payload) {
return __awaiter(this, void 0, void 0, function* () {
console.log('=> receiveGroupLeave');
const { sender_pub_key, chat_uuid, chat_type, sender_alias, isTribeOwner, date_string } = yield helpers.parseReceiveParams(payload);
const { sender_pub_key, chat_uuid, chat_type, sender_alias, isTribeOwner, date_string, network_type } = yield helpers.parseReceiveParams(payload);
const chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } });
if (!chat)
return;
@ -446,7 +448,8 @@ function receiveGroupLeave(payload) {
sender: (sender && sender.id) || 0,
messageContent: '', remoteMessageContent: '',
status: constants_1.default.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
};
if (isTribe) {
msg.senderAlias = sender_alias;

2
dist/src/controllers/chats.js.map

File diff suppressed because one or more lines are too long

1
dist/src/controllers/index.js

@ -150,5 +150,6 @@ exports.ACTIONS = {
[msgtypes.bot_res]: bots.receiveBotRes,
[msgtypes.heartbeat]: confirmations.receiveHeartbeat,
[msgtypes.heartbeat_confirmation]: confirmations.receiveHeartbeatConfirmation,
[msgtypes.boost]: messages.receiveBoost,
};
//# sourceMappingURL=index.js.map

2
dist/src/controllers/index.js.map

File diff suppressed because one or more lines are too long

4
dist/src/controllers/invoices.js

@ -204,6 +204,7 @@ exports.receiveInvoice = (payload) => __awaiter(void 0, void 0, void 0, function
const total_spent = 1;
const dat = payload.content || payload;
const payment_request = dat.message.invoice;
const network_type = dat.network_type || 0;
var date = new Date();
date.setMilliseconds(0);
const { owner, sender, chat, msg_id, chat_type, sender_alias, msg_uuid } = yield helpers.parseReceiveParams(payload);
@ -226,7 +227,8 @@ exports.receiveInvoice = (payload) => __awaiter(void 0, void 0, void 0, function
date: new Date(invoiceDate),
status: constants_1.default.statuses.pending,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type: network_type,
};
const isTribe = chat_type === constants_1.default.chat_types.tribe;
if (isTribe) {

2
dist/src/controllers/invoices.js.map

File diff suppressed because one or more lines are too long

24
dist/src/controllers/media.js

@ -175,7 +175,8 @@ exports.purchase = (req, res) => __awaiter(void 0, void 0, void 0, function* ()
mediaToken: media_token,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type: constants_1.default.network_types.lightning
});
const msg = {
mediaToken: media_token, id: message.id, uuid: message.uuid,
@ -185,6 +186,7 @@ exports.purchase = (req, res) => __awaiter(void 0, void 0, void 0, function* ()
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [contact_id] }),
sender: owner,
type: constants_1.default.message_types.purchase,
realSatsContactId: contact_id,
message: msg,
amount: amount,
success: (data) => __awaiter(void 0, void 0, void 0, function* () {
@ -199,7 +201,7 @@ exports.receivePurchase = (payload) => __awaiter(void 0, void 0, void 0, functio
console.log('=> received purchase', { payload });
var date = new Date();
date.setMilliseconds(0);
const { owner, sender, chat, amount, mediaToken, msg_uuid, chat_type, skip_payment_processing, purchaser_id } = yield helpers.parseReceiveParams(payload);
const { owner, sender, chat, amount, mediaToken, msg_uuid, chat_type, skip_payment_processing, purchaser_id, network_type } = yield helpers.parseReceiveParams(payload);
if (!owner || !sender || !chat) {
return console.log('=> group chat not found!');
}
@ -212,7 +214,8 @@ exports.receivePurchase = (payload) => __awaiter(void 0, void 0, void 0, functio
mediaToken: mediaToken,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
});
socket.sendJson({
type: 'purchase',
@ -319,7 +322,7 @@ exports.receivePurchaseAccept = (payload) => __awaiter(void 0, void 0, void 0, f
console.log('=> receivePurchaseAccept');
var date = new Date();
date.setMilliseconds(0);
const { owner, sender, chat, mediaToken, mediaKey, mediaType, originalMuid } = yield helpers.parseReceiveParams(payload);
const { owner, sender, chat, mediaToken, mediaKey, mediaType, originalMuid, network_type } = yield helpers.parseReceiveParams(payload);
if (!owner || !sender || !chat) {
return console.log('=> no group chat!');
}
@ -349,7 +352,8 @@ exports.receivePurchaseAccept = (payload) => __awaiter(void 0, void 0, void 0, f
originalMuid: originalMuid || '',
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
});
socket.sendJson({
type: 'purchase_accept',
@ -360,7 +364,7 @@ exports.receivePurchaseDeny = (payload) => __awaiter(void 0, void 0, void 0, fun
console.log('=> receivePurchaseDeny');
var date = new Date();
date.setMilliseconds(0);
const { owner, sender, chat, amount, mediaToken } = yield helpers.parseReceiveParams(payload);
const { owner, sender, chat, amount, mediaToken, network_type } = yield helpers.parseReceiveParams(payload);
if (!owner || !sender || !chat) {
return console.log('=> no group chat!');
}
@ -375,7 +379,8 @@ exports.receivePurchaseDeny = (payload) => __awaiter(void 0, void 0, void 0, fun
mediaToken,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
});
socket.sendJson({
type: 'purchase_deny',
@ -386,7 +391,7 @@ exports.receiveAttachment = (payload) => __awaiter(void 0, void 0, void 0, funct
// console.log('received attachment', { payload })
var date = new Date();
date.setMilliseconds(0);
const { owner, sender, chat, mediaToken, mediaKey, mediaType, content, msg_id, chat_type, sender_alias, msg_uuid, reply_uuid } = yield helpers.parseReceiveParams(payload);
const { owner, sender, chat, mediaToken, mediaKey, mediaType, content, msg_id, chat_type, sender_alias, msg_uuid, reply_uuid, network_type } = yield helpers.parseReceiveParams(payload);
if (!owner || !sender || !chat) {
return console.log('=> no group chat!');
}
@ -397,7 +402,8 @@ exports.receiveAttachment = (payload) => __awaiter(void 0, void 0, void 0, funct
sender: sender.id,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
};
if (content)
msg.messageContent = content;

2
dist/src/controllers/media.js.map

File diff suppressed because one or more lines are too long

84
dist/src/controllers/messages.js

@ -139,7 +139,10 @@ exports.sendMessage = (req, res) => __awaiter(void 0, void 0, void 0, function*
// } catch(e) {
// return failure(res, e.message)
// }
const { contact_id, text, remote_text, chat_id, remote_text_map, amount, reply_uuid, } = req.body;
const { contact_id, text, remote_text, chat_id, remote_text_map, amount, reply_uuid, boost, } = req.body;
let msgtype = constants_1.default.message_types.message;
if (boost)
msgtype = constants_1.default.message_types.boost;
var date = new Date();
date.setMilliseconds(0);
const owner = yield models_1.models.Contact.findOne({ where: { isOwner: true } });
@ -148,11 +151,24 @@ exports.sendMessage = (req, res) => __awaiter(void 0, void 0, void 0, function*
owner_id: owner.id,
recipient_id: contact_id,
});
let realSatsContactId;
// IF BOOST NEED TO SEND ACTUAL SATS TO OG POSTER
const isTribe = chat.type === constants_1.default.chat_types.tribe;
if (reply_uuid && boost && amount) {
const ogMsg = yield models_1.models.Message.findOne({ where: {
uuid: reply_uuid,
} });
if (ogMsg && ogMsg.sender) {
realSatsContactId = ogMsg.sender;
}
}
const hasRealAmount = amount && amount > constants_1.default.min_sat_amount;
const remoteMessageContent = remote_text_map ? JSON.stringify(remote_text_map) : remote_text;
const uuid = short.generate();
const msg = {
chatId: chat.id,
uuid: short.generate(),
type: constants_1.default.message_types.message,
uuid: uuid,
type: msgtype,
sender: owner.id,
amount: amount || 0,
date: date,
@ -161,6 +177,9 @@ exports.sendMessage = (req, res) => __awaiter(void 0, void 0, void 0, function*
status: constants_1.default.statuses.pending,
createdAt: date,
updatedAt: date,
network_type: (!isTribe || hasRealAmount || realSatsContactId) ?
constants_1.default.network_types.lightning :
constants_1.default.network_types.mqtt
};
if (reply_uuid)
msg.replyUuid = reply_uuid;
@ -174,22 +193,25 @@ exports.sendMessage = (req, res) => __awaiter(void 0, void 0, void 0, function*
};
if (reply_uuid)
msgToSend.replyUuid = reply_uuid;
network.sendMessage({
const sendMessageParams = {
chat: chat,
sender: owner,
amount: amount || 0,
type: constants_1.default.message_types.message,
type: msgtype,
message: msgToSend,
});
};
if (realSatsContactId)
sendMessageParams.realSatsContactId = realSatsContactId;
// final send
network.sendMessage(sendMessageParams);
});
exports.receiveMessage = (payload) => __awaiter(void 0, void 0, void 0, function* () {
// console.log('received message', { payload })
const total_spent = 1;
const { owner, sender, chat, content, remote_content, msg_id, chat_type, sender_alias, msg_uuid, date_string, reply_uuid } = yield helpers.parseReceiveParams(payload);
const { owner, sender, chat, content, remote_content, msg_id, chat_type, sender_alias, msg_uuid, date_string, reply_uuid, amount, network_type } = yield helpers.parseReceiveParams(payload);
if (!owner || !sender || !chat) {
return console.log('=> no group chat!');
}
const text = content;
const text = content || '';
var date = new Date();
date.setMilliseconds(0);
if (date_string)
@ -198,13 +220,14 @@ exports.receiveMessage = (payload) => __awaiter(void 0, void 0, void 0, function
chatId: chat.id,
uuid: msg_uuid,
type: constants_1.default.message_types.message,
asciiEncodedTotal: total_spent,
sender: sender.id,
date: date,
amount: amount || 0,
messageContent: text,
createdAt: date,
updatedAt: date,
status: constants_1.default.statuses.received
status: constants_1.default.statuses.received,
network_type: network_type,
};
const isTribe = chat_type === constants_1.default.chat_types.tribe;
if (isTribe) {
@ -215,7 +238,6 @@ exports.receiveMessage = (payload) => __awaiter(void 0, void 0, void 0, function
if (reply_uuid)
msg.replyUuid = reply_uuid;
const message = yield models_1.models.Message.create(msg);
// console.log('saved message', message.dataValues)
socket.sendJson({
type: 'message',
response: jsonUtils.messageToJson(message, chat, sender)
@ -224,6 +246,44 @@ exports.receiveMessage = (payload) => __awaiter(void 0, void 0, void 0, function
const theChat = Object.assign(Object.assign({}, chat.dataValues), { contactIds: [sender.id] });
confirmations_1.sendConfirmation({ chat: theChat, sender: owner, msg_id });
});
exports.receiveBoost = (payload) => __awaiter(void 0, void 0, void 0, function* () {
const { owner, sender, chat, content, remote_content, chat_type, sender_alias, msg_uuid, date_string, reply_uuid, amount, network_type } = yield helpers.parseReceiveParams(payload);
console.log('received boost ' + amount + ' sats on network:', network_type);
if (!owner || !sender || !chat) {
return console.log('=> no group chat!');
}
const text = content;
var date = new Date();
date.setMilliseconds(0);
if (date_string)
date = new Date(date_string);
const msg = {
chatId: chat.id,
uuid: msg_uuid,
type: constants_1.default.message_types.boost,
sender: sender.id,
date: date,
amount: amount || 0,
messageContent: text,
createdAt: date,
updatedAt: date,
status: constants_1.default.statuses.received,
network_type
};
const isTribe = chat_type === constants_1.default.chat_types.tribe;
if (isTribe) {
msg.senderAlias = sender_alias;
if (remote_content)
msg.remoteMessageContent = remote_content;
}
if (reply_uuid)
msg.replyUuid = reply_uuid;
const message = yield models_1.models.Message.create(msg);
socket.sendJson({
type: 'boost',
response: jsonUtils.messageToJson(message, chat, sender)
});
});
exports.receiveDeleteMessage = (payload) => __awaiter(void 0, void 0, void 0, function* () {
console.log('=> received delete message');
const { owner, sender, chat, chat_type, msg_uuid } = yield helpers.parseReceiveParams(payload);

2
dist/src/controllers/messages.js.map

File diff suppressed because one or more lines are too long

37
dist/src/controllers/payment.js

@ -51,7 +51,8 @@ exports.sendPayment = (req, res) => __awaiter(void 0, void 0, void 0, function*
amountMsat: parseFloat(amount) * 1000,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type: constants_1.default.network_types.lightning,
};
if (text)
msg.messageContent = text;
@ -115,7 +116,7 @@ exports.receivePayment = (payload) => __awaiter(void 0, void 0, void 0, function
console.log('received payment', { payload });
var date = new Date();
date.setMilliseconds(0);
const { owner, sender, chat, amount, content, mediaType, mediaToken, chat_type, sender_alias, msg_uuid, reply_uuid } = yield helpers.parseReceiveParams(payload);
const { owner, sender, chat, amount, content, mediaType, mediaToken, chat_type, sender_alias, msg_uuid, reply_uuid, network_type } = yield helpers.parseReceiveParams(payload);
if (!owner || !sender || !chat) {
return console.log('=> no group chat!');
}
@ -128,7 +129,8 @@ exports.receivePayment = (payload) => __awaiter(void 0, void 0, void 0, function
amountMsat: parseFloat(amount) * 1000,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
};
if (content)
msg.messageContent = content;
@ -156,15 +158,26 @@ exports.listPayments = (req, res) => __awaiter(void 0, void 0, void 0, function*
try {
const msgs = yield models_1.models.Message.findAll({
where: {
type: { [sequelize_1.Op.or]: [
constants_1.default.message_types.message,
constants_1.default.message_types.payment,
constants_1.default.message_types.direct_payment,
constants_1.default.message_types.keysend,
] },
amount: {
[sequelize_1.Op.gt]: MIN_VAL // greater than
}
[sequelize_1.Op.or]: [
{
type: { [sequelize_1.Op.or]: [
constants_1.default.message_types.payment,
constants_1.default.message_types.direct_payment,
constants_1.default.message_types.keysend,
constants_1.default.message_types.purchase,
] }
},
{
type: { [sequelize_1.Op.or]: [
constants_1.default.message_types.message,
constants_1.default.message_types.boost,
] },
amount: {
[sequelize_1.Op.gt]: MIN_VAL // greater than
},
network_type: constants_1.default.network_types.lightning
}
],
},
order: [['createdAt', 'desc']],
limit,

2
dist/src/controllers/payment.js.map

File diff suppressed because one or more lines are too long

19
dist/src/grpc/index.js

@ -18,8 +18,10 @@ const lightning_1 = require("../utils/lightning");
const network = require("../network");
const moment = require("moment");
const constants_1 = require("../constants");
const unlock_1 = require("../utils/unlock");
const ERR_CODE_UNAVAILABLE = 14;
const ERR_CODE_STREAM_REMOVED = 2;
const ERR_CODE_UNIMPLEMENTED = 12; // locked
function subscribeInvoices(parseKeysendInvoice) {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
const lightning = yield lightning_1.loadLightning();
@ -98,7 +100,7 @@ function subscribeInvoices(parseKeysendInvoice) {
});
});
call.on('status', function (status) {
console.log("Status", status);
console.log("Status", status.code, status);
// The server is unavailable, trying to reconnect.
if (status.code == ERR_CODE_UNAVAILABLE || status.code == ERR_CODE_STREAM_REMOVED) {
i = 0;
@ -134,23 +136,30 @@ function subscribeInvoices(parseKeysendInvoice) {
exports.subscribeInvoices = subscribeInvoices;
var i = 0;
var ctx = 0;
function reconnectToLND(innerCtx) {
function reconnectToLND(innerCtx, callback) {
return __awaiter(this, void 0, void 0, function* () {
ctx = innerCtx;
i++;
console.log(`=> [lnd] reconnecting... attempt #${i}`);
const now = moment().format('YYYY-MM-DD HH:mm:ss').trim();
console.log(`=> ${now} [lnd] reconnecting... attempt #${i}`);
try {
yield network.initGrpcSubscriptions();
const now = moment().format('YYYY-MM-DD HH:mm:ss').trim();
console.log(`=> [lnd] reconnected! ${now}`);
console.log(`=> [lnd] connected! ${now}`);
if (callback)
callback();
}
catch (e) {
if (e.code === ERR_CODE_UNIMPLEMENTED) {
yield unlock_1.tryToUnlockLND();
}
setTimeout(() => __awaiter(this, void 0, void 0, function* () {
if (ctx === innerCtx) { // if another retry fires, then this will not run
yield reconnectToLND(innerCtx);
yield reconnectToLND(innerCtx, callback);
}
}), 2000);
}
});
}
exports.reconnectToLND = reconnectToLND;
//# sourceMappingURL=index.js.map

2
dist/src/grpc/index.js.map

File diff suppressed because one or more lines are too long

3
dist/src/helpers.js

@ -168,6 +168,7 @@ function parseReceiveParams(payload) {
const skip_payment_processing = dat.message.skipPaymentProcessing;
const reply_uuid = dat.message.replyUuid;
const purchaser_id = dat.message.purchaser;
const network_type = dat.network_type || 0;
const isTribeOwner = dat.isTribeOwner ? true : false;
const isConversation = !chat_type || (chat_type && chat_type == constants_1.default.chat_types.conversation);
let sender;
@ -188,7 +189,7 @@ function parseReceiveParams(payload) {
}
chat = yield models_1.models.Chat.findOne({ where: { uuid: chat_uuid } });
}
return { owner, sender, chat, sender_pub_key, sender_alias, isTribeOwner, chat_uuid, amount, content, mediaToken, mediaKey, mediaType, originalMuid, chat_type, msg_id, chat_members, chat_name, chat_host, chat_key, remote_content, msg_uuid, date_string, reply_uuid, skip_payment_processing, purchaser_id, sender_photo_url };
return { owner, sender, chat, sender_pub_key, sender_alias, isTribeOwner, chat_uuid, amount, content, mediaToken, mediaKey, mediaType, originalMuid, chat_type, msg_id, chat_members, chat_name, chat_host, chat_key, remote_content, msg_uuid, date_string, reply_uuid, skip_payment_processing, purchaser_id, sender_photo_url, network_type };
});
}
exports.parseReceiveParams = parseReceiveParams;

2
dist/src/helpers.js.map

File diff suppressed because one or more lines are too long

4
dist/src/models/ts/message.js

@ -129,6 +129,10 @@ __decorate([
sequelize_typescript_1.Column,
__metadata("design:type", String)
], Message.prototype, "replyUuid", void 0);
__decorate([
sequelize_typescript_1.Column(sequelize_typescript_1.DataType.INTEGER),
__metadata("design:type", Number)
], Message.prototype, "network_type", void 0);
Message = __decorate([
sequelize_typescript_1.Table({ tableName: 'sphinx_messages', underscored: true })
], Message);

2
dist/src/models/ts/message.js.map

@ -1 +1 @@
{"version":3,"file":"message.js","sourceRoot":"","sources":["../../../../src/models/ts/message.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,+DAAsE;AAGtE,IAAqB,OAAO,GAA5B,MAAqB,OAAQ,SAAQ,4BAAc;CA2FlD,CAAA;AAnFC;IANC,6BAAM,CAAC;QACN,IAAI,EAAE,+BAAQ,CAAC,MAAM;QACrB,UAAU,EAAE,IAAI;QAChB,MAAM,EAAE,IAAI;QACZ,aAAa,EAAE,IAAI;KACpB,CAAC;;mCACQ;AAGV;IADC,6BAAM;;qCACK;AAGZ;IADC,6BAAM,CAAC,+BAAQ,CAAC,MAAM,CAAC;;uCACV;AAGd;IADC,6BAAM,CAAC,+BAAQ,CAAC,MA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;+CACF;AAGtB;IADC,6BAAM;;yCACS;AAGhB;IADC,6BAAM;;0CACU;AAGjB;IADC,6BAAM;;2CACW;AAOlB;IALC,6BAAM,CAAC;QACN,IAAI,EAAE,+BAAQ,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK;QACnB,SAAS,EAAE,KAAK;KACjB,CAAC;;qCACW;AAGb;IADC,6BAAM;8BACI,IAAI;0CAAA;AAGf;IADC,6BAAM;8BACI,IAAI;0CAAA;AAGf;IADC,6BAAM;;4CACY;AAGnB;IADC,6BAAM;;6CACa;AAGpB;IADC,6BAAM;;0CACU;AAGjB;IADC,6BAAM,CAAC,+BAAQ,CAAC,OAAO,CAAC;;6CACL;AA7FD,OAAO;IAD3B,4BAAK,CAAC,EAAC,SAAS,EAAE,iBAAiB,EAAE,WAAW,EAAE,IAAI,EAAC,CAAC;GACpC,OAAO,CA8F3B;kBA9FoB,OAAO"}

2
dist/src/network/modify.js

@ -79,6 +79,7 @@ function purchaseFromOriginalSender(payload, chat, purchaser) {
sender: owner,
type: constants_1.default.message_types.purchase,
amount: amount,
realSatsContactId: mediaKey.sender,
message: {
mediaToken: mt,
skipPaymentProcessing: true,
@ -97,6 +98,7 @@ function purchaseFromOriginalSender(payload, chat, purchaser) {
chat: Object.assign(Object.assign({}, chat.dataValues), { contactIds: [ogmsg.sender] }),
sender: Object.assign(Object.assign(Object.assign({}, owner.dataValues), purchaser && purchaser.alias && { alias: purchaser.alias }), { role: constants_1.default.chat_roles.reader }),
type: constants_1.default.message_types.purchase,
realSatsContactId: ogmsg.sender,
message: msg,
amount: amount,
success: () => { },

2
dist/src/network/modify.js.map

File diff suppressed because one or more lines are too long

56
dist/src/network/receive.js

@ -33,13 +33,13 @@ in receiveDeleteMessage check the deleter is og sender?
const msgtypes = constants_1.default.message_types;
exports.typesToForward = [
msgtypes.message, msgtypes.group_join, msgtypes.group_leave,
msgtypes.attachment, msgtypes.delete,
msgtypes.attachment, msgtypes.delete, msgtypes.boost,
];
const typesToModify = [
msgtypes.attachment
];
const typesThatNeedPricePerMessage = [
msgtypes.message, msgtypes.attachment
msgtypes.message, msgtypes.attachment, msgtypes.boost
];
exports.typesToReplay = [
msgtypes.message,
@ -135,8 +135,23 @@ function onReceive(payload) {
doAction = true;
}
}
// forward boost sats to recipient
let realSatsContactId = null;
let amtToForward = 0;
if (payload.type === msgtypes.boost && payload.message.replyUuid) {
const ogMsg = yield models_1.models.Message.findOne({ where: {
uuid: payload.message.replyUuid,
} });
if (ogMsg && ogMsg.sender && ogMsg.sender !== 1) {
const theAmtToForward = payload.message.amount - (chat.pricePerMessage || 0) - (chat.escrowAmount || 0);
if (theAmtToForward > 0) {
realSatsContactId = ogMsg.sender;
amtToForward = theAmtToForward;
}
}
}
if (doAction)
forwardMessageToTribe(payload, senderContact);
forwardMessageToTribe(payload, senderContact, realSatsContactId, amtToForward);
else
console.log('=> insufficient payment for this action');
}
@ -170,7 +185,8 @@ function onReceive(payload) {
function doTheAction(data) {
return __awaiter(this, void 0, void 0, function* () {
let payload = data;
if (payload.isTribeOwner) {
if (payload.isTribeOwner) { // this is only for storing locally, my own messages as tribe owner
// actual encryption for tribe happens in personalizeMessage
const ogContent = data.message && data.message.content;
// const ogMediaKey = data.message && data.message.mediaKey
/* decrypt and re-encrypt with phone's pubkey for storage */
@ -190,7 +206,7 @@ function doTheAction(data) {
}
});
}
function forwardMessageToTribe(ogpayload, sender) {
function forwardMessageToTribe(ogpayload, sender, realSatsContactId, amtToForwardToRealSatsContactId) {
return __awaiter(this, void 0, void 0, function* () {
// console.log('forwardMessageToTribe')
const chat = yield models_1.models.Chat.findOne({ where: { uuid: ogpayload.chat.uuid } });
@ -211,8 +227,10 @@ function forwardMessageToTribe(ogpayload, sender) {
send_1.sendMessage({
type, message,
sender: Object.assign(Object.assign(Object.assign({}, owner.dataValues), payload.sender && payload.sender.alias && { alias: payload.sender.alias }), { role: constants_1.default.chat_roles.reader }),
amount: amtToForwardToRealSatsContactId || 0,
chat: chat,
skipPubKey: payload.sender.pub_key,
realSatsContactId,
success: () => { },
receive: () => { },
isForwarded: true,
@ -238,6 +256,7 @@ function initTribesSubscriptions() {
const msg = message.toString();
// check topic is signed by sender?
const payload = yield parseAndVerifyPayload(msg);
payload.network_type = constants_1.default.network_types.mqtt;
onReceive(payload);
}
catch (e) { }
@ -288,14 +307,21 @@ function parseAndVerifyPayload(data) {
}
});
}
function saveAnonymousKeysend(response, memo) {
function saveAnonymousKeysend(response, memo, sender_pubkey) {
return __awaiter(this, void 0, void 0, function* () {
let sender = 0;
if (sender_pubkey) {
const theSender = yield models_1.models.Contact.findOne({ where: { publicKey: sender_pubkey } });
if (theSender && theSender.id) {
sender = theSender.id;
}
}
let settleDate = parseInt(response['settle_date'] + '000');
const amount = response['amt_paid_sat'] || 0;
const msg = yield models_1.models.Message.create({
chatId: 0,
type: constants_1.default.message_types.keysend,
sender: 0,
sender,
amount,
amountMsat: response['amt_paid_msat'],
paymentHash: '',
@ -303,7 +329,8 @@ function saveAnonymousKeysend(response, memo) {
messageContent: memo || '',
status: constants_1.default.statuses.confirmed,
createdAt: new Date(settleDate),
updatedAt: new Date(settleDate)
updatedAt: new Date(settleDate),
network_type: constants_1.default.network_types.lightning
});
socket.sendJson({
type: 'keysend',
@ -319,26 +346,28 @@ function parseKeysendInvoice(i) {
const value = i && i.value && parseInt(i.value);
// "keysend" type is NOT encrypted
// and should be saved even if there is NO content
let isAnonymous = false;
let isKeysendType = false;
let memo = '';
let sender_pubkey;
if (data) {
try {
const payload = parsePayload(data);
if (payload && payload.type === constants_1.default.message_types.keysend) {
isAnonymous = true;
isKeysendType = true;
memo = payload.message && payload.message.content;
sender_pubkey = payload.sender && payload.sender.pub_key;
}
}
catch (e) { } // err could be a threaded TLV
}
else {
isAnonymous = true;
isKeysendType = true;
}
if (isAnonymous) {
if (isKeysendType) {
if (!memo) {
hub_1.sendNotification(-1, '', 'keysend', value || 0);
}
saveAnonymousKeysend(i, memo);
saveAnonymousKeysend(i, memo, sender_pubkey);
return;
}
let payload;
@ -358,6 +387,7 @@ function parseKeysendInvoice(i) {
if (value && dat && dat.message) {
dat.message.amount = value; // ADD IN TRUE VALUE
}
dat.network_type = constants_1.default.network_types.lightning;
onReceive(dat);
}
});

2
dist/src/network/receive.js.map

File diff suppressed because one or more lines are too long

5
dist/src/network/send.js

@ -20,7 +20,7 @@ const intercept = require("./intercept");
const constants_1 = require("../constants");
function sendMessage(params) {
return __awaiter(this, void 0, void 0, function* () {
const { type, chat, message, sender, amount, success, failure, skipPubKey, isForwarded } = params;
const { type, chat, message, sender, amount, success, failure, skipPubKey, isForwarded, realSatsContactId } = params;
if (!chat || !sender)
return;
const isTribe = chat.type === constants_1.default.chat_types.tribe;
@ -88,7 +88,8 @@ function sendMessage(params) {
console.log('-> sending to ', contact.id, destkey);
let mqttTopic = networkType === 'mqtt' ? `${destkey}/${chatUUID}` : '';
// sending a payment to one subscriber, buying a pic from OG poster
if (isTribeOwner && contactIds.length === 1 && amount && amount > constants_1.default.min_sat_amount && msg.type === constants_1.default.message_types.purchase) {
// or boost to og poster
if (isTribeOwner && amount && realSatsContactId === contactId) {
mqttTopic = ''; // FORCE KEYSEND!!!
}
const m = yield msg_1.personalizeMessage(msg, contact, isTribeOwner);

2
dist/src/network/send.js.map

File diff suppressed because one or more lines are too long

23
dist/src/utils/lightning.js

@ -17,6 +17,7 @@ const sha = require("js-sha256");
const crypto = require("crypto");
const path = require("path");
const constants_1 = require("../constants");
const macaroon_1 = require("./macaroon");
// var protoLoader = require('@grpc/proto-loader')
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../../config/app.json'))[env];
@ -29,8 +30,7 @@ var walletUnlocker = null;
const loadCredentials = () => {
var lndCert = fs.readFileSync(config.tls_location);
var sslCreds = grpc.credentials.createSsl(lndCert);
var m = fs.readFileSync(config.macaroon_location);
var macaroon = m.toString('hex');
var macaroon = macaroon_1.getMacaroon();
var metadata = new grpc.Metadata();
metadata.add('macaroon', macaroon);
var macaroonCreds = grpc.credentials.createFromMetadataGenerator((_args, callback) => {
@ -58,7 +58,7 @@ const loadLightning = () => {
else {
try {
var credentials = loadCredentials();
var lnrpcDescriptor = grpc.load("rpc.proto");
var lnrpcDescriptor = grpc.load("proto/rpc.proto");
var lnrpc = lnrpcDescriptor.lnrpc;
lightningClient = new lnrpc.Lightning(config.node_ip + ':' + config.lnd_port, credentials);
return lightningClient;
@ -76,7 +76,7 @@ const loadWalletUnlocker = () => {
else {
var credentials = loadCredentials();
try {
var lnrpcDescriptor = grpc.load("rpc.proto");
var lnrpcDescriptor = grpc.load("proto/walletunlocker.proto");
var lnrpc = lnrpcDescriptor.lnrpc;
walletUnlocker = new lnrpc.WalletUnlocker(config.node_ip + ':' + config.lnd_port, credentials);
return walletUnlocker;
@ -87,6 +87,21 @@ const loadWalletUnlocker = () => {
}
};
exports.loadWalletUnlocker = loadWalletUnlocker;
const unlockWallet = (pwd) => __awaiter(void 0, void 0, void 0, function* () {
return new Promise(function (resolve, reject) {
return __awaiter(this, void 0, void 0, function* () {
let wu = yield loadWalletUnlocker();
wu.unlockWallet({ wallet_password: ByteBuffer.fromUTF8(pwd) }, (err, response) => {
if (err) {
reject(err);
return;
}
resolve(response);
});
});
});
});
exports.unlockWallet = unlockWallet;
const getHeaders = (req) => {
return {
"X-User-Token": req.headers['x-user-token'],

2
dist/src/utils/lightning.js.map

File diff suppressed because one or more lines are too long

22
dist/src/utils/macaroon.js

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require("path");
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../../config/app.json'))[env];
let inMemoryMacaroon = ''; // hex encoded
function getMacaroon() {
if (config.unlock) {
return inMemoryMacaroon;
}
else {
const m = fs.readFileSync(config.macaroon_location);
return m.toString('hex');
}
}
exports.getMacaroon = getMacaroon;
function setInMemoryMacaroon(mac) {
inMemoryMacaroon = mac;
}
exports.setInMemoryMacaroon = setInMemoryMacaroon;
//# sourceMappingURL=macaroon.js.map

1
dist/src/utils/macaroon.js.map

@ -0,0 +1 @@
{"version":3,"file":"macaroon.js","sourceRoot":"","sources":["../../../src/utils/macaroon.ts"],"names":[],"mappings":";;AAAA,yBAAwB;AACxB,6BAA4B;AAE5B,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,aAAa,CAAC;AAClD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;AAE1E,IAAI,gBAAgB,GAAW,EAAE,CAAC,CAAC,cAAc;AAEjD,SAAgB,WAAW;IACzB,IAAG,MAAM,CAAC,MAAM,EAAE;QAChB,OAAO,gBAAgB,CAAA;KACxB;SAAM;QACL,MAAM,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAA;QACnD,OAAO,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;KAC1B;AACH,CAAC;AAPD,kCAOC;AAED,SAAgB,mBAAmB,CAAC,GAAU;IAC5C,gBAAgB,GAAG,GAAG,CAAA;AACxB,CAAC;AAFD,kDAEC"}

1
dist/src/utils/nodeinfo.js

@ -128,6 +128,7 @@ function isClean() {
return false;
});
}
exports.isClean = isClean;
function latestMessage() {
return __awaiter(this, void 0, void 0, function* () {
const lasts = yield models_1.models.Message.findAll({

2
dist/src/utils/nodeinfo.js.map

@ -1 +1 @@
{"version":3,"file":"nodeinfo.js","sourceRoot":"","sources":["../../../src/utils/nodeinfo.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,kDAAyD;AACzD,sCAAqC;AACrC,8CAA0D;AAC1D,sCAAgC;AAEhC,SAAS,QAAQ;IACf,OAAO,IAAI,OAAO,CAAC,CAAO,OAAO,EAAE,MAAM,EAAC,EAAE;QAE1C,IAAI,KAAK,CAAA;QACT,IAAI;YACF,KAAK,GAAG,MAAM,eAAM,CAAC,OAA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,IAAI,CAAA;QACtD,OAAO,KAAK,CAAA;IACd,CAAC;CAAA;AATD,0BASC;AAED,SAAe,aAAa;;QAC1B,MAAM,KAAK,GAAG,MAAM,eAAM,CAAC,OAAO,CAAC,OAAO,CAAC;YACzC,KAAK,EAAE,CAAC;YACR,KAAK,EAAE,CAAC,CAAE,WAAW,EAAE,MAAM,CAAE,CAAC;SACjC,CAAC,CAAA;QACF,MAAM,IAAI,GAAG,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,CAAA;QAC9B,IAAG,IAAI,EAAE;YACP,OAAO,IAAI,CAAC,SAAS,CAAA;SACtB;aAAM;YACL,OAAO,EAAE,CAAA;SACV;IACH,CAAC;CAAA"}

11
dist/src/utils/setup.js

@ -18,6 +18,7 @@ const password_1 = require("../utils/password");
const path = require("path");
const gitinfo_1 = require("../utils/gitinfo");
const fs = require("fs");
const nodeinfo_1 = require("./nodeinfo");
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../../config/app.json'))[env];
const USER_VERSION = 7;
@ -29,7 +30,7 @@ const setupDatabase = () => __awaiter(void 0, void 0, void 0, function* () {
console.log("=> [db] done syncing");
}
catch (e) {
console.log("db sync failed", e);
// console.log("db sync failed", e)
}
yield migrate();
setupOwnerContact();
@ -48,6 +49,7 @@ function setVersion() {
}
function migrate() {
return __awaiter(this, void 0, void 0, function* () {
addTableColumn('sphinx_messages', 'network_type', 'INTEGER');
addTableColumn('sphinx_chats', 'meta');
addTableColumn('sphinx_contacts', 'tip_amount', 'BIGINT');
addTableColumn('sphinx_contacts', 'last_active', 'DATETIME');
@ -226,9 +228,12 @@ function printQR() {
let theIP = public_ip;
// if(!theIP.includes(":")) theIP = public_ip+':3001'
const b64 = Buffer.from(`ip::${theIP}::${password_1.default || ''}`).toString('base64');
console.log('Scan this QR in Sphinx app:');
console.log(b64);
console.log('>>', b64);
connectionStringFile(b64);
const clean = yield nodeinfo_1.isClean();
if (!clean)
return; // skip it if already setup!
console.log('Scan this QR in Sphinx app:');
QRCode.toString(b64, { type: 'terminal' }, function (err, url) {
console.log(url);
});

2
dist/src/utils/setup.js.map

File diff suppressed because one or more lines are too long

2
dist/src/utils/signer.js

@ -24,7 +24,7 @@ exports.loadSigner = () => {
else {
try {
var credentials = lightning_1.loadCredentials();
var lnrpcDescriptor = grpc.load("signer.proto");
var lnrpcDescriptor = grpc.load("proto/signer.proto");
var signer = lnrpcDescriptor.signrpc;
signerClient = new signer.Signer(config.node_ip + ':' + config.lnd_port, credentials);
return signerClient;

2
dist/src/utils/signer.js.map

@ -1 +1 @@
{"version":3,"file":"signer.js","sourceRoot":"","sources":["../../../src/utils/signer.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,6BAA4B;AAC5B,2CAA2C;AAC3C,6BAA4B;AAC5B,yCAAwC;AAExC,kDAAkD;AAClD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,aAAa,CAAC;AAClD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAC,uBAAuB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;AAEzE,IAAI,YAAY,GAAS,IAAI,CAAC;AAEjB,QAAA,UAAU,GAAG,GAAG,EAAE;IAC7B,IAAI,YAAY,EAAE;QAChB,OAAO,YAAY,CAAA;KACpB;SAAM;QACL,IAAG;YACD,IAAI,WAAW,GAAG,2BAAe,EAAE,CAAA;YACnC,IAAI,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;YAChD,IAAI,MAAM,GAAQ,eAAe,CAAC,OAAO,CAAA;YACzC,YAAY,GAAG,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,GAAG,GAAG,GAAG,MAAM,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;YACtF,OAAO,YAAY,CAAA;SACpB;QAAC,OAAM,CAAC,EAAE;YACT,MAAM,CAAC,CAAA;SACR;KACF;AACH,CAAC,CAAA;AA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EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAG,EAAE;QAC5C,IAAI,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACjD,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KACd;IACF,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACtB,CAAC"}

55
dist/src/utils/unlock.js

@ -0,0 +1,55 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const lightning_1 = require("./lightning");
const fs = require('fs');
const readline = require('readline');
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../../config/app.json'))[env];
console.log(JSON.stringify(config, null, 2));
/*
"lnd_pwd_path": "/relay/.lnd/.lndpwd"
*/
function tryToUnlockLND() {
return __awaiter(this, void 0, void 0, function* () {
const p = config.lnd_pwd_path;
if (!p)
return;
console.log('==>', p);
var pwd = yield getFirstLine(config.lnd_pwd_path);
if (!pwd)
return;
console.log('==>', pwd, typeof pwd);
try {
yield lightning_1.unlockWallet(String(pwd));
}
catch (e) {
console.log('[unlock] Error:', e);
}
});
}
exports.tryToUnlockLND = tryToUnlockLND;
function getFirstLine(pathToFile) {
return __awaiter(this, void 0, void 0, function* () {
const readable = fs.createReadStream(pathToFile);
const reader = readline.createInterface({ input: readable });
const line = yield new Promise((resolve) => {
reader.on('line', (line) => {
reader.close();
resolve(line);
});
});
readable.close();
return line;
});
}
//# sourceMappingURL=unlock.js.map

1
dist/src/utils/unlock.js.map

@ -0,0 +1 @@
{"version":3,"file":"unlock.js","sourceRoot":"","sources":["../../../src/utils/unlock.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,6BAA4B;AAC5B,2CAA0C;AAC1C,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;AACxB,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAErC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,aAAa,CAAC;AAClD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;AAE1E,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAC,IAAI,EAAC,CAAC,CAAC,CAAC,CAAA;AAE1C;;EAEE;AAEF,SAAsB,cAAc;;QAChC,MAAM,CAAC,GAAG,MAAM,CAAC,YAAY,CAAA;QAC7B,IAAI,CAAC,CAAC;YAAE,OAAM;QAEd,OAAO,CAAC,GAAG,CAAC,KAAK,EAAC,CAAC,CAAC,CAAA;QAEpB,IAAI,GAAG,GAAG,MAAM,YAAY,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;QAClD,IAAG,CAAC,GAAG;YAAE,OAAM;QAEf,OAAO,CAAC,GAAG,CAAC,KAAK,EAAC,GAAG,EAAC,OAAO,GAAG,CAAC,CAAA;QAEjC,IAAI;YACA,MAAM,wBAAY,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAA;SAClC;QAAC,OAAM,CAAC,EAAE;YACP,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAC,CAAC,CAAC,CAAA;SACnC;IACL,CAAC;CAAA;AAhBD,wCAgBC;AAED,SAAe,YAAY,CAAC,UAAU;;QAClC,MAAM,QAAQ,GAAG,EAAE,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC;QACjD,MAAM,MAAM,GAAG,QAAQ,CAAC,eAAe,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC7D,MAAM,IAAI,GAAG,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YACvC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE;gBACvB,MAAM,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,IAAI,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;QACH,QAAQ,CAAC,KAAK,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC;IAChB,CAAC;CAAA"}

5
package-lock.json

@ -1600,6 +1600,11 @@
"randomfill": "^1.0.3"
}
},
"crypto-js": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.0.0.tgz",
"integrity": "sha512-bzHZN8Pn+gS7DQA6n+iUmBfl0hO5DJq++QP3U6uTucDtk/0iGpXd/Gg7CGR0p8tJhofJyaKoWBuJI4eAO00BBg=="
},
"crypto-random-string": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-1.0.0.tgz",

1
package.json

@ -34,6 +34,7 @@
"cron": "^1.7.2",
"cron-parser": "^2.13.0",
"crypto-browserify": "^3.12.0",
"crypto-js": "^4.0.0",
"dateformat": "^3.0.3",
"decamelize": "^3.1.1",
"express": "^4.16.4",

661
proto/router.proto

@ -0,0 +1,661 @@
syntax = "proto3";
import "rpc.proto";
package routerrpc;
option go_package = "github.com/lightningnetwork/lnd/lnrpc/routerrpc";
// Router is a service that offers advanced interaction with the router
// subsystem of the daemon.
service Router {
/*
SendPaymentV2 attempts to route a payment described by the passed
PaymentRequest to the final destination. The call returns a stream of
payment updates.
*/
rpc SendPaymentV2 (SendPaymentRequest) returns (stream lnrpc.Payment);
/*
TrackPaymentV2 returns an update stream for the payment identified by the
payment hash.
*/
rpc TrackPaymentV2 (TrackPaymentRequest) returns (stream lnrpc.Payment);
/*
EstimateRouteFee allows callers to obtain a lower bound w.r.t how much it
may cost to send an HTLC to the target end destination.
*/
rpc EstimateRouteFee (RouteFeeRequest) returns (RouteFeeResponse);
/*
Deprecated, use SendToRouteV2. SendToRoute attempts to make a payment via
the specified route. This method differs from SendPayment in that it
allows users to specify a full route manually. This can be used for
things like rebalancing, and atomic swaps. It differs from the newer
SendToRouteV2 in that it doesn't return the full HTLC information.
*/
rpc SendToRoute (SendToRouteRequest) returns (SendToRouteResponse) {
option deprecated = true;
}
/*
SendToRouteV2 attempts to make a payment via the specified route. This
method differs from SendPayment in that it allows users to specify a full
route manually. This can be used for things like rebalancing, and atomic
swaps.
*/
rpc SendToRouteV2 (SendToRouteRequest) returns (lnrpc.HTLCAttempt);
/*
ResetMissionControl clears all mission control state and starts with a clean
slate.
*/
rpc ResetMissionControl (ResetMissionControlRequest)
returns (ResetMissionControlResponse);
/*
QueryMissionControl exposes the internal mission control state to callers.
It is a development feature.
*/
rpc QueryMissionControl (QueryMissionControlRequest)
returns (QueryMissionControlResponse);
/*
QueryProbability returns the current success probability estimate for a
given node pair and amount.
*/
rpc QueryProbability (QueryProbabilityRequest)
returns (QueryProbabilityResponse);
/*
BuildRoute builds a fully specified route based on a list of hop public
keys. It retrieves the relevant channel policies from the graph in order to
calculate the correct fees and time locks.
*/
rpc BuildRoute (BuildRouteRequest) returns (BuildRouteResponse);
/*
SubscribeHtlcEvents creates a uni-directional stream from the server to
the client which delivers a stream of htlc events.
*/
rpc SubscribeHtlcEvents (SubscribeHtlcEventsRequest)
returns (stream HtlcEvent);
/*
Deprecated, use SendPaymentV2. SendPayment attempts to route a payment
described by the passed PaymentRequest to the final destination. The call
returns a stream of payment status updates.
*/
rpc SendPayment (SendPaymentRequest) returns (stream PaymentStatus) {
option deprecated = true;
}
/*
Deprecated, use TrackPaymentV2. TrackPayment returns an update stream for
the payment identified by the payment hash.
*/
rpc TrackPayment (TrackPaymentRequest) returns (stream PaymentStatus) {
option deprecated = true;
}
/**
HtlcInterceptor dispatches a bi-directional streaming RPC in which
Forwarded HTLC requests are sent to the client and the client responds with
a boolean that tells LND if this htlc should be intercepted.
In case of interception, the htlc can be either settled, cancelled or
resumed later by using the ResolveHoldForward endpoint.
*/
rpc HtlcInterceptor (stream ForwardHtlcInterceptResponse)
returns (stream ForwardHtlcInterceptRequest);
}
message SendPaymentRequest {
// The identity pubkey of the payment recipient
bytes dest = 1;
/*
Number of satoshis to send.
The fields amt and amt_msat are mutually exclusive.
*/
int64 amt = 2;
/*
Number of millisatoshis to send.
The fields amt and amt_msat are mutually exclusive.
*/
int64 amt_msat = 12;
// The hash to use within the payment's HTLC
bytes payment_hash = 3;
/*
The CLTV delta from the current height that should be used to set the
timelock for the final hop.
*/
int32 final_cltv_delta = 4;
/*
A bare-bones invoice for a payment within the Lightning Network. With the
details of the invoice, the sender has all the data necessary to send a
payment to the recipient. The amount in the payment request may be zero. In
that case it is required to set the amt field as well. If no payment request
is specified, the following fields are required: dest, amt and payment_hash.
*/
string payment_request = 5;
/*
An upper limit on the amount of time we should spend when attempting to
fulfill the payment. This is expressed in seconds. If we cannot make a
successful payment within this time frame, an error will be returned.
This field must be non-zero.
*/
int32 timeout_seconds = 6;
/*
The maximum number of satoshis that will be paid as a fee of the payment.
If this field is left to the default value of 0, only zero-fee routes will
be considered. This usually means single hop routes connecting directly to
the destination. To send the payment without a fee limit, use max int here.
The fields fee_limit_sat and fee_limit_msat are mutually exclusive.
*/
int64 fee_limit_sat = 7;
/*
The maximum number of millisatoshis that will be paid as a fee of the
payment. If this field is left to the default value of 0, only zero-fee
routes will be considered. This usually means single hop routes connecting
directly to the destination. To send the payment without a fee limit, use
max int here.
The fields fee_limit_sat and fee_limit_msat are mutually exclusive.
*/
int64 fee_limit_msat = 13;
/*
Deprecated, use outgoing_chan_ids. The channel id of the channel that must
be taken to the first hop. If zero, any channel may be used (unless
outgoing_chan_ids are set).
*/
uint64 outgoing_chan_id = 8 [jstype = JS_STRING, deprecated = true];
/*
The channel ids of the channels are allowed for the first hop. If empty,
any channel may be used.
*/
repeated uint64 outgoing_chan_ids = 19;
/*
The pubkey of the last hop of the route. If empty, any hop may be used.
*/
bytes last_hop_pubkey = 14;
/*
An optional maximum total time lock for the route. This should not exceed
lnd's `--max-cltv-expiry` setting. If zero, then the value of
`--max-cltv-expiry` is enforced.
*/
int32 cltv_limit = 9;
/*
Optional route hints to reach the destination through private channels.
*/
repeated lnrpc.RouteHint route_hints = 10;
/*
An optional field that can be used to pass an arbitrary set of TLV records
to a peer which understands the new records. This can be used to pass
application specific data during the payment attempt. Record types are
required to be in the custom range >= 65536. When using REST, the values
must be encoded as base64.
*/
map<uint64, bytes> dest_custom_records = 11;
// If set, circular payments to self are permitted.
bool allow_self_payment = 15;
/*
Features assumed to be supported by the final node. All transitive feature
dependencies must also be set properly. For a given feature bit pair, either
optional or remote may be set, but not both. If this field is nil or empty,
the router will try to load destination features from the graph as a
fallback.
*/
repeated lnrpc.FeatureBit dest_features = 16;
/*
The maximum number of partial payments that may be use to complete the full
amount.
*/
uint32 max_parts = 17;
/*
If set, only the final payment update is streamed back. Intermediate updates
that show which htlcs are still in flight are suppressed.
*/
bool no_inflight_updates = 18;
}
message TrackPaymentRequest {
// The hash of the payment to look up.
bytes payment_hash = 1;
/*
If set, only the final payment update is streamed back. Intermediate updates
that show which htlcs are still in flight are suppressed.
*/
bool no_inflight_updates = 2;
}
message RouteFeeRequest {
/*
The destination once wishes to obtain a routing fee quote to.
*/
bytes dest = 1;
/*
The amount one wishes to send to the target destination.
*/
int64 amt_sat = 2;
}
message RouteFeeResponse {
/*
A lower bound of the estimated fee to the target destination within the
network, expressed in milli-satoshis.
*/
int64 routing_fee_msat = 1;
/*
An estimate of the worst case time delay that can occur. Note that callers
will still need to factor in the final CLTV delta of the last hop into this
value.
*/
int64 time_lock_delay = 2;
}
message SendToRouteRequest {
// The payment hash to use for the HTLC.
bytes payment_hash = 1;
// Route that should be used to attempt to complete the payment.
lnrpc.Route route = 2;
}
message SendToRouteResponse {
// The preimage obtained by making the payment.
bytes preimage = 1;
// The failure message in case the payment failed.
lnrpc.Failure failure = 2;
}
message ResetMissionControlRequest {
}
message ResetMissionControlResponse {
}
message QueryMissionControlRequest {
}
// QueryMissionControlResponse contains mission control state.
message QueryMissionControlResponse {
reserved 1;
// Node pair-level mission control state.
repeated PairHistory pairs = 2;
}
// PairHistory contains the mission control state for a particular node pair.
message PairHistory {
// The source node pubkey of the pair.
bytes node_from = 1;
// The destination node pubkey of the pair.
bytes node_to = 2;
reserved 3, 4, 5, 6;
PairData history = 7;
}
message PairData {
// Time of last failure.
int64 fail_time = 1;
/*
Lowest amount that failed to forward rounded to whole sats. This may be
set to zero if the failure is independent of amount.
*/
int64 fail_amt_sat = 2;
/*
Lowest amount that failed to forward in millisats. This may be
set to zero if the failure is independent of amount.
*/
int64 fail_amt_msat = 4;
reserved 3;
// Time of last success.
int64 success_time = 5;
// Highest amount that we could successfully forward rounded to whole sats.
int64 success_amt_sat = 6;
// Highest amount that we could successfully forward in millisats.
int64 success_amt_msat = 7;
}
message QueryProbabilityRequest {
// The source node pubkey of the pair.
bytes from_node = 1;
// The destination node pubkey of the pair.
bytes to_node = 2;
// The amount for which to calculate a probability.
int64 amt_msat = 3;
}
message QueryProbabilityResponse {
// The success probability for the requested pair.
double probability = 1;
// The historical data for the requested pair.
PairData history = 2;
}
message BuildRouteRequest {
/*
The amount to send expressed in msat. If set to zero, the minimum routable
amount is used.
*/
int64 amt_msat = 1;
/*
CLTV delta from the current height that should be used for the timelock
of the final hop
*/
int32 final_cltv_delta = 2;
/*
The channel id of the channel that must be taken to the first hop. If zero,
any channel may be used.
*/
uint64 outgoing_chan_id = 3 [jstype = JS_STRING];
/*
A list of hops that defines the route. This does not include the source hop
pubkey.
*/
repeated bytes hop_pubkeys = 4;
}
message BuildRouteResponse {
/*
Fully specified route that can be used to execute the payment.
*/
lnrpc.Route route = 1;
}
message SubscribeHtlcEventsRequest {
}
/*
HtlcEvent contains the htlc event that was processed. These are served on a
best-effort basis; events are not persisted, delivery is not guaranteed
(in the event of a crash in the switch, forward events may be lost) and
some events may be replayed upon restart. Events consumed from this package
should be de-duplicated by the htlc's unique combination of incoming and
outgoing channel id and htlc id. [EXPERIMENTAL]
*/
message HtlcEvent {
/*
The short channel id that the incoming htlc arrived at our node on. This
value is zero for sends.
*/
uint64 incoming_channel_id = 1;
/*
The short channel id that the outgoing htlc left our node on. This value
is zero for receives.
*/
uint64 outgoing_channel_id = 2;
/*
Incoming id is the index of the incoming htlc in the incoming channel.
This value is zero for sends.
*/
uint64 incoming_htlc_id = 3;
/*
Outgoing id is the index of the outgoing htlc in the outgoing channel.
This value is zero for receives.
*/
uint64 outgoing_htlc_id = 4;
/*
The time in unix nanoseconds that the event occurred.
*/
uint64 timestamp_ns = 5;
enum EventType {
UNKNOWN = 0;
SEND = 1;
RECEIVE = 2;
FORWARD = 3;
}
/*
The event type indicates whether the htlc was part of a send, receive or
forward.
*/
EventType event_type = 6;
oneof event {
ForwardEvent forward_event = 7;
ForwardFailEvent forward_fail_event = 8;
SettleEvent settle_event = 9;
LinkFailEvent link_fail_event = 10;
}
}
message HtlcInfo {
// The timelock on the incoming htlc.
uint32 incoming_timelock = 1;
// The timelock on the outgoing htlc.
uint32 outgoing_timelock = 2;
// The amount of the incoming htlc.
uint64 incoming_amt_msat = 3;
// The amount of the outgoing htlc.
uint64 outgoing_amt_msat = 4;
}
message ForwardEvent {
// Info contains details about the htlc that was forwarded.
HtlcInfo info = 1;
}
message ForwardFailEvent {
}
message SettleEvent {
}
message LinkFailEvent {
// Info contains details about the htlc that we failed.
HtlcInfo info = 1;
// FailureCode is the BOLT error code for the failure.
lnrpc.Failure.FailureCode wire_failure = 2;
/*
FailureDetail provides additional information about the reason for the
failure. This detail enriches the information provided by the wire message
and may be 'no detail' if the wire message requires no additional metadata.
*/
FailureDetail failure_detail = 3;
// A string representation of the link failure.
string failure_string = 4;
}
enum FailureDetail {
UNKNOWN = 0;
NO_DETAIL = 1;
ONION_DECODE = 2;
LINK_NOT_ELIGIBLE = 3;
ON_CHAIN_TIMEOUT = 4;
HTLC_EXCEEDS_MAX = 5;
INSUFFICIENT_BALANCE = 6;
INCOMPLETE_FORWARD = 7;
HTLC_ADD_FAILED = 8;
FORWARDS_DISABLED = 9;
INVOICE_CANCELED = 10;
INVOICE_UNDERPAID = 11;
INVOICE_EXPIRY_TOO_SOON = 12;
INVOICE_NOT_OPEN = 13;
MPP_INVOICE_TIMEOUT = 14;
ADDRESS_MISMATCH = 15;
SET_TOTAL_MISMATCH = 16;
SET_TOTAL_TOO_LOW = 17;
SET_OVERPAID = 18;
UNKNOWN_INVOICE = 19;
INVALID_KEYSEND = 20;
MPP_IN_PROGRESS = 21;
CIRCULAR_ROUTE = 22;
}
enum PaymentState {
/*
Payment is still in flight.
*/
IN_FLIGHT = 0;
/*
Payment completed successfully.
*/
SUCCEEDED = 1;
/*
There are more routes to try, but the payment timeout was exceeded.
*/
FAILED_TIMEOUT = 2;
/*
All possible routes were tried and failed permanently. Or were no
routes to the destination at all.
*/
FAILED_NO_ROUTE = 3;
/*
A non-recoverable error has occured.
*/
FAILED_ERROR = 4;
/*
Payment details incorrect (unknown hash, invalid amt or
invalid final cltv delta)
*/
FAILED_INCORRECT_PAYMENT_DETAILS = 5;
/*
Insufficient local balance.
*/
FAILED_INSUFFICIENT_BALANCE = 6;
}
message PaymentStatus {
// Current state the payment is in.
PaymentState state = 1;
/*
The pre-image of the payment when state is SUCCEEDED.
*/
bytes preimage = 2;
reserved 3;
/*
The HTLCs made in attempt to settle the payment [EXPERIMENTAL].
*/
repeated lnrpc.HTLCAttempt htlcs = 4;
}
message CircuitKey {
/// The id of the channel that the is part of this circuit.
uint64 chan_id = 1;
/// The index of the incoming htlc in the incoming channel.
uint64 htlc_id = 2;
}
message ForwardHtlcInterceptRequest {
/*
The key of this forwarded htlc. It defines the incoming channel id and
the index in this channel.
*/
CircuitKey incoming_circuit_key = 1;
// The incoming htlc amount.
uint64 incoming_amount_msat = 5;
// The incoming htlc expiry.
uint32 incoming_expiry = 6;
/*
The htlc payment hash. This value is not guaranteed to be unique per
request.
*/
bytes payment_hash = 2;
// The requested outgoing channel id for this forwarded htlc. Because of
// non-strict forwarding, this isn't necessarily the channel over which the
// packet will be forwarded eventually. A different channel to the same peer
// may be selected as well.
uint64 outgoing_requested_chan_id = 7;
// The outgoing htlc amount.
uint64 outgoing_amount_msat = 3;
// The outgoing htlc expiry.
uint32 outgoing_expiry = 4;
// Any custom records that were present in the payload.
map<uint64, bytes> custom_records = 8;
}
/**
ForwardHtlcInterceptResponse enables the caller to resolve a previously hold
forward. The caller can choose either to:
- `Resume`: Execute the default behavior (usually forward).
- `Reject`: Fail the htlc backwards.
- `Settle`: Settle this htlc with a given preimage.
*/
message ForwardHtlcInterceptResponse {
/**
The key of this forwarded htlc. It defines the incoming channel id and
the index in this channel.
*/
CircuitKey incoming_circuit_key = 1;
// The resolve action for this intercepted htlc.
ResolveHoldForwardAction action = 2;
// The preimage in case the resolve action is Settle.
bytes preimage = 3;
}
enum ResolveHoldForwardAction {
SETTLE = 0;
FAIL = 1;
RESUME = 2;
}

623
rpc.proto → proto/rpc.proto

@ -1,7 +1,5 @@
syntax = "proto3";
// import "google/api/annotations.proto";
package lnrpc;
option go_package = "github.com/lightningnetwork/lnd/lnrpc";
@ -31,42 +29,31 @@ service Lightning {
confirmed unspent outputs and all unconfirmed unspent outputs under control
of the wallet.
*/
rpc WalletBalance (WalletBalanceRequest) returns (WalletBalanceResponse) {
option (google.api.http) = {
get: "/v1/balance/blockchain"
};
}
rpc WalletBalance (WalletBalanceRequest) returns (WalletBalanceResponse);
/* lncli: `channelbalance`
ChannelBalance returns the total funds available across all open channels
in satoshis.
*/
rpc ChannelBalance (ChannelBalanceRequest)
returns (ChannelBalanceResponse) {
option (google.api.http) = {
get: "/v1/balance/channels"
};
}
ChannelBalance returns a report on the total funds across all open channels,
categorized in local/remote, pending local/remote and unsettled local/remote
balances.
*/
rpc ChannelBalance (ChannelBalanceRequest) returns (ChannelBalanceResponse);
/* lncli: `listchaintxns`
GetTransactions returns a list describing all the known transactions
relevant to the wallet.
*/
rpc GetTransactions (GetTransactionsRequest) returns (TransactionDetails) {
option (google.api.http) = {
get: "/v1/transactions"
};
}
rpc GetTransactions (GetTransactionsRequest) returns (TransactionDetails);
/* lncli: `estimatefee`
EstimateFee asks the chain backend to estimate the fee rate and total fees
for a transaction that pays to multiple specified outputs.
When using REST, the `AddrToAmount` map type can be set by appending
`&AddrToAmount[<address>]=<amount_to_send>` to the URL. Unfortunately this
map type doesn't appear in the REST API documentation because of a bug in
the grpc-gateway library.
*/
rpc EstimateFee (EstimateFeeRequest) returns (EstimateFeeResponse) {
option (google.api.http) = {
get: "/v1/transactions/fee"
};
}
rpc EstimateFee (EstimateFeeRequest) returns (EstimateFeeResponse);
/* lncli: `sendcoins`
SendCoins executes a request to send coins to a particular address. Unlike
@ -75,22 +62,15 @@ service Lightning {
consult its fee model to determine a fee for the default confirmation
target.
*/
rpc SendCoins (SendCoinsRequest) returns (SendCoinsResponse) {
option (google.api.http) = {
post: "/v1/transactions"
body: "*"
};
}
rpc SendCoins (SendCoinsRequest) returns (SendCoinsResponse);
/* lncli: `listunspent`
Deprecated, use walletrpc.ListUnspent instead.
ListUnspent returns a list of all utxos spendable by the wallet with a
number of confirmations between the specified minimum and maximum.
number of confirmations between the specified minimum and maximum.
*/
rpc ListUnspent (ListUnspentRequest) returns (ListUnspentResponse) {
option (google.api.http) = {
get: "/v1/utxos"
};
}
rpc ListUnspent (ListUnspentRequest) returns (ListUnspentResponse);
/*
SubscribeTransactions creates a uni-directional stream from the server to
@ -111,23 +91,14 @@ service Lightning {
/* lncli: `newaddress`
NewAddress creates a new address under control of the local wallet.
*/
rpc NewAddress (NewAddressRequest) returns (NewAddressResponse) {
option (google.api.http) = {
get: "/v1/newaddress"
};
}
rpc NewAddress (NewAddressRequest) returns (NewAddressResponse);
/* lncli: `signmessage`
SignMessage signs a message with this node's private key. The returned
signature string is `zbase32` encoded and pubkey recoverable, meaning that
only the message digest and signature are needed for verification.
*/
rpc SignMessage (SignMessageRequest) returns (SignMessageResponse) {
option (google.api.http) = {
post: "/v1/signmessage"
body: "*"
};
}
rpc SignMessage (SignMessageRequest) returns (SignMessageResponse);
/* lncli: `verifymessage`
VerifyMessage verifies a signature over a msg. The signature must be
@ -135,45 +106,26 @@ service Lightning {
channel database. In addition to returning the validity of the signature,
VerifyMessage also returns the recovered pubkey from the signature.
*/
rpc VerifyMessage (VerifyMessageRequest) returns (VerifyMessageResponse) {
option (google.api.http) = {
post: "/v1/verifymessage"
body: "*"
};
}
rpc VerifyMessage (VerifyMessageRequest) returns (VerifyMessageResponse);
/* lncli: `connect`
ConnectPeer attempts to establish a connection to a remote peer. This is at
the networking level, and is used for communication between nodes. This is
distinct from establishing a channel with a peer.
*/
rpc ConnectPeer (ConnectPeerRequest) returns (ConnectPeerResponse) {
option (google.api.http) = {
post: "/v1/peers"
body: "*"
};
}
rpc ConnectPeer (ConnectPeerRequest) returns (ConnectPeerResponse);
/* lncli: `disconnect`
DisconnectPeer attempts to disconnect one peer from another identified by a
given pubKey. In the case that we currently have a pending or active channel
with the target peer, then this action will be not be allowed.
*/
rpc DisconnectPeer (DisconnectPeerRequest)
returns (DisconnectPeerResponse) {
option (google.api.http) = {
delete: "/v1/peers/{pub_key}"
};
}
rpc DisconnectPeer (DisconnectPeerRequest) returns (DisconnectPeerResponse);
/* lncli: `listpeers`
ListPeers returns a verbose listing of all currently active peers.
*/
rpc ListPeers (ListPeersRequest) returns (ListPeersResponse) {
option (google.api.http) = {
get: "/v1/peers"
};
}
rpc ListPeers (ListPeersRequest) returns (ListPeersResponse);
/*
SubscribePeerEvents creates a uni-directional stream from the server to
@ -187,11 +139,15 @@ service Lightning {
it's identity pubkey, alias, the chains it is connected to, and information
concerning the number of open+pending channels.
*/
rpc GetInfo (GetInfoRequest) returns (GetInfoResponse) {
option (google.api.http) = {
get: "/v1/getinfo"
};
}
rpc GetInfo (GetInfoRequest) returns (GetInfoResponse);
/** lncli: `getrecoveryinfo`
GetRecoveryInfo returns information concerning the recovery mode including
whether it's in a recovery mode, whether the recovery is finished, and the
progress made so far.
*/
rpc GetRecoveryInfo (GetRecoveryInfoRequest)
returns (GetRecoveryInfoResponse);
// TODO(roasbeef): merge with below with bool?
/* lncli: `pendingchannels`
@ -201,21 +157,13 @@ service Lightning {
process of closure, either initiated cooperatively or non-cooperatively.
*/
rpc PendingChannels (PendingChannelsRequest)
returns (PendingChannelsResponse) {
option (google.api.http) = {
get: "/v1/channels/pending"
};
}
returns (PendingChannelsResponse);
/* lncli: `listchannels`
ListChannels returns a description of all the open channels that this node
is a participant in.
*/
rpc ListChannels (ListChannelsRequest) returns (ListChannelsResponse) {
option (google.api.http) = {
get: "/v1/channels"
};
}
rpc ListChannels (ListChannelsRequest) returns (ListChannelsResponse);
/*
SubscribeChannelEvents creates a uni-directional stream from the server to
@ -230,12 +178,7 @@ service Lightning {
ClosedChannels returns a description of all the closed channels that
this node was a participant in.
*/
rpc ClosedChannels (ClosedChannelsRequest)
returns (ClosedChannelsResponse) {
option (google.api.http) = {
get: "/v1/channels/closed"
};
}
rpc ClosedChannels (ClosedChannelsRequest) returns (ClosedChannelsResponse);
/*
OpenChannelSync is a synchronous version of the OpenChannel RPC call. This
@ -243,12 +186,7 @@ service Lightning {
other sync calls, all byte slices are intended to be populated as hex
encoded strings.
*/
rpc OpenChannelSync (OpenChannelRequest) returns (ChannelPoint) {
option (google.api.http) = {
post: "/v1/channels"
body: "*"
};
}
rpc OpenChannelSync (OpenChannelRequest) returns (ChannelPoint);
/* lncli: `openchannel`
OpenChannel attempts to open a singly funded channel specified in the
@ -293,24 +231,17 @@ service Lightning {
closure transaction is confirmed, or a manual fee rate. If neither are
specified, then a default lax, block confirmation target is used.
*/
rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate) {
option (google.api.http) = {
delete: "/v1/channels/{channel_point.funding_txid_str}/{channel_point.output_index}"
};
}
rpc CloseChannel (CloseChannelRequest) returns (stream CloseStatusUpdate);
/* lncli: `abandonchannel`
AbandonChannel removes all channel state from the database except for a
close summary. This method can be used to get rid of permanently unusable
channels due to bugs fixed in newer versions of lnd. Only available
when in debug builds of lnd.
*/
rpc AbandonChannel (AbandonChannelRequest)
returns (AbandonChannelResponse) {
option (google.api.http) = {
delete: "/v1/channels/abandon/{channel_point.funding_txid_str}/{channel_point.output_index}"
};
}
channels due to bugs fixed in newer versions of lnd. This method can also be
used to remove externally funded channels where the funding transaction was
never broadcast. Only available for non-externally funded channels in dev
build.
*/
rpc AbandonChannel (AbandonChannelRequest) returns (AbandonChannelResponse);
/* lncli: `sendpayment`
Deprecated, use routerrpc.SendPaymentV2. SendPayment dispatches a
@ -329,12 +260,7 @@ service Lightning {
Additionally, this RPC expects the destination's public key and the payment
hash (if any) to be encoded as hex strings.
*/
rpc SendPaymentSync (SendRequest) returns (SendResponse) {
option (google.api.http) = {
post: "/v1/channels/transactions"
body: "*"
};
}
rpc SendPaymentSync (SendRequest) returns (SendResponse);
/* lncli: `sendtoroute`
Deprecated, use routerrpc.SendToRouteV2. SendToRoute is a bi-directional
@ -351,24 +277,14 @@ service Lightning {
SendToRouteSync is a synchronous version of SendToRoute. It Will block
until the payment either fails or succeeds.
*/
rpc SendToRouteSync (SendToRouteRequest) returns (SendResponse) {
option (google.api.http) = {
post: "/v1/channels/transactions/route"
body: "*"
};
}
rpc SendToRouteSync (SendToRouteRequest) returns (SendResponse);
/* lncli: `addinvoice`
AddInvoice attempts to add a new invoice to the invoice database. Any
duplicated invoices are rejected, therefore all invoices *must* have a
unique payment preimage.
*/
rpc AddInvoice (Invoice) returns (AddInvoiceResponse) {
option (google.api.http) = {
post: "/v1/invoices"
body: "*"
};
}
rpc AddInvoice (Invoice) returns (AddInvoiceResponse);
/* lncli: `listinvoices`
ListInvoices returns a list of all the invoices currently stored within the
@ -379,22 +295,14 @@ service Lightning {
next request. By default, the first 100 invoices created will be returned.
Backwards pagination is also supported through the Reversed flag.
*/
rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse) {
option (google.api.http) = {
get: "/v1/invoices"
};
}
rpc ListInvoices (ListInvoiceRequest) returns (ListInvoiceResponse);
/* lncli: `lookupinvoice`
LookupInvoice attempts to look up an invoice according to its payment hash.
The passed payment hash *must* be exactly 32 bytes, if not, an error is
returned.
*/
rpc LookupInvoice (PaymentHash) returns (Invoice) {
option (google.api.http) = {
get: "/v1/invoice/{r_hash_str}"
};
}
rpc LookupInvoice (PaymentHash) returns (Invoice);
/*
SubscribeInvoices returns a uni-directional stream (server -> client) for
@ -407,41 +315,25 @@ service Lightning {
of these fields can be set. If no fields are set, then we'll only send out
the latest add/settle events.
*/
rpc SubscribeInvoices (InvoiceSubscription) returns (stream Invoice) {
option (google.api.http) = {
get: "/v1/invoices/subscribe"
};
}
rpc SubscribeInvoices (InvoiceSubscription) returns (stream Invoice);
/* lncli: `decodepayreq`
DecodePayReq takes an encoded payment request string and attempts to decode
it, returning a full description of the conditions encoded within the
payment request.
*/
rpc DecodePayReq (PayReqString) returns (PayReq) {
option (google.api.http) = {
get: "/v1/payreq/{pay_req}"
};
}
rpc DecodePayReq (PayReqString) returns (PayReq);
/* lncli: `listpayments`
ListPayments returns a list of all outgoing payments.
*/
rpc ListPayments (ListPaymentsRequest) returns (ListPaymentsResponse) {
option (google.api.http) = {
get: "/v1/payments"
};
};
rpc ListPayments (ListPaymentsRequest) returns (ListPaymentsResponse);
/*
DeleteAllPayments deletes all outgoing payments from DB.
*/
rpc DeleteAllPayments (DeleteAllPaymentsRequest)
returns (DeleteAllPaymentsResponse) {
option (google.api.http) = {
delete: "/v1/payments"
};
};
returns (DeleteAllPaymentsResponse);
/* lncli: `describegraph`
DescribeGraph returns a description of the latest graph state from the
@ -451,21 +343,13 @@ service Lightning {
the node directional specific routing policy which includes: the time lock
delta, fee information, etc.
*/
rpc DescribeGraph (ChannelGraphRequest) returns (ChannelGraph) {
option (google.api.http) = {
get: "/v1/graph"
};
}
rpc DescribeGraph (ChannelGraphRequest) returns (ChannelGraph);
/* lncli: `getnodemetrics`
GetNodeMetrics returns node metrics calculated from the graph. Currently
the only supported metric is betweenness centrality of individual nodes.
*/
rpc GetNodeMetrics (NodeMetricsRequest) returns (NodeMetricsResponse) {
option (google.api.http) = {
get: "/v1/graph/nodemetrics"
};
}
rpc GetNodeMetrics (NodeMetricsRequest) returns (NodeMetricsResponse);
/* lncli: `getchaninfo`
GetChanInfo returns the latest authenticated network announcement for the
@ -473,21 +357,13 @@ service Lightning {
uniquely identifies the location of transaction's funding output within the
blockchain.
*/
rpc GetChanInfo (ChanInfoRequest) returns (ChannelEdge) {
option (google.api.http) = {
get: "/v1/graph/edge/{chan_id}"
};
}
rpc GetChanInfo (ChanInfoRequest) returns (ChannelEdge);
/* lncli: `getnodeinfo`
GetNodeInfo returns the latest advertised, aggregated, and authenticated
channel information for the specified node identified by its public key.
*/
rpc GetNodeInfo (NodeInfoRequest) returns (NodeInfo) {
option (google.api.http) = {
get: "/v1/graph/node/{pub_key}"
};
}
rpc GetNodeInfo (NodeInfoRequest) returns (NodeInfo);
/* lncli: `queryroutes`
QueryRoutes attempts to query the daemon's Channel Router for a possible
@ -495,22 +371,19 @@ service Lightning {
satoshis. The returned route contains the full details required to craft and
send an HTLC, also including the necessary information that should be
present within the Sphinx packet encapsulated within the HTLC.
When using REST, the `dest_custom_records` map type can be set by appending
`&dest_custom_records[<record_number>]=<record_data_base64_url_encoded>`
to the URL. Unfortunately this map type doesn't appear in the REST API
documentation because of a bug in the grpc-gateway library.
*/
rpc QueryRoutes (QueryRoutesRequest) returns (QueryRoutesResponse) {
option (google.api.http) = {
get: "/v1/graph/routes/{pub_key}/{amt}"
};
}
rpc QueryRoutes (QueryRoutesRequest) returns (QueryRoutesResponse);
/* lncli: `getnetworkinfo`
GetNetworkInfo returns some basic stats about the known channel graph from
the point of view of the node.
*/
rpc GetNetworkInfo (NetworkInfoRequest) returns (NetworkInfo) {
option (google.api.http) = {
get: "/v1/graph/info"
};
}
rpc GetNetworkInfo (NetworkInfoRequest) returns (NetworkInfo);
/* lncli: `stop`
StopDaemon will send a shutdown request to the interrupt handler, triggering
@ -541,23 +414,14 @@ service Lightning {
FeeReport allows the caller to obtain a report detailing the current fee
schedule enforced by the node globally for each channel.
*/
rpc FeeReport (FeeReportRequest) returns (FeeReportResponse) {
option (google.api.http) = {
get: "/v1/fees"
};
}
rpc FeeReport (FeeReportRequest) returns (FeeReportResponse);
/* lncli: `updatechanpolicy`
UpdateChannelPolicy allows the caller to update the fee schedule and
channel policies for all channels globally, or a particular channel.
*/
rpc UpdateChannelPolicy (PolicyUpdateRequest)
returns (PolicyUpdateResponse) {
option (google.api.http) = {
post: "/v1/chanpolicy"
body: "*"
};
}
returns (PolicyUpdateResponse);
/* lncli: `fwdinghistory`
ForwardingHistory allows the caller to query the htlcswitch for a record of
@ -572,12 +436,7 @@ service Lightning {
request to allow the caller to skip a series of records.
*/
rpc ForwardingHistory (ForwardingHistoryRequest)
returns (ForwardingHistoryResponse) {
option (google.api.http) = {
post: "/v1/switch"
body: "*"
};
};
returns (ForwardingHistoryResponse);
/* lncli: `exportchanbackup`
ExportChannelBackup attempts to return an encrypted static channel backup
@ -588,11 +447,7 @@ service Lightning {
from the WalletUnlocker service.
*/
rpc ExportChannelBackup (ExportChannelBackupRequest)
returns (ChannelBackup) {
option (google.api.http) = {
get: "/v1/channels/backup/{chan_point.funding_txid_str}/{chan_point.output_index}"
};
};
returns (ChannelBackup);
/*
ExportAllChannelBackups returns static channel backups for all existing
@ -602,11 +457,7 @@ service Lightning {
each channel.
*/
rpc ExportAllChannelBackups (ChanBackupExportRequest)
returns (ChanBackupSnapshot) {
option (google.api.http) = {
get: "/v1/channels/backup"
};
};
returns (ChanBackupSnapshot);
/*
VerifyChanBackup allows a caller to verify the integrity of a channel backup
@ -614,12 +465,7 @@ service Lightning {
Specifying both will result in an error.
*/
rpc VerifyChanBackup (ChanBackupSnapshot)
returns (VerifyChanBackupResponse) {
option (google.api.http) = {
post: "/v1/channels/backup/verify"
body: "*"
};
};
returns (VerifyChanBackupResponse);
/* lncli: `restorechanbackup`
RestoreChannelBackups accepts a set of singular channel backups, or a
@ -628,12 +474,7 @@ service Lightning {
new channel will be shown under listchannels, as well as pending channels.
*/
rpc RestoreChannelBackups (RestoreChanBackupRequest)
returns (RestoreBackupResponse) {
option (google.api.http) = {
post: "/v1/channels/backup/restore"
body: "*"
};
};
returns (RestoreBackupResponse);
/*
SubscribeChannelBackups allows a client to sub-subscribe to the most up to
@ -645,20 +486,34 @@ service Lightning {
channel(s) removed.
*/
rpc SubscribeChannelBackups (ChannelBackupSubscription)
returns (stream ChanBackupSnapshot) {
};
returns (stream ChanBackupSnapshot);
/* lncli: `bakemacaroon`
BakeMacaroon allows the creation of a new macaroon with custom read and
write permissions. No first-party caveats are added since this can be done
offline.
*/
rpc BakeMacaroon (BakeMacaroonRequest) returns (BakeMacaroonResponse) {
option (google.api.http) = {
post: "/v1/macaroon"
body: "*"
};
};
rpc BakeMacaroon (BakeMacaroonRequest) returns (BakeMacaroonResponse);
/* lncli: `listmacaroonids`
ListMacaroonIDs returns all root key IDs that are in use.
*/
rpc ListMacaroonIDs (ListMacaroonIDsRequest)
returns (ListMacaroonIDsResponse);
/* lncli: `deletemacaroonid`
DeleteMacaroonID deletes the specified macaroon ID and invalidates all
macaroons derived from that ID.
*/
rpc DeleteMacaroonID (DeleteMacaroonIDRequest)
returns (DeleteMacaroonIDResponse);
/* lncli: `listpermissions`
ListPermissions lists all RPC method URIs and their required macaroon
permissions to access them.
*/
rpc ListPermissions (ListPermissionsRequest)
returns (ListPermissionsResponse);
}
message Utxo {
@ -1008,6 +863,13 @@ message SendManyRequest {
// An optional label for the transaction, limited to 500 characters.
string label = 6;
// The minimum number of confirmations each one of your outputs used for
// the transaction must satisfy.
int32 min_confs = 7;
// Whether unconfirmed outputs should be used as inputs for the transaction.
bool spend_unconfirmed = 8;
}
message SendManyResponse {
// The id of the transaction
@ -1038,6 +900,13 @@ message SendCoinsRequest {
// An optional label for the transaction, limited to 500 characters.
string label = 7;
// The minimum number of confirmations each one of your outputs used for
// the transaction must satisfy.
int32 min_confs = 8;
// Whether unconfirmed outputs should be used as inputs for the transaction.
bool spend_unconfirmed = 9;
}
message SendCoinsResponse {
// The transaction ID of the transaction
@ -1115,6 +984,12 @@ message ConnectPeerRequest {
/* If set, the daemon will attempt to persistently connect to the target
* peer. Otherwise, the call will be synchronous. */
bool perm = 2;
/*
The connection timeout value (in seconds) for this request. It won't affect
other requests.
*/
uint64 timeout = 3;
}
message ConnectPeerResponse {
}
@ -1161,6 +1036,30 @@ enum CommitmentType {
UNKNOWN_COMMITMENT_TYPE = 999;
}
message ChannelConstraints {
/*
The CSV delay expressed in relative blocks. If the channel is force closed,
we will need to wait for this many blocks before we can regain our funds.
*/
uint32 csv_delay = 1;
// The minimum satoshis this node is required to reserve in its balance.
uint64 chan_reserve_sat = 2;
// The dust limit (in satoshis) of the initiator's commitment tx.
uint64 dust_limit_sat = 3;
// The maximum amount of coins in millisatoshis that can be pending in this
// channel.
uint64 max_pending_amt_msat = 4;
// The smallest HTLC in millisatoshis that the initiator will accept.
uint64 min_htlc_msat = 5;
// The total number of incoming HTLC's that the initiator will accept.
uint32 max_accepted_htlcs = 6;
}
message Channel {
// Whether this channel is active or not
bool active = 1;
@ -1233,10 +1132,11 @@ message Channel {
repeated HTLC pending_htlcs = 15;
/*
The CSV delay expressed in relative blocks. If the channel is force closed,
we will need to wait for this many blocks before we can regain our funds.
Deprecated. The CSV delay expressed in relative blocks. If the channel is
force closed, we will need to wait for this many blocks before we can regain
our funds.
*/
uint32 csv_delay = 16;
uint32 csv_delay = 16 [deprecated = true];
// Whether this channel is advertised to the network or not.
bool private = 17;
@ -1247,13 +1147,15 @@ message Channel {
// A set of flags showing the current state of the channel.
string chan_status_flags = 19;
// The minimum satoshis this node is required to reserve in its balance.
int64 local_chan_reserve_sat = 20;
// Deprecated. The minimum satoshis this node is required to reserve in its
// balance.
int64 local_chan_reserve_sat = 20 [deprecated = true];
/*
The minimum satoshis the other node is required to reserve in its balance.
Deprecated. The minimum satoshis the other node is required to reserve in
its balance.
*/
int64 remote_chan_reserve_sat = 21;
int64 remote_chan_reserve_sat = 21 [deprecated = true];
// Deprecated. Use commitment_type.
bool static_remote_key = 22 [deprecated = true];
@ -1298,9 +1200,17 @@ message Channel {
frozen channel doest not allow a cooperative channel close by the
initiator. The thaw_height is the height that this restriction stops
applying to the channel. This field is optional, not setting it or using a
value of zero will mean the channel has no additional restrictions.
value of zero will mean the channel has no additional restrictions. The
height can be interpreted in two ways: as a relative height if the value is
less than 500,000, or as an absolute height otherwise.
*/
uint32 thaw_height = 28;
// List constraints for the local node.
ChannelConstraints local_constraints = 29;
// List constraints for the remote node.
ChannelConstraints remote_constraints = 30;
}
message ListChannelsRequest {
@ -1382,6 +1292,79 @@ message ChannelCloseSummary {
force closes, although only one party's close will be confirmed on chain.
*/
Initiator close_initiator = 12;
repeated Resolution resolutions = 13;
}
enum ResolutionType {
TYPE_UNKNOWN = 0;
// We resolved an anchor output.
ANCHOR = 1;
/*
We are resolving an incoming htlc on chain. This if this htlc is
claimed, we swept the incoming htlc with the preimage. If it is timed
out, our peer swept the timeout path.
*/
INCOMING_HTLC = 2;
/*
We are resolving an outgoing htlc on chain. If this htlc is claimed,
the remote party swept the htlc with the preimage. If it is timed out,
we swept it with the timeout path.
*/
OUTGOING_HTLC = 3;
// We force closed and need to sweep our time locked commitment output.
COMMIT = 4;
}
enum ResolutionOutcome {
// Outcome unknown.
OUTCOME_UNKNOWN = 0;
// An output was claimed on chain.
CLAIMED = 1;
// An output was left unclaimed on chain.
UNCLAIMED = 2;
/*
ResolverOutcomeAbandoned indicates that an output that we did not
claim on chain, for example an anchor that we did not sweep and a
third party claimed on chain, or a htlc that we could not decode
so left unclaimed.
*/
ABANDONED = 3;
/*
If we force closed our channel, our htlcs need to be claimed in two
stages. This outcome represents the broadcast of a timeout or success
transaction for this two stage htlc claim.
*/
FIRST_STAGE = 4;
// A htlc was timed out on chain.
TIMEOUT = 5;
}
message Resolution {
// The type of output we are resolving.
ResolutionType resolution_type = 1;
// The outcome of our on chain action that resolved the outpoint.
ResolutionOutcome outcome = 2;
// The outpoint that was spent by the resolution.
OutPoint outpoint = 3;
// The amount that was claimed by the resolution.
uint64 amount_sat = 4;
// The hex-encoded transaction ID of the sweep transaction that spent the
// output.
string sweep_txid = 5;
}
message ClosedChannelsRequest {
@ -1453,6 +1436,20 @@ message Peer {
spamming us with errors at no cost.
*/
repeated TimestampedError errors = 12;
/*
The number of times we have recorded this peer going offline or coming
online, recorded across restarts. Note that this value is decreased over
time if the peer has not recently flapped, so that we can forgive peers
with historically high flap counts.
*/
int32 flap_count = 13;
/*
The timestamp of the last flap we observed for this peer. If this value is
zero, we have not observed any flaps for this peer.
*/
int64 last_flap_ns = 14;
}
message TimestampedError {
@ -1557,6 +1554,19 @@ message GetInfoResponse {
map<uint32, Feature> features = 19;
}
message GetRecoveryInfoRequest {
}
message GetRecoveryInfoResponse {
// Whether the wallet is in recovery mode
bool recovery_mode = 1;
// Whether the wallet recovery progress is finished
bool recovery_finished = 2;
// The recovery progress, ranging from 0 to 1.
double progress = 3;
}
message Chain {
// The blockchain the node is on (eg bitcoin, litecoin)
string chain = 1;
@ -1713,6 +1723,18 @@ message OpenChannelRequest {
carried out in an interactive manner (PSBT based).
*/
FundingShim funding_shim = 14;
/*
The maximum amount of coins in millisatoshi that can be pending within
the channel. It only applies to the remote party.
*/
uint64 remote_max_value_in_flight_msat = 15;
/*
The maximum number of concurrent HTLCs we will allow the remote party to add
to the commitment transaction.
*/
uint32 remote_max_htlcs = 16;
}
message OpenStatusUpdate {
oneof update {
@ -1787,10 +1809,11 @@ message ChanPointShim {
bytes pending_chan_id = 5;
/*
This uint32 indicates if this channel is to be considered 'frozen'. A
frozen channel does not allow a cooperative channel close by the
initiator. The thaw_height is the height that this restriction stops
applying to the channel.
This uint32 indicates if this channel is to be considered 'frozen'. A frozen
channel does not allow a cooperative channel close by the initiator. The
thaw_height is the height that this restriction stops applying to the
channel. The height can be interpreted in two ways: as a relative height if
the value is less than 500,000, or as an absolute height otherwise.
*/
uint32 thaw_height = 6;
}
@ -1808,6 +1831,16 @@ message PsbtShim {
non-empty, it must be a binary serialized PSBT.
*/
bytes base_psbt = 2;
/*
If a channel should be part of a batch (multiple channel openings in one
transaction), it can be dangerous if the whole batch transaction is
published too early before all channel opening negotiations are completed.
This flag prevents this particular channel from broadcasting the transaction
after the negotiation with the remote peer. In a batch of channel openings
this flag should be set to true for every channel but the very last.
*/
bool no_publish = 3;
}
message FundingShim {
@ -1847,12 +1880,19 @@ message FundingPsbtFinalize {
/*
The funded PSBT that contains all witness data to send the exact channel
capacity amount to the PK script returned in the open channel message in a
previous step.
previous step. Cannot be set at the same time as final_raw_tx.
*/
bytes signed_psbt = 1;
// The pending channel ID of the channel to get the PSBT for.
bytes pending_chan_id = 2;
/*
As an alternative to the signed PSBT with all witness data, the final raw
wire format transaction can also be specified directly. Cannot be set at the
same time as signed_psbt.
*/
bytes final_raw_tx = 3;
}
message FundingTransitionMsg {
@ -2108,14 +2148,40 @@ message WalletBalanceResponse {
int64 unconfirmed_balance = 3;
}
message Amount {
// Value denominated in satoshis.
uint64 sat = 1;
// Value denominated in milli-satoshis.
uint64 msat = 2;
}
message ChannelBalanceRequest {
}
message ChannelBalanceResponse {
// Sum of channels balances denominated in satoshis
int64 balance = 1;
// Deprecated. Sum of channels balances denominated in satoshis
int64 balance = 1 [deprecated = true];
// Deprecated. Sum of channels pending balances denominated in satoshis
int64 pending_open_balance = 2 [deprecated = true];
// Sum of channels local balances.
Amount local_balance = 3;
// Sum of channels remote balances.
Amount remote_balance = 4;
// Sum of channels local unsettled balances.
Amount unsettled_local_balance = 5;
// Sum of channels remote unsettled balances.
Amount unsettled_remote_balance = 6;
// Sum of channels pending local balances.
Amount pending_open_local_balance = 7;
// Sum of channels pending balances denominated in satoshis
int64 pending_open_balance = 2;
// Sum of channels pending remote balances.
Amount pending_open_remote_balance = 8;
}
message QueryRoutesRequest {
@ -3069,6 +3135,8 @@ message DeleteAllPaymentsResponse {
message AbandonChannelRequest {
ChannelPoint channel_point = 1;
bool pending_funding_shim_only = 2;
}
message AbandonChannelResponse {
@ -3357,12 +3425,46 @@ message MacaroonPermission {
message BakeMacaroonRequest {
// The list of permissions the new macaroon should grant.
repeated MacaroonPermission permissions = 1;
// The root key ID used to create the macaroon, must be a positive integer.
uint64 root_key_id = 2;
}
message BakeMacaroonResponse {
// The hex encoded macaroon, serialized in binary format.
string macaroon = 1;
}
message ListMacaroonIDsRequest {
}
message ListMacaroonIDsResponse {
// The list of root key IDs that are in use.
repeated uint64 root_key_ids = 1;
}
message DeleteMacaroonIDRequest {
// The root key ID to be removed.
uint64 root_key_id = 1;
}
message DeleteMacaroonIDResponse {
// A boolean indicates that the deletion is successful.
bool deleted = 1;
}
message MacaroonPermissionList {
// A list of macaroon permissions.
repeated MacaroonPermission permissions = 1;
}
message ListPermissionsRequest {
}
message ListPermissionsResponse {
/*
A map between all RPC method URIs and their required macaroon permissions to
access them.
*/
map<string, MacaroonPermissionList> method_permissions = 1;
}
message Failure {
enum FailureCode {
/*
@ -3525,3 +3627,14 @@ message ChannelUpdate {
*/
bytes extra_opaque_data = 12;
}
message MacaroonId {
bytes nonce = 1;
bytes storageId = 2;
repeated Op ops = 3;
}
message Op {
string entity = 1;
repeated string actions = 2;
}

0
signer.proto → proto/signer.proto

238
proto/walletunlocker.proto

@ -0,0 +1,238 @@
syntax = "proto3";
import "rpc.proto";
package lnrpc;
option go_package = "github.com/lightningnetwork/lnd/lnrpc";
/*
* Comments in this file will be directly parsed into the API
* Documentation as descriptions of the associated method, message, or field.
* These descriptions should go right above the definition of the object, and
* can be in either block or // comment format.
*
* An RPC method can be matched to an lncli command by placing a line in the
* beginning of the description in exactly the following format:
* lncli: `methodname`
*
* Failure to specify the exact name of the command will cause documentation
* generation to fail.
*
* More information on how exactly the gRPC documentation is generated from
* this proto file can be found here:
* https://github.com/lightninglabs/lightning-api
*/
// WalletUnlocker is a service that is used to set up a wallet password for
// lnd at first startup, and unlock a previously set up wallet.
service WalletUnlocker {
/*
GenSeed is the first method that should be used to instantiate a new lnd
instance. This method allows a caller to generate a new aezeed cipher seed
given an optional passphrase. If provided, the passphrase will be necessary
to decrypt the cipherseed to expose the internal wallet seed.
Once the cipherseed is obtained and verified by the user, the InitWallet
method should be used to commit the newly generated seed, and create the
wallet.
*/
rpc GenSeed (GenSeedRequest) returns (GenSeedResponse);
/*
InitWallet is used when lnd is starting up for the first time to fully
initialize the daemon and its internal wallet. At the very least a wallet
password must be provided. This will be used to encrypt sensitive material
on disk.
In the case of a recovery scenario, the user can also specify their aezeed
mnemonic and passphrase. If set, then the daemon will use this prior state
to initialize its internal wallet.
Alternatively, this can be used along with the GenSeed RPC to obtain a
seed, then present it to the user. Once it has been verified by the user,
the seed can be fed into this RPC in order to commit the new wallet.
*/
rpc InitWallet (InitWalletRequest) returns (InitWalletResponse);
/* lncli: `unlock`
UnlockWallet is used at startup of lnd to provide a password to unlock
the wallet database.
*/
rpc UnlockWallet (UnlockWalletRequest) returns (UnlockWalletResponse);
/* lncli: `changepassword`
ChangePassword changes the password of the encrypted wallet. This will
automatically unlock the wallet database if successful.
*/
rpc ChangePassword (ChangePasswordRequest) returns (ChangePasswordResponse);
}
message GenSeedRequest {
/*
aezeed_passphrase is an optional user provided passphrase that will be used
to encrypt the generated aezeed cipher seed. When using REST, this field
must be encoded as base64.
*/
bytes aezeed_passphrase = 1;
/*
seed_entropy is an optional 16-bytes generated via CSPRNG. If not
specified, then a fresh set of randomness will be used to create the seed.
When using REST, this field must be encoded as base64.
*/
bytes seed_entropy = 2;
}
message GenSeedResponse {
/*
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
cipher seed obtained by the user. This field is optional, as if not
provided, then the daemon will generate a new cipher seed for the user.
Otherwise, then the daemon will attempt to recover the wallet state linked
to this cipher seed.
*/
repeated string cipher_seed_mnemonic = 1;
/*
enciphered_seed are the raw aezeed cipher seed bytes. This is the raw
cipher text before run through our mnemonic encoding scheme.
*/
bytes enciphered_seed = 2;
}
message InitWalletRequest {
/*
wallet_password is the passphrase that should be used to encrypt the
wallet. This MUST be at least 8 chars in length. After creation, this
password is required to unlock the daemon. When using REST, this field
must be encoded as base64.
*/
bytes wallet_password = 1;
/*
cipher_seed_mnemonic is a 24-word mnemonic that encodes a prior aezeed
cipher seed obtained by the user. This may have been generated by the
GenSeed method, or be an existing seed.
*/
repeated string cipher_seed_mnemonic = 2;
/*
aezeed_passphrase is an optional user provided passphrase that will be used
to encrypt the generated aezeed cipher seed. When using REST, this field
must be encoded as base64.
*/
bytes aezeed_passphrase = 3;
/*
recovery_window is an optional argument specifying the address lookahead
when restoring a wallet seed. The recovery window applies to each
individual branch of the BIP44 derivation paths. Supplying a recovery
window of zero indicates that no addresses should be recovered, such after
the first initialization of the wallet.
*/
int32 recovery_window = 4;
/*
channel_backups is an optional argument that allows clients to recover the
settled funds within a set of channels. This should be populated if the
user was unable to close out all channels and sweep funds before partial or
total data loss occurred. If specified, then after on-chain recovery of
funds, lnd begin to carry out the data loss recovery protocol in order to
recover the funds in each channel from a remote force closed transaction.
*/
ChanBackupSnapshot channel_backups = 5;
/*
stateless_init is an optional argument instructing the daemon NOT to create
any *.macaroon files in its filesystem. If this parameter is set, then the
admin macaroon returned in the response MUST be stored by the caller of the
RPC as otherwise all access to the daemon will be lost!
*/
bool stateless_init = 6;
}
message InitWalletResponse {
/*
The binary serialized admin macaroon that can be used to access the daemon
after creating the wallet. If the stateless_init parameter was set to true,
this is the ONLY copy of the macaroon and MUST be stored safely by the
caller. Otherwise a copy of this macaroon is also persisted on disk by the
daemon, together with other macaroon files.
*/
bytes admin_macaroon = 1;
}
message UnlockWalletRequest {
/*
wallet_password should be the current valid passphrase for the daemon. This
will be required to decrypt on-disk material that the daemon requires to
function properly. When using REST, this field must be encoded as base64.
*/
bytes wallet_password = 1;
/*
recovery_window is an optional argument specifying the address lookahead
when restoring a wallet seed. The recovery window applies to each
individual branch of the BIP44 derivation paths. Supplying a recovery
window of zero indicates that no addresses should be recovered, such after
the first initialization of the wallet.
*/
int32 recovery_window = 2;
/*
channel_backups is an optional argument that allows clients to recover the
settled funds within a set of channels. This should be populated if the
user was unable to close out all channels and sweep funds before partial or
total data loss occurred. If specified, then after on-chain recovery of
funds, lnd begin to carry out the data loss recovery protocol in order to
recover the funds in each channel from a remote force closed transaction.
*/
ChanBackupSnapshot channel_backups = 3;
/*
stateless_init is an optional argument instructing the daemon NOT to create
any *.macaroon files in its file system.
*/
bool stateless_init = 4;
}
message UnlockWalletResponse {
}
message ChangePasswordRequest {
/*
current_password should be the current valid passphrase used to unlock the
daemon. When using REST, this field must be encoded as base64.
*/
bytes current_password = 1;
/*
new_password should be the new passphrase that will be needed to unlock the
daemon. When using REST, this field must be encoded as base64.
*/
bytes new_password = 2;
/*
stateless_init is an optional argument instructing the daemon NOT to create
any *.macaroon files in its filesystem. If this parameter is set, then the
admin macaroon returned in the response MUST be stored by the caller of the
RPC as otherwise all access to the daemon will be lost!
*/
bool stateless_init = 3;
/*
new_macaroon_root_key is an optional argument instructing the daemon to
rotate the macaroon root key when set to true. This will invalidate all
previously generated macaroons.
*/
bool new_macaroon_root_key = 4;
}
message ChangePasswordResponse {
/*
The binary serialized admin macaroon that can be used to access the daemon
after rotating the macaroon root key. If both the stateless_init and
new_macaroon_root_key parameter were set to true, this is the ONLY copy of
the macaroon that was created from the new root key and MUST be stored
safely by the caller. Otherwise a copy of this macaroon is also persisted on
disk by the daemon, together with other macaroon files.
*/
bytes admin_macaroon = 1;
}

132
src/auth.ts

@ -0,0 +1,132 @@
import * as crypto from 'crypto'
import { models } from './models'
import * as cryptoJS from 'crypto-js'
import * as path from 'path'
import { success, failure } from './utils/res'
import {setInMemoryMacaroon} from './utils/macaroon'
const fs = require('fs')
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../config/app.json'))[env];
/*
"unlock": true,
"encrypted_macaroon_path": "/relay/.lnd/admin.macaroon.enc"
*/
export async function unlocker(req, res): Promise<boolean> {
const { password } = req.body
if(!password) {
failure(res, 'no password')
return false
}
const encMacPath = config.encrypted_macaroon_path
if(!encMacPath) {
failure(res, 'no macaroon path')
return false
}
let hexMac:string
try {
var encMac = fs.readFileSync(config.encrypted_macaroon_path, "utf8");
if(!encMac) {
failure(res, 'no macaroon')
return false
}
console.log("PWD",password,typeof password)
console.log("ENCMAC",encMac,typeof encMac)
const decMac = decryptMacaroon(password, encMac)
if(!decMac) {
failure(res, 'failed to decrypt macaroon')
return false
}
hexMac = base64ToHex(decMac)
} catch(e) {
failure(res, e)
return false
}
if(hexMac) {
setInMemoryMacaroon(hexMac)
success(res, 'success!')
return true
} else {
failure(res, 'failed to set macaroon in memory')
return false
}
}
export async function authModule(req, res, next) {
if (
req.path == '/app' ||
req.path == '/' ||
req.path == '/unlock' ||
req.path == '/info' ||
req.path == '/action' ||
req.path == '/contacts/tokens' ||
req.path == '/latest' ||
req.path.startsWith('/static') ||
req.path == '/contacts/set_dev'
) {
next()
return
}
if (process.env.HOSTING_PROVIDER === 'true') {
// const domain = process.env.INVITE_SERVER
const host = req.headers.origin
console.log('=> host:', host)
const referer = req.headers.referer
console.log('=> referer:', referer)
if (req.path === '/invoices') {
next()
return
}
}
const token = req.headers['x-user-token'] || req.cookies['x-user-token']
if (token == null) {
res.writeHead(401, 'Access invalid for user', { 'Content-Type': 'text/plain' });
res.end('Invalid credentials');
} else {
const user = await models.Contact.findOne({ where: { isOwner: true } })
const hashedToken = crypto.createHash('sha256').update(token).digest('base64');
if (user.authToken == null || user.authToken != hashedToken) {
res.writeHead(401, 'Access invalid for user', { 'Content-Type': 'text/plain' });
res.end('Invalid credentials');
} else {
next();
}
}
}
function decryptMacaroon(password: string, macaroon: string) {
try {
const decrypted = cryptoJS.AES.decrypt(macaroon || '', password).toString(cryptoJS.enc.Base64)
const decryptResult = atob(decrypted)
return decryptResult
} catch (e) {
console.error('cipher mismatch, macaroon decryption failed')
console.error(e)
return ''
}
}
export function base64ToHex (str) {
const raw = atob(str)
let result = ''
for (let i = 0; i < raw.length; i++) {
const hex = raw.charCodeAt(i).toString(16)
result += (hex.length === 2 ? hex : '0' + hex)
}
return result.toUpperCase()
}
const atob = a => Buffer.from(a, 'base64').toString('binary')

5
src/constants.ts

@ -56,6 +56,11 @@ const constants = {
"heartbeat": 26,
"heartbeat_confirmation": 27,
"keysend": 28, // no e2e
"boost": 29,
},
network_types: {
"lightning": 0,
"mqtt": 1,
},
payment_errors: {
"timeout": "Timed Out",

3
src/controllers/bots.ts

@ -176,6 +176,7 @@ export async function receiveBotInstall(payload) {
const sender_pub_key = dat.sender && dat.sender.pub_key
const bot_uuid = dat.bot_uuid
const chat_uuid = dat.chat && dat.chat.uuid
if(!chat_uuid || !sender_pub_key) return console.log('no chat uuid or sender pub key')
const owner = await models.Contact.findOne({ where: { isOwner: true } })
@ -298,6 +299,7 @@ export async function receiveBotRes(payload) {
const bot_name = dat.bot_name
const sender_alias = dat.sender.alias
const date_string = dat.message.date
const network_type = dat.network_type||0
if(!chat_uuid) return console.log('=> receiveBotRes Error no chat_uuid')
@ -339,6 +341,7 @@ export async function receiveBotRes(payload) {
createdAt: date,
updatedAt: date,
senderAlias: sender_alias || 'Bot',
network_type
}
const message = await models.Message.create(msg)
socket.sendJson({

20
src/controllers/chatTribes.ts

@ -114,7 +114,7 @@ export async function joinTribe(req, res){
export async function receiveMemberRequest(payload) {
console.log('=> receiveMemberRequest')
const { sender_pub_key, sender_alias, chat_uuid, chat_members, chat_type, isTribeOwner } = await helpers.parseReceiveParams(payload)
const { sender_pub_key, sender_alias, chat_uuid, chat_members, chat_type, isTribeOwner, network_type } = await helpers.parseReceiveParams(payload)
const chat = await models.Chat.findOne({ where: { uuid: chat_uuid } })
if (!chat) return console.log('no chat')
@ -170,7 +170,8 @@ export async function receiveMemberRequest(payload) {
sender: (theSender && theSender.id) || 0,
messageContent:'', remoteMessageContent:'',
status: constants.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
}
if(isTribe) {
msg.senderAlias = sender_alias
@ -316,7 +317,7 @@ export async function approveOrRejectMember(req,res) {
export async function receiveMemberApprove(payload) {
console.log('=> receiveMemberApprove')
const { owner, chat, chat_name, sender } = await helpers.parseReceiveParams(payload)
const { owner, chat, chat_name, sender, network_type } = await helpers.parseReceiveParams(payload)
if(!chat) return console.log('no chat')
await chat.update({status: constants.chat_statuses.approved})
@ -328,7 +329,8 @@ export async function receiveMemberApprove(payload) {
sender: (sender && sender.id) || 0,
messageContent:'', remoteMessageContent:'',
status: constants.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
}
const message = await models.Message.create(msg)
socket.sendJson({
@ -362,7 +364,7 @@ export async function receiveMemberApprove(payload) {
export async function receiveMemberReject(payload) {
console.log('=> receiveMemberReject')
const { chat, sender, chat_name } = await helpers.parseReceiveParams(payload)
const { chat, sender, chat_name, network_type } = await helpers.parseReceiveParams(payload)
if(!chat) return console.log('no chat')
await chat.update({status: constants.chat_statuses.rejected})
// dang.. nothing really to do here?
@ -374,7 +376,8 @@ export async function receiveMemberReject(payload) {
sender: (sender && sender.id) || 0,
messageContent:'', remoteMessageContent:'',
status: constants.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
}
const message = await models.Message.create(msg)
socket.sendJson({
@ -391,7 +394,7 @@ export async function receiveMemberReject(payload) {
export async function receiveTribeDelete(payload) {
console.log('=> receiveTribeDelete')
const { chat, sender } = await helpers.parseReceiveParams(payload)
const { chat, sender, network_type } = await helpers.parseReceiveParams(payload)
if(!chat) return console.log('no chat')
// await chat.update({status: constants.chat_statuses.rejected})
// update on tribes server too
@ -403,7 +406,8 @@ export async function receiveTribeDelete(payload) {
sender: (sender && sender.id) || 0,
messageContent:'', remoteMessageContent:'',
status: constants.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
}
const message = await models.Message.create(msg)
socket.sendJson({

13
src/controllers/chats.ts

@ -67,7 +67,7 @@ export async function kickChatMember(req, res){
export async function receiveGroupKick(payload) {
console.log('=> receiveGroupKick')
const { chat, sender, date_string } = await helpers.parseReceiveParams(payload)
const { chat, sender, date_string, network_type } = await helpers.parseReceiveParams(payload)
if (!chat) return
// const owner = await models.Contact.findOne({where:{isOwner:true}})
@ -92,6 +92,7 @@ export async function receiveGroupKick(payload) {
messageContent:'', remoteMessageContent:'',
status: constants.statuses.confirmed,
date: date, createdAt: date, updatedAt: date,
network_type
}
const message = await models.Message.create(msg)
@ -323,7 +324,7 @@ export const deleteChat = async (req, res) => {
export async function receiveGroupJoin(payload) {
console.log('=> receiveGroupJoin')
const { sender_pub_key, sender_alias, chat_uuid, chat_members, chat_type, isTribeOwner, date_string } = await helpers.parseReceiveParams(payload)
const { sender_pub_key, sender_alias, chat_uuid, chat_members, chat_type, isTribeOwner, date_string, network_type } = await helpers.parseReceiveParams(payload)
const chat = await models.Chat.findOne({ where: { uuid: chat_uuid } })
if (!chat) return
@ -393,7 +394,8 @@ export async function receiveGroupJoin(payload) {
sender: (theSender && theSender.id) || 0,
messageContent:'', remoteMessageContent:'',
status: constants.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
}
if(isTribe) {
msg.senderAlias = sender_alias
@ -413,7 +415,7 @@ export async function receiveGroupJoin(payload) {
export async function receiveGroupLeave(payload) {
console.log('=> receiveGroupLeave')
const { sender_pub_key, chat_uuid, chat_type, sender_alias, isTribeOwner, date_string } = await helpers.parseReceiveParams(payload)
const { sender_pub_key, chat_uuid, chat_type, sender_alias, isTribeOwner, date_string, network_type } = await helpers.parseReceiveParams(payload)
const chat = await models.Chat.findOne({ where: { uuid: chat_uuid } })
if (!chat) return
@ -454,7 +456,8 @@ export async function receiveGroupLeave(payload) {
sender: (sender && sender.id) || 0,
messageContent:'', remoteMessageContent:'',
status: constants.statuses.confirmed,
date: date, createdAt: date, updatedAt: date
date: date, createdAt: date, updatedAt: date,
network_type
}
if(isTribe) {
msg.senderAlias = sender_alias

1
src/controllers/index.ts

@ -151,4 +151,5 @@ export const ACTIONS = {
[msgtypes.bot_res]: bots.receiveBotRes,
[msgtypes.heartbeat]: confirmations.receiveHeartbeat,
[msgtypes.heartbeat_confirmation]: confirmations.receiveHeartbeatConfirmation,
[msgtypes.boost]: messages.receiveBoost,
}

4
src/controllers/invoices.ts

@ -221,6 +221,7 @@ export const receiveInvoice = async (payload) => {
const total_spent = 1
const dat = payload.content || payload
const payment_request = dat.message.invoice
const network_type = dat.network_type||0
var date = new Date();
date.setMilliseconds(0)
@ -246,7 +247,8 @@ export const receiveInvoice = async (payload) => {
date: new Date(invoiceDate),
status: constants.statuses.pending,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type: network_type,
}
const isTribe = chat_type===constants.chat_types.tribe
if(isTribe) {

24
src/controllers/media.ts

@ -195,7 +195,8 @@ export const purchase = async (req, res) => {
mediaToken: media_token,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type: constants.network_types.lightning
})
const msg={
@ -206,6 +207,7 @@ export const purchase = async (req, res) => {
chat: {...chat.dataValues, contactIds:[contact_id]},
sender: owner,
type: constants.message_types.purchase,
realSatsContactId: contact_id, // ALWAYS will be keysend, so doesnt matter if tribe owner or not
message: msg,
amount: amount,
success: async (data) => {
@ -224,7 +226,7 @@ export const receivePurchase = async (payload) => {
var date = new Date();
date.setMilliseconds(0)
const {owner, sender, chat, amount, mediaToken, msg_uuid, chat_type, skip_payment_processing, purchaser_id} = await helpers.parseReceiveParams(payload)
const {owner, sender, chat, amount, mediaToken, msg_uuid, chat_type, skip_payment_processing, purchaser_id, network_type} = await helpers.parseReceiveParams(payload)
if(!owner || !sender || !chat) {
return console.log('=> group chat not found!')
}
@ -238,7 +240,8 @@ export const receivePurchase = async (payload) => {
mediaToken: mediaToken,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
})
socket.sendJson({
type: 'purchase',
@ -351,7 +354,7 @@ export const receivePurchaseAccept = async (payload) => {
var date = new Date();
date.setMilliseconds(0)
const {owner, sender, chat, mediaToken, mediaKey, mediaType, originalMuid} = await helpers.parseReceiveParams(payload)
const {owner, sender, chat, mediaToken, mediaKey, mediaType, originalMuid, network_type} = await helpers.parseReceiveParams(payload)
if(!owner || !sender || !chat) {
return console.log('=> no group chat!')
}
@ -383,7 +386,8 @@ export const receivePurchaseAccept = async (payload) => {
originalMuid:originalMuid||'',
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
})
socket.sendJson({
type: 'purchase_accept',
@ -395,7 +399,7 @@ export const receivePurchaseDeny = async (payload) => {
console.log('=> receivePurchaseDeny')
var date = new Date()
date.setMilliseconds(0)
const {owner, sender, chat, amount, mediaToken} = await helpers.parseReceiveParams(payload)
const {owner, sender, chat, amount, mediaToken, network_type} = await helpers.parseReceiveParams(payload)
if(!owner || !sender || !chat) {
return console.log('=> no group chat!')
}
@ -410,7 +414,8 @@ export const receivePurchaseDeny = async (payload) => {
mediaToken,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
})
socket.sendJson({
type: 'purchase_deny',
@ -424,7 +429,7 @@ export const receiveAttachment = async (payload) => {
var date = new Date();
date.setMilliseconds(0)
const {owner, sender, chat, mediaToken, mediaKey, mediaType, content, msg_id, chat_type, sender_alias, msg_uuid, reply_uuid} = await helpers.parseReceiveParams(payload)
const {owner, sender, chat, mediaToken, mediaKey, mediaType, content, msg_id, chat_type, sender_alias, msg_uuid, reply_uuid, network_type} = await helpers.parseReceiveParams(payload)
if(!owner || !sender || !chat) {
return console.log('=> no group chat!')
}
@ -436,7 +441,8 @@ export const receiveAttachment = async (payload) => {
sender: sender.id,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
}
if(content) msg.messageContent = content
if(mediaToken) msg.mediaToken = mediaToken

88
src/controllers/messages.ts

@ -157,8 +157,12 @@ export const sendMessage = async (req, res) => {
remote_text_map,
amount,
reply_uuid,
boost,
} = req.body
let msgtype = constants.message_types.message
if(boost) msgtype = constants.message_types.boost
var date = new Date()
date.setMilliseconds(0)
@ -169,11 +173,26 @@ export const sendMessage = async (req, res) => {
recipient_id: contact_id,
})
let realSatsContactId
// IF BOOST NEED TO SEND ACTUAL SATS TO OG POSTER
const isTribe = chat.type===constants.chat_types.tribe
if(reply_uuid && boost && amount) {
const ogMsg = await models.Message.findOne({where:{
uuid: reply_uuid,
}})
if(ogMsg && ogMsg.sender) {
realSatsContactId = ogMsg.sender
}
}
const hasRealAmount = amount && amount>constants.min_sat_amount
const remoteMessageContent = remote_text_map?JSON.stringify(remote_text_map) : remote_text
const uuid = short.generate()
const msg:{[k:string]:any}={
chatId: chat.id,
uuid: short.generate(),
type: constants.message_types.message,
uuid: uuid,
type: msgtype,
sender: owner.id,
amount: amount||0,
date: date,
@ -182,6 +201,9 @@ export const sendMessage = async (req, res) => {
status: constants.statuses.pending,
createdAt: date,
updatedAt: date,
network_type: (!isTribe || hasRealAmount || realSatsContactId) ?
constants.network_types.lightning :
constants.network_types.mqtt
}
if(reply_uuid) msg.replyUuid=reply_uuid
// console.log(msg)
@ -195,24 +217,28 @@ export const sendMessage = async (req, res) => {
content: remote_text_map || remote_text || text
}
if(reply_uuid) msgToSend.replyUuid=reply_uuid
network.sendMessage({
const sendMessageParams:{[k:string]:any} = {
chat: chat,
sender: owner,
amount: amount||0,
type: constants.message_types.message,
type: msgtype,
message: msgToSend,
})
}
if(realSatsContactId) sendMessageParams.realSatsContactId = realSatsContactId
// final send
network.sendMessage(sendMessageParams)
}
export const receiveMessage = async (payload) => {
// console.log('received message', { payload })
const total_spent = 1
const {owner, sender, chat, content, remote_content, msg_id, chat_type, sender_alias, msg_uuid, date_string, reply_uuid} = await helpers.parseReceiveParams(payload)
const {owner, sender, chat, content, remote_content, msg_id, chat_type, sender_alias, msg_uuid, date_string, reply_uuid, amount, network_type} = await helpers.parseReceiveParams(payload)
if(!owner || !sender || !chat) {
return console.log('=> no group chat!')
}
const text = content
const text = content||''
var date = new Date();
date.setMilliseconds(0)
@ -222,13 +248,14 @@ export const receiveMessage = async (payload) => {
chatId: chat.id,
uuid: msg_uuid,
type: constants.message_types.message,
asciiEncodedTotal: total_spent,
sender: sender.id,
date: date,
amount: amount||0,
messageContent: text,
createdAt: date,
updatedAt: date,
status: constants.statuses.received
status: constants.statuses.received,
network_type: network_type,
}
const isTribe = chat_type===constants.chat_types.tribe
if(isTribe) {
@ -238,8 +265,6 @@ export const receiveMessage = async (payload) => {
if(reply_uuid) msg.replyUuid = reply_uuid
const message = await models.Message.create(msg)
// console.log('saved message', message.dataValues)
socket.sendJson({
type: 'message',
response: jsonUtils.messageToJson(message, chat, sender)
@ -251,6 +276,45 @@ export const receiveMessage = async (payload) => {
sendConfirmation({ chat:theChat, sender: owner, msg_id })
}
export const receiveBoost = async (payload) => {
const {owner, sender, chat, content, remote_content, chat_type, sender_alias, msg_uuid, date_string, reply_uuid, amount, network_type} = await helpers.parseReceiveParams(payload)
console.log('received boost ' +amount+ ' sats on network:', network_type)
if(!owner || !sender || !chat) {
return console.log('=> no group chat!')
}
const text = content
var date = new Date();
date.setMilliseconds(0)
if(date_string) date=new Date(date_string)
const msg:{[k:string]:any} = {
chatId: chat.id,
uuid: msg_uuid,
type: constants.message_types.boost,
sender: sender.id,
date: date,
amount: amount||0,
messageContent: text,
createdAt: date,
updatedAt: date,
status: constants.statuses.received,
network_type
}
const isTribe = chat_type===constants.chat_types.tribe
if(isTribe) {
msg.senderAlias = sender_alias
if(remote_content) msg.remoteMessageContent=remote_content
}
if(reply_uuid) msg.replyUuid = reply_uuid
const message = await models.Message.create(msg)
socket.sendJson({
type: 'boost',
response: jsonUtils.messageToJson(message, chat, sender)
})
}
export const receiveDeleteMessage = async (payload) => {
console.log('=> received delete message')
const {owner, sender, chat, chat_type, msg_uuid} = await helpers.parseReceiveParams(payload)

37
src/controllers/payment.ts

@ -63,7 +63,8 @@ export const sendPayment = async (req, res) => {
amountMsat: parseFloat(amount) * 1000,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type: constants.network_types.lightning,
}
if(text) msg.messageContent = text
if(remote_text) msg.remoteMessageContent = remote_text
@ -128,7 +129,7 @@ export const receivePayment = async (payload) => {
var date = new Date();
date.setMilliseconds(0)
const {owner, sender, chat, amount, content, mediaType, mediaToken, chat_type, sender_alias, msg_uuid, reply_uuid} = await helpers.parseReceiveParams(payload)
const {owner, sender, chat, amount, content, mediaType, mediaToken, chat_type, sender_alias, msg_uuid, reply_uuid, network_type} = await helpers.parseReceiveParams(payload)
if(!owner || !sender || !chat) {
return console.log('=> no group chat!')
}
@ -142,7 +143,8 @@ export const receivePayment = async (payload) => {
amountMsat: parseFloat(amount) * 1000,
date: date,
createdAt: date,
updatedAt: date
updatedAt: date,
network_type
}
if(content) msg.messageContent = content
if(mediaType) msg.mediaType = mediaType
@ -172,15 +174,26 @@ export const listPayments = async (req, res) => {
try {
const msgs = await models.Message.findAll({
where:{
type: {[Op.or]: [
constants.message_types.message, // for example /loopout message
constants.message_types.payment,
constants.message_types.direct_payment,
constants.message_types.keysend,
]},
amount: {
[Op.gt]: MIN_VAL // greater than
}
[Op.or]: [
{
type: {[Op.or]: [
constants.message_types.payment,
constants.message_types.direct_payment,
constants.message_types.keysend,
constants.message_types.purchase,
]}
},
{
type: {[Op.or]: [
constants.message_types.message, // paid bot msgs, or price_per_message msgs
constants.message_types.boost,
]},
amount: {
[Op.gt]: MIN_VAL // greater than
},
network_type: constants.network_types.lightning
}
],
},
order: [['createdAt', 'desc']],
limit,

17
src/grpc/index.ts

@ -7,9 +7,11 @@ import {loadLightning} from '../utils/lightning'
import * as network from '../network'
import * as moment from 'moment'
import constants from '../constants'
import {tryToUnlockLND} from '../utils/unlock'
const ERR_CODE_UNAVAILABLE = 14
const ERR_CODE_STREAM_REMOVED = 2
const ERR_CODE_UNIMPLEMENTED = 12 // locked
export function subscribeInvoices(parseKeysendInvoice) {
return new Promise(async(resolve,reject)=>{
@ -95,7 +97,7 @@ export function subscribeInvoices(parseKeysendInvoice) {
}
});
call.on('status', function(status) {
console.log("Status", status);
console.log("Status", status.code, status);
// The server is unavailable, trying to reconnect.
if (status.code == ERR_CODE_UNAVAILABLE || status.code == ERR_CODE_STREAM_REMOVED) {
i = 0
@ -129,18 +131,23 @@ export function subscribeInvoices(parseKeysendInvoice) {
var i = 0
var ctx = 0
async function reconnectToLND(innerCtx:number){
export async function reconnectToLND(innerCtx:number, callback?:Function) {
ctx = innerCtx
i++
console.log(`=> [lnd] reconnecting... attempt #${i}`)
const now = moment().format('YYYY-MM-DD HH:mm:ss').trim();
console.log(`=> ${now} [lnd] reconnecting... attempt #${i}`)
try {
await network.initGrpcSubscriptions()
const now = moment().format('YYYY-MM-DD HH:mm:ss').trim();
console.log(`=> [lnd] reconnected! ${now}`)
console.log(`=> [lnd] connected! ${now}`)
if(callback) callback()
} catch(e) {
if(e.code===ERR_CODE_UNIMPLEMENTED) {
await tryToUnlockLND()
}
setTimeout(async()=>{ // retry each 2 secs
if(ctx===innerCtx) { // if another retry fires, then this will not run
await reconnectToLND(innerCtx)
await reconnectToLND(innerCtx, callback)
}
},2000)
}

3
src/helpers.ts

@ -154,6 +154,7 @@ export async function parseReceiveParams(payload) {
const skip_payment_processing = dat.message.skipPaymentProcessing
const reply_uuid = dat.message.replyUuid
const purchaser_id = dat.message.purchaser
const network_type = dat.network_type||0
const isTribeOwner = dat.isTribeOwner?true:false
const isConversation = !chat_type || (chat_type && chat_type == constants.chat_types.conversation)
@ -176,7 +177,7 @@ export async function parseReceiveParams(payload) {
}
chat = await models.Chat.findOne({ where: { uuid: chat_uuid } })
}
return { owner, sender, chat, sender_pub_key, sender_alias, isTribeOwner, chat_uuid, amount, content, mediaToken, mediaKey, mediaType, originalMuid, chat_type, msg_id, chat_members, chat_name, chat_host, chat_key, remote_content, msg_uuid, date_string, reply_uuid, skip_payment_processing, purchaser_id, sender_photo_url }
return { owner, sender, chat, sender_pub_key, sender_alias, isTribeOwner, chat_uuid, amount, content, mediaToken, mediaKey, mediaType, originalMuid, chat_type, msg_id, chat_members, chat_name, chat_host, chat_key, remote_content, msg_uuid, date_string, reply_uuid, skip_payment_processing, purchaser_id, sender_photo_url, network_type }
}
async function asyncForEach(array, callback) {

3
src/models/ts/message.ts

@ -92,4 +92,7 @@ export default class Message extends Model<Message> {
@Column
replyUuid: string
@Column(DataType.INTEGER)
network_type: number
}

2
src/network/modify.ts

@ -67,6 +67,7 @@ export async function purchaseFromOriginalSender(payload, chat, purchaser){
sender: owner,
type: constants.message_types.purchase,
amount: amount,
realSatsContactId: mediaKey.sender,
message: {
mediaToken: mt,
skipPaymentProcessing: true,
@ -87,6 +88,7 @@ export async function purchaseFromOriginalSender(payload, chat, purchaser){
role: constants.chat_roles.reader,
},
type: constants.message_types.purchase,
realSatsContactId: ogmsg.sender,
message: msg,
amount: amount,
success: ()=>{},

58
src/network/receive.ts

@ -25,13 +25,13 @@ const msgtypes = constants.message_types
export const typesToForward=[
msgtypes.message, msgtypes.group_join, msgtypes.group_leave,
msgtypes.attachment, msgtypes.delete,
msgtypes.attachment, msgtypes.delete, msgtypes.boost,
]
const typesToModify=[
msgtypes.attachment
]
const typesThatNeedPricePerMessage = [
msgtypes.message, msgtypes.attachment
msgtypes.message, msgtypes.attachment, msgtypes.boost
]
export const typesToReplay=[ // should match typesToForward
msgtypes.message,
@ -121,7 +121,22 @@ async function onReceive(payload){
if(ogMsg) doAction = true
}
}
if(doAction) forwardMessageToTribe(payload, senderContact)
// forward boost sats to recipient
let realSatsContactId = null
let amtToForward = 0
if(payload.type===msgtypes.boost && payload.message.replyUuid) {
const ogMsg = await models.Message.findOne({where:{
uuid: payload.message.replyUuid,
}})
if(ogMsg && ogMsg.sender && ogMsg.sender!==1) {
const theAmtToForward = payload.message.amount - (chat.pricePerMessage||0) - (chat.escrowAmount||0)
if(theAmtToForward>0) {
realSatsContactId = ogMsg.sender
amtToForward = theAmtToForward
}
}
}
if(doAction) forwardMessageToTribe(payload, senderContact, realSatsContactId, amtToForward)
else console.log('=> insufficient payment for this action')
}
if(isTribeOwner && payload.type===msgtypes.purchase) {
@ -152,7 +167,8 @@ async function onReceive(payload){
async function doTheAction(data){
let payload = data
if(payload.isTribeOwner) {
if(payload.isTribeOwner) { // this is only for storing locally, my own messages as tribe owner
// actual encryption for tribe happens in personalizeMessage
const ogContent = data.message && data.message.content
// const ogMediaKey = data.message && data.message.mediaKey
/* decrypt and re-encrypt with phone's pubkey for storage */
@ -170,7 +186,7 @@ async function doTheAction(data){
}
}
async function forwardMessageToTribe(ogpayload, sender){
async function forwardMessageToTribe(ogpayload, sender, realSatsContactId, amtToForwardToRealSatsContactId){
// console.log('forwardMessageToTribe')
const chat = await models.Chat.findOne({where:{uuid:ogpayload.chat.uuid}})
@ -195,8 +211,10 @@ async function forwardMessageToTribe(ogpayload, sender){
...payload.sender&&payload.sender.alias && {alias:payload.sender.alias},
role: constants.chat_roles.reader,
},
amount: amtToForwardToRealSatsContactId||0,
chat: chat,
skipPubKey: payload.sender.pub_key,
realSatsContactId,
success: ()=>{},
receive: ()=>{},
isForwarded: true,
@ -218,6 +236,7 @@ export async function initTribesSubscriptions(){
const msg = message.toString()
// check topic is signed by sender?
const payload = await parseAndVerifyPayload(msg)
payload.network_type = constants.network_types.mqtt
onReceive(payload)
} catch(e){}
})
@ -261,13 +280,20 @@ async function parseAndVerifyPayload(data){
}
}
async function saveAnonymousKeysend(response, memo) {
async function saveAnonymousKeysend(response, memo, sender_pubkey) {
let sender = 0
if(sender_pubkey) {
const theSender = await models.Contact.findOne({ where: { publicKey: sender_pubkey }})
if(theSender && theSender.id) {
sender = theSender.id
}
}
let settleDate = parseInt(response['settle_date'] + '000');
const amount = response['amt_paid_sat'] || 0
const msg = await models.Message.create({
chatId: 0,
type: constants.message_types.keysend,
sender: 0,
sender,
amount,
amountMsat: response['amt_paid_msat'],
paymentHash: '',
@ -275,7 +301,8 @@ async function saveAnonymousKeysend(response, memo) {
messageContent: memo||'',
status: constants.statuses.confirmed,
createdAt: new Date(settleDate),
updatedAt: new Date(settleDate)
updatedAt: new Date(settleDate),
network_type: constants.network_types.lightning
})
socket.sendJson({
type:'keysend',
@ -291,24 +318,26 @@ export async function parseKeysendInvoice(i){
// "keysend" type is NOT encrypted
// and should be saved even if there is NO content
let isAnonymous = false
let isKeysendType = false
let memo = ''
let sender_pubkey;
if(data){
try {
const payload = parsePayload(data)
if(payload && payload.type===constants.message_types.keysend) {
isAnonymous = true
isKeysendType = true
memo = payload.message && payload.message.content
sender_pubkey = payload.sender && payload.sender.pub_key
}
} catch(e) {} // err could be a threaded TLV
} else {
isAnonymous = true
isKeysendType = true
}
if(isAnonymous) {
if(isKeysendType) {
if(!memo) {
sendNotification(-1, '', 'keysend', value||0)
}
saveAnonymousKeysend(i, memo)
saveAnonymousKeysend(i, memo, sender_pubkey)
return
}
@ -325,7 +354,8 @@ export async function parseKeysendInvoice(i){
const dat = payload
if(value && dat && dat.message){
dat.message.amount = value // ADD IN TRUE VALUE
}
}
dat.network_type = constants.network_types.lightning
onReceive(dat)
}
}

7
src/network/send.ts

@ -11,7 +11,7 @@ import constants from '../constants'
type NetworkType = undefined | 'mqtt' | 'lightning'
export async function sendMessage(params) {
const { type, chat, message, sender, amount, success, failure, skipPubKey, isForwarded } = params
const { type, chat, message, sender, amount, success, failure, skipPubKey, isForwarded, realSatsContactId } = params
if(!chat || !sender) return
const isTribe = chat.type===constants.chat_types.tribe
@ -83,9 +83,10 @@ export async function sendMessage(params) {
console.log('-> sending to ', contact.id, destkey)
let mqttTopic = networkType==='mqtt' ? `${destkey}/${chatUUID}` : ''
// sending a payment to one subscriber, buying a pic from OG poster
if(isTribeOwner && contactIds.length===1 && amount && amount>constants.min_sat_amount && msg.type===constants.message_types.purchase) {
// or boost to og poster
if(isTribeOwner && amount && realSatsContactId===contactId) {
mqttTopic = '' // FORCE KEYSEND!!!
}

25
src/utils/lightning.ts

@ -6,6 +6,7 @@ import * as sha from 'js-sha256'
import * as crypto from 'crypto'
import * as path from 'path'
import constants from '../constants'
import {getMacaroon} from './macaroon'
// var protoLoader = require('@grpc/proto-loader')
const env = process.env.NODE_ENV || 'development';
@ -20,8 +21,7 @@ var walletUnlocker = <any> null;
const loadCredentials = () => {
var lndCert = fs.readFileSync(config.tls_location);
var sslCreds = grpc.credentials.createSsl(lndCert);
var m = fs.readFileSync(config.macaroon_location);
var macaroon = m.toString('hex');
var macaroon = getMacaroon()
var metadata = new grpc.Metadata()
metadata.add('macaroon', macaroon)
var macaroonCreds = grpc.credentials.createFromMetadataGenerator((_args, callback) => {
@ -50,7 +50,7 @@ const loadLightning = () => {
} else {
try{
var credentials = loadCredentials()
var lnrpcDescriptor = grpc.load("rpc.proto");
var lnrpcDescriptor = grpc.load("proto/rpc.proto");
var lnrpc: any = lnrpcDescriptor.lnrpc
lightningClient = new lnrpc.Lightning(config.node_ip + ':' + config.lnd_port, credentials);
return lightningClient
@ -66,7 +66,7 @@ const loadWalletUnlocker = () => {
} else {
var credentials = loadCredentials()
try{
var lnrpcDescriptor = grpc.load("rpc.proto");
var lnrpcDescriptor = grpc.load("proto/walletunlocker.proto");
var lnrpc: any = lnrpcDescriptor.lnrpc
walletUnlocker = new lnrpc.WalletUnlocker(config.node_ip + ':' + config.lnd_port, credentials);
return walletUnlocker
@ -76,6 +76,22 @@ const loadWalletUnlocker = () => {
}
}
const unlockWallet = async (pwd:string) => {
return new Promise(async function(resolve, reject) {
let wu = await loadWalletUnlocker()
wu.unlockWallet(
{ wallet_password: ByteBuffer.fromUTF8(pwd) },
(err, response) => {
if(err) {
reject(err)
return
}
resolve(response)
}
)
})
}
const getHeaders = (req) => {
return {
"X-User-Token": req.headers['x-user-token'],
@ -455,4 +471,5 @@ export {
queryRoute,
listChannels,
channelBalance,
unlockWallet,
}

20
src/utils/macaroon.ts

@ -0,0 +1,20 @@
import * as fs from 'fs'
import * as path from 'path'
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../../config/app.json'))[env]
let inMemoryMacaroon: string = ''; // hex encoded
export function getMacaroon() {
if(config.unlock) {
return inMemoryMacaroon
} else {
const m = fs.readFileSync(config.macaroon_location)
return m.toString('hex');
}
}
export function setInMemoryMacaroon(mac:string) {
inMemoryMacaroon = mac
}

2
src/utils/nodeinfo.ts

@ -109,7 +109,7 @@ function nodeinfo(){
export {nodeinfo}
async function isClean(){
export async function isClean(){
// has owner but with no auth token
const cleanOwner = await models.Contact.findOne({ where: { isOwner: true, authToken: null }})
const msgs = await models.Message.count()

13
src/utils/setup.ts

@ -7,6 +7,7 @@ import password from '../utils/password'
import * as path from 'path'
import { checkTag, checkCommitHash } from '../utils/gitinfo'
import * as fs from 'fs';
import {isClean} from './nodeinfo'
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../../config/app.json'))[env]
@ -20,7 +21,7 @@ const setupDatabase = async () => {
await sequelize.sync()
console.log("=> [db] done syncing")
} catch (e) {
console.log("db sync failed", e)
// console.log("db sync failed", e)
}
await migrate()
setupOwnerContact()
@ -37,6 +38,8 @@ async function setVersion() {
async function migrate() {
addTableColumn('sphinx_messages', 'network_type', 'INTEGER')
addTableColumn('sphinx_chats', 'meta')
addTableColumn('sphinx_contacts', 'tip_amount', 'BIGINT')
@ -225,9 +228,13 @@ async function printQR() {
// if(!theIP.includes(":")) theIP = public_ip+':3001'
const b64 = Buffer.from(`ip::${theIP}::${password || ''}`).toString('base64')
console.log('Scan this QR in Sphinx app:')
console.log(b64)
console.log('>>', b64)
connectionStringFile(b64)
const clean = await isClean()
if(!clean) return // skip it if already setup!
console.log('Scan this QR in Sphinx app:')
QRCode.toString(b64, { type: 'terminal' }, function (err, url) {
console.log(url)
})

2
src/utils/signer.ts

@ -16,7 +16,7 @@ export const loadSigner = () => {
} else {
try{
var credentials = loadCredentials()
var lnrpcDescriptor = grpc.load("signer.proto");
var lnrpcDescriptor = grpc.load("proto/signer.proto");
var signer: any = lnrpcDescriptor.signrpc
signerClient = new signer.Signer(config.node_ip + ':' + config.lnd_port, credentials);
return signerClient

46
src/utils/unlock.ts

@ -0,0 +1,46 @@
import * as path from 'path'
import { unlockWallet } from './lightning'
const fs = require('fs')
const readline = require('readline');
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../../config/app.json'))[env]
console.log(JSON.stringify(config,null,2))
/*
"lnd_pwd_path": "/relay/.lnd/.lndpwd"
*/
export async function tryToUnlockLND() {
const p = config.lnd_pwd_path
if (!p) return
console.log('==>',p)
var pwd = await getFirstLine(config.lnd_pwd_path);
if(!pwd) return
console.log('==>',pwd,typeof pwd)
try {
await unlockWallet(String(pwd))
} catch(e) {
console.log('[unlock] Error:',e)
}
}
async function getFirstLine(pathToFile) {
const readable = fs.createReadStream(pathToFile);
const reader = readline.createInterface({ input: readable });
const line = await new Promise((resolve) => {
reader.on('line', (line) => {
reader.close();
resolve(line);
});
});
readable.close();
return line;
}
Loading…
Cancel
Save