Skip to content

Commit

Permalink
problem: can't get pubkey from extension
Browse files Browse the repository at this point in the history
  • Loading branch information
gsovereignty committed Apr 21, 2024
1 parent 8dc8fe4 commit 09ed37b
Show file tree
Hide file tree
Showing 8 changed files with 348 additions and 162 deletions.
3 changes: 2 additions & 1 deletion src/lib/components/ChatLayout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
} from 'svelte-awesome-icons';
import Button from './Button.svelte';
import LoginButton from './LoginButton.svelte';
import Login from '@/ndk/Login.svelte';
export let hideFaucet = false;
</script>
Expand Down Expand Up @@ -59,7 +60,7 @@
>
</div>
<div class="mb-2 overflow-hidden place-items-center">
<Button><Home size={24} /></Button>
<Login />
</div>
</div>
</div>
Expand Down
156 changes: 156 additions & 0 deletions src/lib/ndk/Login.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<script lang="ts">
import type NDK from '@nostr-dev-kit/ndk';
import { NDKNip07Signer, NDKNip46Signer, NDKPrivateKeySigner, NDKUser } from '@nostr-dev-kit/ndk';
import { onMount } from 'svelte';
import { get } from 'svelte/store';
import { connect, currentUser, ndk } from './ndk';
import Button from '@/components/Button.svelte';
import { KeySolid } from 'svelte-awesome-icons';
onMount(() => {
connect();
});
type LoginMethod = 'none' | 'pk' | 'nip07' | 'nip46';
export async function loginNip07(alertUser?: boolean) {
const user = await login($ndk, undefined, 'nip07');
if (!user && alertUser) {
alert('Please use a nostr signing extension such as GetAlby to login');
} else {
currentUser.update((cu) => {
cu = user || undefined;
return cu;
});
localStorage.setItem('nostr-key-method', 'nip07');
let cu = get(currentUser);
if (cu) {
localStorage.setItem('nostr-target-npub', cu.npub);
cu.fetchProfile();
let signer = new NDKNip07Signer();
ndk.update((current) => {
current.signer = signer;
return current;
});
}
}
}
export async function login(
ndk: NDK,
bunkerNDK?: NDK,
method?: LoginMethod
): Promise<NDKUser | null> {
// Check if there is a localStorage item with the key "nostr-key-method"
const nostrKeyMethod = method || localStorage.getItem('nostr-key-method');
switch (nostrKeyMethod) {
case 'none':
return null;
case 'pk':
const key = localStorage.getItem('nostr-key');
if (!key) return null;
const signer = new NDKPrivateKeySigner(key);
ndk.signer = signer;
const user = await signer.user();
if (user) user.ndk = ndk;
return user;
case 'nip07':
return nip07SignIn(ndk);
case 'nip46': {
const promise = new Promise<NDKUser | null>((resolve, reject) => {
const existingPrivateKey = localStorage.getItem('nostr-nsecbunker-key');
if (!bunkerNDK) bunkerNDK = ndk;
if (existingPrivateKey) {
bunkerNDK.connect(2500);
bunkerNDK.pool.on('relay:connect', async () => {
const user = await nip46SignIn(ndk, bunkerNDK!, existingPrivateKey);
resolve(user);
});
}
});
return promise;
}
default: {
const promise = new Promise<NDKUser | null>((resolve, reject) => {
// Attempt to see window.nostr a few times, there is a race condition
// since the page might begin rendering before the nostr extension is loaded
let loadAttempts = 0;
const loadNip07Interval = setInterval(() => {
if (window.nostr) {
clearInterval(loadNip07Interval);
const user = nip07SignIn(ndk);
resolve(user);
}
if (loadAttempts++ > 10) clearInterval(loadNip07Interval);
}, 100);
});
return promise;
}
}
}
/**
* This function attempts to sign in using a NIP-07 extension.
*/
async function nip07SignIn(ndk: NDK): Promise<NDKUser | null> {
const storedNpub = localStorage.getItem('currentUserNpub');
let user: NDKUser | null = null;
if (storedNpub) {
user = new NDKUser({ npub: storedNpub });
user.ndk = ndk;
}
if (window.nostr) {
try {
ndk.signer = new NDKNip07Signer();
user = await ndk.signer.user();
user.ndk = ndk;
localStorage.setItem('currentUserNpub', user.npub);
ndk = ndk;
} catch (e) {}
}
return user;
}
/**
* This function attempts to sign in using a NIP-46 extension.
*/
async function nip46SignIn(
ndk: NDK,
bunkerNDK: NDK,
existingPrivateKey: string
): Promise<NDKUser | null> {
const npub = localStorage.getItem('nostr-target-npub')!;
const remoteUser = new NDKUser({ npub });
let user: NDKUser | null = null;
remoteUser.ndk = bunkerNDK;
// check if there is a private key stored in localStorage
let localSigner: NDKPrivateKeySigner | null = null;
if (existingPrivateKey) {
localSigner = new NDKPrivateKeySigner(existingPrivateKey);
}
const remoteSigner = new NDKNip46Signer(bunkerNDK, remoteUser.pubkey, localSigner);
await remoteSigner.blockUntilReady();
ndk.signer = remoteSigner;
user = remoteUser;
user.ndk = ndk;
return user;
}
</script>

