# Here's some code!

```js
import React, { useEffect, useState } from "react";
import { useNDKContext } from "@/context/NDKContext";
import { parseEvent } from "@/utils/nostr";
import { ProgressSpinner } from "primereact/progressspinner";

const PurchasedListItem = ({ eventId, category }) => {
    const { ndk } = useNDKContext();
    const [event, setEvent] = useState(null);

    useEffect(() => {
        const fetchEvent = async () => {
            if (!eventId) return;

            try {
                await ndk.connect();
                const event = await ndk.fetchEvent(eventId);
                if (event) {
                    setEvent(parseEvent(event));
                }
            } catch (error) {
                console.error("Error fetching event:", error);
            }
        }
        fetchEvent();
    }, [eventId, ndk]);

    return !event || !ndk ? <ProgressSpinner className="w-[40px] h-[40px]" /> : (<a className="text-blue-500 underline hover:text-blue-600" href={category === "courses" ? `/courses/${event.id}` : `/details/${event.id}`}>{event.title}</a>);
}

export default PurchasedListItem;
```


```js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useRouter } from 'next/router';
import { InputText } from 'primereact/inputtext';
import { InputNumber } from 'primereact/inputnumber';
import { InputSwitch } from 'primereact/inputswitch';
import { Button } from 'primereact/button';
import { useToast } from '@/hooks/useToast';
import { useSession } from 'next-auth/react';
import 'primeicons/primeicons.css';

const WorkshopForm = ({ draft = null }) => {
    const [title, setTitle] = useState(draft?.title || '');
    const [summary, setSummary] = useState(draft?.summary || '');
    const [price, setPrice] = useState(draft?.price || 0);
    const [isPaidResource, setIsPaidResource] = useState(draft?.price ? true : false);
    const [videoUrl, setVideoUrl] = useState(draft?.content || '');
    const [coverImage, setCoverImage] = useState(draft?.image || '');
    const [topics, setTopics] = useState(draft?.topics || ['']);

    const router = useRouter();
    const { data: session, status } = useSession();
    const [user, setUser] = useState(null);
    const { showToast } = useToast();

    useEffect(() => {
        if (session) {
            setUser(session.user);
        }
    }, [session]);

    useEffect(() => {
        if (draft) {
            setTitle(draft.title);
            setSummary(draft.summary);
            setPrice(draft.price || 0);
            setIsPaidResource(draft.price ? true : false);
            setVideoUrl(draft.content);
            setCoverImage(draft.image);
            setTopics(draft.topics || ['']);
        }
    }, [draft]);

    const handleSubmit = async (e) => {
        e.preventDefault();
        let embedCode = '';

        // Check if it's a YouTube video
        if (videoUrl.includes('youtube.com') || videoUrl.includes('youtu.be')) {
            const videoId = videoUrl.split('v=')[1] || videoUrl.split('/').pop();
            embedCode = `<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;max-width:100%;"><iframe src="https://www.youtube.com/embed/${videoId}" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;" allowfullscreen></iframe></div>`;
        }
        // Check if it's a Vimeo video
        else if (videoUrl.includes('vimeo.com')) {
            const videoId = videoUrl.split('/').pop();
            embedCode = `<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;max-width:100%;"><iframe src="https://player.vimeo.com/video/${videoId}" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;" allowfullscreen></iframe></div>`;
        }
        // Add more conditions here for other video services

        const userResponse = await axios.get(`/api/users/${user.pubkey}`);

        if (!userResponse.data) {
            showToast('error', 'Error', 'User not found', 'Please try again.');
            return;
        }

        const payload = {
            title,
            summary,
            type: 'workshop',
            price: isPaidResource ? price : null,
            content: embedCode,
            image: coverImage,
            user: userResponse.data.id,
            topics: [...topics.map(topic => topic.trim().toLowerCase()), 'plebdevs', 'workshop']
        };

        if (payload && payload.user) {
            const url = draft ? `/api/drafts/${draft.id}` : '/api/drafts';
            const method = draft ? 'put' : 'post';

            axios[method](url, payload)
                .then(response => {
                    if (response.status === 200 || response.status === 201) {
                        showToast('success', 'Success', draft ? 'Workshop updated successfully.' : 'Workshop saved as draft.');

                        if (response.data?.id) {
                            router.push(`/draft/${response.data.id}`);
                        }
                    }
                })
                .catch(error => {
                    console.error(error);
                    showToast('error', 'Error', 'Failed to save workshop. Please try again.');
                });
        }
    };

    const onUpload = (event) => {
        showToast('success', 'Success', 'File Uploaded');
        console.log(event.files[0]);
    }

    const handleTopicChange = (index, value) => {
        const updatedTopics = topics.map((topic, i) => i === index ? value : topic);
        setTopics(updatedTopics);
    };

    const addTopic = (e) => {
        e.preventDefault();
        setTopics([...topics, '']); // Add an empty string to the topics array
    };

    const removeTopic = (e, index) => {
        e.preventDefault();
        const updatedTopics = topics.filter((_, i) => i !== index);
        setTopics(updatedTopics);
    };

    return (
        <form onSubmit={handleSubmit}>
            <div className="p-inputgroup flex-1">
                <InputText value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" />
            </div>
            <div className="p-inputgroup flex-1 mt-4">
                <InputText value={summary} onChange={(e) => setSummary(e.target.value)} placeholder="Summary" />
            </div>

            <div className="p-inputgroup flex-1 mt-4 flex-col">
                <p className="py-2">Paid Workshop</p>
                <InputSwitch checked={isPaidResource} onChange={(e) => setIsPaidResource(e.value)} />
                {isPaidResource && (
                    <div className="p-inputgroup flex-1 py-4">
                        <i className="pi pi-bolt p-inputgroup-addon text-2xl text-yellow-500"></i>
                        <InputNumber value={price} onValueChange={(e) => setPrice(e.value)} placeholder="Price (sats)" />
                    </div>
                )}
            </div>
            <div className="p-inputgroup flex-1 mt-4">
                <InputText value={videoUrl} onChange={(e) => setVideoUrl(e.target.value)} placeholder="Video URL" />
            </div>
            <div className="p-inputgroup flex-1 mt-4">
                <InputText value={coverImage} onChange={(e) => setCoverImage(e.target.value)} placeholder="Cover Image URL" />
            </div>
            <div className="mt-4 flex-col w-full">
                {topics.map((topic, index) => (
                    <div className="p-inputgroup flex-1" key={index}>
                        <InputText value={topic} onChange={(e) => handleTopicChange(index, e.target.value)} placeholder="Topic" className="w-full mt-2" />
                        {index > 0 && (
                            <Button icon="pi pi-times" className="p-button-danger mt-2" onClick={(e) => removeTopic(e, index)} />
                        )}
                    </div>
                ))}
                <div className="w-full flex flex-row items-end justify-end py-2">
                    <Button icon="pi pi-plus" onClick={addTopic} />
                </div>
            </div>
            <div className="flex justify-center mt-8">
                <Button type="submit" severity="success" outlined label={draft ? "Update" : "Submit"} />
            </div>
        </form>
    );
}

