Ruulul / hyper-nostr

33 stars 9 forks source link

📒 Cook Book - Problem 2: Getting Unknown Users #7

Open benzmuircroft opened 10 months ago

benzmuircroft commented 10 months ago

Please note that this code is more than likely totally wrong (Until updated/fixed by @5-142857 as discussed on discord)

NIPs

For a full list of the Nostr protocol NIPS (Nostr Implementation Protocols) see: nostr-protocol/nips

📒 Getting Unknown Users

A user is about to join a p2p app, but the app needs to check if bob's sponsor exists. Due to the nature of p2p applications, there is no central server, so how does a user check for users they have not peered with before? This is where hyper-nostr helps out, with a list that everyone syncs of all users

Other assumptions

(Should be clarified)

;(async function(){
  const SDK = await import("hyper-sdk");
  const createSwarm = (await import('hyper-nostr')).default;
  const { generatePrivateKey, getPublicKey, getEventHash, signEvent } = require('nostr-tools');
  const goodbye = require('graceful-goodbye');

  const yourStorageFolder = './all-users';

  const sdk = await SDK.create({
      storage: yourStorageFolder,
      autoJoin: true
  });
  goodbye(_ => sdk.close());

  const bob = await createSwarm(sdk, 'all-users');
  const bob.priv = generatePrivateKey();
  const bob.pub = getPublicKey(bob.priv);

  let ev = {
    kind: 30000,  // keep only latest (see nip 1)
    created_at: (+new Date() / 1000),
    pubkey: bob.pub,
    content: 'bob',
    tags: []
  };
  ev.id = getEventHash(ev);
  ev.sign = signEvent(ev, bob.priv);

  bob.sendEvent('EVENT', ev); // bob joins the shared list of users

  await bob.update();

  // bob's sponsor is going to be alice! Let's check the db to see if alice is really a user ...

  let sponsor = await bob.queryEvent({ content: 'alice' });

  if (sponsor) {
    console.log(sponsor); // yay!
    /*
    {
      kind: 30000, // keep only latest (see nip 1)
      created_at: 1234567890000,
      pubkey: 'r6d0ds6wtyt4y4gtydrt',
      content: 'alice',
      tags: []
    }
    */
  }
  else {
    console.log('No alice here! Please choose a different sponsor.');
  }

})();