<Button onClick={()=>{loginNip07(true)}}><KeySolid /></Button>
26 changes: 26 additions & 0 deletions src/lib/ndk/ndk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { seedRelays, short } from '@/snort_workers/seed_relays';
import type { NDKUser } from '@nostr-dev-kit/ndk';
import NDKSvelte from '@nostr-dev-kit/ndk-svelte';
import { writable } from 'svelte/store';

export const currentUser = writable<NDKUser | undefined>(undefined);

const _ndk: NDKSvelte = new NDKSvelte({
explicitRelayUrls: short
});

export const ndk = writable(_ndk);

let connected = false;

export async function connect() {
if (!connected) {
connected = true;
try {
await _ndk.connect();
console.log('NDK connected');
} catch (e) {
console.error(e);
}
}
}
1 change: 0 additions & 1 deletion src/lib/snort_workers/master_worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ async function connect() {
workerDataStore.subscribe((data) => {
let end = execTime("28 workerDataStore.subscribe")
let fed = new FrontendData();
fed._ourPubkey = data.ourPubkey();
fed.baseFollows = data.ourFollows;
let roots: NostrEvent[] = [];
for (let r of data.roots) {
Expand Down
1 change: 1 addition & 0 deletions src/lib/snort_workers/seed_relays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ export let seedRelays = Array.from(new Set([
"wss://relayable.org/",]))

export let short = [
"wss://nostr.mutinywallet.com/", // I mean, just for now I guess
"wss://relay.nostr.band",
"wss://relay.current.fyi",
'wss://purplepag.es',
Expand Down
12 changes: 7 additions & 5 deletions src/lib/snort_workers/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

import { BloomFilter } from 'bloomfilter';
import type { NostrEvent } from 'nostr-tools';

Expand All @@ -20,6 +21,7 @@ export class WorkerData {
_ourPubkey: string | undefined;
ourFollows: Set<string>;
ourBloom: BloomFilter;
bloomSize: number;
ourPubkey(): string {
return this._ourPubkey
? this._ourPubkey
Expand All @@ -45,9 +47,10 @@ export class WorkerData {
}
latestReplaceable: Map<string, Map<string, NostrEvent>>;
constructor(pubkey?: string) {
this.bloomSize = 0;
this.ourBloom = new BloomFilter(
32 * 256, // number of bits to allocate.
16 // number of hash functions.
32 * 256, // bits to allocate.
16 // number of hashes
);
this.missingEvents = new Set();
this.latestReplaceable = new Map();
Expand All @@ -64,12 +67,11 @@ export class WorkerData {
export class FrontendData {
roots: NostrEvent[];
replies: Map<string, Set<string>>;
_ourPubkey: string;
baseFollows: Set<string>;
events: Map<string, NostrEvent>;
missingEvents: Set<string>;
//ourBloom: BloomFilter;
constructor() {
this.missingEvents = new Set();
//this.ourBloom = new BloomFilter()
this.roots = [];
this.replies = new Map();
this.baseFollows = new Set();
Expand Down
Loading

0 comments on commit 09ed37b

Please sign in to comment.