export default WorkshopForm;
```


```js
    const buildEvent = async (draft) => {
        const NewDTag = uuidv4();
        const event = new NDKEvent();
        let type;
        let encryptedContent;

        switch (draft?.type) {
            case 'resource':
                if (draft?.price) {
                    // encrypt the content with NEXT_PUBLIC_APP_PRIV_KEY to NEXT_PUBLIC_APP_PUBLIC_KEY
                    encryptedContent = await nip04.encrypt(process.env.NEXT_PUBLIC_APP_PRIV_KEY, process.env.NEXT_PUBLIC_APP_PUBLIC_KEY, draft.content);
                }

                event.kind = draft?.price ? 30402 : 30023 // Determine kind based on if price is present
                event.content = draft?.price ? encryptedContent : draft.content
                event.tags = [
                    ['d', NewDTag],
                    ['title', draft.title],
                    ['summary', draft.summary],
                    ['image', draft.image],
                    ...draft.topics.map(topic => ['t', topic]),
                    ['published_at', Math.floor(Date.now() / 1000).toString()],
                    // Include price and location tags only if price is present
                    ...(draft?.price ? [['price', draft.price.toString()], ['location', `https://plebdevs.com/details/${draft.id}`]] : []),
                ]

                type = 'resource';
                break;
            case 'workshop':
                if (draft?.price) {
                    // encrypt the content with NEXT_PUBLIC_APP_PRIV_KEY to NEXT_PUBLIC_APP_PUBLIC_KEY
                    encryptedContent = await nip04.encrypt(process.env.NEXT_PUBLIC_APP_PRIV_KEY, process.env.NEXT_PUBLIC_APP_PUBLIC_KEY, draft.content);
                }
                event.kind = draft?.price ? 30402 : 30023
                event.content = draft?.price ? encryptedContent : draft.content
                event.tags = [
                    ['d', NewDTag],
                    ['title', draft.title],
                    ['summary', draft.summary],
                    ['image', draft.image],
                    ...draft.topics.map(topic => ['t', topic]),
                    ['published_at', Math.floor(Date.now() / 1000).toString()],
                ]
                type = 'workshop';
                break;
            case 'course':
                event.kind = 30023
                event.content = draft.content
                event.tags = [
                    ['d', NewDTag],
                    ['title', draft.title],
                    ['summary', draft.summary],
                    ['image', draft.image],
                    ...draft.topics.map(topic => ['t', topic]),
                    ['published_at', Math.floor(Date.now() / 1000).toString()],
                ]
                type = 'course';
                break;
            default:
                return null;
        }

        return { unsignedEvent: event, type };
    };

    return (
        <div className='w-full px-24 pt-12 mx-auto mt-4 max-tab:px-0 max-mob:px-0 max-tab:pt-2 max-mob:pt-2'>
            <div className='w-full flex flex-row justify-between max-tab:flex-col max-mob:flex-col'>
                <i className='pi pi-arrow-left pl-8 cursor-pointer hover:opacity-75 max-tab:pl-2 max-mob:pl-2' onClick={() => router.push('/')} />
                <div className='w-[75vw] mx-auto flex flex-row items-start justify-between max-tab:flex-col max-mob:flex-col max-tab:w-[95vw] max-mob:w-[95vw]'>
                    <div className='flex flex-col items-start max-w-[45vw] max-tab:max-w-[100vw] max-mob:max-w-[100vw]'>
                        <div className='pt-2 flex flex-row justify-start w-full'>
                            {/* List out topics */}
                            {draft?.topics && draft.topics.map((topic, index) => {
                                if (topic === "plebdevs") return;
                                return (
                                    <Tag className='mr-2 text-white' key={index} value={topic}></Tag>
                                )
                            })
                            }
                        </div>
                        <h1 className='text-4xl mt-6'>{draft?.title}</h1>
                        <p className='text-xl mt-6'>{draft?.summary}</p>
                        <div className='flex flex-row w-full mt-6 items-center'>
                            <Image
                                alt="resource thumbnail"
                                src={returnImageProxy(draft?.author?.avatar, draft?.author?.pubkey)}
                                width={50}
                                height={50}
                                className="rounded-full mr-4"
                            />
                            {user && user?.pubkey && (
                                <p className='text-lg'>
                                    Created by{' '}
                                    <a href={`https://nostr.com/${hexToNpub(user?.pubkey)}`} rel='noreferrer noopener' target='_blank' className='text-blue-500 hover:underline'>
                                        {user?.username || user?.pubkey.slice(0, 10)}{'... '}
                                    </a>
                                </p>
                            )}
                        </div>
                    </div>
                    <div className='flex flex-col max-tab:mt-12 max-mob:mt-12'>
                        {draft && (
                            <div style={{ width: width < 768 ? "auto" : width }} onClick={() => router.push(`/details/${draft.id}`)} className="flex flex-col items-center mx-auto cursor-pointer rounded-md shadow-lg">
                                <div style={{ maxWidth: width, minWidth: width }} className="max-tab:h-auto max-mob:h-auto">
                                    <Image
                                        alt="resource thumbnail"
                                        src={returnImageProxy(draft.image)}
                                        quality={100}
                                        width={width}
                                        height={height}
                                        className="w-full h-full object-cover object-center rounded-md"
                                    />
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
            <div className='w-[75vw] mx-auto flex flex-row justify-end mt-12'>
                <div className='w-fit flex flex-row justify-between'>
                    <Button onClick={handleSubmit} label="Publish" severity='success' outlined className="w-auto m-2" />
                    <Button onClick={() => router.push(`/draft/${draft?.id}/edit`)} label="Edit" severity='warning' outlined className="w-auto m-2" />
                    <Button onClick={handleDelete} label="Delete" severity='danger' outlined className="w-auto m-2 mr-0" />
                </div>
            </div>
            <div className='w-[75vw] mx-auto mt-12 p-12 border-t-2 border-gray-300 max-tab:p-0 max-mob:p-0 max-tab:max-w-[100vw] max-mob:max-w-[100vw]'>
                {
                    draft?.content && <MDDisplay source={draft.content} />
                }
            </div>
        </div>
    );
}
```


Test test another course to test full course flow


testing new course flow with tis one baby


need iframe video embed to render in 16:9 but fill in as much space as possible in parent component


Testing a paid resource lets see what happens


```js
import { useState, useEffect, useCallback, useContext, useRef } from 'react';
import axios from 'axios';
import { nip57, nip19 } from 'nostr-tools';
import { NostrContext } from '@/context/NostrContext';
import { lnurlEncode } from '@/utils/lnurl';
import { parseEvent } from '@/utils/nostr';
import { v4 as uuidv4 } from 'uuid';

const defaultRelays = [
    "wss://nos.lol/",
    "wss://relay.damus.io/",
    "wss://relay.snort.social/",
    "wss://relay.nostr.band/",
    "wss://nostr.mutinywallet.com/",
    "wss://relay.mutinywallet.com/",
    "wss://relay.primal.net/"
];

const AUTHOR_PUBKEY = process.env.NEXT_PUBLIC_AUTHOR_PUBKEY;

export function useNostr() {
    const pool = useContext(NostrContext);
    const subscriptionQueue = useRef([]);
    const lastSubscriptionTime = useRef(0);
    const throttleDelay = 2000;

    const processSubscriptionQueue = useCallback(() => {
        if (subscriptionQueue.current.length === 0) return;

        const currentTime = Date.now();
        if (currentTime - lastSubscriptionTime.current < throttleDelay) {
            setTimeout(processSubscriptionQueue, throttleDelay);
            return;
        }

        const subscription = subscriptionQueue.current.shift();
        subscription();

        lastSubscriptionTime.current = currentTime;
        setTimeout(processSubscriptionQueue, throttleDelay);
    }, [throttleDelay]);

    const subscribe = useCallback(
        (filters, opts) => {
            if (!pool) return;

            const subscriptionFn = () => {
                return pool.subscribeMany(defaultRelays, filters, opts);
            };

            subscriptionQueue.current.push(subscriptionFn);
            processSubscriptionQueue();
        },
        [pool, processSubscriptionQueue]
    );

    const publish = useCallback(
        async (event) => {
            if (!pool) return;

            try {
                console.log('publishing event', event)
                const result = await Promise.any(pool.publish(defaultRelays, event));
                console.log('result', result)
                console.log('Published event to at least one relay');
                return true;
            } catch (error) {
                console.error('Failed to publish event:', error);
                return false;
            }
        },
        [pool]
    );
```


This should be a draft but pubbed at the right moment


lorem ipsum doggie


```js
import React, { useState, useEffect } from "react";
import axios from "axios";
import { InputText } from "primereact/inputtext";
import { InputNumber } from "primereact/inputnumber";
import { InputSwitch } from "primereact/inputswitch";
import { Button } from "primereact/button";
import { Dropdown } from "primereact/dropdown";
import { v4 as uuidv4, v4 } from 'uuid';
import { useLocalStorageWithEffect } from "@/hooks/useLocalStorage";
import { useNostr } from "@/hooks/useNostr";
import { useRouter } from "next/router";
import { useToast } from "@/hooks/useToast";
import { nip19 } from "nostr-tools"
import { parseEvent } from "@/utils/nostr";
import ContentDropdownItem from "@/components/content/dropdowns/ContentDropdownItem";
import 'primeicons/primeicons.css';

const CourseForm = () => {
    const [title, setTitle] = useState('');
    const [summary, setSummary] = useState('');
    const [checked, setChecked] = useState(false);
    const [price, setPrice] = useState(0);
    const [coverImage, setCoverImage] = useState('');
    const [lessons, setLessons] = useState([{ id: uuidv4(), title: 'Select a lesson' }]);
    const [selectedLessons, setSelectedLessons] = useState([]);
    const [topics, setTopics] = useState(['']);
    const [user, setUser] = useLocalStorageWithEffect('user', {});
    const [drafts, setDrafts] = useState([]);
    const [resources, setResources] = useState([]);
    const [workshops, setWorkshops] = useState([]);
    const { fetchResources, fetchWorkshops, publish, fetchSingleEvent } = useNostr();
    const [pubkey, setPubkey] = useState('');

    const router = useRouter();
    const { showToast } = useToast();

    const fetchAllContent = async () => {
        try {
            // Fetch drafts from the database
            const draftsResponse = await axios.get(`/api/drafts/all/${user.id}`);
            const drafts = draftsResponse.data;

            // Fetch resources and workshops from Nostr
            const resources = await fetchResources();
            const workshops = await fetchWorkshops();

            if (drafts.length > 0) {
                setDrafts(drafts);
            }
            if (resources.length > 0) {
                console.log('resources:', resources);
                setResources(resources);
            }
            if (workshops.length > 0) {
                setWorkshops(workshops);
            }
        } catch (err) {
            console.error(err);
            // Handle error
        }
    };

    useEffect(() => {
        if (user && user.id) {
            fetchAllContent();
        }
    }, [user]);

    /**
 * Course Creation Flow:
 * 1. Generate a new course ID
 * 2. Process each lesson:
 *    - If unpublished: create event, publish to Nostr, save to DB, delete draft
 *    - If published: use existing data
 * 3. Create and publish course event to Nostr
 * 4. Save course to database
 * 5. Show success message and redirect to course page
 */

    const handleSubmit = async (e) => {
        e.preventDefault();

        const newCourseId = uuidv4();
        const processedLessons = [];

        try {
            // Step 1: Process lessons
            console.log('selectedLessons:', selectedLessons);
            for (const lesson of selectedLessons) {
                let noteId = lesson.noteId;

                if (!lesson.published_at) {
                    // Publish unpublished lesson
                    const event = createLessonEvent(lesson);
                    const signedEvent = await window.nostr.signEvent(event);
                    const published = await publish(signedEvent);

                    if (!published) {
                        throw new Error(`Failed to publish lesson: ${lesson.title}`);
                    }

                    noteId = signedEvent.id;

                    // Save to db and delete draft
                    await Promise.all([
                        axios.post('/api/resources', {
                            id: lesson.id,
                            noteId: noteId,
                            userId: user.id,
                            price: lesson.price || 0,
                        }),
                        axios.delete(`/api/drafts/${lesson.id}`)
                    ]);

                }

                processedLessons.push({ id: lesson?.d || lesson.id });
            }

            // Step 2: Create and publish course
            const courseEvent = createCourseEvent(newCourseId, title, summary, coverImage, selectedLessons);
            const signedCourseEvent = await window.nostr.signEvent(courseEvent);
            const published = await publish(signedCourseEvent);

            if (!published) {
                throw new Error('Failed to publish course');
            }

            // Step 3: Save course to db
            console.log('processedLessons:', processedLessons);
            await axios.post('/api/courses', {
                id: newCourseId,
                resources: {
                    connect: processedLessons.map(lesson => ({ id: lesson?.id }))
                },
                noteId: signedCourseEvent.id,
                user: {
                    connect: { id: user.id }
                },
                price: price || 0
            });

            // Step 4: Show success message and redirect
            showToast('success', 'Course created successfully');
            router.push(`/course/${signedCourseEvent.id}`);

        } catch (error) {
            console.error('Error creating course:', error);
            showToast('error', error.message || 'Failed to create course. Please try again.');
        }
    };

    const createLessonEvent = (lesson) => ({
        kind: lesson.price ? 30402 : 30023,
        content: lesson.content,
        created_at: Math.floor(Date.now() / 1000),
        tags: [
            ['d', lesson.id],
            ['title', lesson.title],
            ['summary', lesson.summary],
            ['image', lesson.image],
            ...lesson.topics.map(topic => ['t', topic]),
            ['published_at', Math.floor(Date.now() / 1000).toString()],
            ...(lesson.price ? [
                ['price', lesson.price],
                ['location', `https://plebdevs.com/${lesson.topics[1]}/${lesson.id}`]
            ] : [])
        ]
    });

    const createCourseEvent = (courseId, title, summary, coverImage, lessons) => ({
        kind: 30004,
        created_at: Math.floor(Date.now() / 1000),
        content: "",
        tags: [
            ['d', courseId],
            ['name', title],
            ['picture', coverImage],
            ['image', coverImage],
            ['description', summary],
            ['l', "Education"],
            ...lessons.map((lesson) => ['a', `${lesson.kind}:${lesson.pubkey}:${lesson.d}`]),
        ],
    });

    const handleLessonChange = (e, index) => {
        const selectedLessonId = e.value;
        const selectedLesson = getContentOptions(index).flatMap(group => group.items).find(lesson => lesson.value === selectedLessonId);

        const updatedLessons = lessons.map((lesson, i) =>
            i === index ? { ...lesson, id: selectedLessonId, title: selectedLesson.label.props.content.title } : lesson
        );
        setLessons(updatedLessons);
    };

    const handleLessonSelect = (content) => {
        setSelectedLessons([...selectedLessons, content]);
        addLesson();
    };

    const addLesson = () => {
        setLessons([...lessons, { id: uuidv4(), title: 'Select a lesson' }]);
    };

    const removeLesson = (index) => {
        const updatedLessons = lessons.filter((_, i) => i !== index);
        const updatedSelectedLessons = selectedLessons.filter((_, i) => i !== index);

        if (updatedLessons.length === 0) {
            updatedLessons.push({ id: uuidv4(), title: 'Select a lesson' });
        }

        setLessons(updatedLessons);
        setSelectedLessons(updatedSelectedLessons);
    };

    const addTopic = () => {
        setTopics([...topics, '']);
    };

    const removeTopic = (index) => {
        const updatedTopics = topics.filter((_, i) => i !== index);
        setTopics(updatedTopics);
    };

    const handleTopicChange = (index, value) => {
        const updatedTopics = topics.map((topic, i) => i === index ? value : topic);
        setTopics(updatedTopics);
    };

    const getContentOptions = (index) => {
        const draftOptions = drafts.map(draft => ({
            label: <ContentDropdownItem content={draft} onSelect={(content) => handleLessonSelect(content, index)} selected={lessons[index] && lessons[index].id === draft.id} />,
            value: draft.id
        }));

        const resourceOptions = resources.map(resource => {
            const { id, kind, pubkey, content, title, summary, image, published_at, d, topics } = parseEvent(resource);
            return {
                label: <ContentDropdownItem content={{ id, kind, pubkey, content, title, summary, image, published_at, d, topics }} onSelect={(content) => handleLessonSelect(content, index)} selected={lessons[index] && lessons[index].id === id} />,
                value: id
            };
        });

        const workshopOptions = workshops.map(workshop => {
            const { id, kind, pubkey, content, title, summary, image, published_at, d, topics } = parseEvent(workshop);
            return {
                label: <ContentDropdownItem content={{ id, kind, pubkey, content, title, summary, image, published_at, d, topics }} onSelect={(content) => handleLessonSelect(content, index)} selected={lessons[index] && lessons[index].id === id} />,
                value: id
            };
        });

        return [
            {
                label: 'Drafts',
                items: draftOptions
            },
            {
                label: 'Resources',
                items: resourceOptions
            },
            {
                label: 'Workshops',
                items: workshopOptions
            }
        ];
    };

    const lessonOptions = getContentOptions();

    return (
        <form onSubmit={handleSubmit}>
            <div className="p-inputgroup flex-1">
                <InputText value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" />
            </div>
            <div className="p-inputgroup flex-1 mt-4">
                <InputText value={summary} onChange={(e) => setSummary(e.target.value)} placeholder="Summary" />
            </div>
            <div className="p-inputgroup flex-1 mt-4">
                <InputText value={coverImage} onChange={(e) => setCoverImage(e.target.value)} placeholder="Cover Image URL" />
            </div>
            <div className="p-inputgroup flex-1 mt-4 flex-col">
                <p className="py-2">Paid Course</p>
                <InputSwitch checked={checked} onChange={(e) => setChecked(e.value)} />
                {checked && (
                    <div className="p-inputgroup flex-1 py-4">
                        <InputNumber value={price} onValueChange={(e) => setPrice(e.value)} placeholder="Price (sats)" />
                    </div>
                )}
            </div>
            <div className="mt-8 flex-col w-full">
                <div className="mt-4 flex-col w-full">
                    {selectedLessons.map((lesson, index) => (
                        <div key={lesson.id} className="p-inputgroup flex-1 mt-4">
                            <ContentDropdownItem content={lesson} selected={true} />
                            <Button icon="pi pi-times" className="p-button-danger" onClick={() => removeLesson(index)} />
                        </div>
                    ))}
                    {lessons.map((lesson, index) => (
                        <div key={lesson.id} className="p-inputgroup flex-1 mt-4">
                            <Dropdown
                                value={lesson.title}
                                options={getContentOptions(index)}
                                onChange={(e) => handleLessonChange(e, index)}
                                placeholder="Select a Lesson"
                                itemTemplate={(option) => option.label}
                                optionLabel="label"
                                optionGroupLabel="label"
                                optionGroupChildren="items"
                            />
                        </div>
                    ))}
                </div>
            </div>
            <div className="mt-4 flex-col w-full">
                {topics.map((topic, index) => (
                    <div key={index} className="p-inputgroup flex-1 mt-4">
                        <InputText value={topic} onChange={(e) => handleTopicChange(index, e.target.value)} placeholder={`Topic #${index + 1}`} className="w-full" />
                        {index > 0 && (
                            <Button icon="pi pi-times" className="p-button-danger mt-2" onClick={() => removeTopic(index)} />
                        )}
                    </div>
                ))}
                <Button type="button" icon="pi pi-plus" onClick={addTopic} className="p-button-outlined mt-2" />
            </div>
            <div className="flex justify-center mt-8">
                <Button type="submit" label="Submit" className="p-button-raised p-button-success" />
            </div>
        </form>
    );
}

export default CourseForm;
```


testing with an unpublished resoure abby


<iframe width="560" height="315" src="https://www.youtube.com/embed/-G3bpS5zJ6g" frameborder="0" allowfullscreen></iframe>


also wanna test publishing draft in the middle of this flow


```js
import React, { useRef } from 'react';
import { OverlayPanel } from 'primereact/overlaypanel';
import ZapForm from './ZapForm';
import { ProgressSpinner } from 'primereact/progressspinner';

const ZapDisplay = ({ zapAmount, event }) => {
    const op = useRef(null);
    return (
        <>
            <p className="text-xs cursor-pointer" onClick={(e) => op.current.toggle(e)}>
                <i className="pi pi-bolt text-yellow-300"></i>

                {zapAmount || zapAmount === 0 ? zapAmount : <ProgressSpinner />}
            </p>
            <OverlayPanel className='w-[40%] h-[40%]' ref={op}>
                <ZapForm event={event} />
            </OverlayPanel>
        </>
    )
}

export default ZapDisplay;
```


```js
import React, { createContext, useContext, useRef } from 'react';
import { Toast } from 'primereact/toast';

const ToastContext = createContext();

export const useToast = () => useContext(ToastContext);

export const ToastProvider = ({ children }) => {
    const toast = useRef(null);

    const showToast = (severity, summary, detail) => {
        toast.current.show({ severity, summary, detail });
    };

    return (
        <ToastContext.Provider value={{ showToast }}>
            <Toast ref={toast} />
            {children}
        </ToastContext.Provider>
    );
};
```


<iframe width="560" height="315" src="https://www.youtube.com/embed/WA9gVKKPsBo" frameborder="0" allowfullscreen></iframe>


Testing another course listr with the correct format hopefully


# test

## hello world

**haha**

lol

```js
const y = (m * x) + b;
```

Once again testing another resource lorem ipsum


<pre class="ql-syntax" spellcheck="false"># Bitcoin: A Peer-to-Peer Electronic Cash System

Satoshi Nakamoto
[satoshin@gmx.com](mailto:satoshin@gmx.com)
www.bitcoin.org

**Abstract.** A purely peer-to-peer version of electronic cash would allow online payments to be sent directly from one party to another without going through a financial institution. Digital signatures provide part of the solution, but the main benefits are lost if a trusted third party is still required to prevent double-spending. We propose a solution to the double-spending problem using a peer-to-peer network. The network timestamps transactions by hashing them into an ongoing chain of hash-based proof-of-work, forming a record that cannot be changed without redoing the proof-of-work. The longest chain not only serves as proof of the sequence of events witnessed, but proof that it came from the largest pool of CPU power. As long as a majority of CPU power is controlled by nodes that are not cooperating to attack the network, they'll generate the longest chain and outpace attackers. The network itself requires minimal structure. Messages are broadcast on a best effort basis, and nodes can leave and rejoin the network at will, accepting the longest proof-of-work chain as proof of what happened while they were gone.

## 1. Introduction

Commerce on the Internet has come to rely almost exclusively on financial institutions serving as trusted third parties to process electronic payments. While the system works well enough for most transactions, it still suffers from the inherent weaknesses of the trust based model. Completely non-reversible transactions are not really possible, since financial institutions cannot avoid mediating disputes. The cost of mediation increases transaction costs, limiting the minimum practical transaction size and cutting off the possibility for small casual transactions, and there is a broader cost in the loss of ability to make non-reversible payments for non-reversible services. With the possibility of reversal, the need for trust spreads. Merchants must be wary of their customers, hassling them for more information than they would otherwise need. A certain percentage of fraud is accepted as unavoidable. These costs and payment uncertainties can be avoided in person by using physical currency, but no mechanism exists to make payments over a communications channel without a trusted party.

What is needed is an electronic payment system based on cryptographic proof instead of trust, allowing any two willing parties to transact directly with each other without the need for a trusted third party. Transactions that are computationally impractical to reverse would protect sellers from fraud, and routine escrow mechanisms could easily be implemented to protect buyers. In this paper, we propose a solution to the double-spending problem using a peer-to-peer distributed timestamp server to generate computational proof of the chronological order of transactions. The system is secure as long as honest nodes collectively control more CPU power than any cooperating group of attacker nodes.

## 2. Transactions

We define an electronic coin as a chain of digital signatures. Each owner transfers the coin to the next by digitally signing a hash of the previous transaction and the public key of the next owner and adding these to the end of the coin. A payee can verify the signatures to verify the chain of ownership.

```
      ┌─────────────────────┐               ┌─────────────────────┐              ┌─────────────────────┐
      │                     │               │                     │              │                     │
      │    Transaction      │               │    Transaction      │              │    Transaction      │
      │                     │               │                     │              │                     │
      │   ┌─────────────┐   │               │   ┌─────────────┐   │              │   ┌─────────────┐   │
      │   │ Owner 1's   │   │               │   │ Owner 2's   │   │              │   │ Owner 3's   │   │
      │   │ Public Key  │   │               │   │ Public Key  │   │              │   │ Public Key  │   │
      │   └───────┬─────┘   │               │   └───────┬─────┘   │              │   └───────┬─────┘   │
      │           │    .    │               │           │    .    │              │           │         │
──────┼─────────┐ │    .    ├───────────────┼─────────┐ │    .    ├──────────────┼─────────┐ │         │
      │         │ │    .    │               │         │ │    .    │              │         │ │         │
      │      ┌──▼─▼──┐ .    │               │      ┌──▼─▼──┐ .    │              │      ┌──▼─▼──┐      │
      │      │ Hash  │ .    │               │      │ Hash  │ .    │              │      │ Hash  │      │
      │      └───┬───┘ .    │    Verify     │      └───┬───┘ .    │    Verify    │      └───┬───┘      │
      │          │     ............................    │     ...........................    │          │
      │          │          │               │     │    │          │              │     │    │          │
      │   ┌──────▼──────┐   │               │   ┌─▼────▼──────┐   │              │   ┌─▼────▼──────┐   │
      │   │ Owner 0's   │   │      Sign     │   │ Owner 1's   │   │      Sign    │   │ Owner 2's   │   │
      │   │ Signature   │   │      ...........─►│ Signature   │   │     ...........─►│ Signature   │   │
      │   └─────────────┘   │      .        │   └─────────────┘   │     .        │   └─────────────┘   │
      │                     │      .        │                     │     .        │                     │
      └─────────────────────┘      .        └─────────────────────┘     .        └─────────────────────┘
                                   .                                    .
          ┌─────────────┐          .            ┌─────────────┐         .            ┌─────────────┐
          │ Owner 1's   │...........            │ Owner 2's   │..........            │ Owner 3's   │
          │ Private Key │                       │ Private Key │                      │ Private Key │
          └─────────────┘                       └─────────────┘                      └─────────────┘
```

The problem of course is the payee can't verify that one of the owners did not double-spend the coin. A common solution is to introduce a trusted central authority, or mint, that checks every transaction for double spending. After each transaction, the coin must be returned to the mint to issue a new coin, and only coins issued directly from the mint are trusted not to be double-spent. The problem with this solution is that the fate of the entire money system depends on the company running the mint, with every transaction having to go through them, just like a bank.

We need a way for the payee to know that the previous owners did not sign any earlier transactions. For our purposes, the earliest transaction is the one that counts, so we don't care about later attempts to double-spend. The only way to confirm the absence of a transaction is to be aware of all transactions. In the mint based model, the mint was aware of all transactions and decided which arrived first. To accomplish this without a trusted party, transactions must be publicly announced [^1], and we need a system for participants to agree on a single history of the order in which they were received. The payee needs proof that at the time of each transaction, the majority of nodes agreed it was the first received.

## 3. Timestamp Server

The solution we propose begins with a timestamp server. A timestamp server works by taking a hash of a block of items to be timestamped and widely publishing the hash, such as in a newspaper or Usenet post [^2] [^3] [^4] [^5]. The timestamp proves that the data must have existed at the time, obviously, in order to get into the hash. Each timestamp includes the previous timestamp in its hash, forming a chain, with each additional timestamp reinforcing the ones before it.

```
             ┌──────┐                        ┌──────┐
────────────►│      ├───────────────────────►│      ├───────────────────►
             │ Hash │                        │ Hash │
        ┌───►│      │                   ┌───►│      │
        │    └──────┘                   │    └──────┘
        │                               │
       ┌┴──────────────────────────┐   ┌┴──────────────────────────┐
       │ Block                     │   │ Block                     │
       │ ┌─────┐ ┌─────┐ ┌─────┐   │   │ ┌─────┐ ┌─────┐ ┌─────┐   │
       │ │Item │ │Item │ │...  │   │   │ │Item │ │Item │ │...  │   │
       │ └─────┘ └─────┘ └─────┘   │   │ └─────┘ └─────┘ └─────┘   │
       │                           │   │                           │
       └───────────────────────────┘   └───────────────────────────┘
```

## 4. Proof-of-Work

To implement a distributed timestamp server on a peer-to-peer basis, we will need to use a proof-of-work system similar to Adam Back's Hashcash [^6], rather than newspaper or Usenet posts. The proof-of-work involves scanning for a value that when hashed, such as with SHA-256, the hash begins with a number of zero bits. The average work required is exponential in the number of zero bits required and can be verified by executing a single hash.

For our timestamp network, we implement the proof-of-work by incrementing a nonce in the block until a value is found that gives the block's hash the required zero bits. Once the CPU effort has been expended to make it satisfy the proof-of-work, the block cannot be changed without redoing the work. As later blocks are chained after it, the work to change the block would include redoing all the blocks after it.

```
       ┌────────────────────────────────────────┐      ┌────────────────────────────────────────┐
       │  Block                                 │      │  Block                                 │
       │  ┌──────────────────┐ ┌──────────────┐ │      │  ┌──────────────────┐ ┌──────────────┐ │
───────┼─►│ Prev Hash        │ │ Nonce        │ ├──────┼─►│ Prev Hash        │ │ Nonce        │ │
       │  └──────────────────┘ └──────────────┘ │      │  └──────────────────┘ └──────────────┘ │
       │                                        │      │                                        │
       │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │      │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
       │ │ Tx       │ │ Tx       │ │ ...      │ │      │ │ Tx       │ │ Tx       │ │ ...      │ │
       │ └──────────┘ └──────────┘ └──────────┘ │      │ └──────────┘ └──────────┘ └──────────┘ │
       │                                        │      │                                        │
       └────────────────────────────────────────┘      └────────────────────────────────────────┘
```

The proof-of-work also solves the problem of determining representation in majority decision making. If the majority were based on one-IP-address-one-vote, it could be subverted by anyone able to allocate many IPs. Proof-of-work is essentially one-CPU-one-vote. The majority decision is represented by the longest chain, which has the greatest proof-of-work effort invested in it. If a majority of CPU power is controlled by honest nodes, the honest chain will grow the fastest and outpace any competing chains. To modify a past block, an attacker would have to redo the proof-of-work of the block and all blocks after it and then catch up with and surpass the work of the honest nodes. We will show later that the probability of a slower attacker catching up diminishes exponentially as subsequent blocks are added.

To compensate for increasing hardware speed and varying interest in running nodes over time, the proof-of-work difficulty is determined by a moving average targeting an average number of blocks per hour. If they're generated too fast, the difficulty increases.

## 5. Network

The steps to run the network are as follows:

1. New transactions are broadcast to all nodes.
2. Each node collects new transactions into a block.
3. Each node works on finding a difficult proof-of-work for its block.
4. When a node finds a proof-of-work, it broadcasts the block to all nodes.
5. Nodes accept the block only if all transactions in it are valid and not already spent.
6. Nodes express their acceptance of the block by working on creating the next block in the chain, using the hash of the accepted block as the previous hash.

Nodes always consider the longest chain to be the correct one and will keep working on extending it. If two nodes broadcast different versions of the next block simultaneously, some nodes may receive one or the other first. In that case, they work on the first one they received, but save the other branch in case it becomes longer. The tie will be broken when the next proof-of-work is found and one branch becomes longer; the nodes that were working on the other branch will then switch to the longer one.

New transaction broadcasts do not necessarily need to reach all nodes. As long as they reach many nodes, they will get into a block before long. Block broadcasts are also tolerant of dropped messages. If a node does not receive a block, it will request it when it receives the next block and realizes it missed one.

## 6. Incentive

By convention, the first transaction in a block is a special transaction that starts a new coin owned by the creator of the block. This adds an incentive for nodes to support the network, and provides a way to initially distribute coins into circulation, since there is no central authority to issue them. The steady addition of a constant of amount of new coins is analogous to gold miners expending resources to add gold to circulation. In our case, it is CPU time and electricity that is expended.

The incentive can also be funded with transaction fees. If the output value of a transaction is less than its input value, the difference is a transaction fee that is added to the incentive value of the block containing the transaction. Once a predetermined number of coins have entered circulation, the incentive can transition entirely to transaction fees and be completely inflation free.

The incentive may help encourage nodes to stay honest. If a greedy attacker is able to assemble more CPU power than all the honest nodes, he would have to choose between using it to defraud people by stealing back his payments, or using it to generate new coins. He ought to find it more profitable to play by the rules, such rules that favour him with more new coins than everyone else combined, than to undermine the system and the validity of his own wealth.

## 7. Reclaiming Disk Space

Once the latest transaction in a coin is buried under enough blocks, the spent transactions before it can be discarded to save disk space. To facilitate this without breaking the block's hash, transactions are hashed in a Merkle Tree [^7] [^2] [^5], with only the root included in the block's hash. Old blocks can then be compacted by stubbing off branches of the tree. The interior hashes do not need to be stored.

```
┌──────────────────────────────────────────┐    ┌──────────────────────────────────────────┐
│                                          │    │                                          │
│ Block ┌─────────────────────────────┐    │    │ Block ┌─────────────────────────────┐    │
│       │  Block Header (Block Hash)  │    │    │       │  Block Header (Block Hash)  │    │
│       │ ┌────────────┐ ┌─────────┐  │    │    │       │ ┌────────────┐ ┌─────────┐  │    │
│       │ │ Prev Hash  │ │ Nonce   │  │    │    │       │ │ Prev Hash  │ │ Nonce   │  │    │
│       │ └────────────┘ └─────────┘  │    │    │       │ └────────────┘ └─────────┘  │    │
│       │                             │    │    │       │                             │    │
│       │     ┌─────────────┐         │    │    │       │     ┌─────────────┐         │    │
│       │     │  Root Hash  │         │    │    │       │     │  Root Hash  │         │    │
│       │     └─────▲─▲─────┘         │    │    │       │     └─────▲─▲─────┘         │    │
│       │           │ │               │    │    │       │           │ │               │    │
│       │           │ │               │    │    │       │           │ │               │    │
│       └───────────┼─┼───────────────┘    │    │       └───────────┼─┼───────────────┘    │
│                   │ │                    │    │                   │ │                    │
│     ..........    │ │     ..........     │    │     ┌────────┐    │ │     ..........     │
│     .        ─────┘ └─────.        .     │    │     │        ├────┘ └─────.        .     │
│     . Hash01 .            . Hash23 .     │    │     │ Hash01 │            . Hash23 .     │
│     .▲.....▲..            .▲.....▲..     │    │     │        │            .▲.....▲..     │
│      │     │               │     │       │    │     └────────┘             │     │       │
│      │     │               │     │       │    │                            │     │       │
│      │     │               │     │       │    │                            │     │       │
│ .....│.. ..│.....     .....│.. ..│.....  │    │                       ┌────┴─┐ ..│.....  │
│ .      . .      .     .      . .      .  │    │                       │      │ .      .  │
│ .Hash0 . .Hash1 .     .Hash2 . .Hash3 .  │    │                       │Hash2 │ .Hash3 .  │
│ ...▲.... ...▲....     ...▲.... ...▲....  │    │                       │      │ .      .  │
│    │        │            │        │      │    │                       └──────┘ ...▲....  │
│    │        │            │        │      │    │                                   │      │
│    │        │            │        │      │    │                                   │      │
│ ┌──┴───┐ ┌──┴───┐     ┌──┴───┐ ┌──┴───┐  │    │                                ┌──┴───┐  │
│ │ Tx0  │ │ Tx1  │     │ Tx2  │ │ Tx3  │  │    │                                │ Tx3  │  │
│ └──────┘ └──────┘     └──────┘ └──────┘  │    │                                └──────┘  │
│                                          │    │                                          │
└──────────────────────────────────────────┘    └──────────────────────────────────────────┘
     Transactions Hashed in a Merkle Tree              After Pruning Tx0-2 from the Block
```

A block header with no transactions would be about 80 bytes. If we suppose blocks are generated every 10 minutes, 80 bytes * 6 * 24 * 365 = 4.2MB per year. With computer systems typically selling with 2GB of RAM as of 2008, and Moore's Law predicting current growth of 1.2GB per year, storage should not be a problem even if the block headers must be kept in memory.

## 8. Simplified Payment Verification

It is possible to verify payments without running a full network node. A user only needs to keep a copy of the block headers of the longest proof-of-work chain, which he can get by querying network nodes until he's convinced he has the longest chain, and obtain the Merkle branch linking the transaction to the block it's timestamped in. He can't check the transaction for himself, but by linking it to a place in the chain, he can see that a network node has accepted it, and blocks added after it further confirm the network has accepted it.

```
     Longest Proof-of-Work Chain
        ┌────────────────────────────────────────┐      ┌────────────────────────────────────────┐       ┌────────────────────────────────────────┐
        │   Block Header                         │      │   Block Header                         │       │   Block Header                         │
        │  ┌──────────────────┐ ┌──────────────┐ │      │  ┌──────────────────┐ ┌──────────────┐ │       │  ┌──────────────────┐ ┌──────────────┐ │
 ───────┼─►│ Prev Hash        │ │ Nonce        │ ├──────┼─►│ Prev Hash        │ │ Nonce        │ ├───────┼─►│ Prev Hash        │ │ Nonce        │ ├────────►
        │  └──────────────────┘ └──────────────┘ │      │  └──────────────────┘ └──────────────┘ │       │  └──────────────────┘ └──────────────┘ │
        │                                        │      │                                        │       │                                        │
        │     ┌───────────────────┐              │      │    ┌────────────────────┐              │       │     ┌───────────────────┐              │
        │     │   Merkle Root     │              │      │    │   Merkle Root      │              │       │     │   Merkle Root     │              │
        │     └───────────────────┘              │      │    └────────▲─▲─────────┘              │       │     └───────────────────┘              │
        │                                        │      │             │ │                        │       │                                        │
        └────────────────────────────────────────┘      └─────────────┼─┼────────────────────────┘       └────────────────────────────────────────┘
                                                                      │ │
                                                                      │ │
                                                        ┌────────┐    │ │     ..........
                                                        │        ├────┘ └─────.        .
                                                        │ Hash01 │            . Hash23 .
                                                        │        │            .▲.....▲..
                                                        └────────┘             │     │
                                                                               │     │
                                                                               │     │   Merkle Branch for Tx3
                                                                               │     │
                                                                         ┌─────┴─┐ ..│.....
                                                                         │       │ .      .
                                                                         │ Hash2 │ .Hash3 .
                                                                         │       │ .      .
                                                                         └───────┘ ...▲....
                                                                                │
                                                                                │
                                                                                ┌───┴───┐
                                                                                │  Tx3  │
                                                                                └───────┘
```

As such, the verification is reliable as long as honest nodes control the network, but is more vulnerable if the network is overpowered by an attacker. While network nodes can verify transactions for themselves, the simplified method can be fooled by an attacker's fabricated transactions for as long as the attacker can continue to overpower the network. One strategy to protect against this would be to accept alerts from network nodes when they detect an invalid block, prompting the user's software to download the full block and alerted transactions to confirm the inconsistency. Businesses that receive frequent payments will probably still want to run their own nodes for more independent security and quicker verification.

## 9. Combining and Splitting Value

Although it would be possible to handle coins individually, it would be unwieldy to make a separate transaction for every cent in a transfer. To allow value to be split and combined, transactions contain multiple inputs and outputs. Normally there will be either a single input from a larger previous transaction or multiple inputs combining smaller amounts, and at most two outputs: one for the payment, and one returning the change, if any, back to the sender.

```
     ┌──────────────────────┐
     │ Transaction          │
     │                      │
     │   ┌─────┐  ┌─────┐   │
─────┼──►│ in  │  │ out │ ──┼─────►
     │   └─────┘  └─────┘   │
     │                      │
     │                      │
     │   ┌─────┐  ┌─────┐   │
─────┼──►│ in  │  │ ... │ ──┼─────►
     │   └─────┘  └─────┘   │
     │                      │
     │                      │
     │   ┌─────┐            │
─────┼──►│...  │            │
     │   └─────┘            │
     │                      │
     └──────────────────────┘
```
It should be noted that fan-out, where a transaction depends on several transactions, and those transactions depend on many more, is not a problem here. There is never the need to extract a complete standalone copy of a transaction's history.

## 10. Privacy

The traditional banking model achieves a level of privacy by limiting access to information to the parties involved and the trusted third party. The necessity to announce all transactions publicly precludes this method, but privacy can still be maintained by breaking the flow of information in another place: by keeping public keys anonymous. The public can see that someone is sending an amount to someone else, but without information linking the transaction to anyone. This is similar to the level of information released by stock exchanges, where the time and size of individual trades, the "tape", is made public, but without telling who the parties were.

```
Traditional Privacy Models                                                │
                                      ┌─────────────┐   ┌──────────────┐  │  ┌────────┐
┌──────────────┐  ┌──────────────┐    │  Trusted    │   │              │  │  │        │
│  Identities  ├──┤ Transactions ├───►│ Third Party ├──►│ Counterparty │  │  │ Public │
└──────────────┘  └──────────────┘    │             │   │              │  │  │        │
                                      └─────────────┘   └──────────────┘  │  └────────┘
                                                                          │

New Privacy Model
                                       ┌────────┐
┌──────────────┐ │ ┌──────────────┐    │        │
│  Identities  │ │ │ Transactions ├───►│ Public │
└──────────────┘ │ └──────────────┘    │        │
                                       └────────┘
```
As an additional firewall, a new key pair should be used for each transaction to keep them from being linked to a common owner. Some linking is still unavoidable with multi-input transactions, which necessarily reveal that their inputs were owned by the same owner. The risk is that if the owner of a key is revealed, linking could reveal other transactions that belonged to the same owner.

## 11. Calculations
We consider the scenario of an attacker trying to generate an alternate chain faster than the honest chain. Even if this is accomplished, it does not throw the system open to arbitrary changes, such as creating value out of thin air or taking money that never belonged to the attacker. Nodes are not going to accept an invalid transaction as payment, and honest nodes will never accept a block containing them. An attacker can only try to change one of his own transactions to take back money he recently spent.

The race between the honest chain and an attacker chain can be characterized as a Binomial Random Walk. The success event is the honest chain being extended by one block, increasing its lead by +1, and the failure event is the attacker's chain being extended by one block, reducing the gap by -1.

The probability of an attacker catching up from a given deficit is analogous to a Gambler's Ruin problem. Suppose a gambler with unlimited credit starts at a deficit and plays potentially an infinite number of trials to try to reach breakeven. We can calculate the probability he ever reaches breakeven, or that an attacker ever catches up with the honest chain, as follows [^8]:

```plaintext
p = probability an honest node finds the next block<
q = probability the attacker finds the next block
q = probability the attacker will ever catch up from z blocks behind
``````

$$
qz =
\begin{cases}
1 & \text{if } p \leq q \\
\left(\frac{q}{p}\right) z & \text{if } p > q
\end{cases}
$$

Given our assumption that p > q, the probability drops exponentially as the number of blocks the attacker has to catch up with increases. With the odds against him, if he doesn't make a lucky lunge forward early on, his chances become vanishingly small as he falls further behind.

We now consider how long the recipient of a new transaction needs to wait before being sufficiently certain the sender can't change the transaction. We assume the sender is an attacker who wants to make the recipient believe he paid him for a while, then switch it to pay back to himself after some time has passed. The receiver will be alerted when that happens, but the sender hopes it will be too late.

The receiver generates a new key pair and gives the public key to the sender shortly before signing. This prevents the sender from preparing a chain of blocks ahead of time by working on it continuously until he is lucky enough to get far enough ahead, then executing the transaction at that moment. Once the transaction is sent, the dishonest sender starts working in secret on a parallel chain containing an alternate version of his transaction.

The recipient waits until the transaction has been added to a block and z blocks have been linked after it. He doesn't know the exact amount of progress the attacker has made, but assuming the honest blocks took the average expected time per block, the attacker's potential progress will be a Poisson distribution with expected value:

$$
\lambda = z\frac{q}{p}
$$

To get the probability the attacker could still catch up now, we multiply the Poisson density for each amount of progress he could have made by the probability he could catch up from that point:

$$
\sum_{k=0}^{\infty} \frac{\lambda^k e^{-\lambda}}{k!} \cdot \left\{
\begin{array}{cl}
\left(\frac{q}{p}\right)^{(z-k)} & \text{if } k \leq z \\
1 & \text{if } k > z
\end{array}
\right.
$$

Rearranging to avoid summing the infinite tail of the distribution...

$$
1 - \sum_{k=0}^{z} \frac{\lambda^k e^{-\lambda}}{k!} \left(1-\left(\frac{q}{p}\right)^{(z-k)}\right)
$$

Converting to C code...

```c
#include <math.h>

double AttackerSuccessProbability(double q, int z)
{
    double p = 1.0 - q;
    double lambda = z * (q / p);
    double sum = 1.0;
    int i, k;
    for (k = 0; k <= z; k++)
    {
        double poisson = exp(-lambda);
        for (i = 1; i <= k; i++)
            poisson *= lambda / i;
        sum -= poisson * (1 - pow(q / p, z - k));
    }
    return sum;
}
```
Running some results, we can see the probability drop off exponentially with z.

```plaintext
q=0.1
z=0 P=1.0000000
z=1 P=0.2045873
z=2 P=0.0509779
z=3 P=0.0131722
z=4 P=0.0034552
z=5 P=0.0009137
z=6 P=0.0002428
z=7 P=0.0000647
z=8 P=0.0000173
z=9 P=0.0000046
z=10 P=0.0000012

q=0.3
z=0 P=1.0000000
z=5 P=0.1773523
z=10 P=0.0416605
z=15 P=0.0101008
z=20 P=0.0024804
z=25 P=0.0006132
z=30 P=0.0001522
z=35 P=0.0000379
z=40 P=0.0000095
z=45 P=0.0000024
z=50 P=0.0000006
```
Solving for P less than 0.1%...
```plaintext
P < 0.001
q=0.10 z=5
q=0.15 z=8
q=0.20 z=11
q=0.25 z=15
q=0.30 z=24
q=0.35 z=41
q=0.40 z=89
q=0.45 z=340
```
## 12. Conclusion
We have proposed a system for electronic transactions without relying on trust. We started with the usual framework of coins made from digital signatures, which provides strong control of ownership, but is incomplete without a way to prevent double-spending. To solve this, we proposed a peer-to-peer network using proof-of-work to record a public history of transactions that quickly becomes computationally impractical for an attacker to change if honest nodes control a majority of CPU power. The network is robust in its unstructured simplicity. Nodes work all at once with little coordination. They do not need to be identified, since messages are not routed to any particular place and only need to be delivered on a best effort basis. Nodes can leave and rejoin the network at will, accepting the proof-of-work chain as proof of what happened while they were gone. They vote with their CPU power, expressing their acceptance of valid blocks by working on extending them and rejecting invalid blocks by refusing to work on them. Any needed rules and incentives can be enforced with this consensus mechanism.
<br>

### References
---
[^1]: W. Dai, "b-money," http://www.weidai.com/bmoney.txt, 1998.
[^2]: H. Massias, X.S. Avila, and J.-J. Quisquater, "Design of a secure timestamping service with minimal
trust requirements," In 20th Symposium on Information Theory in the Benelux, May 1999.
[^3]: S. Haber, W.S. Stornetta, "How to time-stamp a digital document," In Journal of Cryptology, vol 3, no
2, pages 99-111, 1991.
[^4]: D. Bayer, S. Haber, W.S. Stornetta, "Improving the efficiency and reliability of digital time-stamping,"
In Sequences II: Methods in Communication, Security and Computer Science, pages 329-334, 1993.
[^5]: S. Haber, W.S. Stornetta, "Secure names for bit-strings," In Proceedings of the 4th ACM Conference
on Computer and Communications Security, pages 28-35, April 1997.
[^6]: A. Back, "Hashcash - a denial of service counter-measure,"
http://www.hashcash.org/papers/hashcash.pdf, 2002.
[^7]: R.C. Merkle, "Protocols for public key cryptosystems," In Proc. 1980 Symposium on Security and
Privacy, IEEE Computer Society, pages 122-133, April 1980.
[^8]: W. Feller, "An introduction to probability theory and its applications," 1957.
</pre><p><br></p>


<iframe width="560" height="315" src="https://www.youtube.com/embed/WoEsme3nvRg" frameborder="0" allowfullscreen></iframe>