import React, {useState, useEffect} from 'react'
import useBooleanState from 'use-boolean-state'
import useComputedState from 'use-computed-state'
import {
getPublicKey,
getEventHash,
serializeEvent,
verifySignature,
signEvent
} from 'nostr-tools'
import Item from '../components/item'
export default function EventSigning({value}) {
let [privateKey, setPrivateKey] = useState(
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
)
let [isValidSignature, signatureGood, signatureBad] = useBooleanState(false)
let privateKeyIsValid = useComputedState(
() => privateKey.match(/[a-f0-9]{64}/),
[privateKey]
)
let publicKey = useComputedState(
() => (privateKeyIsValid ? getPublicKey(privateKey) : null),
[privateKeyIsValid]
)
let signature = useComputedState(async () => {
evt.pubkey = publicKey
return await signEvent(evt, privateKey)
}, [value, privateKey])
let evt = JSON.parse(value)
useEffect(() => {
verifySignature(evt)
.then(ok => (ok ? signatureGood() : signatureBad()))
.catch(signatureBad)
}, [value])
return (
<>
-
{serializeEvent(evt)}
-
{getEventHash(evt)}
{evt.sig ? (
- {isValidSignature.toString()}
) : (
<>
-
setPrivateKey(e.target.value.toLowerCase())}
/>{' '}
{privateKeyIsValid ? 'valid' : 'invalid'}
- {publicKey}
- {privateKeyIsValid ? signature : ''}
>
)}
>
)
}
EventSigning.match = value => {
try {
let evt = JSON.parse(value)
return evt.kind && evt.content && evt.tags
} catch (err) {
/**/
}
return false
}