initial commit.

This commit is contained in:
fiatjaf 2021-01-04 14:15:27 -03:00
commit b077271d46
7 changed files with 99 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules

39
event.js Normal file
View File

@ -0,0 +1,39 @@
import shajs from 'sha.js'
import BigInteger from 'bigi'
import schnorr from 'bip-schnorr'
export function serializeEvent(evt) {
return JSON.stringify([
0,
evt.pubkey,
evt.created_at,
evt.kind,
evt.tags,
evt.content
])
}
export function getEventID(event) {
let hash = shajs('sha256').update(serializeEvent(event)).digest()
return hash.toString('hex')
}
export function verifySignature(event) {
try {
schnorr.verify(
Buffer.from(event.pubkey, 'hex'),
Buffer.from(getEventID(event), 'hex'),
Buffer.from(event.sig, 'hex')
)
return true
} catch (err) {
return false
}
}
export function signEvent(event, key) {
let eventHash = shajs('sha256').update(serializeEvent(event)).digest()
schnorr
.sign(new BigInteger(key, 16), eventHash, makeRandom32())
.toString('hex')
}

4
index.js Normal file
View File

@ -0,0 +1,4 @@
export {relayConnect} from './relay'
export {signEvent, verifySignature, serializeEvent, getEventID} from './event'
export {pubkeyFromPrivate} from './schnorr'
export {makeRandom32} from './utils'

13
package.json Normal file
View File

@ -0,0 +1,13 @@
{
"name": "nostr-tools",
"version": "0.0.1",
"dependencies": {
"assert": "^2.0.0",
"bigi": "^1.4.2",
"bip-schnorr": "^0.6.2",
"buffer": "^6.0.3",
"ecurve": "^1.0.6",
"pws": "^5.0.2",
"sha.js": "^2.4.11"
}
}

27
relay.js Normal file
View File

@ -0,0 +1,27 @@
import PersistentWebSocket from 'pws'
export function relayConnect(url, onEventCallback) {
if (url.length && url[url.length - 1] === '/') url = url.slice(0, -1)
const ws = new PersistentWebSocket(url + '/ws?session=' + Math.random(), {
pingTimeout: 30 * 1000
})
ws.onopen = () => console.log('connected to ', url)
ws.onerror = err => console.log('error connecting', url, err)
ws.onmessage = e => {
let event = JSON.parse(e.data)
event.context
}
return {
url,
subscribe() {},
request() {},
publish() {},
close() {
ws.close()
}
}
}

10
schnorr.js Normal file
View File

@ -0,0 +1,10 @@
import BigInteger from 'bigi'
import ecurve from 'ecurve'
const curve = ecurve.getCurveByName('secp256k1')
const G = curve.G
export function pubkeyFromPrivate(privateHex) {
const privKey = BigInteger.fromHex(privateHex)
return G.multiply(privKey).getEncoded(true).slice(1).toString('hex')
}

5
utils.js Normal file
View File

@ -0,0 +1,5 @@
export function makeRandom32() {
var array = new Uint32Array(32)
window.crypto.getRandomValues(array)
return Buffer.from(array)
}