Skip to content
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

feat: Allow verification of Event objects #85 #86

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 46 additions & 5 deletions src/Event/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,14 +231,21 @@ public function toJson(): string
/**
* {@inheritdoc}
*/
public function verify(string $json = ''): bool
public function verify(string|object $input = ''): bool
{
try {
if ($json === '') {
$json = $this->toJson();
$event = json_decode($json, flags: \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_THROW_ON_ERROR);
if ($input === '') {
$event = json_decode(
$this->toJson(),
flags: \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_THROW_ON_ERROR,
);
} elseif (is_string($input)) {
$event = json_decode(
$input,
flags: \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_THROW_ON_ERROR,
);
} else {
$event = json_decode($json, flags: \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_THROW_ON_ERROR);
$event = $input;
}
} catch (\JsonException) {
return false;
Expand Down Expand Up @@ -303,4 +310,38 @@ public function verify(string $json = ''): bool
return (new SchnorrSignature())->verify($event->pubkey, $event->sig, $event->id);
}

/**
* Create an Event object from a verified event input.
*
* @param string|object $input The event data as JSON string or decoded object
* @return ?static Returns an Event object if valid, null otherwise
*/
public static function fromVerified(string|object $input): ?static
{
$event = new static();
if (!$event->verify($input)) {
return null;
}

try {
if (is_string($input)) {
$data = json_decode($input, flags: \JSON_THROW_ON_ERROR);
} else {
$data = $input;
}

$event->setId($data->id)
->setPublicKey($data->pubkey)
->setCreatedAt($data->created_at)
->setKind($data->kind)
->setContent($data->content)
->setSignature($data->sig)
->setTags($data->tags);

return $event;
} catch (\Throwable) {
return null;
}
}

}
15 changes: 14 additions & 1 deletion src/EventInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,21 @@ public function toJson(): string;
/**
* Returns true if event object encodes to a valid Nostr event JSON string.
*
* @param string|object $input
* The input to verify.
*
* @return bool
*/
public function verify(): bool;
public function verify(string|object $input = ''): bool;

/**
* Create an Event object from a verified event input.
*
* @param string|object $input
* The event data as JSON string or decoded object.
*
* @return ?static
* Returns an Event object if valid, null otherwise.
*/
public static function fromVerified(string|object $input): ?static;
}
16 changes: 16 additions & 0 deletions src/Examples/verify-event-object.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);
// Suppress deprecated warnings
error_reporting(E_ALL & ~E_DEPRECATED);

require_once __DIR__ . '/../../vendor/autoload.php';

use swentel\nostr\Event\Event;

$json = json_decode('{"kind":27236,"created_at":1707827688371,"tags":[],"content":"","pubkey":"07adfda9c5adc80881bb2a5220f6e3181e0c043b90fa115c4f183464022968e6","id":"7eaf0e97515c7ea8846fa2b1e28a480bec506a3f911a1ec998662201f986b0bf","sig":"22a99a1e60266c89720bf0af46ec60132eff17782aa7f582c6f990c25ef54bcefb79fdd8a95ca8bbdab9e96a0d1fd85b77a6c37e192bf74b77dd013a1d539028"}');

$event = new Event();
$isValid = $event->verify($json);

print $isValid;
7 changes: 6 additions & 1 deletion src/Examples/verify.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
<?php

declare(strict_types=1);
// Suppress deprecated warnings
error_reporting(E_ALL & ~E_DEPRECATED);

use nostrverse\nostr\Event\Event;
require_once __DIR__ . '/../../vendor/autoload.php';

use swentel\nostr\Event\Event;

$json = '{"kind":27236,"created_at":1707827688371,"tags":[],"content":"","pubkey":"07adfda9c5adc80881bb2a5220f6e3181e0c043b90fa115c4f183464022968e6","id":"7eaf0e97515c7ea8846fa2b1e28a480bec506a3f911a1ec998662201f986b0bf","sig":"22a99a1e60266c89720bf0af46ec60132eff17782aa7f582c6f990c25ef54bcefb79fdd8a95ca8bbdab9e96a0d1fd85b77a6c37e192bf74b77dd013a1d539028"}';


