fixed coordinates, orderAck, lnd streams

This commit is contained in:
hatim boufnichel 2021-02-27 20:58:45 +01:00
parent 470fe36b29
commit 1383116935
4 changed files with 37 additions and 143 deletions

View file

@ -1,63 +0,0 @@
/**
* @format
*/
const Common = require('shock-common')
const mapValues = require('lodash/mapValues')
const pickBy = require('lodash/pickBy')
const Bluebird = require('bluebird')
const Logger = require('winston')
const Key = require('../services/gunDB/contact-api/key')
const { getUser, getMySecret, mySEA } = require('./gunDB/Mediator')
/**
* @param {string} coordID
* @param {Common.Coordinate} data
* @returns {Promise<void>}
*/
module.exports.writeCoordinate = async (coordID, data) => {
if (coordID !== data.id) {
throw new Error('CoordID must be equal to data.id')
}
try {
/**
* Because there are optional properties, typescript can also allow them
* to be specified but with a value of `undefined`. Filter out these.
* @type {Record<string, number|boolean|string>}
*/
const sanitizedData = pickBy(data, v => typeof v !== 'undefined')
const encData = await Bluebird.props(
mapValues(sanitizedData, v => {
return mySEA.encrypt(v, getMySecret())
})
)
getUser()
.get(Key.COORDINATES)
.get(coordID)
.put(encData, ack => {
if (ack.err && typeof ack.err !== 'number') {
Logger.info(
`Error writting corrdinate, coordinate id: ${coordID}, data: ${JSON.stringify(
data,
null,
2
)}`
)
Logger.error(ack.err)
}
})
} catch (e) {
Logger.info(
`Error writing coordinate, coordinate id: ${coordID}, data: ${JSON.stringify(
data,
null,
2
)}`
)
Logger.error(e.message)
}
}

View file

