-
Notifications
You must be signed in to change notification settings - Fork 81
[nostr]: New command to publish events to nostr relays #497
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
niteshbalusu11
wants to merge
9
commits into
alexbosworth:master
Choose a base branch
from
niteshbalusu11:nostr-support
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
afd3109
initial commit for nostr client support
niteshbalusu11 9705c69
clean up code and add comments
niteshbalusu11 53df58a
fix help section of command
niteshbalusu11 67e8061
fix post publish in package.json
niteshbalusu11 640e0eb
switch to using single nostr.json file
niteshbalusu11 461d14a
use logger.error for relay error logging
niteshbalusu11 d1a92aa
remove unused try catch block
niteshbalusu11 50e7fda
add ability to decode bech32 private key
niteshbalusu11 c5306b8
remove test message and allow posting of any event
niteshbalusu11 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| const asyncAuto = require('async/auto'); | ||
| const {returnResult} = require('asyncjs-util'); | ||
|
|
||
| const {homePath} = require('../storage'); | ||
|
|
||
| const defaultRelaysFile = {relays: []}; | ||
| const {isArray} = Array; | ||
| const isWebsocket = (n) => /^wss?:\/\/(([^:]+)(:(\d+))?)/.test(n); | ||
| const {parse} = JSON; | ||
| const relayFilePath = () => homePath({file: 'nostr.json'}).path; | ||
| const stringify = obj => JSON.stringify(obj, null, 2); | ||
|
|
||
| /** Adjust relays | ||
|
|
||
| { | ||
| [add]: [<Relay Uri To Add String>] | ||
| fs: { | ||
| getFile: <Read File Contents Function> (path, cbk) => {} | ||
| makeDirectory: <Make Directory Function> (path, cbk) => {} | ||
| writeFile: <Write File Contents Function> (path, contents, cbk) => {} | ||
| } | ||
| logger: <Winston Logger Object> | ||
| node: <Saved Node Name String> | ||
| [remove]: [<Relay Uri To String>] | ||
| } | ||
|
|
||
| @returns via cbk or Promise | ||
| */ | ||
| module.exports = (args, cbk) => { | ||
| return new Promise((resolve, reject) => { | ||
| return asyncAuto({ | ||
| // Check arguments | ||
| validate: cbk => { | ||
| if (!isArray(args.add)) { | ||
| return cbk([400, 'ExpectedArrayOfRelaysToAddToAdjustRelays']); | ||
| } | ||
|
|
||
| if (!args.fs) { | ||
| return cbk([400, 'ExpectedFilesystemMethodsToAdjustRelays']); | ||
| } | ||
|
|
||
| if (!args.logger) { | ||
| return cbk([400, 'ExpectedLoggerToAdjustRelays']); | ||
| } | ||
|
|
||
| if (!isArray(args.remove)) { | ||
| return cbk([400, 'ExpectedArrayOfRelaysToRemoveToAdjustRelays']); | ||
| } | ||
|
|
||
| if (!args.add.length && !args.remove.length) { | ||
| return cbk([400, 'ExpectedEitherAddOrRemoveRelayListToAdjustRelays']); | ||
| } | ||
|
|
||
| if (!!args.add.filter(n => !isWebsocket(n)).length) { | ||
| return cbk([400, 'RelaysToAddMustBeValidWebSocketUris']); | ||
| } | ||
|
|
||
| if (!!args.remove.filter(n => !isWebsocket(n)).length) { | ||
| return cbk([400, 'RelaysToRemoveMustBeValidWebSocketUris']); | ||
| } | ||
|
|
||
| return cbk(); | ||
| }, | ||
|
|
||
| // Register the home directory | ||
| registerHomeDir: ['validate', ({}, cbk) => { | ||
| return args.fs.makeDirectory(homePath({}).path, err => { | ||
| // Ignore errors, the directory may already be there | ||
| return cbk(); | ||
| }); | ||
| }], | ||
|
|
||
| // Read file and adjust | ||
| adjustRelays: ['registerHomeDir', ({}, cbk) => { | ||
| const node = args.node || ''; | ||
|
|
||
| return args.fs.getFile(relayFilePath(), (err, res) => { | ||
| // Exit if there is no relays file | ||
| if (!!err || !res) { | ||
| return cbk([400, 'ExpectedValidJsonNostrFileToAdjustRelays']); | ||
| } | ||
|
|
||
| try { | ||
| const file = parse(res.toString()); | ||
|
|
||
| if (!file.nostr || !isArray(file.nostr) || !file.nostr.length) { | ||
| return cbk([400, 'ExpectedAtLeastOneNostrKeyInNostrFileToAdjustRelays']); | ||
| } | ||
|
|
||
| const findNode = file.nostr.find(n => n.node === node); | ||
|
|
||
| if (!findNode) { | ||
| return cbk([400, 'ExpectedSavedNostrKeyInNostrFileToAdjustRelays']); | ||
| } | ||
|
|
||
| // Adjust the relays file | ||
| args.add.forEach(n => { | ||
| const findRelay = findNode.relays.find(relay => relay === n); | ||
|
|
||
| if (!findRelay) { | ||
| findNode.relays.push(n); | ||
| } | ||
| }); | ||
|
|
||
| args.remove.forEach(n => { | ||
| const findRelay = findNode.relays.find(relay => relay === n); | ||
|
|
||
| if (!!findRelay) { | ||
| findNode.relays = findNode.relays.filter(relay => relay !== n) | ||
| } | ||
| }); | ||
|
|
||
| return cbk(null, {file, relays: findNode.relays}); | ||
| } catch (err) { | ||
| return cbk([400, 'ExpectedValidJsonRelaysFileToAdjustRelays', {err}]); | ||
| } | ||
| }); | ||
| }], | ||
|
|
||
| // Adjust relays | ||
| writeFile: ['adjustRelays', ({adjustRelays}, cbk) => { | ||
| return args.fs.writeFile(relayFilePath(), stringify(adjustRelays.file), err => { | ||
| if (!!err) { | ||
| return cbk([503, 'UnexpectedErrorSavingRelayFileUpdate', {err}]); | ||
| } | ||
|
|
||
| args.logger.info({relays_adjusted: adjustRelays.relays}); | ||
|
|
||
| return cbk(); | ||
| }); | ||
| }], | ||
| }, | ||
| returnResult({reject, resolve}, cbk)); | ||
| }); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| const asyncAuto = require('async/auto'); | ||
| const {returnResult} = require('asyncjs-util'); | ||
| const {createHash} = require('crypto'); | ||
|
|
||
| const tinysecp256k1 = require('tiny-secp256k1'); | ||
|
|
||
| const {decryptWithNode} = require('../encryption'); | ||
| const {homePath} = require('../storage'); | ||
| const publishToRelays = require('./publish_to_relays'); | ||
|
|
||
| const createdAt = () => Math.round(Date.now() / 1000); | ||
| const eventKind = 1; | ||
| const hexAsBuffer = hex => Buffer.from(hex, 'hex'); | ||
| const {isArray} = Array; | ||
| const nostrFilePath = () => homePath({file: 'nostr.json'}).path; | ||
| const {parse} = JSON; | ||
| const sha256 = n => createHash('sha256').update(n).digest(); | ||
| const stringAsUtf8 = n => Buffer.from(n, 'utf-8'); | ||
| const {stringify} = JSON; | ||
| const unit8AsHex = n => Buffer.from(n).toString('hex'); | ||
|
|
||
| /** Build nostr event to publish | ||
|
|
||
| { | ||
| fs: { | ||
| getFile: <Read File Contents Function> (path, cbk) => {} | ||
| } | ||
| lnd: <Authenticated LND API Object> | ||
| logger: <Winston Logger Object> | ||
| message: <Message For Event String> | ||
| node: <Saved Node Name String> | ||
| } | ||
|
|
||
| @returns via cbk or Promise | ||
| */ | ||
| module.exports = (args, cbk) => { | ||
| return new Promise((resolve, reject) => { | ||
| return asyncAuto({ | ||
| // Import the ECPair library | ||
| ecp: async () => (await import('ecpair')).ECPairFactory(tinysecp256k1), | ||
|
|
||
| // Check arguments | ||
| validate: cbk => { | ||
| if (!args.fs) { | ||
| return cbk([400, 'ExpectedFilesystemMethodsToBuildEvent']); | ||
| } | ||
|
|
||
| if (!args.message) { | ||
| return cbk([400, 'ExpectedMessageEventToBuildEvent']); | ||
| } | ||
|
|
||
| if (!args.lnd) { | ||
| return cbk([400, 'ExpectedLndToBuildEvent']); | ||
| } | ||
|
|
||
| if (!args.logger) { | ||
| return cbk([400, 'ExpectedLoggerToBuildEvent']); | ||
| } | ||
|
|
||
| return cbk(); | ||
| }, | ||
|
|
||
| // Get relays and nostr key | ||
| readFile: ['validate', ({}, cbk) => { | ||
| const node = args.node || ''; | ||
|
|
||
| return args.fs.getFile(nostrFilePath(), (err, res) => { | ||
| if (!!err || !res) { | ||
| return cbk([400, 'FailedToReadRelaysJsonFileToBuildEvent']); | ||
| } | ||
|
|
||
| try { | ||
| const result = parse(res.toString()); | ||
|
|
||
| if (!result.nostr || !isArray(result.nostr) || !result.nostr.length) { | ||
| return cbk([400, 'ExpectedNostrKeyAndRelaysToBuildEvent']); | ||
| } | ||
|
|
||
| const findNode = result.nostr.find(n => n.node === node); | ||
|
|
||
| if (!findNode) { | ||
| return cbk([400, 'ExpectedNostrKeyAndRelaysForSavedNode']); | ||
| } | ||
|
|
||
| if (!findNode.key) { | ||
| return cbk([400, 'ExpectedNostrKeyToBuildEvent']); | ||
| } | ||
|
|
||
| if (!findNode.relays.length) { | ||
| return cbk([400, 'ExpectedAtLeastOneRelayToBuildEvent']); | ||
| } | ||
|
|
||
| return cbk(null, {key: findNode.key, relays: findNode.relays}) | ||
| } catch (err) { | ||
| return cbk([400, 'FailedToParseRelaysJsonFileToBuildEvent']); | ||
| } | ||
| }); | ||
| }], | ||
|
|
||
| // Decrypt nostr private key | ||
| decrypt: ['readFile', ({readFile}, cbk) => { | ||
| return decryptWithNode({ | ||
| encrypted: readFile.key, | ||
| lnd: args.lnd, | ||
| }, | ||
| cbk); | ||
| }], | ||
|
|
||
| // Build the nostr event | ||
| buildEvent: [ | ||
| 'decrypt', | ||
| 'ecp', | ||
| 'readFile', ({decrypt, ecp}, cbk) => { | ||
| const key = ecp.fromPrivateKey(hexAsBuffer(decrypt.message)); | ||
| const publicKey = unit8AsHex(key.publicKey.slice(1)); | ||
| const created = createdAt(); | ||
| const content = `This is a test from BalanceOfSatoshis: \n Group Open Invite Code: ${args.message}`; | ||
|
|
||
| const commit = stringify([0, publicKey, created, eventKind, [], content]); | ||
| const buf = stringAsUtf8(commit); | ||
| const hash = sha256(buf); | ||
|
|
||
| const eventId = unit8AsHex(hash); | ||
|
|
||
| const signature = unit8AsHex(tinysecp256k1.signSchnorr(hash, hexAsBuffer(decrypt.message))); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does this work? Wouldn't it be the key signing? |
||
|
|
||
| const event = { | ||
| content, | ||
| id: eventId, | ||
| pubkey: publicKey, | ||
| created_at: created, | ||
| kind: eventKind, | ||
| tags: [], | ||
| sig: signature, | ||
| } | ||
|
|
||
| return cbk(null, {event}); | ||
| }], | ||
|
|
||
| // Publish event to relays | ||
| publish: ['buildEvent', 'readFile', ({buildEvent, readFile}, cbk) => { | ||
| return publishToRelays({ | ||
| event: stringify(['EVENT', buildEvent.event]), | ||
| logger: args.logger, | ||
| relays: readFile.relays | ||
| }, cbk); | ||
| }], | ||
| }, | ||
| returnResult({reject, resolve}, cbk)); | ||
| }); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| const manageNostr = require('./manage_nostr'); | ||
|
|
||
| module.exports = {manageNostr}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.