<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by anurag asawa on Medium]]></title>
        <description><![CDATA[Stories by anurag asawa on Medium]]></description>
        <link>https://medium.com/@anuragasawa200?source=rss-edc1c46370c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*szTFj24s8vQoSvBZ</url>
            <title>Stories by anurag asawa on Medium</title>
            <link>https://medium.com/@anuragasawa200?source=rss-edc1c46370c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:43:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anuragasawa200/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Built the MCP Server to Sync AI with Fast-Changing Docs]]></title>
            <link>https://medium.com/@anuragasawa200/how-i-built-the-mcp-server-to-sync-ai-with-fast-changing-docs-35a016baacfd?source=rss-edc1c46370c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/35a016baacfd</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ton]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[anurag asawa]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 12:45:49 GMT</pubDate>
            <atom:updated>2025-09-15T17:11:08.814Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever ask an AI about a new updates, like TON’s recently launched TOLK language, only to get advice that’s already out of date? I saw this frustration all the time working with developers on projects whose documentation changes very fast.</p><p>Tech moves at breakneck speed — docs get updated, APIs shift, new languages like TOLK drop — but AI assistants lag behind, feeding us answers that send us down dead ends. Through conversations with TON community developers, we all hit the same wall: ask about a new feature, get stale advice, waste hours debugging, then find out the docs changed. That problem drove me to build a solution: the TON Docs MCP Server, a tool that lets AI pull live documentation and stay as current as the tech we’re building.</p><h3>First Thinking Approach Was Building The RAG System</h3><p>I reached for the obvious solution: <strong>RAG</strong> <strong>(Retrieval-Augmented Generation)</strong>. The logic seemed bulletproof — store all the documentation in a vector database, embed everything, and let the AI retrieve relevant context on demand.</p><pre>const ragQuery = async (question: string) =&gt; <br>{ <br>const embeddings = await generateEmbeddings(question); <br>const relevantDocs = await vectorDB.similaritySearch(embeddings); <br>return formatContext(relevantDocs);<br> };</pre><p><strong><em>The wake-up call came quickly:</em></strong></p><p>The fundamental flaw wasn’t technical — it was conceptual. RAG systems are essentially sophisticated caches. And like all caches, they have a nasty habit of becoming stale at the worst possible moments.</p><ul><li><strong>The Maintenance Nightmare</strong>: Every documentation update required re-indexing. Miss one update, and you’re back to giving outdated advice.</li><li><strong>The Cost Spiral</strong>: Vector databases aren’t free. Embedding generation isn’t free.</li></ul><h3>The Real and Simplistic Solution</h3><p>While analyzing the consequences of traditional RAG approaches and exploring the problem space, I had a simple realization:</p><p><strong>Why not just read the documentation directly from GitHub?</strong></p><p>Classic case of overcomplicating things when the simple approach was right there. GitHub repositories contain the most up-to-date documentation. GitHub has a raw content API. Instead of building elaborate caching systems that inevitably become stale, why not just ask the source directly?</p><p>This insight led to what I call the “direct integration approach” — and ultimately, the building of the TON Docs MCP.</p><h3>Understanding MCP and Why It Was The Missing Piece</h3><p>Before diving into the solution, let me explain MCP (Model Context Protocol) for those unfamiliar. Think of MCP as a standardized way for AI assistants to access external tools and data in real-time.</p><p>Instead of training models with static data, MCP lets you create “servers” that AI assistants can query dynamically. It’s like giving your AI assistant the ability to make API calls, but in a structured, reliable way.</p><p><strong>The beauty of MCP:</strong></p><ul><li>Real-time data access</li><li>Standardized protocol</li><li>Works across different AI platforms</li><li>No need for model retraining</li></ul><h3>System Architecture</h3><p>The diagram above illustrates how the TON Docs MCP Server creates a seamless bridge between AI assistants (like Claude or Cursor) and live documentation sources. Here’s how the system works in practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*v1hWtUyHbeoRLEfBnGSBWQ.png" /><figcaption>MCP Server Architecture</figcaption></figure><p>When a developer asks a question about TOLK smart contracts, the system doesn’t rely on pre-indexed knowledge. Instead, it:</p><ol><li><strong>Receives the query</strong> through the MCP protocol from the IDE or AI assistant</li><li><strong>Routes to the appropriate tool</strong> — whether that’s TOLK Help, FunC Stdlib, or FunC Cookbook based on the query context</li><li><strong>Fetches live documentation</strong> directly from GitHub’s raw content API</li><li><strong>Processes and contextualizes</strong> the information specifically for the user’s question</li><li><strong>Returns structured responses</strong> with code examples, setup guides, and syntax documentation</li></ol><p>The beauty of this architecture lies in its simplicity. Each tool specializes in a specific aspect of TON development:</p><ul><li><strong>TOLK Help Tool</strong>: Handles queries about TON’s newer smart contract language</li><li><strong>FunC Help Tools</strong>: Manages questions about the original FunC language, split into core help, standard library reference, and cookbook patterns</li><li><strong>Documentation Sources</strong>: All pointing directly to the authoritative GitHub repositories</li></ul><p>This eliminates the traditional bottleneck of keeping cached information synchronized with rapidly changing documentation.</p><p>The implementation starts with creating the MCP server and exposing our specialized tools. Here’s how the server registers each tool to handle different types of TON development queries:</p><pre>// lib/index.ts - The surprisingly simple foundation<br>export function createMcp() {<br>  return createMcpHandler(<br>    (server: McpServer) =&gt; {<br>      // Register TOLK tools<br>      TOLKTools.forEach((tool: TONTool) =&gt; {<br>        server.tool(tool.title, tool.description, tool.parameters, tool.func);<br>      });<br><br>      // Register FunC tools  <br>      FUNCTools.forEach((tool: TONTool) =&gt; {<br>        server.tool(tool.title, tool.description, tool.parameters, tool.func);<br>      });<br>    }<br>  );<br>}</pre><p>We firstly creates the MCP handler and iterates through our predefined tool arrays — TolkTools for the newer TOLK language and FuncTools for the original FunC language. Each tool gets registered with the server using its title, description, input parameters, and the actual function that processes queries.</p><p>The key insight here is that we fetch documentation at query time, not at index time.</p><h3>Language-Specific Intelligence (Making Sections)</h3><p>Here’s where the system gets interesting. Instead of generic documentation retrieval, I built specialized tools for different TON development languages.</p><p><strong>For TOLK</strong> (TON’s newer smart contract language):</p><ul><li>tolk-help: Comprehensive development assistance</li><li>tolk-quick-reference: Fast syntax lookups</li></ul><p><strong>For FunC</strong> (TON’s original language):</p><ul><li>func-help: Core language documentation</li><li>func-cookbook: Battle-tested patterns</li><li>func-stdlib: Standard library reference</li><li>func-quick-reference: Quick syntax guide</li></ul><h4>The GitHub Integration Magic</h4><p>The real breakthrough came from embracing GitHub’s raw content API:</p><pre>const TOLK_DOCS_URL = &quot;https://raw.githubusercontent.com/ton-community/ton-docs/main/docs/v3/documentation/smart-contracts/tolk/&quot;;<br><br>export const TOLK_DOCS: any = {<br>  smart_contract: TOLK_DOCS_URL + &quot;counter-smart-contract.mdx&quot;,<br>  guide: TOLK_DOCS_URL + &quot;language-guide.mdx&quot;,<br>  setup: TOLK_DOCS_URL + &quot;environment-setup.mdx&quot;,<br>  overview: TOLK_DOCS_URL + &quot;overview.mdx&quot;,<br>  tolk_func_difference: TOLK_DOCS_URL + &quot;tolk-vs-func/in-detail.mdx&quot;,<br>};</pre><p><strong>This simple approach guarantees:</strong></p><ul><li>Documentation is always current</li><li>Zero manual updates required</li><li>Minimal infrastructure overhead</li><li>Direct access to authoritative sources</li></ul><h3>Connecting the Dots with MCP Client Integration</h3><p>Getting this working with Cursor is refreshingly simple:</p><ol><li>Open command palette (Cmd/Ctrl + Shift + P)</li><li>Select <strong>&gt; Cursor Settings &gt; MCP &gt; Add new global MCP server</strong></li><li>Add this configuration:</li></ol><pre>// Cursor Integration<br>{<br>  &quot;mcpServers&quot;: {<br>    &quot;TON-Docs-MCP&quot;: {<br>      &quot;url&quot;: &quot;https://ton-docs-mcp.vercel.app/mcp&quot;<br>    }<br>  }<br>}<br><br>// Claude Desktop Integration<br>{<br>  &quot;mcp&quot;: {<br>    &quot;servers&quot;: {<br>      &quot;ton-docs&quot;: {<br>        &quot;env&quot;: {<br>          &quot;MCP_SERVER_URL&quot;: &quot;https://ton-docs-mcp.vercel.app/mcp&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><h3>Comparison between RAG vs. Real-Time</h3><p>Having built both systems, I can now provide a honest comparison:</p><h3>Traditional RAG Approach</h3><p><strong>The Good:</strong></p><ul><li>Excellent semantic search capabilities</li><li>Handles complex, nuanced queries well</li><li>Works offline once indexed</li></ul><p><strong>The Reality:</strong></p><ul><li>Information becomes stale quickly</li><li>High maintenance overhead</li><li>Significant ongoing costs</li><li>Complex infrastructure requirements</li></ul><h3>Direct GitHub Integration (My Approach)</h3><p><strong>The Good:</strong></p><ul><li>Always current information</li><li>Minimal infrastructure complexity</li><li>Cost-effective scaling</li><li>Direct access to source of truth</li></ul><p><strong>The Trade-offs:</strong></p><ul><li>When Docs are Large Need to add LLM for selecting the files</li><li>Potential rate limiting issues</li><li>Less sophisticated semantic search</li></ul><h3>Key Takeaways for Developers</h3><p>If you’re building similar systems, here are the hard-won lessons:</p><ol><li><strong>Question your assumptions.</strong> Just because everyone uses RAG doesn’t mean it’s the suitable solution.</li><li><strong>Embrace simplicity.</strong> The most elegant solution is often the simplest one that solves the core problem.</li><li><strong>Build for maintainability.</strong> The system you don’t have to maintain is better than the sophisticated system you constantly debug.</li></ol><h3>Wrapping Up</h3><p>Sometimes the best solutions hide in plain sight. While I was busy building elaborate caching and embedding systems, the answer was right there: just read the documentation from where it lives.</p><p>The TON Docs MCP Server represents more than just a technical solution. In a world where information changes rapidly, the key isn’t building better caches, but eliminating the need for them altogether.</p><blockquote><strong>Want to try it yourself?</strong></blockquote><ul><li><a href="https://github.com/your-repo/ton-docs-mcp">TON Docs MCP Server Repository</a></li><li><a href="https://ton-docs-mcp.vercel.app/mcp">TON Docs MCP Serve</a>r</li><li><a href="https://modelcontextprotocol.io/">Model Context Protocol Documentation</a></li></ul><p>The future of AI-powered development tools isn’t about making models smarter — it’s about making them more connected to the reality of our rapidly evolving world.</p><p><em>Have you faced similar challenges with keeping AI assistants up-to-date? I’d love to hear about your approaches and experiences in the comments below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35a016baacfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Exploring Google’s Gemini Live Client Taught Me About AI Streaming]]></title>
            <link>https://medium.com/@anuragasawa200/what-exploring-googles-gemini-live-client-taught-me-about-ai-streaming-fd3252b62d88?source=rss-edc1c46370c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd3252b62d88</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[deepmind]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[anurag asawa]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 13:56:20 GMT</pubDate>
            <atom:updated>2025-03-27T13:57:41.771Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how AI can respond in real-time, like a friend texting back instantly? I did. While poking around Google’s AI Studio offerings, I stumbled across the Gemini Live client — a feature that streams AI responses as they’re generated, no waiting required. It’s a far cry from the old “send-and-wait” API calls I was used to. In this article, I’ll share my journey of exploring this tech, the insights I gained, and how you can use it too. Expect a mix of curiosity, code, and practical tips to spark your own experiments.</p><h3>My Learning Experience</h3><p>I’d been poking at Google AI Studio for a while, mostly running random prompts to see what the latest Gemini models could do. While scrolling through the <a href="https://ai.google.dev/gemini-api/docs/live">Gemini API docs</a>, I spotted something called the “Live” feature. A streaming connection with an AI sounded cool — like, could it actually send responses as fast as I type?</p><p>I pulled down the <a href="https://github.com/googleapis/js-genai">Google GenAI JavaScript library</a> and watched a quick <a href="https://www.youtube.com/watch?v=9hE5-98ZeCg">YouTube video</a> to get the gist. From there, I started digging into its codebase to understand how it worked under the hood. It took some time to wrap my head around the setup — connecting sessions, handling callbacks, and processing streaming data — but I eventually got it working. Here are the implementations I made to test it out:</p><h3>Technical Details and Examples</h3><h3>The Old Approach vs. The Live Approach</h3><p>Traditionally, interacting with an AI model is like mailing a letter: you send a request (text, image, whatever) and wait for the reply to arrive in one piece. It’s fine for static tasks — say, generating a poem — but it’s clunky for anything needing instant feedback. Imagine texting someone and waiting 5 seconds for each reply. Yawn.</p><p>The Gemini Live client changes that. It’s more like a phone call: responses stream in as the AI “speaks,” piece by piece. During my experiments, I saw how this could power real-time apps — think chatbots that type as they think or tools that analyze data on the fly. It’s not just faster; it feels alive.</p><h3>Use Cases and Examples: Beyond Simple Text</h3><p>The potential applications are vast:</p><ul><li><strong>Interactive Storytelling:</strong> Create dynamic narratives where the story evolves based on real-time user input, creating a truly immersive experience.</li><li><strong>Real-Time Tutoring:</strong> Build intelligent tutoring systems that provide immediate feedback and guidance as students work through problems.</li><li><strong>Responsive Chatbots:</strong> Develop chatbots that can engage in natural, fluid conversations, providing instant answers and suggestions.</li><li><strong>Live Code Generation:</strong> Assist developers by generating code snippets and suggestions in real-time as they type.</li><li><strong>Live Translation:</strong> Provide live translation of spoken or written language, facilitating seamless cross-lingual communication.</li><li><strong>Live Data Analysis:</strong> Stream data and receive real-time analysis and insight.</li></ul><h3>Code Example: Basic Text Streaming</h3><p>Here’s the first function I built to test text prompts. (Set your GEMINI_API_KEY in your environment variables before running.)</p><pre>import { GoogleGenAI, Modality } from &quot;@google/genai&quot;;<br><br>async function liveClientBasic() {<br>  const responseQueue = [];<br>  let session = null;<br><br>  try {<br>    // Initialize the client<br>    const client = new GoogleGenAI({<br>      apiKey: process.env.GEMINI_API_KEY,<br>      httpOptions: { apiVersion: &quot;v1alpha&quot; },<br>    });<br><br>    // Start a live session<br>    session = await client.live.connect({<br>      model: &quot;gemini-2.0-flash-exp&quot;,<br>      callbacks: {<br>        onopen: () =&gt; console.log(&quot;Live session opened&quot;),<br>        onmessage: (message) =&gt; responseQueue.push(message),<br>        onerror: (e) =&gt; console.log(&quot;Error:&quot;, e.message),<br>        onclose: (e) =&gt; console.log(&quot;Close:&quot;, e.reason),<br>      },<br>      config: { responseModalities: [Modality.TEXT] },<br>    });<br><br>    // Send a fun prompt<br>    session.sendClientContent({<br>      turns: &quot;Tell me a short story about vibe coding&quot;,<br>      turnComplete: true,<br>    });<br><br>    // Collect the streamed response<br>    const turnMessages = await handleTurn(responseQueue);<br>    let fullResponse = &quot;&quot;;<br>    turnMessages.forEach((msg) =&gt; {<br>      if (msg.serverContent?.modelTurn?.parts) {<br>        msg.serverContent.modelTurn.parts.forEach((part) =&gt; {<br>          if (part.text) fullResponse += part.text;<br>        });<br>      }<br>    });<br>    console.log(&quot;Full Response:&quot;, fullResponse);<br><br>    session.close();<br>    return turnMessages;<br>  } catch (error) {<br>    console.error(&quot;Error:&quot;, error);<br>    if (session) session.close();<br>    throw error;<br>  }<br>}<br><br>async function handleTurn(queue) {<br>  const turn = [];<br>  let done = false;<br>  while (!done) {<br>    const message = await waitMessage(queue);<br>    turn.push(message);<br>    if (message.serverContent?.turnComplete) done = true;<br>  }<br>  return turn;<br>}<br><br>async function waitMessage(queue) {<br>  let message;<br>  while (!message) {<br>    message = queue.shift();<br>    if (!message) await new Promise((resolve) =&gt; setTimeout(resolve, 100));<br>  }<br>  return message;<br>}</pre><p>This sets up a live connection, sends a prompt about “vibe coding,” and logs the response as it streams in. The handleTurn function waits for all parts until the AI finishes its “turn.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7FBj1vppGS3yrAL1sJmqA.png" /><figcaption>Flow Diagram of Code Execution</figcaption></figure><h3>Code Example: Streaming with an Image</h3><p>Next, I tested multimodal input — text plus an image. Here’s the code:</p><pre>async function liveClientWithImage() {<br>  const responseQueue = [];<br>  let session = null;<br><br>  try {<br>    const client = new GoogleGenAI({<br>      apiKey: process.env.GEMINI_API_KEY,<br>      httpOptions: { apiVersion: &quot;v1alpha&quot; },<br>    });<br><br>    session = await client.live.connect({<br>      model: &quot;gemini-2.0-flash-exp&quot;,<br>      callbacks: {<br>        onopen: () =&gt; console.log(&quot;Live session opened&quot;),<br>        onmessage: (message) =&gt; responseQueue.push(message),<br>        onerror: (e) =&gt; console.log(&quot;Error:&quot;, e.message),<br>        onclose: (e) =&gt; console.log(&quot;Close:&quot;, e.reason),<br>      },<br>      config: { responseModalities: [Modality.TEXT] },<br>    });<br><br>    // Send text + a tiny black square image<br>    const turns = [<br>      &quot;This image is just black, can you see it?&quot;,<br>      {<br>        inlineData: {<br>          data: &quot;iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAC0lEQVR4nGNgQAYAAA4AAamRc7EAAAAASUVORK5CYII=&quot;,<br>          mimeType: &quot;image/png&quot;,<br>        },<br>      },<br>    ];<br>    session.sendClientContent({ turns, turnComplete: true });<br><br>    const turnMessages = await handleTurn(responseQueue);<br>    let fullResponse = &quot;&quot;;<br>    turnMessages.forEach((msg) =&gt; {<br>      if (msg.serverContent?.modelTurn?.parts) {<br>        msg.serverContent.modelTurn.parts.forEach((part) =&gt; {<br>          if (part.text) fullResponse += part.text;<br>        });<br>      }<br>    });<br>    console.log(&quot;Full Response:&quot;, fullResponse);<br><br>    session.close();<br>    return turnMessages;<br>  } catch (error) {<br>    console.error(&quot;Error:&quot;, error);<br>    if (session) session.close();<br>    throw error;<br>  }<br>}</pre><p>The AI processed both the text and the base64-encoded image (a 2x2 black square), streaming back a response like, “Yes, I see a small black image.” It’s a simple test, but it shows the power of multimodal streaming.</p><h3>Key Insights</h3><h4>1. Embrace Asynchronous Architecture</h4><p>Real-time AI demands a fundamental shift from traditional synchronous programming:</p><ul><li>Design non-blocking response mechanisms</li><li>Implement efficient message queuing</li><li>Prioritize system responsiveness over raw processing speed</li></ul><h4>2. Context is Your Most Valuable Resource</h4><p>In live AI interactions, context preservation is critical:</p><ul><li>Maintain stateful conversation sessions</li><li>Design systems that can retain and leverage conversational history</li></ul><h4>3.Multi-Modal Thinking</h4><p>Expand beyond text-only interactions:</p><ul><li>Support diverse input types (text, images, mixed media)</li><li>Create flexible response handling</li></ul><h3>Resources</h3><ul><li><a href="https://github.com/googleapis/js-genai">GitHub - googleapis/js-genai: TypeScript/JavaScript SDK for Gemini and Vertex AI. [PREVIEW]</a></li><li><a href="https://ai.google.dev/gemini-api/docs/live">Live API | Gemini API | Google AI for Developers</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9hE5-98ZeCg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9hE5-98ZeCg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9hE5-98ZeCg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f0c6813c52f9d9edbf392083ff0ec11/href">https://medium.com/media/4f0c6813c52f9d9edbf392083ff0ec11/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd3252b62d88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitcoin Mining Explained: How Computers Validate the Blockchain]]></title>
            <link>https://medium.com/@anuragasawa200/bitcoin-mining-explained-how-computers-validate-the-blockchain-a41ac66cb534?source=rss-edc1c46370c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a41ac66cb534</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[mining]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[btc-mining]]></category>
            <dc:creator><![CDATA[anurag asawa]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 16:22:33 GMT</pubDate>
            <atom:updated>2025-03-06T16:22:33.880Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Bitcoin mining is the computational process that secures the Bitcoin network, validates transactions, and introduces new bitcoins into circulation. It’s the backbone of this revolutionary digital currency system, serving multiple crucial functions simultaneously.</blockquote><h3>What Bitcoin Mining Actually Does</h3><p>At its core, Bitcoin mining is the process that:</p><ol><li><strong>Verifies and confirms transactions</strong> on the Bitcoin network without requiring a central authority</li><li><strong>Secures the blockchain</strong> against attacks through computational work</li><li><strong>Issues new bitcoins</strong> into circulation according to a predetermined schedule</li><li><strong>Reaches consensus</strong> across a distributed network about the state of the ledger</li></ol><p>Mining achieves these goals by requiring participants (miners) to solve complex mathematical puzzles, creating a competitive system where computational power equals influence, but no single entity can control the network.</p><h3>Key Bitcoin Mining Terms</h3><p>Before examining the complete mining flow, let’s establish clear definitions for some essential terms:</p><ol><li><strong>Difficulty Target</strong>: A 256-bit number that defines the required difficulty for a valid block hash, represented in a compact format in the block header; a lower value indicates higher mining difficulty as the hash must be below this target.</li><li><strong>Merkle Tree Hash</strong>: A binary tree structure of hashes where every leaf node contains a transaction hash and every non-leaf node contains the hash of its child nodes, culminating in a single hash (the Merkle root) that efficiently represents all transactions in a block.</li><li><strong>wtxid (Witness Transaction ID)</strong>: Introduced in <a href="https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki">BIP141</a> (Segregated Witness), this is a transaction identifier that includes both the transaction data and witness data, unlike the traditional txid which excludes witness data, solving transaction malleability issues.</li><li><strong>Block Capacity</strong>: The maximum amount of transaction data that can fit into a single block, traditionally limited by a 1MB size restriction but now measured in “weight units” (maximum 4M weight units) since SegWit implementation, allowing for more transactions per block.</li></ol><h3>The Mining Process: A Complete Flow</h3><h3>1. Transaction Collection from the Mempool</h3><p>When a Bitcoin transaction is broadcast to the network, it first lands in the <strong>mempool</strong> (memory pool), a temporary holding area for unconfirmed transactions. Miners scan the mempool to select transactions for inclusion in the next block. Here’s what happens:</p><ul><li>Users broadcast transactions to the Bitcoin network through their wallets</li><li>Full nodes receive these transactions and validate them against the blockchain’s rules</li><li>Valid transactions are added to the node’s mempool</li><li>Each node maintains its own mempool, which may differ slightly from other nodes</li><li>Miners select transactions from their mempools to include in their candidate blocks</li></ul><p>Miners typically prioritize transactions with higher fees, as this maximizes their potential reward. This creates a market-based fee system where users can pay more for faster confirmation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0qLb0MQgvT370J-pAFjXg.png" /><figcaption>Mining Flow Diagram</figcaption></figure><h3>2. Block Construction</h3><p>Once a miner has selected transactions from the mempool, they begin constructing a candidate block. This involves:</p><ul><li>Creating a coinbase transaction (the first transaction in the block) that:</li><li>Has no inputs</li><li>Contains the block reward (currently 3.125 BTC after the 2024 halving)</li><li>Includes any transaction fees from the selected transactions</li><li>Has a destination address controlled by the miner</li><li>Selecting and organizing the remaining transactions into a Merkle tree</li><li>Calculating the Merkle root hash (a single hash that represents all transactions)</li></ul><p>The Merkle tree is particularly important for future simplified payment verification (SPV) clients, as it allows for efficient verification of whether a transaction is included in a block without downloading the entire block.</p><h3>3. Block Header Creation</h3><p>The block header is a crucial 80-byte data structure that contains metadata about the block. It includes:</p><ul><li><strong>Version</strong>: Indicates which version of the Bitcoin protocol rules the block follows</li><li><strong>Previous Block Hash</strong>: Links this block to the previous one in the chain</li><li><strong>Merkle Root</strong>: The single hash representing all transactions in the block</li><li><strong>Timestamp</strong>: The approximate creation time of the block</li><li><strong>Difficulty Target</strong>: A compact representation of the current difficulty</li><li><strong>Nonce</strong>: A field that miners modify to try to produce a valid block</li></ul><p>The block header is what miners will repeatedly hash in their attempt to find a valid block.</p><h3>4. Proof-of-Work Challenge</h3><p>Now comes the heart of mining: the proof-of-work challenge. Miners must find a block header hash that is less than the current difficulty target. This is done by:</p><ol><li>Taking the block header</li><li>Changing the nonce value</li><li>Computing the SHA-256 hash of the header</li><li>Checking if the hash is less than the difficulty target</li><li>If not, incrementing the nonce and repeating the process</li></ol><p>Since SHA-256 is designed to be unpredictable, the only way to find a valid hash is through repeated attempts (brute force). This is why mining requires significant computational power.</p><h3>5. Difficulty Target Adjustment</h3><p>The difficulty target is adjusted every 2016 blocks (approximately every two weeks) to maintain an average block time of 10 minutes. Here’s how it works:</p><ul><li>The system calculates how long it took to mine the previous 2016 blocks</li><li>If it took less than two weeks, the difficulty increases</li><li>If it took more than two weeks, the difficulty decreases</li><li>The adjustment is proportional to the deviation from the two-week target</li><li>The maximum adjustment is limited to a factor of 4 in either direction</li></ul><p>The difficulty target is represented as a 256-bit number, where a lower number means a harder challenge. In block headers, this is stored in a compact format to save space.</p><h3>6. Mining Success and Block Propagation</h3><p>When a miner finally finds a valid nonce that produces a hash below the difficulty target:</p><ol><li>They immediately broadcast their block to the network</li><li>Other nodes verify that:</li></ol><ul><li>All transactions in the block are valid</li><li>The block follows all Bitcoin protocol rules</li><li>The block header hash is indeed less than the difficulty target</li></ul><p>3. If valid, nodes add the block to their version of the blockchain</p><p>4. Nodes then remove transactions included in the block from their. mempools</p><p>5. Miners start working on the next block using the new block’s hash as the previous block hash</p><p>This process creates the mechanism for achieving consensus without central authority.</p><h3>7. Chain Reorganizations</h3><p>Sometimes, two miners might find valid blocks at nearly the same time, creating a temporary fork in the blockchain. In this case:</p><ul><li>Both blocks are initially accepted by different parts of the network</li><li>Miners choose which block to build upon</li><li>The chain that accumulates more proof-of-work (becomes longer) is eventually accepted as the valid chain</li><li>Transactions in the orphaned block return to the mempool (if they’re not already included in the winning chain)</li></ul><p>This is why Bitcoin transactions typically need multiple confirmations before being considered final.</p><h3>8. Mining with SegWit</h3><p>The mining process with SegWit includes these additional steps:</p><ol><li>When constructing the Merkle tree, the miner includes a commitment to witness data in the coinbase transaction</li><li>This witness commitment is a hash of all wtxids in the block</li><li>The block’s Merkle root still only includes traditional txids for backwards compatibility</li><li>Nodes that support SegWit verify both the traditional transactions and the witness data</li><li>Legacy nodes only verify the traditional transaction data, ignoring witness data</li></ol><p>This design allows SegWit and non-SegWit nodes to coexist on the network, while providing increased transaction capacity for nodes that support the new format.</p><blockquote>Bitcoin mining is often misunderstood as simply “creating new bitcoins,” but as we’ve seen, it’s the fundamental process that enables the entire Bitcoin ecosystem to function in a decentralized, trustless manner. The intricate balance of cryptographic puzzles, economic incentives, and network consensus rules creates a system that has remained secure and operational for over a decade, revolutionizing our understanding of digital value transfer.</blockquote><p><strong><em>References:<br></em></strong><a href="https://www.youtube.com/watch?v=PYsy89r0C30">Consensus algorithm by Andreas</a></p><p><a href="https://github.com/kallerosenbaum/grokkingbitcoin/blob/master/ch07-proof-of-work.adoc">Grokking Bitcoin</a></p><p><a href="https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki">BIP141</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a41ac66cb534" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of Bitcoin Transaction Types: Understanding P2WSH]]></title>
            <link>https://medium.com/@anuragasawa200/the-evolution-of-bitcoin-transaction-types-understanding-p2wsh-f9eafdc78f43?source=rss-edc1c46370c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9eafdc78f43</guid>
            <category><![CDATA[psbt]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[p2sh]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[p2wsh]]></category>
            <dc:creator><![CDATA[anurag asawa]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 20:40:23 GMT</pubDate>
            <atom:updated>2025-02-26T20:40:23.498Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to P2WSH</h3><p>Pay-to-Witness-Script-Hash (P2WSH) represents a significant advancement in Bitcoin transaction technology. As part of the Segregated Witness (SegWit) upgrade, P2WSH enables complex Bitcoin scripts while delivering crucial benefits including reduced fees, improved scalability, and enhanced security.</p><h3>Bitcoin Transaction Types</h3><h4>The Simple Lock: P2PKH</h4><p>The original Bitcoin transaction type, Pay-to-Public-Key-Hash (P2PKH), functions like a simple lock with a single key. Only the holder of the private key can unlock and spend these funds.</p><h4>The Complex Lock: P2SH</h4><p>Pay-to-Script-Hash (P2SH) introduced more sophisticated locking mechanisms, supporting complex conditions like multi-signature requirements and timelocks. P2SH allows these conditions to be represented by a compact hash rather than the full script.</p><h4>The Advanced Solution: P2WSH</h4><p>P2WSH builds upon P2SH by incorporating SegWit benefits. By separating witness data (signatures and redemption scripts) from transaction identifiers, P2WSH addresses several limitations of earlier transaction types:</p><ul><li>Eliminates transaction malleability</li><li>Reduces transaction fees through witness data discounting</li><li>Increases effective block capacity</li><li>Enables advanced Layer 2 scaling solutions</li><li>Maintains script privacy until spending</li></ul><h3>When to Implement P2WSH</h3><p>P2WSH provides optimal value in these scenarios:</p><ul><li><strong>Multi-signature wallets</strong>: When multiple parties must authorize a transaction</li><li><strong>Complex conditional payments</strong>: For time-locked funds or conditional releases</li><li><strong>Advanced scripting needs</strong>: When leveraging Bitcoin’s script language for specialized conditions</li><li><strong>Fee optimization</strong>: For transactions with complex scripts that benefit from witness discounting</li></ul><h3>Implementation Approaches</h3><h4>Professional Method: Partially Signed Bitcoin Transactions (PSBT)</h4><p>For most users, PSBT offers the most straightforward implementation:</p><ol><li>Create a multisig wallet using standard payments API</li><li>Generate the PSBT transaction</li><li>Distribute for signatures from required parties</li><li>Finalize automatically with compatible software</li></ol><h4>Advanced Method: Manual Construction</h4><p>For developers requiring complete control:</p><ol><li>Design and build custom multisig setup</li><li>Manually create P2WSH scripts</li><li>Implement custom signature collection</li><li>Assemble and verify the complete transaction</li></ol><h3>Technical Construction of Bitcoin Transactions</h3><p>Creating valid transactions requires understanding several distinct components:</p><h4>Transaction Foundation</h4><ul><li><strong>Version</strong>: Specifies transaction rules version</li><li><strong>Input/Output Counts</strong>: Declares number of sources and destinations</li><li><strong>Locktime</strong>: Sets earliest time transaction can be included in a block</li></ul><h4>Input Components</h4><ul><li><strong>Previous Transaction Hash</strong>: References UTXO being spent</li><li><strong>Output Index</strong>: Specifies which output from previous transaction</li><li><strong>ScriptSig</strong>: Provides proof of spending authority</li><li><strong>Sequence Number</strong>: Enables advanced features like replace-by-fee</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*60k8GHNVpsMbAiZvmIJb4g.png" /><figcaption>Bitcoin Transaction Components</figcaption></figure><h3>Output Components</h3><ul><li><strong>Value</strong>: Amount in satoshis being transferred</li><li><strong>ScriptPubKey</strong>: Defines conditions required to spend these funds</li></ul><h3>Witness Structure (SegWit-specific)</h3><ul><li><strong>Stack Elements</strong>: Data needed to satisfy script conditions</li><li><strong>Signature Formatting</strong>: Properly structured digital signatures</li><li><strong>Script Compliance</strong>: Values satisfying the witness script</li></ul><h3>Creating a Multi-Signature P2WSH Transaction</h3><ol><li><strong>Define Requirements</strong>: Determine M-of-N signature threshold</li><li><strong>Create Witness Script</strong>: Implement the multisig logic</li><li><strong>Generate P2WSH Address</strong>: Hash the witness script</li><li><strong>Fund the Address</strong>: Send bitcoin to the generated address</li><li><strong>Prepare Spending Transaction</strong>: Create transaction spending these funds</li><li><strong>Gather Signatures</strong>: Collect required number of valid signatures</li><li><strong>Assemble Complete Transaction</strong>: Combine signatures with witness script</li><li><strong>Broadcast</strong>: Submit to the Bitcoin network</li></ol><h3>Resources</h3><ul><li><a href="https://learnmeabitcoin.com/technical/script/p2wsh/">P2WSH</a></li><li><a href="https://github.com/bitcoin/bitcoin/blob/master/doc/psbt.md">bitcoin/doc/psbt.md at master · bitcoin/bitcoin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9eafdc78f43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>