@ -11,8 +11,7 @@ const { ErrorCode } = Constants
const { const {
sendPaymentV2Invoice, sendPaymentV2Invoice,
decodePayReq, decodePayReq
myLNDPub
} = require('../../../utils/lightningServices/v2') } = require('../../../utils/lightningServices/v2')
/** /**
@ -261,7 +260,7 @@ const acceptRequest = async (
newlyCreatedOutgoingFeedID, newlyCreatedOutgoingFeedID,
ourSecret ourSecret
) )
//why await if you dont need the response?
await /** @type {Promise<void>} */ (new Promise((res, rej) => { await /** @type {Promise<void>} */ (new Promise((res, rej) => {
gun gun
.get(Key.HANDSHAKE_NODES) .get(Key.HANDSHAKE_NODES)
@ -359,7 +358,7 @@ const generateHandshakeAddress = async () => {
} }
}) })
})) }))
//why await if you dont need the response?
await /** @type {Promise<void>} */ (new Promise((res, rej) => { await /** @type {Promise<void>} */ (new Promise((res, rej) => {
gun gun
.get(Key.HANDSHAKE_NODES) .get(Key.HANDSHAKE_NODES)
@ -644,7 +643,7 @@ const sendHandshakeRequest = async (recipientPublicKey, gun, user, SEA) => {
handshakeAddress: await SEA.encrypt(currentHandshakeAddress, mySecret), handshakeAddress: await SEA.encrypt(currentHandshakeAddress, mySecret),
timestamp timestamp
} }
//why await if you dont need the response?
await /** @type {Promise<void>} */ (new Promise((res, rej) => { await /** @type {Promise<void>} */ (new Promise((res, rej) => {
//@ts-ignore //@ts-ignore
user.get(Key.STORED_REQS).set(storedReq, ack => { user.get(Key.STORED_REQS).set(storedReq, ack => {
@ -1406,10 +1405,9 @@ const createPostNew = async (tags, title, content) => {
* @param {string[]} tags * @param {string[]} tags
* @param {string} title * @param {string} title
* @param {Common.Schema.ContentItem[]} content * @param {Common.Schema.ContentItem[]} content
* @param {ISEA} SEA
* @returns {Promise<Common.Schema.Post>} * @returns {Promise<Common.Schema.Post>}
*/ */
const createPost = async (tags, title, content, SEA) => { const createPost = async (tags, title, content) => {
if (content.length === 0) { if (content.length === 0) {
throw new Error(`A post must contain at least one paragraph/image/video`) throw new Error(`A post must contain at least one paragraph/image/video`)
} }
@ -1486,7 +1484,7 @@ const createPost = async (tags, title, content, SEA) => {
) )
})) }))
const [postID, newPost] = await createPostNew(tags, title, content, SEA) const [postID, newPost] = await createPostNew(tags, title, content)
await Common.makePromise((res, rej) => { await Common.makePromise((res, rej) => {
require('../Mediator') require('../Mediator')
@ -1595,7 +1593,7 @@ const follow = async (publicKey, isPrivate) => {
status: 'ok', status: 'ok',
user: publicKey user: publicKey
} }
//why await if you dont need the response?
await /** @type {Promise<void>} */ (new Promise((res, rej) => { await /** @type {Promise<void>} */ (new Promise((res, rej) => {
require('../Mediator') require('../Mediator')
.getUser() .getUser()

View file

@ -2,15 +2,12 @@
* @format * @format
*/ */
// @ts-check // @ts-check
const Gun = require('gun')
const { performance } = require('perf_hooks')
const logger = require('winston') const logger = require('winston')
const isFinite = require('lodash/isFinite') const isFinite = require('lodash/isFinite')
const isNumber = require('lodash/isNumber') const isNumber = require('lodash/isNumber')
const isNaN = require('lodash/isNaN') const isNaN = require('lodash/isNaN')
const Common = require('shock-common') const Common = require('shock-common')
const crypto = require('crypto') const crypto = require('crypto')
// @ts-expect-error TODO fix this
const fetch = require('node-fetch') const fetch = require('node-fetch')
const { const {
Constants: { ErrorCode }, Constants: { ErrorCode },
@ -18,11 +15,6 @@ const {
} = Common } = Common
const SchemaManager = require('../../../schema') const SchemaManager = require('../../../schema')
const LightningServices = require('../../../../utils/lightningServices') const LightningServices = require('../../../../utils/lightningServices')
const {
addInvoice,
myLNDPub
} = require('../../../../utils/lightningServices/v2')
const { writeCoordinate } = require('../../../coordinates')
const Key = require('../key') const Key = require('../key')
const Utils = require('../utils') const Utils = require('../utils')
const { gunUUID } = require('../../../../utils') const { gunUUID } = require('../../../../utils')
@ -65,6 +57,28 @@ const ordersProcessed = new Set()
let currentOrderAddr = '' let currentOrderAddr = ''
/**
* @param {InvoiceRequest} invoiceReq
* @returns {Promise<InvoiceResponse>}
*/
const _addInvoice = invoiceReq =>
new Promise((resolve, rej) => {
const {
services: { lightning }
} = LightningServices
lightning.addInvoice(invoiceReq, (
/** @type {any} */ error,
/** @type {InvoiceResponse} */ response
) => {
if (error) {
rej(error)
} else {
resolve(response)
}
})
})
/** /**
* @param {string} addr * @param {string} addr
* @param {ISEA} SEA * @param {ISEA} SEA
@ -150,12 +164,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
`onOrders() -> Will now create an invoice : ${JSON.stringify(invoiceReq)}` `onOrders() -> Will now create an invoice : ${JSON.stringify(invoiceReq)}`
) )
const invoice = await addInvoice( const invoice = await _addInvoice(invoiceReq)
invoiceReq.value,
invoiceReq.memo,
true,
invoiceReq.expiry
)
logger.info( logger.info(
'onOrders() -> Successfully created the invoice, will now encrypt it' 'onOrders() -> Successfully created the invoice, will now encrypt it'
@ -166,14 +175,12 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
logger.info( logger.info(
`onOrders() -> Will now place the encrypted invoice in order to response usergraph: ${addr}` `onOrders() -> Will now place the encrypted invoice in order to response usergraph: ${addr}`
) )
// @ts-expect-error const ackNode = gunUUID()
const ackNode = Gun.text.random()
/** @type {import('shock-common').Schema.OrderResponse} */ /** @type {import('shock-common').Schema.OrderResponse} */
const orderResponse = { const orderResponse = {
response: encInvoice, response: encInvoice,
type: 'invoice', type: 'invoice',
//@ts-expect-error
ackNode ackNode
} }
@ -221,8 +228,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
} }
getUser() getUser()
.get('postToTipCount') .get('postToTipCount')
// CAST: Checked above. .get(postID)
.get(/** @type {string} */ (order.ackInfo))
.set(null) // each item in the set is a tip .set(null) // each item in the set is a tip
break break
} }
@ -308,7 +314,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
) )
) )
} else { } else {
res() res(null)
} }
}) })
}) })
@ -340,6 +346,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
seed_token: seedToken, seed_token: seedToken,
wallet_token: token wallet_token: token
} }
//@ts-expect-error
const res = await fetch(`${seedUrl}/api/enroll_token`, { const res = await fetch(`${seedUrl}/api/enroll_token`, {
method: 'POST', method: 'POST',
headers: { headers: {
@ -373,7 +380,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
) )
) )
} else { } else {
res() res(null)
} }
}) })
}) })