$event = new Event();
$isValid = $event->verify($json);

Expand Down
123 changes: 123 additions & 0 deletions tests/FromVerifiedTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?php

declare(strict_types=1);

use PHPUnit\Framework\TestCase;
use swentel\nostr\Event\Event;
use swentel\nostr\Key\Key;
use swentel\nostr\Sign\Sign;

class FromVerifiedTest extends TestCase
{
private string $privateKey;
private string $publicKey;
private array $validEventData;
private string $validEventJson;

protected function setUp(): void
{
// Generate test keys
$keyGenerator = new Key();
$this->privateKey = $keyGenerator->generatePrivateKey();
$this->publicKey = $keyGenerator->getPublicKey($this->privateKey);

// Create a valid event
$event = new Event();
$event->setPublicKey($this->publicKey)
->setCreatedAt(time())
->setKind(1)
->setContent('Test message')
->setTags([['t', 'test']]);

// Sign the event
$signer = new Sign();
$signer->signEvent($event, $this->privateKey);

// Store the event data for tests
$this->validEventData = $event->toArray();
$this->validEventJson = $event->toJson();
}

public function testFromVerifiedWithValidJsonString(): void
{
$event = Event::fromVerified($this->validEventJson);

$this->assertNotNull($event);
$this->assertInstanceOf(Event::class, $event);
$this->assertEquals($this->validEventData['pubkey'], $event->getPublicKey());
$this->assertEquals($this->validEventData['content'], $event->getContent());
$this->assertEquals($this->validEventData['kind'], $event->getKind());
$this->assertEquals($this->validEventData['created_at'], $event->getCreatedAt());
$this->assertEquals($this->validEventData['tags'], $event->getTags());
$this->assertEquals($this->validEventData['id'], $event->getId());
$this->assertEquals($this->validEventData['sig'], $event->getSignature());
}

public function testFromVerifiedWithValidObject(): void
{
$eventObj = json_decode($this->validEventJson);
$event = Event::fromVerified($eventObj);

$this->assertNotNull($event);
$this->assertInstanceOf(Event::class, $event);
$this->assertEquals($this->validEventData['pubkey'], $event->getPublicKey());
}

public function testFromVerifiedWithInvalidJson(): void
{
$invalidJson = '{invalid json}';
$event = Event::fromVerified($invalidJson);

$this->assertNull($event);
}

public function testFromVerifiedWithMissingFields(): void
{
$incompleteData = [
'pubkey' => $this->publicKey,
'created_at' => time(),
'kind' => 1,
'content' => 'Test',
// Missing id, sig, and tags
];

$event = Event::fromVerified(json_encode($incompleteData));
$this->assertNull($event);
}

public function testFromVerifiedWithInvalidSignature(): void
{
$eventData = json_decode($this->validEventJson, true);
$eventData['sig'] = str_repeat('0', 128); // Invalid signature

$event = Event::fromVerified(json_encode($eventData));
$this->assertNull($event);
}

public function testFromVerifiedWithInvalidId(): void
{
$eventData = json_decode($this->validEventJson, true);
$eventData['id'] = str_repeat('0', 64); // Invalid ID that doesn't match content

$event = Event::fromVerified(json_encode($eventData));
$this->assertNull($event);
}

public function testFromVerifiedWithInvalidTags(): void
{
$eventData = json_decode($this->validEventJson, true);
$eventData['tags'] = [['t', 123]]; // Tags must be strings

$event = Event::fromVerified(json_encode($eventData));
$this->assertNull($event);
}

public function testFromVerifiedWithInvalidTypes(): void
{
$eventData = json_decode($this->validEventJson, true);
$eventData['created_at'] = '1234'; // Should be int

$event = Event::fromVerified(json_encode($eventData));
$this->assertNull($event);
}
}