View file

@ -6,8 +6,6 @@ const logger = require('winston')
const Common = require('shock-common') const Common = require('shock-common')
const Ramda = require('ramda') const Ramda = require('ramda')
const { writeCoordinate } = require('../../services/coordinates')
const lightningServices = require('./lightning-services') const lightningServices = require('./lightning-services')
/** /**
* @typedef {import('./types').PaymentV2} PaymentV2 * @typedef {import('./types').PaymentV2} PaymentV2
@ -237,28 +235,12 @@ const decodePayReq = payReq =>
) )
}) })
/**
* @returns {Promise<string>}
*/
const myLNDPub = () =>
Common.makePromise((res, rej) => {
const { lightning } = lightningServices.getServices()
lightning.getInfo({}, (err, data) => {
if (err) {
rej(new Error(err.message))
} else {
res(data.identity_pubkey)
}
})
})
/** /**
* aklssjdklasd * aklssjdklasd
* @param {SendPaymentV2Request} sendPaymentRequest * @param {SendPaymentV2Request} sendPaymentRequest
* @returns {Promise<PaymentV2>} * @returns {Promise<PaymentV2>}
*/ */
const sendPaymentV2 = async sendPaymentRequest => { const sendPaymentV2 = sendPaymentRequest => {
const { const {
services: { router } services: { router }
} = lightningServices } = lightningServices
@ -269,10 +251,7 @@ const sendPaymentV2 = async sendPaymentRequest => {
) )
} }
/** return Common.makePromise((res, rej) => {
* @type {import("./types").PaymentV2}
*/
const paymentV2 = await Common.makePromise((res, rej) => {
const stream = router.sendPaymentV2(sendPaymentRequest) const stream = router.sendPaymentV2(sendPaymentRequest)
stream.on( stream.on(
@ -311,33 +290,6 @@ const sendPaymentV2 = async sendPaymentRequest => {
} }
) )
}) })
/** @type {Common.Coordinate} */
const coord = {
amount: Number(paymentV2.value_sat),
id: paymentV2.payment_hash,
inbound: false,
timestamp: Date.now(),
toLndPub: await myLNDPub(),
fromLndPub: undefined,
invoiceMemo: undefined,
type: 'payment'
}
if (sendPaymentRequest.payment_request) {
const invoice = await decodePayReq(sendPaymentRequest.payment_request)
coord.invoiceMemo = invoice.description
coord.toLndPub = invoice.destination
}
if (sendPaymentRequest.dest) {
coord.toLndPub = sendPaymentRequest.dest.toString('base64')
}
await writeCoordinate(paymentV2.payment_hash, coord)
return paymentV2
} }
/** /**