<?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 Muhammad Talha on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Talha on Medium]]></description>
        <link>https://medium.com/@muhammadtalha1?source=rss-bfee9d0fba03------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9mN7UgP7j_F5V4u8KKtQ1Q.png</url>
            <title>Stories by Muhammad Talha on Medium</title>
            <link>https://medium.com/@muhammadtalha1?source=rss-bfee9d0fba03------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:40:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammadtalha1/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[JWT (JSON Web Tokens): The Complete Guide Every Developer Should Read]]></title>
            <link>https://medium.com/@muhammadtalha1/jwt-json-web-tokens-the-complete-guide-every-developer-should-read-2942e2786fcd?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/2942e2786fcd</guid>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[jwt-auth]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 05:28:14 GMT</pubDate>
            <atom:updated>2026-06-17T05:28:14.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zlowSxFXIgr4EcENpR0J_w.png" /></figure><p><em>A deep dive into what JWTs are, how they work, why they’re secure, and how they compare to sessions with everything you need to implement them confidently.</em></p><h3>Introduction</h3><p>If you’ve ever built or consumed an API, chances are you’ve stumbled across the term <strong>JWT</strong> JSON Web Token. It shows up everywhere: authentication systems, microservices, third-party integrations, and more. Yet, many developers use it without fully understanding <em>what’s actually happening under the hood</em>.</p><p>This guide is your one-stop reference. By the end, you’ll understand:</p><ul><li>What JWT is and how it’s structured</li><li>How public/private key cryptography plays into it</li><li>The difference between authentication and authorization</li><li>How JWT compares to session-based auth</li><li>How to securely store and invalidate tokens</li><li>What refresh tokens are and why you need them</li></ul><p>Let’s get into it.</p><h3>Before We Begin: Two Concepts You Must Know</h3><p>Before we dive into JWT itself, there are two foundational concepts you need to be comfortable with. Don’t worry you don’t need to be an expert in either; a working understanding is enough.</p><h3>1. Public/Private Key Cryptography</h3><p>This is a security mechanism where <strong>two mathematically linked keys</strong> are generated together:</p><ul><li><strong>Public Key</strong> — Can be freely distributed to anyone. No risk in sharing it.</li><li><strong>Private Key</strong> — Must <em>never</em> be shared. Keep it locked on your server.</li></ul><p>Here’s the key insight: <strong>data encrypted with a public key can only be decrypted with the corresponding private key.</strong> So even if your public key is out in the open, only the holder of the private key can make sense of the encrypted data.</p><p>JWT works on a similar principle your server holds a secret that only it can use to sign and verify tokens.</p><h3>2. Stateless vs. Stateful</h3><p>This concept appears in many areas of computer science, not just JWT.</p><ul><li><strong>Stateless</strong> means the server does <em>not</em> store any session information anywhere (no database, no file). The system trusts whoever holds the valid token.</li><li><strong>Stateful</strong> means the server <em>does</em> store session state usually in a database and checks against it on every request.</li></ul><p>JWT is a <strong>stateless</strong> mechanism. Whoever holds the token is considered authorized. This raises an obvious question: <em>“What if someone steals the token?”</em>We’ll address that thoroughly a bit later.</p><h3>What Is a JSON Web Token (JWT)?</h3><p>A JWT is essentially a <strong>long encrypted string</strong> made up of letters and numbers. It looks something like this:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</pre><p>Formally, JWT is defined as an <strong>open industry standard (RFC 7519)</strong> for securely representing <em>claims</em> between two parties. In plain English: it’s a secure way for a client and server (or server to server) to say <em>“I am who I claim to be, and here’s the proof.”</em></p><h3>The Structure of a JWT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOHS8F9FUaFBEud3fcCVGw.png" /></figure><p>A JWT is divided into <strong>three parts</strong>, separated by dots (.):</p><pre>HEADER.PAYLOAD.SIGNATURE</pre><p>Let’s break each one down.</p><h3>Part 1: Header (Red)</h3><p>The header contains <strong>metadata about the token itself </strong>specifically, what type of token it is and which algorithm was used to sign it.</p><p>A decoded header looks like this:</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><ul><li>alg — The signing algorithm. HS256 (HMAC SHA-256) is the most widely used default, but you can use others like RS256, ES256, etc.</li><li>typ — The type of token, which is always JWT.</li></ul><h3>Part 2: Payload (Purple)</h3><p>The payload contains the <strong>actual data</strong> also called <em>claims</em>. This is the information you want to transmit securely.</p><p>A decoded payload might look like this:</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;Jane Doe&quot;,<br>  &quot;email&quot;: &quot;jane@example.com&quot;,<br>  &quot;iat&quot;: 1516239022,<br>  &quot;exp&quot;: 1516242622<br>}</pre><p>Here’s what the common fields mean:</p><p>Field Meaning sub Subject usually the user&#39;s unique ID name User&#39;s name email User&#39;s email iat Issued At when the token was created (Unix timestamp) exp Expiry when the token becomes invalid</p><blockquote><strong><em>Pro tip:</em></strong><em> Most developers store just the user’s </em><em>id (primary key) in the payload. Why? Because with a single database query, you can fetch </em>all<em> the user&#39;s information. Keeping the token lightweight is generally better practice. That said, non-sensitive info like name or email is commonly included too.</em></blockquote><blockquote><strong><em>Important:</em></strong><em> The </em><em>exp field is arguably the </em>most critical<em> field in the payload. Token expiry is what keeps JWT secure in practice. More on this below.</em></blockquote><h3>Part 3: Signature (Blue)</h3><p>This is where the <strong>security magic</strong> happens.</p><p>The signature is generated by:</p><ol><li>Taking the encoded header</li><li>Taking the encoded payload</li><li>Combining them with a <strong>secret key</strong> stored on your server</li><li>Running everything through the signing algorithm (e.g., HS256)</li></ol><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload),<br>  your-256-bit-secret<br>)</pre><p>The resulting signature ensures <strong>tamper detection</strong>. If even a single character in the header or payload is changed, the signature becomes invalid. The server will immediately reject it.</p><p><strong>The secret key</strong> (your “private key” equivalent in symmetric JWT setups) is stored securely on your server and is <em>never</em> distributed. Only your server can sign and verify tokens.</p><h3>Authentication vs. Authorization</h3><p>These two terms are often confused. They are <em>not</em> the same thing.</p><h3>Authentication “Who are you?”</h3><p>Authentication is the process of <strong>verifying your identity</strong>. When you registered on a service, you gave them:</p><ul><li>A username</li><li>A password</li><li>An email</li></ul><p>When you log in, the server checks those credentials. If they match, you’re <em>authenticated</em> the server knows who you are.</p><p><strong>Authentication alone does not grant you access to any resource.</strong></p><h3>Authorization “What are you allowed to do?”</h3><p>Authorization determines <strong>what resources you’re allowed to access</strong> after being authenticated.</p><p>For example:</p><ul><li>A regular user is <em>authorized</em> to view their own dashboard.</li><li>An admin user is <em>authorized</em> to view the admin panel.</li><li>A guest user is <em>not authorized</em> to view billing information.</li></ul><p>JWT was originally designed specifically for <strong>authorization</strong> — encoding information about what a user is allowed to access. Over time, it also became widely adopted for authentication, and it handles both extremely well.</p><h3>A Real-World Multi-Service Example</h3><p>Imagine you have three services:</p><ul><li>docs.chaicode.com</li><li>chaicode.com</li><li>app.chaicode.com</li></ul><p>A user logs in once. Rather than maintaining separate sessions for each service (stateful), you issue a JWT signed with a shared secret. All three services know the secret and can independently verify the token — <strong>no database call needed on any of them.</strong></p><p>This is one of JWT’s biggest advantages in microservice and multi-service architectures.</p><h3>How JWT Works: Step-by-Step Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xRBUZNjhiTrZY66YXutWw.png" /></figure><p>Here’s the complete request-response lifecycle of JWT-based authentication:</p><pre>1. Client sends login credentials (username + password)<br>        ↓<br>2. Server validates credentials against the database<br>        ↓<br>3. Server generates a signed JWT using the private secret<br>        ↓<br>4. Server sends the JWT back to the client<br>        ↓<br>5. Client stores the JWT (localStorage, sessionStorage, or cookie)<br>        ↓<br>6. On every subsequent request, client sends the JWT in the Authorization header:<br>   Authorization: Bearer &lt;token&gt;<br>        ↓<br>7. Server receives the request, verifies the JWT signature using its secret<br>        ↓<br>8. If valid → process the request. If invalid/expired → return 401 Unauthorized.</pre><p><strong>The critical difference from sessions:</strong> At step 7, the server validates the token <em>entirely on its own</em> no database lookup required. This is what makes JWT stateless and highly scalable.</p><h3>JWT vs. Session-Based Authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D23JQIiEbu4qHPVZtzLeHg.png" /></figure><p>Let’s compare both side by side in a three-tier architecture (Client → Server → Database).</p><h3>Session-Based Auth (Stateful)</h3><pre>1. Client logs in → server validates credentials via DB<br>2. Server creates a Session ID and stores it in the database<br>3. Server sends the Session ID to the client (usually as a cookie)<br>4. Client stores the Session ID cookie<br>5. On every request → client sends the Session ID cookie<br>6. Server must query the DB to validate the Session ID<br>7. If valid → process the request<br>8. Then query the DB again for the actual resource data</pre><p><strong>The problem:</strong> Every single authenticated request requires <em>at least one extra database call</em> just to verify the session. In a high-traffic application, this adds up fast more I/O operations, more latency, more resource consumption.</p><h3>JWT-Based Auth (Stateless)</h3><pre>1. Client logs in → server validates credentials via DB<br>2. Server generates a JWT signed with its private secret<br>3. Server sends the JWT to the client<br>4. Client stores the JWT<br>5. On every request → client sends the JWT<br>6. Server validates the JWT signature locally (NO DB call needed)<br>7. If valid → process the request (DB call only for actual resource data)</pre><p><strong>The advantage:</strong> Validation happens entirely in memory on the server. No extra database round-trip for auth. This makes JWT:</p><ul><li><strong>More scalable </strong>can handle far more concurrent users</li><li><strong>Faster</strong> one fewer DB call per request</li><li><strong>Simpler to distribute</strong> works seamlessly across multiple services</li></ul><h3>How to Securely Store JWT on the Client Side</h3><p>This is one of the most frequently asked questions about JWT. Here are your options:</p><h3>1. localStorage</h3><ul><li>Simple to implement</li><li>Vulnerable to <strong>XSS (Cross-Site Scripting)</strong> attacks malicious JavaScript can read localStorage and steal your token</li></ul><h3>2. sessionStorage</h3><ul><li>Data is cleared when the browser tab is closed</li><li>Still vulnerable to XSS attacks for the same reason as localStorage</li></ul><h3>3. HTTP-Only Cookies (Recommended)</h3><ul><li>JavaScript <strong>cannot</strong> access HTTP-only cookies — immune to XSS</li><li>Can be combined with the Secure flag (HTTPS only) and SameSite attribute (CSRF protection)</li><li>Requires proper CSRF protection setup</li></ul><p><strong>Best practice recommendation:</strong></p><blockquote><em>Store your JWT in an </em><strong><em>HTTP-only, Secure cookie</em></strong><em> with the </em><em>SameSite=Strict or </em><em>SameSite=Lax attribute. This provides the best balance of security and usability.</em></blockquote><p>But honestly, the single most effective security measure for JWT is something else entirely…</p><h3>Token Expiry: The Most Important Security Feature</h3><p><strong>Short-lived tokens are your best defense.</strong></p><p>If a token is stolen but expires in 15 minutes, the attacker’s window is extremely limited. Many production systems use expiry windows like:</p><ul><li>15 minutes — for access tokens in high-security applications</li><li>1 hour — for standard applications</li><li>1 day — for lower-security use cases</li></ul><p>Every JWT library whether in Node.js, Django, Ruby on Rails, Go, or any other language provides a straightforward way to set expiry:</p><pre>// Node.js example (using jsonwebtoken)<br>const token = jwt.sign(<br>  { userId: user.id, email: user.email },<br>  process.env.JWT_SECRET,<br>  { expiresIn: &#39;15m&#39; } // Expires in 15 minutes<br>);</pre><h3>How to Invalidate a JWT</h3><p>Since JWT is stateless, you can’t “delete” a token from a database (because it isn’t stored there). So how do you invalidate one? A few strategies:</p><ol><li><strong>Let it expire</strong> — The simplest approach. Short expiry + refresh tokens (see below).</li><li><strong>Blacklist the token</strong> — Store invalidated tokens in a database (Redis works great here) and check against the list on each request. Note: this adds statefulness back.</li><li><strong>Rotate the signing secret</strong> — Invalidates <em>all</em> tokens at once. Useful for security incidents, but a nuclear option.</li><li><strong>Whitelist approach</strong> — Only tokens in a whitelist are considered valid.</li></ol><p>The most common and practical approach in production is the <strong>short expiry + refresh token</strong> pattern.</p><h3>Refresh Tokens: Keeping Users Logged In Securely</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKx6doA066kDn-QNRkPVMg.png" /></figure><p>Here’s the problem: if your access token expires in 15 minutes, users would have to log in every 15 minutes. That’s a terrible user experience.</p><p><strong>Refresh tokens solve this.</strong></p><h3>How It Works</h3><p>When a user logs in, the server issues <em>two</em> tokens:</p><ol><li><strong>Access Token</strong> — Short-lived (e.g., 15 minutes). Used to authenticate API requests.</li><li><strong>Refresh Token</strong> — Long-lived (e.g., 7 days or 30 days). Stored in the database <em>and</em> sent to the client.</li></ol><pre>Login Flow:<br>Client → [credentials] → Server<br>Server → [access_token + refresh_token] → Client<br>Server also saves refresh_token in DB</pre><pre>Normal Request Flow:<br>Client → [request + access_token] → Server<br>Server validates token locally → Returns resource</pre><pre>When Access Token Expires:<br>Client → [request + expired_access_token] → Server<br>Server → 401 Unauthorized (token expired)<br>Client → [refresh_token] → Server (special refresh endpoint)<br>Server validates refresh_token against DB<br>Server → [new_access_token] → Client<br>Client retries original request with new access_token</pre><p><strong>Why is the refresh token stored in the database?</strong></p><p>Because it allows you to <strong>revoke</strong> it. If a user logs out, or if you detect suspicious activity, you can delete the refresh token from the database. When the client tries to refresh, it fails effectively logging the user out permanently.</p><p>This hybrid approach gives you:</p><ul><li>The <strong>performance</strong> of stateless JWT (no DB lookup on every request)</li><li>The <strong>control</strong> of stateful sessions (can revoke access when needed)</li></ul><h3>Common Use Cases for JWT</h3><p>JWT is versatile. Here’s where you’ll encounter it most:</p><p>Use Case Description <strong>User Authentication</strong> Verify who a user is after login <strong>Authorization</strong> Control which resources a user can access <strong>API Security</strong> Secure REST/GraphQL APIs <strong>Information Exchange</strong> Safely pass data between services <strong>Microservices Auth</strong> Single token works across all services with shared secret <strong>Server-to-Server Communication</strong> Services authenticate each other without shared sessions</p><h3>JWT Advantages and Disadvantages</h3><h3>Advantages</h3><ul><li><strong>Stateless &amp; Scalable</strong> — No server-side session storage needed</li><li><strong>Self-contained</strong> — All necessary info is in the token itself</li><li><strong>Cross-domain</strong> — Works seamlessly across different domains and services</li><li><strong>Performance</strong> — No database lookup needed for validation</li><li><strong>Flexible</strong> — Works with any language and any framework</li><li><strong>Open Standard</strong> — RFC 7519, widely adopted and battle-tested</li></ul><h3>Disadvantages</h3><ul><li><strong>Token size</strong> — JWTs can be larger than session cookies, increasing request size</li><li><strong>Cannot be invalidated instantly</strong> — Stateless nature makes immediate revocation complex (needs blacklisting or short expiry)</li><li><strong>Secret management</strong> — If your secret key is compromised, all tokens are compromised</li><li><strong>Payload is encoded, not encrypted</strong> — Anyone can decode the payload (Base64). Never store sensitive data like passwords in the payload.</li></ul><h3>Important: JWT Payload is NOT Encrypted</h3><p>This trips up a lot of developers.</p><p>JWT uses <strong>Base64URL encoding</strong>, not encryption, for the header and payload. This means <strong>anyone who has your JWT can decode the payload</strong> and read its contents.</p><pre>// Anyone can do this:<br>const payload = atob(&quot;eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0&quot;);<br>// → {&quot;sub&quot;:&quot;1234567890&quot;,&quot;name&quot;:&quot;John Doe&quot;}</pre><p>What JWT <em>does</em> guarantee is <strong>integrity</strong> through the signature, no one can <em>modify</em> the payload without the server detecting it.</p><p><strong>Rule of thumb:</strong> Never store sensitive data (passwords, payment info, SSNs) in a JWT payload. Stick to non-sensitive identifiers like user ID, email, and role.</p><h3>Quick Implementation Reference</h3><p>JWT libraries exist for virtually every language and framework:</p><pre>// Node.js — jsonwebtoken<br>const jwt = require(&#39;jsonwebtoken&#39;);<br>const token = jwt.sign({ userId: &#39;123&#39; }, process.env.SECRET, { expiresIn: &#39;1h&#39; });<br>const decoded = jwt.verify(token, process.env.SECRET);</pre><pre># Python / Django — PyJWT<br>import jwt<br>token = jwt.encode({&quot;user_id&quot;: &quot;123&quot;, &quot;exp&quot;: datetime.utcnow() + timedelta(hours=1)}, SECRET_KEY, algorithm=&quot;HS256&quot;)<br>decoded = jwt.decode(token, SECRET_KEY, algorithms=[&quot;HS256&quot;])</pre><pre>// Java — jjwt<br>String token = Jwts.builder()<br>    .setSubject(&quot;123&quot;)<br>    .setExpiration(new Date(System.currentTimeMillis() + 3600000))<br>    .signWith(SignatureAlgorithm.HS256, secretKey)<br>    .compact();</pre><p>You can also explore and debug JWTs visually at <a href="https://jwt.io/"><strong>jwt.io</strong></a> — the official JWT website.</p><h3>Summary: Everything at a Glance</h3><p>Concept Key Takeaway <strong>What is JWT</strong> A signed, self-contained token in three Base64-encoded parts <strong>Structure</strong> Header (algorithm) + Payload (data) + Signature (verification) <strong>Signing</strong> Server signs using a secret key; anyone with the key can verify <strong>Stateless</strong> No DB lookup needed to validate scales beautifully <strong>Authentication</strong> Proves <em>who</em> you are <strong>Authorization</strong> Proves <em>what</em> you can access <strong>Storage</strong> Prefer HTTP-only cookies; avoid localStorage when possible <strong>Expiry</strong> Always set short expiry on access tokens (15m–1h) <strong>Refresh Tokens</strong> Long-lived token stored in DB; used to renew expired access tokens <strong>Invalidation</strong> Expire them, blacklist them, or rotate your secret <strong>Payload</strong> Encoded, NOT encrypted never store sensitive data <strong>vs. Sessions</strong> JWT = no extra DB call per request; Sessions = extra DB call every time</p><h3>Final Thoughts</h3><p>JWT is a powerful, battle-tested standard that powers authentication and authorization in applications of all sizes from indie projects to systems at Twitter, Google, and Netflix. It’s not magic, and it’s not scary once you understand the mechanics.</p><p>The key principles to walk away with:</p><ol><li><strong>Always set token expiry.</strong> Short-lived tokens dramatically reduce your attack surface.</li><li><strong>Use refresh tokens</strong> to balance security with user experience.</li><li><strong>Never store sensitive data</strong> in the JWT payload it’s readable by anyone.</li><li><strong>Store tokens securely</strong> HTTP-only cookies are your safest bet.</li><li><strong>Understand the stateless tradeoff</strong> no DB lookup means faster performance but limited revocation control.</li></ol><p>JWT isn’t a silver bullet nothing in security is. But when implemented correctly, it’s one of the most efficient and scalable authentication mechanisms available to developers today.</p><p><em>Found this helpful? Share it with your team. Have questions? Drop them in the comments let’s talk JWT.</em></p><p><strong>Tags:</strong> JWT Authentication Web Security Backend Development API Node.js Authorization Developer Guide</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2942e2786fcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is an Automated Market Maker (AMM)?]]></title>
            <link>https://medium.com/@muhammadtalha1/what-is-an-automated-market-maker-amm-2d69f1f6c6c9?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d69f1f6c6c9</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[liquidity-pool]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[automated-market-maker]]></category>
            <category><![CDATA[amm]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 05:42:47 GMT</pubDate>
            <atom:updated>2026-06-16T05:42:47.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJBus2kUn_2QBFNhqWJbXw.png" /></figure><h4>A Complete Beginner’s Guide — Analogies, Diagrams &amp; Zero Jargon</h4><p><em>Reading time: ~12 minutes | Level: Absolute Beginner</em></p><h3>Before We Start A 30-Second Reality Check</h3><p>You have probably seen words like <strong>Uniswap, DeFi, liquidity pool,</strong> or <strong>swap tokens</strong> thrown around in crypto conversations. At the heart of all of them sits one surprisingly elegant idea called an <strong>Automated Market Maker or AMM.</strong></p><p>Most explanations drown you in blockchain terminology before you even understand the basics. This guide does the opposite. We start with a story about farmers, potatoes, and a magical genie — and by the end, you will understand exactly how billions of dollars of crypto trades happen every single day without a single human being setting prices.</p><p><strong>What you will learn:</strong></p><ul><li>What an AMM is and why it was invented</li><li>How it prices assets automatically using a formula</li><li>The famous <strong>x × y = k</strong> equation with a real worked example</li><li>Who the key players are (traders vs liquidity providers)</li><li>How AMMs compare to traditional exchanges</li></ul><h3>Part 1 — The World Before AMMs (And Why They Were Needed)</h3><p>To appreciate AMMs, you first need to understand what they replaced.</p><h4>The Traditional Way: The Order Book</h4><p>When you buy a stock or crypto on a centralised exchange like Binance, you interact with an <strong>order book.</strong> It is literally a list of buy orders and sell orders. When a buyer’s price matches a seller’s price, the trade happens.</p><pre>┌─────────────────────────────────────────────┐<br>│              ORDER BOOK                     │<br>│                                             │<br>│  SELL ORDERS          BUY ORDERS            │<br>│  ─────────────        ──────────            │<br>│  $2,050 → 3 ETH       $1,990 ← 2 ETH       │<br>│  $2,040 → 1 ETH       $1,980 ← 5 ETH       │<br>│  $2,000 → 2 ETH  ←→   $2,000 ← 2 ETH  ✓   │<br>│                   MATCH!                    │<br>└─────────────────────────────────────────────┘</pre><p>This works fine for popular assets with millions of traders. But for newer or less popular crypto tokens? The order book is practically empty. You could wait hours for your trade to go through. This is called a <strong>liquidity problem.</strong></p><p>AMMs were invented to solve this. Instead of matching buyers with sellers, an AMM always has tokens ready to trade — 24/7, instantly, with zero human involvement.</p><pre>┌───────────────────────────────────────────────────────────┐<br>│         TRADITIONAL EXCHANGE vs AMM                       │<br>│                                                           │<br>│  Feature              Order Book       AMM                │<br>│  ─────────────────────────────────────────────────────    │<br>│  Who sets price?      Human traders    Algorithm (x*y=k)  │<br>│  Need a counterparty? YES              NO                 │<br>│  Available 24/7?      Sometimes        Always             │<br>│  Who provides tokens? Institutions     Anyone can         │<br>│  Runs out of stock?   Yes              Never (price rises)│<br>└───────────────────────────────────────────────────────────┘</pre><h3>Part 2 — The Potato-Apple Story (Intuition First, Maths Second)</h3><p>Before we touch any formula, let us build the intuition through a story.</p><h4>Setting the Scene</h4><p>Imagine you are a potato farmer. You grow thousands of potatoes every season but you are completely sick of eating them. What you want are apples. Problem is, everyone in your village is also a potato farmer. Nobody has apples.</p><p>Then a trader arrives. He says:</p><blockquote>“I found a village over east that grows only apples and they are sick of apples too. If your village puts in 50,000 potatoes and they put in 50,000 apples, I will set up a permanent trading post where anyone can swap potatoes for apples, any time they want.”</blockquote><p>Your village agrees. The trading post opens. The trader has a magical genie who stores all the tokens and enforces one simple rule:</p><pre>┌─────────────────────────────────────────────────┐<br>│            THE GENIE&#39;S ONE RULE                 │<br>│                                                 │<br>│     Potatoes × Apples = 2,500,000,000           │<br>│                                                 │<br>│     50,000    ×  50,000  =  2,500,000,000       │<br>│                                                 │<br>│  This number NEVER changes. Ever.               │<br>└─────────────────────────────────────────────────┘</pre><h4>The Trading Post — Before Any Trades</h4><pre>┌─────────────────────────────────────────────────┐<br>│              LIQUIDITY POOL                     │<br>│                                                 │<br>│   🥔  POTATOES          🍎  APPLES              │<br>│   ─────────────         ──────────              │<br>│     50,000                50,000                │<br>│                                                 │<br>│   Constant k = 50,000 × 50,000 = 2,500,000,000 │<br>└─────────────────────────────────────────────────┘</pre><p>Both tokens start at the same quantity, so they each have equal value — priced at $1 each.</p><h4>A Farmer Makes the First Trade</h4><p>A potato farmer walks up with 7,000 potatoes and wants apples. He drops 7,000 potatoes into the pool.</p><pre>STEP 1: Farmer deposits 7,000 potatoes<br>──────────────────────────────────────────<br>  Potatoes in pool: 50,000 + 7,000 = 57,000</pre><pre>STEP 2: Genie applies the rule<br>──────────────────────────────────────────<br>  57,000 × Apples = 2,500,000,000<br>  Apples = 2,500,000,000 ÷ 57,000 = 43,860</pre><pre>STEP 3: Pool currently has 50,000 apples<br>──────────────────────────────────────────<br>  Apples to give farmer = 50,000 − 43,860 = 6,140</pre><h4>The Trading Post — After the Trade</h4><pre>┌─────────────────────────────────────────────────┐<br>│              LIQUIDITY POOL (after trade)       │<br>│                                                 │<br>│   🥔  POTATOES          🍎  APPLES              │<br>│   ─────────────         ──────────              │<br>│     57,000                43,860                │<br>│                                                 │<br>│   Check: 57,000 × 43,860 ≈ 2,500,000,000  ✓   │<br>└─────────────────────────────────────────────────┘</pre><pre>  Farmer gave:     7,000 potatoes   ⬆ pool got more<br>  Farmer received: 6,140 apples     ⬇ pool has less</pre><p><strong>Why did the farmer only get 6,140 apples instead of 7,000?</strong></p><p>Because as he kept taking apples out, each apple became scarcer — and therefore more expensive. The price automatically adjusted with every single unit he removed. This is supply and demand, powered entirely by maths.</p><blockquote><strong><em>The Core Insight:</em></strong><em> More of something in the pool = cheaper. Less of something = more expensive. No human needed to decide this.</em></blockquote><h3>Part 3 — The Formula: x × y = k</h3><p>What you just saw with potatoes and apples is the exact same formula used by Uniswap and dozens of other major DeFi exchanges. It is called the <strong>Constant Product AMM</strong> and its formula is:</p><pre>┌─────────────────────────────────────────┐<br>│                                         │<br>│           x  ×  y  =  k                │<br>│                                         │<br>│  x = quantity of Token A in the pool    │<br>│  y = quantity of Token B in the pool    │<br>│  k = a constant that never changes      │<br>│                                         │<br>└─────────────────────────────────────────┘</pre><p>That is the entire pricing engine of a multi-billion-dollar market. Three letters.</p><h4>A Real Worked Example</h4><p>Let us replace potatoes and apples with actual crypto tokens.</p><pre>SETUP<br>──────────────────────────────────────────────────<br>  Pool contains:<br>    Token A (ETH)  = 100 tokens<br>    Token B (USDC) = 200 tokens<br>    Constant k     = 100 × 200 = 20,000</pre><pre>  A trader wants to BUY 60 ETH from the pool.<br>  How many USDC must they deposit?</pre><pre>┌──────┬──────────────────────────────────────┬────────────────┐<br>│ Step │ Action                               │ Result         │<br>├──────┼──────────────────────────────────────┼────────────────┤<br>│  1   │ Pool starts with 100 ETH, 200 USDC   │ k = 20,000     │<br>│  2   │ Trader takes 60 ETH. ETH remaining:  │ 100 − 60 = 40  │<br>│  3   │ Apply formula: 40 × y = 20,000       │ y = 500 USDC   │<br>│  4   │ Pool has 200 USDC. Needs 500.        │ 500−200 = 300  │<br>│  5   │ Verify: 40 × 500                     │ = 20,000  ✓    │<br>└──────┴──────────────────────────────────────┴────────────────┘</pre><pre>  Trader paid:     300 USDC<br>  Trader received: 60 ETH<br>  k stayed:        20,000 (unchanged)</pre><h4>The Pool Before and After</h4><pre>BEFORE TRADE                     AFTER TRADE<br>────────────────────             ────────────────────<br>ETH Pool:   100                  ETH Pool:    40<br>USDC Pool:  200                  USDC Pool:   500<br>k:          20,000               k:           20,000 ✓</pre><pre>            ETH got scarcer → price of ETH went UP<br>            USDC increased  → price of USDC went DOWN</pre><p>No human set those new prices. The formula did it instantly and automatically.</p><h3>Part 4 — The Bonding Curve (Visualising the Price)</h3><p>The formula x × y = k produces a specific shape when drawn on a graph. You have probably seen this curve in Uniswap’s documentation and wondered what it meant.</p><pre>y (Token B)<br>│<br>│ *<br>│   *<br>│     *<br>│        *<br>│             *<br>│                  *<br>│                        *  *  *<br>└──────────────────────────────────▶ x (Token A)</pre><pre>         The Bonding Curve: x × y = k</pre><p><strong>What this curve is telling you:</strong></p><ul><li>Every dot on this curve is a valid state of the pool</li><li>When a trade happens, the pool moves from one dot to another — it never leaves the curve</li><li>Moving right (more Token A) = Token A gets cheaper</li><li>Moving up (more Token B) = Token B gets cheaper</li><li>The curve never touches zero on either axis — meaning the pool <strong>never runs completely dry</strong></li></ul><pre>Small trade               Large trade<br>          ──────────                ──────────<br>          Moves a tiny bit          Moves a large amount<br>          along the curve           along the curve<br>          Small price change        Big price change</pre><p>This is why large trades are more expensive per unit than small ones — a concept called <strong>price impact</strong> or <strong>slippage.</strong></p><blockquote><strong><em>Key takeaway:</em></strong><em> A bigger pool (more tokens) means the curve is flatter in the middle, so large trades cause less price impact. This is why AMMs prefer deep liquidity.</em></blockquote><h3>Part 5 — The Two Key Players in Every AMM</h3><h4>Player 1: The Trader</h4><pre>┌──────────────────────────────────────────────────────┐<br>│  TRADER                                              │<br>│                                                      │<br>│  Comes to swap Token A → Token B (or vice versa)    │<br>│                                                      │<br>│  [Trader] ──── deposits Token A ────▶ [POOL]        │<br>│  [Trader] ◀─── receives Token B ──── [POOL]         │<br>│                                                      │<br>│  Pays a small fee (typically 0.3%) on each swap      │<br>│  Their trade moves the price along the curve         │<br>└──────────────────────────────────────────────────────┘</pre><h4>Player 2: The Liquidity Provider (LP)</h4><pre>┌──────────────────────────────────────────────────────┐<br>│  LIQUIDITY PROVIDER (LP)                             │<br>│                                                      │<br>│  Deposits BOTH tokens into the pool in equal value   │<br>│  In our story — this was the potato &amp; apple villages │<br>│                                                      │<br>│  [LP] ─── deposits ETH + USDC ──▶ [POOL]            │<br>│  [LP] ◀── earns share of fees ─── [POOL]            │<br>│                                                      │<br>│  Earns a fraction of every trade fee                 │<br>│  Can withdraw original deposit + fees any time       │<br>└──────────────────────────────────────────────────────┘</pre><h4>How the Fee Flow Works</h4><pre>TRADE FLOW<br>──────────────────────────────────────────────────────<br>  Trader swaps $1,000 of ETH for USDC<br>      ↓<br>  0.3% fee = $3 stays inside the pool<br>      ↓<br>  Pool grows slightly larger<br>      ↓<br>  All LPs earn proportionally to their share of pool<br>      ↓<br>  LP withdraws later → original deposit + accumulated fees</pre><p>Even if each fee is tiny, hundreds of trades per day across a large pool adds up to meaningful passive income for LPs.</p><h3>Part 6 — Different AMM Models</h3><p>The x × y = k model is the most famous but not the only one. Different DeFi platforms built variations for different needs:</p><pre>┌──────────────────┬────────────────┬────────────────┬──────────────────┐<br>│ AMM Model        │ Formula        │ Used By        │ Best For         │<br>├──────────────────┼────────────────┼────────────────┼──────────────────┤<br>│ Constant Product │ x × y = k      │ Uniswap        │ General pairs    │<br>│ Constant Sum     │ x + y = k      │ Balancer       │ Equal-value      │<br>│ Curve StableSwap │ Hybrid         │ Curve Finance  │ Stablecoins      │<br>│ Hybrid AMM       │ Multi-formula  │ SushiSwap      │ Mixed strategies │<br>└──────────────────┴────────────────┴────────────────┴──────────────────┘</pre><p>All of them share the same core idea: <strong>a formula, not a human, sets the price.</strong></p><h3>Quick Recap — Everything You Just Learned</h3><pre>✅  An AMM replaces the order book with a mathematical formula<br>✅  It uses a Liquidity Pool — a smart contract holding two tokens<br>✅  The formula x × y = k keeps the pool balanced at all times<br>✅  Buy more of a token → it becomes scarcer → price rises automatically<br>✅  Traders pay fees. Liquidity Providers earn those fees<br>✅  Larger pools = smaller price impact = more stable trading<br>✅  Uniswap, Curve, SushiSwap, Balancer all use variations of this idea</pre><h3>Glossary</h3><p>TermWhat It Means<br><strong>AMM: </strong>Automated Market Maker uses a formula to price assets instead of human traders.<br><strong>DEX: </strong>Decentralised Exchange runs on smart contracts with no company in charge<br><strong>Liquidity Pool: </strong>A smart contract holding two tokens that anyone can trade against.<br><strong>Liquidity Provider (LP): </strong>A user who deposits tokens into the pool and earns trading fees <strong>x × y = k </strong>The Constant Product formula x and y are token quantities, k never changes.</p><p><strong>Slippage: </strong>The difference between expected and actual trade price due to pool movement <strong>Smart Contract </strong>Self-executing code on a blockchain runs automatically, no humans required</p><h3>What’s Next? — Liquidity Pools</h3><p>You now understand <strong>how an AMM prices tokens.</strong> But we skipped over a crucial question — how does the Liquidity Pool actually work under the hood?</p><p>In the next article:</p><ul><li>What happens when multiple LPs deposit at different times and prices?</li><li>What are LP tokens, and how do they track your share of the pool?</li><li>What is <strong>Impermanent Loss</strong> — and why every LP must understand it before depositing</li><li>How to withdraw your original deposit after the price has shifted</li></ul><p>Impermanent Loss is the single most misunderstood concept in all of DeFi. Understanding it is what separates informed participants from those who get surprised by unexpected losses. That is coming up next.</p><p><em>If this helped you, share it with one friend who is just getting started in crypto.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d69f1f6c6c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling Functions Between Hyperledger Fabric Chaincodes: The Right Way]]></title>
            <link>https://coinsbench.com/calling-functions-between-hyperledger-fabric-chaincodes-the-right-way-0877403dfd3d?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/0877403dfd3d</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[private-blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[chaincode]]></category>
            <category><![CDATA[hyperledger]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 07:53:09 GMT</pubDate>
            <atom:updated>2026-06-15T09:19:45.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*0ncObJ6nH80Vm523srLREw.jpeg" /></figure><p>If you’ve deployed a couple of chaincodes on Hyperledger Fabric, you’ve probably faced this question: <em>“How do I reuse a function from one chaincode in another without duplicating code?”</em></p><p>The answer isn’t immediately obvious, and many developers end up with duplicated logic across chaincodes or, worse, try to share files directly between projects. Both approaches lead to maintenance nightmares and architectural problems.</p><p>In this post, I’ll walk you through <strong>the professional way</strong> to share functionality between chaincodes using <strong>cross-chaincode invocation</strong> — and why it’s the right architectural choice.</p><h3>The Problem: Why Code Duplication Doesn’t Scale</h3><p>Let’s say you’re building a consortium blockchain for educational verification. You have:</p><ol><li><strong>Digital Identity Chaincode</strong> — Validates users, manages email/phone verification</li><li><strong>Degree Verification Chaincode</strong> — Issues and verifies degrees</li></ol><p>Both need to validate email addresses and check if a user exists. You have three choices:</p><ol><li><strong>Copy-paste the functions</strong> into both chaincodes (bad)</li><li><strong>Share files directly</strong> using relative imports like require(&#39;../common/validators.js&#39;) (worse)</li><li><strong>Use cross-chaincode invocation</strong> (correct)</li></ol><p>Option 1 and 2 break the fundamental principle of microservices: <strong>independent deployment</strong>. If you update email validation logic, you’d need to redeploy both chaincodes. Plus, you risk version mismatches and consistency issues.</p><p>The professional approach is <strong>cross-chaincode invocation</strong> — one chaincode explicitly calls functions in another chaincode through the Fabric SDK.</p><h3>Understanding Cross-Chaincode Invocation</h3><p>Cross-chaincode invocation allows a chaincode to invoke functions in another chaincode on the <strong>same channel</strong>. It’s essentially an RPC (Remote Procedure Call) within the blockchain network.</p><h3>How It Works (Conceptually)</h3><pre>┌─────────────────────────────────────────────────────────┐<br>│  Degree Verification Chaincode                          │<br>│                                                         │<br>│  func IssueDegree(ctx, userID, degreeData) {            │<br>│      // Need to validate user first                     │<br>│      call Identity Chaincode                            │<br>│      └─→ CheckUserExists(userID) ───────┐               │<br>│                                          │              │<br>│                                          ▼              │<br>│                           ┌──────────────────────────┐  │<br>│                           │ Digital Identity         │  │<br>│                           │ CheckUserExists(id)      │  │<br>│                           │ ValidateEmail(email)     │  │<br>│                           │ GetUser(id)              │  │<br>│                           └──────────────────────────┘  │<br>│      ← Response: true/false                             │<br>│      if valid, proceed with degree issuance             │<br>│  }                                                      │<br>└─────────────────────────────────────────────────────────┘</pre><h3>The Core Fabric API</h3><p>In Go, you invoke another chaincode using the ChaincodeStubInterface:</p><pre>response := ctx.GetStub().InvokeChaincode(<br>    &quot;target-chaincode-name&quot;,           // Name of chaincode to call<br>    [][]byte{<br>        []byte(&quot;FunctionName&quot;),        // Function to invoke<br>        []byte(&quot;arg1&quot;),                // Arguments<br>        []byte(&quot;arg2&quot;),<br>    },<br>    &quot;channel-name&quot;,                    // Channel where chaincode exists<br>)</pre><pre>// Check response<br>if response.Status != 200 {<br>    return fmt.Errorf(&quot;failed: %s&quot;, response.Message)<br>}</pre><pre>// Process response ([]byte format)<br>resultData := response.Payload</pre><p>This is powerful because:</p><ul><li>Both chaincodes remain independently deployable</li><li>No code duplication</li><li>Proper versioning control</li><li>Clean separation of concerns</li><li>Follows distributed systems best practices</li></ul><h3>Deep Dive: Setting Up Cross-Chaincode Communication</h3><h3>Step 1: Create the Identity Chaincode (Shared Functions)</h3><p>Here’s a minimal but complete Digital Identity chaincode with the functions we want to share:</p><pre>// chaincode/identity/identity.go<br>package main</pre><pre>import (<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;regexp&quot;</pre><pre>    &quot;github.com/hyperledger/fabric-contract-api-go/contractapi&quot;<br>)</pre><pre>type DigitalIdentityContract struct {<br>    contractapi.Contract<br>}</pre><pre>type User struct {<br>    UserID      string `json:&quot;user_id&quot;`<br>    Email       string `json:&quot;email&quot;`<br>    PhoneNumber string `json:&quot;phone_number&quot;`<br>    Status      string `json:&quot;status&quot;`<br>    CreatedAt   string `json:&quot;created_at&quot;`<br>}</pre><pre>// SHARED FUNCTION 1: Validate Email<br>func (c *DigitalIdentityContract) ValidateEmail(<br>    ctx contractapi.TransactionContextInterface,<br>    email string,<br>) (bool, error) {<br>    // RFC 5322 simplified regex for email<br>    emailRegex := regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`)<br>    <br>    if !emailRegex.MatchString(email) {<br>        return false, nil<br>    }<br>    <br>    return true, nil<br>}</pre><pre>// SHARED FUNCTION 2: Check User Exists<br>func (c *DigitalIdentityContract) CheckUserExists(<br>    ctx contractapi.TransactionContextInterface,<br>    userID string,<br>) (bool, error) {<br>    userBytes, err := ctx.GetStub().GetState(userID)<br>    if err != nil {<br>        return false, err<br>    }<br>    <br>    return userBytes != nil, nil<br>}</pre><pre>// SHARED FUNCTION 3: Get User Data<br>func (c *DigitalIdentityContract) GetUser(<br>    ctx contractapi.TransactionContextInterface,<br>    userID string,<br>) (*User, error) {<br>    userBytes, err := ctx.GetStub().GetState(userID)<br>    if err != nil {<br>        return nil, err<br>    }<br>    <br>    if userBytes == nil {<br>        return nil, fmt.Errorf(&quot;user not found&quot;)<br>    }<br>    <br>    var user User<br>    if err := json.Unmarshal(userBytes, &amp;user); err != nil {<br>        return nil, err<br>    }<br>    <br>    return &amp;user, nil<br>}</pre><pre>// Public function: Create User<br>func (c *DigitalIdentityContract) CreateUser(<br>    ctx contractapi.TransactionContextInterface,<br>    userID, email, phone string,<br>) error {<br>    // Validate email first<br>    isValid, err := c.ValidateEmail(ctx, email)<br>    if err != nil || !isValid {<br>        return fmt.Errorf(&quot;invalid email format&quot;)<br>    }<br>    <br>    user := User{<br>        UserID:      userID,<br>        Email:       email,<br>        PhoneNumber: phone,<br>        Status:      &quot;active&quot;,<br>        CreatedAt:   &quot;2024-01-15&quot;,<br>    }<br>    <br>    userJSON, _ := json.Marshal(user)<br>    return ctx.GetStub().PutState(userID, userJSON)<br>}</pre><pre>func (c *DigitalIdentityContract) InitLedger(<br>    ctx contractapi.TransactionContextInterface,<br>) error {<br>    return nil<br>}</pre><h3>Step 2: Create the Degree Chaincode (Calls Identity)</h3><p>Now let’s create the Degree chaincode that <strong>calls functions</strong> from the Identity chaincode:</p><pre>// chaincode/degree/degree.go<br>package main</pre><pre>import (<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;</pre><pre>    &quot;github.com/hyperledger/fabric-contract-api-go/contractapi&quot;<br>)</pre><pre>type DegreeContract struct {<br>    contractapi.Contract<br>}</pre><pre>type Degree struct {<br>    DegreeID     string `json:&quot;degree_id&quot;`<br>    UserID       string `json:&quot;user_id&quot;`<br>    University   string `json:&quot;university&quot;`<br>    Field        string `json:&quot;field&quot;`<br>    GPA          string `json:&quot;gpa&quot;`<br>    VerifiedDate string `json:&quot;verified_date&quot;`<br>    Status       string `json:&quot;status&quot;` // &quot;issued&quot;, &quot;revoked&quot;<br>}</pre><pre>// Helper: Safely invoke another chaincode with error handling<br>func (c *DegreeContract) invokeIdentityChaincode(<br>    ctx contractapi.TransactionContextInterface,<br>    function string,<br>    args ...string,<br>) ([]byte, error) {<br>    <br>    // Build the argument array<br>    invokeArgs := make([][]byte, 0)<br>    invokeArgs = append(invokeArgs, []byte(function))<br>    <br>    for _, arg := range args {<br>        invokeArgs = append(invokeArgs, []byte(arg))<br>    }<br>    <br>    // Invoke the identity chaincode<br>    response := ctx.GetStub().InvokeChaincode(<br>        &quot;identity-chaincode&quot;,    // Must match the name deployed on Fabric<br>        invokeArgs,<br>        &quot;mychannel&quot;,             // Must be the same channel<br>    )<br>    <br>    // Check for errors<br>    if response.Status != 200 {<br>        return nil, fmt.Errorf(<br>            &quot;identity-chaincode invocation failed (status %d): %s&quot;,<br>            response.Status,<br>            response.Message,<br>        )<br>    }<br>    <br>    if response.Payload == nil {<br>        return nil, fmt.Errorf(&quot;empty response from identity-chaincode&quot;)<br>    }<br>    <br>    return response.Payload, nil<br>}</pre><pre>// Public function: Issue Degree (uses cross-chaincode call)<br>func (c *DegreeContract) IssueDegree(<br>    ctx contractapi.TransactionContextInterface,<br>    degreeID, userID, university, field, gpa string,<br>) error {<br>    <br>    // Step 1: Call identity chaincode to verify user exists<br>    userExistsPayload, err := c.invokeIdentityChaincode(<br>        ctx,<br>        &quot;CheckUserExists&quot;,<br>        userID,<br>    )<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to check user: %w&quot;, err)<br>    }<br>    <br>    // Parse response (should be &quot;true&quot; or &quot;false&quot;)<br>    userExists := string(userExistsPayload) == &quot;true&quot;<br>    if !userExists {<br>        return fmt.Errorf(&quot;user does not exist in identity system&quot;)<br>    }<br>    <br>    // Step 2: Create and store the degree<br>    degree := Degree{<br>        DegreeID:     degreeID,<br>        UserID:       userID,<br>        University:   university,<br>        Field:        field,<br>        GPA:          gpa,<br>        VerifiedDate: &quot;2024-01-15&quot;,<br>        Status:       &quot;issued&quot;,<br>    }<br>    <br>    degreeJSON, _ := json.Marshal(degree)<br>    <br>    if err := ctx.GetStub().PutState(degreeID, degreeJSON); err != nil {<br>        return fmt.Errorf(&quot;failed to store degree: %w&quot;, err)<br>    }<br>    <br>    return nil<br>}</pre><pre>// Public function: Verify Degree<br>func (c *DegreeContract) VerifyDegree(<br>    ctx contractapi.TransactionContextInterface,<br>    degreeID string,<br>) (string, error) {<br>    <br>    degreeBytes, err := ctx.GetStub().GetState(degreeID)<br>    if err != nil {<br>        return &quot;&quot;, err<br>    }<br>    <br>    if degreeBytes == nil {<br>        return &quot;&quot;, fmt.Errorf(&quot;degree not found&quot;)<br>    }<br>    <br>    var degree Degree<br>    if err := json.Unmarshal(degreeBytes, &amp;degree); err != nil {<br>        return &quot;&quot;, err<br>    }<br>    <br>    return degree.Status, nil<br>}</pre><pre>func (c *DegreeContract) InitLedger(<br>    ctx contractapi.TransactionContextInterface,<br>) error {<br>    return nil<br>}</pre><h3>Installation &amp; Setup Across Operating Systems</h3><h3>Linux Setup</h3><pre># 1. Install Go 1.20+<br>wget https://go.dev/dl/go1.20.linux-amd64.tar.gz<br>tar -C /usr/local -xzf go1.20.linux-amd64.tar.gz<br>export PATH=$PATH:/usr/local/go/bin</pre><pre># 2. Initialize both chaincodes<br>cd chaincode/identity<br>GO111MODULE=on go mod init github.com/yourorg/identity-chaincode<br>go mod tidy</pre><pre>cd ../degree<br>GO111MODULE=on go mod init github.com/yourorg/degree-chaincode<br>go mod tidy</pre><pre># 3. Package chaincodes<br>cd ../../<br>peer lifecycle chaincode package identity.tar.gz \<br>  --path ./chaincode/identity \<br>  --lang golang \<br>  --label identity_1.0</pre><pre>peer lifecycle chaincode package degree.tar.gz \<br>  --path ./chaincode/degree \<br>  --lang golang \<br>  --label degree_1.0</pre><pre># 4. Install on peers<br>peer lifecycle chaincode install identity.tar.gz<br>peer lifecycle chaincode install degree.tar.gz</pre><pre># 5. Approve and commit (see Fabric documentation)</pre><h3>macOS Setup</h3><pre># 1. Install Go via Homebrew<br>brew install go@1.20<br>export PATH=&quot;/usr/local/opt/go@1.20/bin:$PATH&quot;</pre><pre># 2. Verify installation<br>go version  # Should show go1.20.x</pre><pre># 3. Follow same steps as Linux from step 2 onwards<br>cd chaincode/identity<br>GO111MODULE=on go mod init github.com/yourorg/identity-chaincode<br>go mod tidy</pre><pre># Continue with packaging and installation...</pre><h3>Windows Setup</h3><pre># 1. Download and install Go 1.20+<br># Visit: https://go.dev/dl/<br># Choose windows-amd64.msi and run installer</pre><pre># 2. Verify installation (PowerShell as Admin)<br>go version</pre><pre># 3. Set environment variables<br>$env:GO111MODULE = &quot;on&quot;</pre><pre># 4. Initialize chaincodes<br>cd chaincode/identity<br>go mod init github.com/yourorg/identity-chaincode<br>go mod tidy</pre><pre>cd ../degree<br>go mod init github.com/yourorg/degree-chaincode<br>go mod tidy</pre><pre># 5. For peer commands, use Fabric binaries<br># Download from: <a href="https://github.com/hyperledger/fabric/releases">https://github.com/hyperledger/fabric/releases</a></pre><h3>Comparing Approaches: Why InvokeChaincode is Superior</h3><p>Before committing to this approach, let’s compare the three options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*-fLwxLEsYgCnVcAJYfOygg.png" /></figure><p><strong>Verdict</strong>: InvokeChaincode wins for professional, scalable systems. Yes, there’s slight latency, but the architectural benefits far outweigh this cost.</p><h3>Critical: Common Mistakes That Will Cause Failures</h3><h3>Mistake 1: Wrong Chaincode Name</h3><pre>// WRONG - Name doesn&#39;t match deployment<br>response := ctx.GetStub().InvokeChaincode(<br>    &quot;identity&quot;,  // Deployed as &quot;identity-chaincode&quot;!<br>    args,<br>    &quot;mychannel&quot;,<br>)</pre><pre>// CORRECT<br>response := ctx.GetStub().InvokeChaincode(<br>    &quot;identity-chaincode&quot;,  // Match exactly<br>    args,<br>    &quot;mychannel&quot;,<br>)</pre><p><strong>Error you’ll see</strong>: 500 - chaincode not found</p><h3>Mistake 2: Function Name Case Sensitivity</h3><pre>// WRONG - Function doesn&#39;t exist<br>invokeArgs := [][]byte{<br>    []byte(&quot;checkuserexists&quot;),  // Wrong case!<br>}</pre><pre>// CORRECT<br>invokeArgs := [][]byte{<br>    []byte(&quot;CheckUserExists&quot;),  // Matches Go function name<br>}</pre><p><strong>Error you’ll see</strong>: unknown function checkuserexists</p><h3>Mistake 3: Different Channels</h3><pre>// WRONG - Chaincodes on different channels<br>// identity-chaincode is on &quot;channel-a&quot;<br>// degree-chaincode is on &quot;channel-b&quot;<br>response := ctx.GetStub().InvokeChaincode(<br>    &quot;identity-chaincode&quot;,<br>    args,<br>    &quot;channel-b&quot;,  // Can&#39;t invoke across channels!<br>)</pre><pre>// CORRECT - Deploy both on same channel<br>response := ctx.GetStub().InvokeChaincode(<br>    &quot;identity-chaincode&quot;,<br>    args,<br>    &quot;mychannel&quot;,  // Both exist here<br>)</pre><p><strong>Error you’ll see</strong>: chaincode not available on this channel</p><h3>Mistake 4: Not Checking Response Status</h3><pre>// WRONG - Assuming success<br>response := ctx.GetStub().InvokeChaincode(...)<br>resultData := response.Payload  // Could be nil or error!</pre><pre>// CORRECT - Always validate<br>response := ctx.GetStub().InvokeChaincode(...)<br>if response.Status != 200 {<br>    return nil, fmt.Errorf(&quot;invocation failed: %s&quot;, response.Message)<br>}<br>if response.Payload == nil {<br>    return nil, fmt.Errorf(&quot;empty response received&quot;)<br>}<br>resultData := response.Payload</pre><h3>Mistake 5: Not Handling Type Conversions</h3><pre>// WRONG - Payload is []byte, not bool<br>response := ctx.GetStub().InvokeChaincode(...)<br>userExists := response.Payload  // This is []byte!</pre><pre>if userExists {  // Type error!<br>    // ...<br>}</pre><pre>// CORRECT - Convert to proper type<br>response := ctx.GetStub().InvokeChaincode(...)<br>userExists := string(response.Payload) == &quot;true&quot;<br>if userExists {<br>    // ...<br>}</pre><h3>Handling Multiple Channels: A Practical Approach</h3><p>In enterprise setups, you might have:</p><ul><li><strong>Channel A</strong>: Between Organizations X and Y</li><li><strong>Channel B</strong>: Between Organizations Y and Z</li></ul><p>You can’t directly invoke across channels, but you can design around this:</p><pre>// Pattern: Create a routing chaincode if you need cross-channel logic<br>func (c *DegreeContract) IssueDegreeAcrossChannels(<br>    ctx contractapi.TransactionContextInterface,<br>    degreeID, userID string,<br>) error {<br>    // For channel-specific validation, call the appropriate chaincode<br>    channelID := ctx.GetStub().GetChannelID()  // Get current channel<br>    <br>    var identityChaincodeOnChannel string<br>    <br>    // Route to correct chaincode based on channel<br>    switch channelID {<br>    case &quot;channel-a&quot;:<br>        identityChaincodeOnChannel = &quot;identity-chaincode-a&quot;<br>    case &quot;channel-b&quot;:<br>        identityChaincodeOnChannel = &quot;identity-chaincode-b&quot;<br>    default:<br>        return fmt.Errorf(&quot;unknown channel: %s&quot;, channelID)<br>    }<br>    <br>    // Invoke the appropriate chaincode<br>    response := ctx.GetStub().InvokeChaincode(<br>        identityChaincodeOnChannel,<br>        [][]byte{[]byte(&quot;CheckUserExists&quot;), []byte(userID)},<br>        channelID,<br>    )<br>    <br>    if response.Status != 200 {<br>        return fmt.Errorf(&quot;validation failed: %s&quot;, response.Message)<br>    }<br>    <br>    return nil<br>}</pre><h3>Transaction Atomicity: What You Need to Know</h3><p>Here’s the truth: <strong>Cross-chaincode invocations are NOT atomic</strong>. This is important.</p><p>If you invoke a chaincode like this:</p><pre>func (c *DegreeContract) IssueDegree(ctx contractapi.TransactionContextInterface, userID string) error {<br>    <br>    // Call 1: Validate user<br>    response1 := ctx.GetStub().InvokeChaincode(...)<br>    if response1.Status != 200 {<br>        return fmt.Errorf(&quot;validation failed&quot;)<br>    }<br>    <br>    // Call 2: Create degree<br>    ctx.GetStub().PutState(...)<br>    <br>    // What if Call 2 fails after Call 1 succeeds?<br>    // Both are logged, but not as a single atomic unit<br>}</pre><p><strong>What this means</strong>:</p><ul><li>Each cross-chaincode invocation is a <strong>separate transaction</strong></li><li>If your logic fails after calling another chaincode, the other chaincode’s state <strong>already committed</strong></li><li>You need to design your business logic accordingly</li></ul><p><strong>How to handle this</strong>:</p><pre>// Use a transaction ID to track related operations<br>func (c *DegreeContract) IssueDegreeWithTracking(<br>    ctx contractapi.TransactionContextInterface,<br>    degreeID, userID string,<br>) error {<br>    txID := ctx.GetStub().GetTxID()  // Unique transaction ID<br>    <br>    // Validate first<br>    response := ctx.GetStub().InvokeChaincode(...)<br>    if response.Status != 200 {<br>        // Log the failed transaction with txID for audit trail<br>        return fmt.Errorf(&quot;validation failed for tx %s&quot;, txID)<br>    }<br>    <br>    // Only proceed if validation succeeded<br>    degree := Degree{<br>        DegreeID:      degreeID,<br>        UserID:        userID,<br>        TransactionID: txID,  // Link to validation tx<br>    }<br>    <br>    degreeJSON, _ := json.Marshal(degree)<br>    return ctx.GetStub().PutState(degreeID, degreeJSON)<br>}</pre><p>This way, even though the transactions aren’t atomic, you have a complete audit trail.</p><h3>Security Considerations</h3><h3>1. Validate All Inputs</h3><pre>// DON&#39;T - Trust user input<br>func (c *DegreeContract) IssueDegree(ctx contractapi.TransactionContextInterface, userID string) error {<br>    response := ctx.GetStub().InvokeChaincode(<br>        &quot;identity-chaincode&quot;,<br>        [][]byte{[]byte(&quot;CheckUserExists&quot;), []byte(userID)},<br>        &quot;mychannel&quot;,<br>    )<br>}</pre><pre>// DO - Sanitize and validate<br>func (c *DegreeContract) IssueDegree(ctx contractapi.TransactionContextInterface, userID string) error {<br>    if userID == &quot;&quot; {<br>        return fmt.Errorf(&quot;userID cannot be empty&quot;)<br>    }<br>    if len(userID) &gt; 255 {<br>        return fmt.Errorf(&quot;userID too long&quot;)<br>    }<br>    <br>    response := ctx.GetStub().InvokeChaincode(...)<br>}</pre><h3>2. Check Endorsement Policies</h3><p>When degree-chaincode calls identity-chaincode, <strong>both chaincodes must be endorsed</strong>. Configure your endorsement policies to require appropriate organizations:</p><pre># In your channel policy<br>/Channel/Application/DegreeEndorsement: <br>  AND(&#39;Org1MSP.peer&#39;, &#39;Org2MSP.peer&#39;)</pre><pre>/Channel/Application/IdentityEndorsement:<br>  AND(&#39;Org1MSP.peer&#39;, &#39;Org2MSP.peer&#39;)</pre><h3>3. Use Access Control</h3><pre>func (c *DegreeContract) IssueDegree(ctx contractapi.TransactionContextInterface, degreeID, userID string) error {<br>    <br>    // Get client identity<br>    clientID, err := ctx.GetClientIdentity().GetID()<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to get client identity&quot;)<br>    }<br>    <br>    // Only universities can issue degrees<br>    if !strings.HasSuffix(clientID, &quot;university&quot;) {<br>        return fmt.Errorf(&quot;only universities can issue degrees&quot;)<br>    }<br>    <br>    // Proceed with issuance...<br>    return nil<br>}</pre><h3>Error Handling: The Right Way</h3><p>Here’s a robust pattern for handling cross-chaincode invocations:</p><pre>// Define custom errors<br>type InvocationError struct {<br>    ChaincodeID string<br>    Function    string<br>    Reason      string<br>    Status      int32<br>}</pre><pre>func (e *InvocationError) Error() string {<br>    return fmt.Sprintf(&quot;Failed to invoke %s.%s: %s (status %d)&quot;, <br>        e.ChaincodeID, e.Function, e.Reason, e.Status)<br>}</pre><pre>// Reusable invocation with proper error handling<br>func (c *DegreeContract) safeInvokeIdentity(<br>    ctx contractapi.TransactionContextInterface,<br>    function string,<br>    args ...string,<br>) ([]byte, error) {<br>    <br>    invokeArgs := make([][]byte, 0)<br>    invokeArgs = append(invokeArgs, []byte(function))<br>    for _, arg := range args {<br>        invokeArgs = append(invokeArgs, []byte(arg))<br>    }<br>    <br>    response := ctx.GetStub().InvokeChaincode(<br>        &quot;identity-chaincode&quot;,<br>        invokeArgs,<br>        &quot;mychannel&quot;,<br>    )<br>    <br>    if response.Status != 200 {<br>        return nil, &amp;InvocationError{<br>            ChaincodeID: &quot;identity-chaincode&quot;,<br>            Function:    function,<br>            Reason:      response.Message,<br>            Status:      response.Status,<br>        }<br>    }<br>    <br>    if response.Payload == nil {<br>        return nil, &amp;InvocationError{<br>            ChaincodeID: &quot;identity-chaincode&quot;,<br>            Function:    function,<br>            Reason:      &quot;empty payload received&quot;,<br>            Status:      500,<br>        }<br>    }<br>    <br>    return response.Payload, nil<br>}</pre><pre>// Usage<br>func (c *DegreeContract) IssueDegree(ctx contractapi.TransactionContextInterface, userID string) error {<br>    payload, err := c.safeInvokeIdentity(ctx, &quot;CheckUserExists&quot;, userID)<br>    if err != nil {<br>        // Detailed error information for debugging<br>        return fmt.Errorf(&quot;validation error: %w&quot;, err)<br>    }<br>    <br>    userExists := string(payload) == &quot;true&quot;<br>    if !userExists {<br>        return fmt.Errorf(&quot;user %s not found in identity system&quot;, userID)<br>    }<br>    <br>    return nil<br>}</pre><h3>Wrapping Up: The Takeaways</h3><p><strong>Key Points</strong>:</p><ol><li><strong>Cross-chaincode invocation</strong> via InvokeChaincode() is the professional way to share functions between chaincodes.</li><li><strong>Always verify</strong>:</li></ol><ul><li>Chaincode names match exactly (case-sensitive)</li><li>Both chaincodes exist on the same channel</li><li>Response status is 200 before processing payload</li><li>Payload is not nil</li></ul><p>Chaincode names match exactly (case-sensitive)</p><ul><li>Chaincode names match exactly (case-sensitive)</li><li>Response status is 200 before processing payload</li><li>Payload is not nil</li></ul><ol><li><strong>Understand the limitations</strong>:</li></ol><ul><li>Not atomic (each invocation is a separate transaction)</li><li>Requires both chaincodes to be endorsed</li><li>Introduces slight latency (acceptable for most use cases)</li></ul><ol><li><strong>Think about architecture</strong> — If a function is truly shared, consider whether it should be a separate microservice instead of a chaincode.</li><li>This approach keeps your chaincodes modular, independent, and scalable — exactly what you need for production consortium blockchains.</li><li><strong>Handle errors gracefully</strong> — Use the error handling pattern shown above.</li></ol><h3>What’s Next?</h3><p>Once you’ve mastered cross-chaincode invocation, consider exploring:</p><ul><li><strong>Event-driven architecture</strong> with Fabric events for loose coupling</li><li><strong>Private data collections</strong> for sensitive information</li><li><strong>Custom endorsement policies</strong> for complex governance</li></ul><p>Happy coding on Fabric!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0877403dfd3d" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/calling-functions-between-hyperledger-fabric-chaincodes-the-right-way-0877403dfd3d">Calling Functions Between Hyperledger Fabric Chaincodes: The Right Way</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Zero-Knowledge Encrypted Document Vault: Complete Developer Guide]]></title>
            <link>https://medium.com/coinmonks/build-a-zero-knowledge-encrypted-document-vault-complete-developer-guide-97b5fe7d8a4e?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/97b5fe7d8a4e</guid>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[decryption]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 07:49:44 GMT</pubDate>
            <atom:updated>2026-06-09T07:51:03.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cgqpclQ18PlxF4K8i4ahw.png" /></figure><blockquote><strong><em>By the end of this guide, you’ll have built a file-sharing system where you the developer running the server cannot read your users’ files.</em></strong></blockquote><p>⏱ <em>Estimated read time: 20 minutes</em> · 🏷 <em>Tags: cryptography, javascript, ipfs, security, web-dev, zero-knowledge</em></p><h3>Introduction</h3><p>Most “secure” file apps encrypt data <strong>at rest on the server</strong>. That means the server holds the encryption key. Which means the server or anyone who compromises it can read your files. That’s not security. That’s trust.</p><p>A <strong>Zero-Knowledge</strong> vault is different. Files are encrypted in the browser before they are uploaded. The server stores only encrypted blobs. The encryption keys are wrapped using the user’s RSA public key and stored separately on IPFS. The private key <strong>never leaves the user’s device</strong>. Ever.</p><p>This guide walks through a complete, working implementation called <strong>SECUREDOC</strong>. We’ll cover every meaningful piece of code: key pair generation, Pinata/IPFS storage, the upload encryption pipeline, the share re-wrap flow, decryption, and access revocation. Each section includes both <strong>real JavaScript</strong> and <strong>language-agnostic pseudo-code</strong> so you can implement this in Python, Go, Rust, or any runtime with standard crypto libraries.</p><blockquote><strong><em>TL;DR</em></strong></blockquote><ul><li>Every user has an RSA-2048 key pair generated in their browser</li><li>Files are encrypted with a random AES-256-GCM key per document</li><li>That AES key is RSA-encrypted (wrapped) with the user’s public key and stored on IPFS</li><li>Sharing = re-wrapping the AES key for the recipient’s public key, locally in the browser</li><li>The server only stores: encrypted blobs (IPFS CIDs), wrapped key CIDs, and metadata</li><li><strong>The server cannot decrypt anything ever</strong></li></ul><h3>The Architecture at a Glance</h3><p>Before diving into code, here’s the full system map:</p><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                        USER&#39;S BROWSER                           │<br>│                                                                 │<br>│  RSA Key Pair ──────── stays here (private key never leaves)    │<br>│  AES Encrypt  ──────── file encrypted before any network call   │<br>│  Key Wrapping ──────── AES key encrypted with RSA public key    │<br>└──────────────┬──────────────────────────────────────┬──────────┘<br>               │                                      │<br>               ▼                                      ▼<br>    ┌─────────────────────┐              ┌──────────────────────┐<br>    │   PINATA / IPFS     │              │   EXPRESS BACKEND    │<br>    │                     │              │                      │<br>    │ Encrypted Blob CID  │              │ Document metadata    │<br>    │ Wrapped Key CID     │              │ Access Control List  │<br>    │ (can&#39;t read either) │              │ Public key registry  │<br>    └─────────────────────┘              └──────────────────────┘</pre><h3>Part 1 — The Cryptography, Plain English</h3><p>You don’t need a math degree. You need two concepts.</p><h3>RSA-OAEP: Asymmetric Encryption</h3><p>RSA uses <strong>two linked keys</strong>:</p><ul><li><strong>Public key</strong> — share this freely. Anyone can use it to encrypt data <em>for you</em>.</li><li><strong>Private key</strong> — keep this secret. Only you can use it to decrypt data encrypted with your public key.</li></ul><p>The golden rule: <strong>data encrypted with a public key can only be decrypted with its matching private key.</strong> Even the person who encrypted it can’t decrypt it again without the private key.</p><p>We use <strong>RSA-OAEP with SHA-256</strong> the modern, padding-safe variant. Never use raw RSA (textbook RSA) in production.</p><h3>AES-GCM: Symmetric Encryption</h3><p>AES is <strong>symmetric</strong> the same key encrypts and decrypts. It’s extremely fast for large files.</p><p>We use <strong>AES-256-GCM</strong> specifically because GCM mode provides both confidentiality <em>and</em> authentication. If anyone tampers with the encrypted bytes, decryption throws a hard error you can’t get garbled output, you get nothing.</p><h3>The Hybrid Pattern</h3><p>RSA is slow on large data. AES is fast but requires sharing the key securely. Solution: use both.</p><pre># Pseudo-code — the core pattern<br>symmetricKey = AES_GCM.generate_256bit_key()          # fast key for the file<br>encryptedFile = AES_GCM.encrypt(symmetricKey, file)   # encrypt the big file<br>wrappedKey = RSA_OAEP.encrypt(userPublicKey, symmetricKey)  # protect the small key</pre><pre># What gets stored / transmitted:<br>store(encryptedFile)  # safe — useless without the AES key<br>store(wrappedKey)     # safe — only the private key holder can open this</pre><p>That’s the entire vault in four lines. Everything else is implementation detail.</p><h3>Part 2 — Setting Up Pinata (IPFS Storage)</h3><p><strong>IPFS</strong> is a decentralized content-addressed storage network. <strong>Pinata</strong> is a managed pinning service that gives you a reliable HTTP API on top of it. Files are stored by their content hash (CID) immutable, permanent, and globally accessible.</p><h3>Step 1: Create a Pinata Account and Generate a JWT</h3><ol><li>Sign up at <a href="https://app.pinata.cloud/">app.pinata.cloud</a> (free tier works)</li><li>Go to <strong>API Keys</strong> → <strong>New Key</strong></li><li>Under <strong>Scopes</strong>, enable <strong>pinFileToIPFS only</strong> — this is the only scope you need</li><li>Click <strong>Generate</strong> copy the <strong>JWT token</strong> immediately (it won’t be shown again)</li></ol><blockquote><em>⚠️ </em><strong><em>Principle of least privilege:</em></strong><em> Enable only </em><em>pinFileToIPFS. If this JWT is ever leaked, an attacker can pin new files but cannot delete or manage your existing pins. Never use an Admin key in a client-side app.</em></blockquote><h3>Step 2: The Gateway URL</h3><p>Every file pinned to IPFS gets a CID. Fetch it back using:</p><pre>GET https://gateway.pinata.cloud/ipfs/&lt;CID&gt;</pre><p>Because every file in this system is <strong>AES-encrypted before upload</strong>, anyone who fetches the raw bytes from IPFS gets an unreadable blob. The CID being public is completely fine.</p><h3>Step 3: The Core Upload Function</h3><p>We use pinFileToIPFS for everything both the large encrypted blobs and the small wrapped key JSON files.</p><pre>// JavaScript (browser)<br>async function pinataPinFile(fileBlob, filename, metadata = {}) {<br>  const form = new FormData();<br>  form.append(&quot;file&quot;, fileBlob, filename);<br>  form.append(&quot;pinataMetadata&quot;, JSON.stringify({<br>    name: filename,<br>    keyvalues: metadata           // optional searchable tags<br>  }));<br>  form.append(&quot;pinataOptions&quot;, JSON.stringify({ cidVersion: 1 }));  // CIDv1 recommended</pre><pre>  const response = await fetch(&quot;https://api.pinata.cloud/pinning/pinFileToIPFS&quot;, {<br>    method: &quot;POST&quot;,<br>    headers: { Authorization: `Bearer ${PINATA_JWT}` },<br>    body: form<br>    // Note: do NOT set Content-Type header manually — <br>    // the browser sets it automatically with the correct boundary for multipart<br>  });</pre><pre>  if (!response.ok) {<br>    const err = await response.text();<br>    throw new Error(`Pinata upload failed (${response.status}): ${err}`);<br>  }</pre><pre>  const data = await response.json();<br>  return data.IpfsHash;  // e.g. &quot;bafybeifgc2voidpz2rh773vkvqutkpu...&quot;<br>}</pre><pre># Pseudo-code (Python / Go / Rust / any language)<br>function pinataPinFile(fileBytes, filename, metadata):<br>  form = new MultipartForm()<br>  form.add_file_field(&quot;file&quot;, fileBytes, filename)<br>  form.add_text_field(&quot;pinataMetadata&quot;, json_encode({ name: filename, keyvalues: metadata }))<br>  form.add_text_field(&quot;pinataOptions&quot;, json_encode({ cidVersion: 1 }))</pre><pre>  response = http_post(<br>    url     = &quot;https://api.pinata.cloud/pinning/pinFileToIPFS&quot;,<br>    headers = { &quot;Authorization&quot;: &quot;Bearer &quot; + PINATA_JWT },<br>    body    = form<br>  )<br>  return response.json()[&quot;IpfsHash&quot;]</pre><blockquote><strong><em>CORS note:</em></strong><em> Pinata’s API supports browser-side CORS out of the box. You can call it directly from client-side JavaScript with no proxy. If you’re calling from a server-side backend (Node, Python, Go), standard HTTP requests work no special setup.</em></blockquote><h3>Part 3 — Wallet Creation (Key Pair Generation)</h3><p>Each user’s “wallet” is an RSA-2048 key pair. Generated in the browser. The private key never touches the network — not even encrypted at first generation.</p><h3>Generate the RSA Key Pair</h3><pre>// JavaScript (browser — Web Crypto API)<br>async function generateKeyPair() {<br>  const keyPair = await crypto.subtle.generateKey(<br>    {<br>      name: &quot;RSA-OAEP&quot;,<br>      modulusLength: 2048,                          // 2048-bit — solid for 2025+<br>      publicExponent: new Uint8Array([1, 0, 1]),    // 65537 — standard safe exponent<br>      hash: &quot;SHA-256&quot;<br>    },<br>    true,                                            // extractable: yes (needed to export to JWK)<br>    [&quot;encrypt&quot;, &quot;decrypt&quot;]<br>  );<br>  return keyPair;  // { publicKey: CryptoKey, privateKey: CryptoKey }<br>}</pre><pre># Pseudo-code<br>function generateKeyPair():<br>  return RSA.generate(<br>    algorithm = &quot;RSA-OAEP&quot;,<br>    key_size  = 2048,<br>    exponent  = 65537,<br>    hash      = &quot;SHA-256&quot;,<br>    usages    = [&quot;encrypt&quot;, &quot;decrypt&quot;]<br>  )<br>  # Returns: { publicKey, privateKey }<br>  # privateKey NEVER leaves this function&#39;s caller context to the network</pre><h3>Export the Public Key as JWK</h3><p>JWK (JSON Web Key) is the standard interoperable format for sharing cryptographic keys.</p><pre>// JavaScript<br>const pubKeyJWK = await crypto.subtle.exportKey(&quot;jwk&quot;, keyPair.publicKey);<br>// Result: { kty: &quot;RSA&quot;, alg: &quot;RSA-OAEP-256&quot;, n: &quot;qW80Lgi...&quot;, e: &quot;AQAB&quot;, ... }<br>// Safe to send to the server — this is the PUBLIC key only</pre><h3>Derive a User Identity from the Public Key</h3><p>Instead of random UUIDs, the user’s identity is <strong>derived from their public key</strong>. This means the identity is cryptographically bound you can’t claim someone else’s identity without their key.</p><pre>// JavaScript<br>async function deriveUserDID(publicKey) {<br>  const pubJWKString = JSON.stringify(await crypto.subtle.exportKey(&quot;jwk&quot;, publicKey));<br>  <br>  // SHA-256 hash of the public key JSON<br>  const hashBuffer = await crypto.subtle.digest(<br>    &quot;SHA-256&quot;,<br>    new TextEncoder().encode(pubJWKString)<br>  );<br>  <br>  const hex = Array.from(new Uint8Array(hashBuffer))<br>    .map(b =&gt; b.toString(16).padStart(2, &quot;0&quot;))<br>    .join(&quot;&quot;);<br>  <br>  return `did:local:${hex.slice(0, 32)}`;<br>  // e.g. &quot;did:local:8912c294b807019086b09342da9f7cf0&quot;<br>}</pre><pre># Pseudo-code<br>function deriveUserDID(publicKey):<br>  pubKeyStr = json_encode(export_jwk(publicKey))<br>  hash      = SHA256(utf8_encode(pubKeyStr))<br>  return &quot;did:local:&quot; + hex_encode(hash)[0:32]</pre><h3>Register with the Backend</h3><p>After creating the wallet locally, send the <strong>public key</strong> and the <strong>encrypted wallet</strong> to the server. The encrypted wallet is the private key locked with the user’s password the server stores it but cannot open it.</p><pre>// JavaScript<br>async function registerUser(email, password, keyPair, did, encryptedWallet) {<br>  const publicKeyJWK = await crypto.subtle.exportKey(&quot;jwk&quot;, keyPair.publicKey);</pre><pre>  const response = await fetch(&quot;/api/auth/register&quot;, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({<br>      email,<br>      password,             // hashed with bcrypt server-side<br>      did,<br>      publicKey: publicKeyJWK,    // ✅ safe to send — public key only<br>      encryptedWallet             // ✅ private key AES-locked with user&#39;s password<br>      // privateKey               // ❌ NEVER include this<br>    })<br>  });<br>  return response.json(); // returns JWT token<br>}</pre><blockquote><strong><em>What is </em></strong><strong><em>encryptedWallet?</em></strong><em> Before sending, the private key is exported to JWK format and encrypted with AES-GCM using a key derived from the user&#39;s password via PBKDF2. The server stores this encrypted blob (</em><em>{ salt, iv, ciphertext }). On login, the server returns the blob and the browser decrypts it locally using the password. The password itself is </em><strong><em>never sent to the server in the wallet derivation step</em></strong><em> only the hash sent for </em><em>bcrypt password verification.</em></blockquote><h3>Part 4 — Upload &amp; Encrypt a Document</h3><p>This is the core of the vault. Here’s the full pipeline:</p><pre>File<br> │<br> ├─[1]─ Generate AES-256-GCM key (K)  ←── unique per document<br> │<br> ├─[2]─ Encrypt file with K  ──────────→  Encrypted Blob<br> │<br> ├─[3]─ SHA-256(original file)  ───────→  Integrity Hash<br> │<br> ├─[4]─ RSA_OAEP_encrypt(publicKey, K)  → Wrapped Key (U1)<br> │<br> ├─[5]─ Upload Encrypted Blob → Pinata  → Blob CID<br> │<br> ├─[6]─ Upload Wrapped Key   → Pinata  → Key CID<br> │<br> └─[7]─ POST metadata to server  ───────→ Document registered</pre><h3>Step 1: Generate a Symmetric Key</h3><pre>// JavaScript<br>async function generateSymmetricKey() {<br>  return crypto.subtle.generateKey(<br>    { name: &quot;AES-GCM&quot;, length: 256 },<br>    true,                            // extractable — needed for key wrapping<br>    [&quot;encrypt&quot;, &quot;decrypt&quot;]<br>  );<br>}</pre><pre># Pseudo-code<br>function generateSymmetricKey():<br>  return AES_GCM.generate_key(bits=256, extractable=true)</pre><p><strong>Every document gets its own unique key.</strong> This is critical: if one key is ever compromised, only that document is affected.</p><h3>Step 2: Encrypt the File</h3><pre>// JavaScript<br>async function encryptFile(symmetricKey, fileArrayBuffer) {<br>  // 12-byte random IV — MUST be unique for every encryption with the same key<br>  const iv = crypto.getRandomValues(new Uint8Array(12));</pre><pre>  const ciphertext = await crypto.subtle.encrypt(<br>    { name: &quot;AES-GCM&quot;, iv },<br>    symmetricKey,<br>    fileArrayBuffer<br>  );</pre><pre>  return { ciphertext, iv };<br>  // ciphertext: ArrayBuffer (file bytes, fully encrypted)<br>  // iv: Uint8Array(12) (must be stored alongside ciphertext to decrypt)<br>}</pre><pre># Pseudo-code<br>function encryptFile(symmetricKey, fileBytes):<br>  iv         = random_bytes(12)       # CRITICAL: never reuse IV with same key<br>  ciphertext = AES_GCM.encrypt(<br>    key  = symmetricKey,<br>    iv   = iv,<br>    data = fileBytes<br>  )<br>  return { ciphertext, iv }<br>  # AES-GCM appends a 16-byte auth tag to ciphertext automatically<br>  # If ciphertext is tampered with, decryption will throw — not return garbage</pre><blockquote><em>⚠️ </em><strong><em>The IV is not a secret.</em></strong><em> Store it alongside the ciphertext. What’s critical is that you </em><strong><em>never reuse the same IV with the same key</em></strong><em> — doing so completely breaks AES-GCM confidentiality. Since every document gets a new random key, this is automatically safe.</em></blockquote><h3>Step 3: Wrap the AES Key with RSA</h3><p>This step protects the symmetric key. The wrapped key can be stored publicly on IPFS — only the private key holder can open it.</p><pre>// JavaScript<br>async function wrapSymmetricKey(symmetricKey, rsaPublicKey) {<br>  // Export the AES key to raw bytes<br>  const rawKeyBytes = await crypto.subtle.exportKey(&quot;raw&quot;, symmetricKey);<br>  // rawKeyBytes is 32 bytes (256 bits)</pre><pre>  // Encrypt those bytes with RSA-OAEP<br>  const wrappedKey = await crypto.subtle.encrypt(<br>    { name: &quot;RSA-OAEP&quot; },<br>    rsaPublicKey,<br>    rawKeyBytes<br>  );</pre><pre>  return wrappedKey;<br>  // wrappedKey: ArrayBuffer — 256 bytes for RSA-2048<br>  // Safe to store publicly — only the RSA private key can reverse this<br>}</pre><pre># Pseudo-code<br>function wrapSymmetricKey(symmetricKey, rsaPublicKey):<br>  rawBytes   = export_raw_bytes(symmetricKey)        # 32 bytes<br>  wrappedKey = RSA_OAEP.encrypt(rsaPublicKey, rawBytes)<br>  return wrappedKey<br>  # Result: ~256 bytes. Useless without the matching private key.</pre><h3>Step 4: Upload Encrypted Blob to Pinata/IPFS</h3><pre>// JavaScript<br>async function uploadEncryptedBlob(iv, ciphertext, originalFilename) {<br>  // Pack into a single binary blob: [1 byte version][12 bytes IV][N bytes ciphertext]<br>  const ivBytes = new Uint8Array(iv);<br>  const ctBytes = new Uint8Array(ciphertext);<br>  const packed  = new Uint8Array(1 + ivBytes.length + ctBytes.length);<br>  packed[0] = 1;                          // version byte — for future format changes<br>  packed.set(ivBytes, 1);<br>  packed.set(ctBytes, 1 + ivBytes.length);</pre><pre>  const blob = new Blob([packed.buffer], { type: &quot;application/octet-stream&quot; });<br>  return pinataPinFile(blob, `${originalFilename}.enc`, { type: &quot;zk-enc-blob&quot; });<br>  // Returns CID — e.g. &quot;bafybeifgc2voidpz2rh773...&quot;<br>}</pre><pre># Pseudo-code<br>function uploadEncryptedBlob(iv, ciphertext, filename):<br>  packed = concat_bytes([byte(1), iv, ciphertext])   # version + IV + data<br>  return ipfs_upload(packed, filename + &quot;.enc&quot;)</pre><h3>Step 5: Upload Wrapped Key to Pinata/IPFS</h3><pre>// JavaScript<br>async function uploadWrappedKey(wrappedKeyBuffer, ownerDID) {<br>  const payload = {<br>    wrappedKey: btoa(String.fromCharCode(...new Uint8Array(wrappedKeyBuffer))),<br>    // base64-encoded wrapped key — safe to store publicly<br>    owner: ownerDID<br>  };<br>  const blob = new Blob([JSON.stringify(payload)], { type: &quot;application/json&quot; });<br>  return pinataPinFile(blob, `wrapped_key.json`, { type: &quot;zk-wrapped-key&quot; });<br>  // Returns CID — e.g. &quot;bafkreidjmhvyxz5ckzi5ouuo2...&quot;<br>}</pre><pre># Pseudo-code<br>function uploadWrappedKey(wrappedKeyBytes, ownerDID):<br>  payload = json_encode({<br>    wrappedKey: base64_encode(wrappedKeyBytes),<br>    owner: ownerDID<br>  })<br>  return ipfs_upload(payload, &quot;wrapped_key.json&quot;)</pre><h3>Step 6: Anchor Metadata on the Backend</h3><pre>// JavaScript<br>async function anchorDocument(docId, hash, blobCID, keyCID, ownerDID, filename) {<br>  const response = await fetch(&quot;/api/documents&quot;, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({<br>      docId,<br>      hash,                       // SHA-256 of the ORIGINAL plaintext file<br>      encryptedBlobCid: blobCID,  // IPFS CID of the encrypted blob<br>      wrappedKeyCid:    keyCID,   // IPFS CID of the wrapped key JSON<br>      ownerDid:         ownerDID,<br>      filename<br>    })<br>  });<br>  if (!response.ok) throw new Error(&quot;Failed to anchor document on server&quot;);<br>}</pre><p>The server stores <strong>only CIDs and metadata</strong> never file contents, never keys in plaintext.</p><h3>The Full Upload Function</h3><pre>// JavaScript — full upload pipeline<br>async function uploadDocument(file, userPublicKey, userDID) {<br>  const fileBuffer = await file.arrayBuffer();</pre><pre>  // 1. Generate a unique AES key for this document<br>  const symKey = await generateSymmetricKey();</pre><pre>  // 2. Encrypt the file<br>  const { ciphertext, iv } = await encryptFile(symKey, fileBuffer);</pre><pre>  // 3. SHA-256 hash of original file (integrity anchor)<br>  const hashBuf = await crypto.subtle.digest(&quot;SHA-256&quot;, fileBuffer);<br>  const hash = Array.from(new Uint8Array(hashBuf))<br>    .map(b =&gt; b.toString(16).padStart(2, &quot;0&quot;)).join(&quot;&quot;);</pre><pre>  // 4. Wrap the AES key with the user&#39;s RSA public key<br>  const wrappedKey = await wrapSymmetricKey(symKey, userPublicKey);</pre><pre>  // 5. Upload encrypted blob to IPFS<br>  const blobCID = await uploadEncryptedBlob(iv, ciphertext, file.name);</pre><pre>  // 6. Upload wrapped key to IPFS<br>  const keyCID = await uploadWrappedKey(wrappedKey, userDID);</pre><pre>  // 7. Register document on backend<br>  const docId = `doc_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;<br>  await anchorDocument(docId, hash, blobCID, keyCID, userDID, file.name);</pre><pre>  console.log(&quot; Upload complete.&quot;);<br>  console.log(&quot;   The server stored: blobCID, keyCID, SHA-256 hash, filename&quot;);<br>  console.log(&quot;   The server did NOT see: file contents, AES key, or private key&quot;);<br>}</pre><pre># Pseudo-code (any language)<br>function uploadDocument(file, publicKey, userDID):<br>  fileBytes   = read(file)<br>  symKey      = AES_GCM.generate_key(256)<br>  iv, cipher  = AES_GCM.encrypt(symKey, fileBytes)<br>  hash        = SHA256(fileBytes)<br>  wrappedKey  = RSA_OAEP.encrypt(publicKey, export_raw(symKey))<br>  blobCID     = ipfs_upload(pack(iv, cipher))<br>  keyCID      = ipfs_upload(json({ wrappedKey: base64(wrappedKey) }))<br>  server_post(&quot;/api/documents&quot;, { blobCID, keyCID, hash, userDID, filename })</pre><h3>Part 5 — Sharing a Document (The Re-Wrap Flow)</h3><p>This is the most technically interesting part of the entire system. When User 1 shares a document with User 2, <strong>the server never sees the AES key in plaintext</strong>. The re-encryption is done entirely in User 1’s browser.</p><h3>The 6-Step Share Flow</h3><pre>① Fetch User 2&#39;s public key from the server&#39;s key registry<br>   (safe — public keys are meant to be shared)</pre><pre>② Fetch Wrapped Key (U1) from IPFS<br>   (encrypted with User 1&#39;s public key — safe to fetch over network)</pre><pre>③ [LOCAL] Decrypt Wrapped Key (U1) with User 1&#39;s PRIVATE KEY<br>   ↳ Recovers raw AES key bytes in browser memory<br>   ↳ Private key never leaves the browser. Raw AES key never hits the network.</pre><pre>④ [LOCAL] Re-encrypt raw AES key bytes with User 2&#39;s PUBLIC KEY<br>   ↳ Creates Wrapped Key (U2)<br>   ↳ Only User 2&#39;s private key can open this</pre><pre>⑤ Upload Wrapped Key (U2) to Pinata/IPFS<br>   ↳ Returns new CID</pre><pre>⑥ Update Access Control List on server<br>   ↳ Server links User 2&#39;s DID to the new key CID for this document</pre><h3>The Code</h3><pre>// JavaScript — full share flow<br>async function shareDocument(<br>  docId, senderPrivateKey, senderDID,<br>  recipientDID, existingWrappedKeyCID<br>) {<br>  // Step 1: Fetch recipient&#39;s public key from server registry<br>  const pkRes = await fetch(`/api/did/${encodeURIComponent(recipientDID)}/publickey`);<br>  if (!pkRes.ok) throw new Error(&quot;Recipient not found. Have they created their wallet?&quot;);</pre><pre>  const { publicKey: recipientJWK } = await pkRes.json();<br>  const recipientPublicKey = await crypto.subtle.importKey(<br>    &quot;jwk&quot;,<br>    recipientJWK,<br>    { name: &quot;RSA-OAEP&quot;, hash: &quot;SHA-256&quot; },<br>    false,        // non-extractable — we only use it for encrypt<br>    [&quot;encrypt&quot;]<br>  );</pre><pre>  // Step 2: Fetch Wrapped Key (U1) from IPFS<br>  const keyData = await fetch(<br>    `https://gateway.pinata.cloud/ipfs/${existingWrappedKeyCID}`<br>  ).then(r =&gt; r.json());<br>  <br>  const wrappedKeyU1 = Uint8Array.from(<br>    atob(keyData.wrappedKey), c =&gt; c.charCodeAt(0)<br>  ).buffer;</pre><pre>  // Step 3: LOCAL ONLY — Unwrap the AES key with sender&#39;s private key<br>  // The raw AES bytes live only in browser memory. Never sent anywhere.<br>  const rawAESKeyBytes = await crypto.subtle.decrypt(<br>    { name: &quot;RSA-OAEP&quot; },<br>    senderPrivateKey,   // stays on device<br>    wrappedKeyU1<br>  );<br>  // rawAESKeyBytes: 32 bytes in memory — the original AES-256 key</pre><pre>  // Step 4: LOCAL ONLY — Re-encrypt with recipient&#39;s public key<br>  const wrappedKeyU2 = await crypto.subtle.encrypt(<br>    { name: &quot;RSA-OAEP&quot; },<br>    recipientPublicKey,<br>    rawAESKeyBytes       // same 32 bytes, now encrypted for recipient<br>  );</pre><pre>  // Step 5: Upload new wrapped key to IPFS<br>  const newKeyCID = await uploadWrappedKey(wrappedKeyU2, recipientDID);</pre><pre>  // Step 6: Update ACL on server<br>  await fetch(&quot;/api/share&quot;, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({<br>      docId,<br>      recipientDid: recipientDID,<br>      wrappedKeyCid: newKeyCID,<br>      requesterDid: senderDID     // server verifies this is the document owner<br>    })<br>  });</pre><pre>  console.log(&quot; Access granted to&quot;, recipientDID);<br>  console.log(&quot;   Server stored: new key CID for recipient&quot;);<br>  console.log(&quot;   Server did NOT see: raw AES key or any private key&quot;);<br>}</pre><pre># Pseudo-code (any language)<br>function shareDocument(docId, senderPrivKey, senderDID, recipientDID, keyCID):<br>  recipPubKey  = fetch_from_server(&quot;/api/did/&quot; + recipientDID + &quot;/publickey&quot;)<br>  wrappedU1    = ipfs_fetch(keyCID).wrappedKey          # still encrypted<br>  rawAESBytes  = RSA_OAEP.decrypt(senderPrivKey, wrappedU1)  # LOCAL ONLY<br>  wrappedU2    = RSA_OAEP.encrypt(recipPubKey, rawAESBytes)  # LOCAL ONLY<br>  newCID       = ipfs_upload(json({ wrappedKey: base64(wrappedU2) }))<br>  server_post(&quot;/api/share&quot;, { docId, recipientDID, wrappedKeyCid: newCID, senderDID })</pre><blockquote><em>💡 </em><strong><em>Key insight:</em></strong><em> The </em><strong><em>encrypted file on IPFS is never touched during a share</em></strong><em>. Only a new wrapped key is created and uploaded. You can share a document with 100 users and the file is stored on IPFS exactly once. Each user gets their own personally-addressed wrapped copy of the AES key.</em></blockquote><h3>Part 6 — Decrypting &amp; Downloading a Document</h3><p>When a user opens a document, their browser fetches the encrypted blob and their wrapped key, decrypts everything locally, and triggers a download.</p><pre>// JavaScript — full decrypt flow<br>async function decryptAndDownload(blobCID, wrappedKeyCID, filename, userPrivateKey) {<br>  // 1. Fetch encrypted blob from IPFS<br>  const blobResponse = await fetch(`https://gateway.pinata.cloud/ipfs/${blobCID}`);<br>  const packedBuffer = await blobResponse.arrayBuffer();</pre><pre>  // Unpack: skip version byte (index 0), read 12-byte IV, read remaining ciphertext<br>  const packed   = new Uint8Array(packedBuffer);<br>  const iv       = packed.slice(1, 13);          // bytes 1–12<br>  const ciphertext = packed.slice(13).buffer;     // bytes 13 to end</pre><pre>  // 2. Fetch wrapped key from IPFS<br>  const keyData = await fetch(`https://gateway.pinata.cloud/ipfs/${wrappedKeyCID}`)<br>    .then(r =&gt; r.json());<br>  const wrappedKey = Uint8Array.from(<br>    atob(keyData.wrappedKey), c =&gt; c.charCodeAt(0)<br>  ).buffer;</pre><pre>  // 3. Unwrap AES key with user&#39;s RSA private key (LOCAL)<br>  const rawAESBytes = await crypto.subtle.decrypt(<br>    { name: &quot;RSA-OAEP&quot; },<br>    userPrivateKey,<br>    wrappedKey<br>  );</pre><pre>  // Import raw bytes as a usable AES-GCM CryptoKey<br>  const symmetricKey = await crypto.subtle.importKey(<br>    &quot;raw&quot;, rawAESBytes,<br>    { name: &quot;AES-GCM&quot; },<br>    false,                  // non-extractable after import<br>    [&quot;decrypt&quot;]<br>  );</pre><pre>  // 4. Decrypt the file<br>  const plaintextBuffer = await crypto.subtle.decrypt(<br>    { name: &quot;AES-GCM&quot;, iv },<br>    symmetricKey,<br>    ciphertext<br>  );<br>  // If this succeeds, the key was correct AND the ciphertext wasn&#39;t tampered with<br>  // (AES-GCM authentication tag is verified automatically)</pre><pre>  // 5. Trigger browser download<br>  const url = URL.createObjectURL(new Blob([plaintextBuffer]));<br>  const a   = document.createElement(&quot;a&quot;);<br>  a.href = url;<br>  a.download = filename;<br>  document.body.appendChild(a);<br>  a.click();<br>  document.body.removeChild(a);<br>  setTimeout(() =&gt; URL.revokeObjectURL(url), 1000);</pre><pre>  console.log(&quot; Decrypted and downloaded. Server saw zero plaintext.&quot;);<br>}</pre><pre># Pseudo-code (any language)<br>function decryptAndDownload(blobCID, keyCID, filename, privateKey):<br>  encryptedBlob = ipfs_fetch(blobCID)<br>  iv, ciphertext = unpack(encryptedBlob)       # skip version byte, split at byte 13</pre><pre>  wrappedKey    = ipfs_fetch(keyCID).wrappedKey<br>  rawAESBytes   = RSA_OAEP.decrypt(privateKey, base64_decode(wrappedKey))<br>  symmetricKey  = AES_GCM.import_key(rawAESBytes)</pre><pre>  plaintext     = AES_GCM.decrypt(symmetricKey, iv, ciphertext)<br>  save_to_disk(filename, plaintext)</pre><blockquote><strong><em>On SHA-256 integrity:</em></strong><em> After decryption, you can optionally verify the file by computing </em><em>SHA256(plaintext) and comparing it to the </em><em>hash field stored in the server&#39;s document registry during upload. If they match, the file is bit-for-bit identical to what was originally uploaded. Any IPFS-level tampering would also cause the AES-GCM auth tag check to fail first, so this is a secondary defense-in-depth measure.</em></blockquote><h3>Part 7 — Revoking Access</h3><p>When you revoke a user’s access, the server removes their entry from the document’s Access Control List.</p><pre>// JavaScript<br>async function revokeAccess(docId, recipientDID, ownerDID) {<br>  const response = await fetch(&quot;/api/share&quot;, {<br>    method: &quot;DELETE&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({<br>      docId,<br>      recipientDid: recipientDID,<br>      requesterDid: ownerDID      // server verifies this matches the document owner<br>    })<br>  });</pre><pre>  const result = await response.json();<br>  if (result.success) {<br>    console.log(`Access revoked for ${recipientDID}`);<br>  }<br>}</pre><pre># Pseudo-code<br>function revokeAccess(docId, recipientDID, ownerDID):<br>  server_delete(&quot;/api/share&quot;, { docId, recipientDID, ownerDID })</pre><h3>What Revocation Does and Doesn’t Do</h3><p><strong>What it does:</strong></p><ul><li>Removes the recipient’s DID from the server’s ACL for this document</li><li>The GET /api/documents/:did endpoint no longer returns the document for the revoked user</li><li>Their wrapped key CID pointer is deleted from the server’s records</li><li>Future attempts to list or access the document via the API will fail with 403</li></ul><p><strong>What it doesn’t do:</strong></p><ul><li>IPFS content is <strong>immutable </strong>the wrapped key file (U2) that was previously uploaded to IPFS is not deleted. It’s addressed by content hash and pinned globally.</li><li>If the recipient already fetched and locally cached the wrapped key CID <em>before revocation</em>, they technically still have the bytes to decrypt the document.</li></ul><blockquote><strong><em>For strong cryptographic revocation:</em></strong><em> Re-encrypt the document with a </em><strong><em>brand new AES key</em></strong><em> after revocation. Then re-wrap the new key for every remaining authorized user and update all the CIDs. This is computationally more expensive but makes the old wrapped keys useless. For most real-world applications documents, file sharing, medical records ACL-level revocation is standard and sufficient.</em></blockquote><h3>Part 8 — The Backend API (Key Routes)</h3><p>The server handles authentication, key registry, document metadata, and ACL management. Here are the routes you need to implement:</p><h3>POST /api/auth/register</h3><pre>Request:<br>{<br>  &quot;email&quot;: &quot;alice@example.com&quot;,<br>  &quot;password&quot;: &quot;supersecret123&quot;,        ← hashed with bcrypt(12) server-side<br>  &quot;did&quot;: &quot;did:local:8912c294b807...&quot;,<br>  &quot;publicKey&quot;: { &quot;kty&quot;: &quot;RSA&quot;, &quot;alg&quot;: &quot;RSA-OAEP-256&quot;, &quot;n&quot;: &quot;...&quot;, &quot;e&quot;: &quot;AQAB&quot; },<br>  &quot;encryptedWallet&quot;: { &quot;version&quot;: 1, &quot;salt&quot;: &quot;...&quot;, &quot;iv&quot;: &quot;...&quot;, &quot;ciphertext&quot;: &quot;...&quot; }<br>}</pre><pre>Response 201:<br>{ &quot;token&quot;: &quot;eyJhbGci...&quot;, &quot;user&quot;: { &quot;id&quot;: &quot;user_1&quot;, &quot;email&quot;: &quot;alice@...&quot;, &quot;did&quot;: &quot;...&quot; } }</pre><h3>POST /api/auth/login</h3><pre>Request:<br>{ &quot;email&quot;: &quot;alice@example.com&quot;, &quot;password&quot;: &quot;supersecret123&quot; }</pre><pre>Response 200:<br>{<br>  &quot;token&quot;: &quot;eyJhbGci...&quot;,<br>  &quot;user&quot;: { &quot;id&quot;: &quot;user_1&quot;, ... },<br>  &quot;encryptedWallet&quot;: { &quot;version&quot;: 1, &quot;salt&quot;: &quot;...&quot;, &quot;iv&quot;: &quot;...&quot;, &quot;ciphertext&quot;: &quot;...&quot; },<br>  &quot;publicKey&quot;: { &quot;kty&quot;: &quot;RSA&quot;, ... }<br>}<br>← Server returns encryptedWallet so the browser can decrypt it locally<br>← The plaintext private key is NEVER in this response</pre><h3>POST /api/documents</h3><pre>Request:<br>{<br>  &quot;docId&quot;: &quot;doc_1779097856281_287z&quot;,<br>  &quot;hash&quot;: &quot;6a1e70b95c82514041db571...&quot;,<br>  &quot;encryptedBlobCid&quot;: &quot;bafybeifgc2voidpz2...&quot;,<br>  &quot;wrappedKeyCid&quot;: &quot;bafkreidjmhvyxz5ck...&quot;,<br>  &quot;ownerDid&quot;: &quot;did:local:8912c294...&quot;,<br>  &quot;filename&quot;: &quot;my_will.pdf&quot;<br>}<br>Response 200: { &quot;success&quot;: true, &quot;docId&quot;: &quot;doc_1779097856281_287z&quot; }</pre><h3>GET /api/documents/:did</h3><p>Returns all documents the given DID has access to (either as owner or shared recipient).</p><pre>Response 200:<br>{<br>  &quot;documents&quot;: [<br>    {<br>      &quot;docId&quot;: &quot;doc_1779...&quot;,<br>      &quot;filename&quot;: &quot;my_will.pdf&quot;,<br>      &quot;hash&quot;: &quot;6a1e70b9...&quot;,<br>      &quot;encryptedBlobCid&quot;: &quot;bafybeifgc2...&quot;,<br>      &quot;wrappedKeyCid&quot;: &quot;bafkreidjm...&quot;,   ← the wrapped key for THIS DID<br>      &quot;isOwner&quot;: true<br>    }<br>  ]<br>}</pre><h3>POST /api/share</h3><pre>Request:<br>{<br>  &quot;docId&quot;: &quot;doc_1779...&quot;,<br>  &quot;recipientDid&quot;: &quot;did:local:0ef56523...&quot;,<br>  &quot;wrappedKeyCid&quot;: &quot;bafkreic22hrkc6vy...&quot;,   ← CID of the new Wrapped Key (U2)<br>  &quot;requesterDid&quot;: &quot;did:local:8912c294...&quot;     ← must be document owner<br>}<br>Response 200: { &quot;success&quot;: true }</pre><h3>DELETE /api/share</h3><pre>Request:<br>{<br>  &quot;docId&quot;: &quot;doc_1779...&quot;,<br>  &quot;recipientDid&quot;: &quot;did:local:0ef56523...&quot;,<br>  &quot;requesterDid&quot;: &quot;did:local:8912c294...&quot;<br>}<br>Response 200: { &quot;success&quot;: true }</pre><h3>Part 9 — The Zero-Knowledge Proof: Live Demo</h3><p>The best way to prove the system works is to try to break it. Here’s what happens when someone tries to decrypt a document without authorization:</p><pre>// JavaScript — attempting to decrypt without the correct wrapped key<br>async function demonstrateZeroKnowledge(blobCID) {<br>  // Step 1: Fetch the encrypted blob from IPFS (always works — IPFS is public)<br>  const response     = await fetch(`https://gateway.pinata.cloud/ipfs/${blobCID}`);<br>  const packedBuffer = await response.arrayBuffer();<br>  const packed       = new Uint8Array(packedBuffer);<br>  const iv           = packed.slice(1, 13);<br>  const ciphertext   = packed.slice(13).buffer;</pre><pre>  // Step 2: Try to decrypt with a completely wrong AES key<br>  const wrongKey = await crypto.subtle.generateKey(<br>    { name: &quot;AES-GCM&quot;, length: 256 }, false, [&quot;decrypt&quot;]<br>  );</pre><pre>  try {<br>    await crypto.subtle.decrypt({ name: &quot;AES-GCM&quot;, iv }, wrongKey, ciphertext);<br>    console.error(&quot;This should NEVER happen — something is wrong&quot;);<br>  } catch (err) {<br>    // AES-GCM verifies an authentication tag on decrypt.<br>    // A wrong key produces the wrong tag → hard cryptographic failure.<br>    console.log(&quot;✅ Decryption FAILED as expected&quot;);<br>    console.log(&quot;   Error:&quot;, err.name, &quot;—&quot;, err.message);<br>    // Output: OperationError — The operation failed for an operation-specific reason<br>    console.log(&quot;   Without the correct wrapped key from the ACL,&quot;);<br>    console.log(&quot;   decryption is mathematically impossible.&quot;);<br>    console.log(&quot;   Not hard. Not unlikely. Impossible.&quot;);<br>  }<br>}</pre><p><strong>The result:</strong> OperationError — The operation failed for an operation-specific reason</p><p>AES-GCM appends a <strong>16-byte authentication tag</strong> to every ciphertext. Any decryption attempt with the wrong key produces the wrong tag — and the Web Crypto API throws immediately. You don’t get garbled output. You don’t get partial data. You get nothing.</p><p>This is the zero-knowledge guarantee in action. An attacker with full read access to the server database and full read access to IPFS has exactly the same problem as a random person on the internet: they can fetch the encrypted blobs, but without the correct wrapped key and a private key to unwrap it, the data is permanently inaccessible.</p><h3>Part 10 — Implementing This in Other Languages</h3><p>Every crypto primitive used here is available in all major languages. The concepts are identical only the syntax differs.</p><h3>Python Example (Key Wrapping)</h3><pre>from cryptography.hazmat.primitives.asymmetric import rsa, padding<br>from cryptography.hazmat.primitives import hashes<br>from cryptography.hazmat.primitives.ciphers.aead import AESGCM<br>import os, base64</pre><pre># Generate RSA key pair<br>private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)<br>public_key  = private_key.public_key()</pre><pre># Generate AES-256 key<br>aes_key = os.urandom(32)</pre><pre># Encrypt file with AES-GCM<br>iv          = os.urandom(12)<br>aesgcm      = AESGCM(aes_key)<br>ciphertext  = aesgcm.encrypt(iv, file_bytes, None)</pre><pre># Wrap AES key with RSA public key<br>wrapped_key = public_key.encrypt(<br>  aes_key,<br>  padding.OAEP(<br>    mgf=padding.MGF1(algorithm=hashes.SHA256()),<br>    algorithm=hashes.SHA256(),<br>    label=None<br>  )<br>)</pre><pre># Unwrap (decrypt) with private key<br>recovered_key = private_key.decrypt(<br>  wrapped_key,<br>  padding.OAEP(<br>    mgf=padding.MGF1(algorithm=hashes.SHA256()),<br>    algorithm=hashes.SHA256(),<br>    label=None<br>  )<br>)<br># recovered_key == aes_key ✓</pre><p>The architecture is the same. Upload the encrypted blob and base64(wrapped_key) to Pinata, anchor the CIDs on the server.</p><h3>Part 11 — Security Quick Tips</h3><p>🔐 <strong>Never log or persist the private key in plaintext.</strong> Keep it in memory only. Wipe it on logout by overwriting the variable and triggering garbage collection.</p><p>🔐 <strong>Always generate a fresh IV per encryption.</strong> crypto.getRandomValues(new Uint8Array(12)) every single time. Reusing an IV with the same AES key breaks GCM confidentiality catastrophically.</p><p>🔐 <strong>Scope your Pinata JWT to </strong><strong>pinFileToIPFS only.</strong> If leaked, an attacker can pin new files but cannot delete, query, or manage your existing pins.</p><p>🔐 <strong>Serve the app over HTTPS.</strong> Client-side crypto only protects data in transit on IPFS and the server. A MITM attacker who can inject JavaScript into your app page can steal the private key before it’s used. HTTPS prevents this.</p><p>🔐 <strong>Use environment variables for </strong><strong>JWT_SECRET.</strong> Never hardcode it. A leaked JWT secret means token forgery. Generate with openssl rand -hex 64.</p><p>🔐 <strong>sessionStorage, not localStorage, for the session wallet.</strong> sessionStorage is cleared when the tab closes. localStorage persists indefinitely across sessions and is a much larger attack surface. The private key session copy should be tab-scoped.</p><p>🔐 <strong>Treat the DID registry as a trust anchor.</strong> In this implementation, the server hosts the public key registry. A compromised server could serve a malicious public key to a sharer, causing them to wrap a key for an attacker’s key rather than the intended recipient. For production, anchor public keys on an immutable ledger (blockchain, Hyperledger, or a transparency log).</p><h3>What’s Next</h3><p>This implementation is production-grade for a wide range of use cases. If you want to push it further: <strong>key rotation</strong> (re-wrap all document keys when a user regenerates their RSA pair), <strong>WebAuthn binding</strong> (tie private key decryption to a hardware security key, TouchID, or FaceID so even sessionStorage compromise can’t expose the key), and <strong>recovery mnemonics</strong> (give users a 12-word BIP39 phrase at registration currently, a forgotten password permanently loses the private key and all documents with it).</p><p>The full source code for this reference implementation is available on GitHub. If you build something with it, I’d love to hear about it.<br><br>Github Link : <a href="https://github.com/muhammadtalha198/ZeroKnowladge_Document_Upload">https://github.com/muhammadtalha198/ZeroKnowladge_Document_Upload</a></p><h3>Conclusion</h3><p>Here’s what you’ve built:</p><ul><li>Files encrypted <strong>before</strong> they leave the browser with AES-256-GCM</li><li>AES keys wrapped with <strong>RSA-2048-OAEP</strong> and stored on IPFS</li><li>Document sharing via <strong>client-side key re-wrapping</strong> — the server is blind throughout</li><li>Access revocation enforced at <strong>ACL level</strong></li><li>An attacker with full server + IPFS access gets <strong>mathematically nothing useful</strong></li></ul><p>The cryptographic primitives RSA-OAEP and AES-GCM are available in every modern language and runtime. The pseudo-code in this guide maps directly to Python’s cryptography library, Go&#39;s crypto/rsa and crypto/cipher packages, Rust&#39;s rsa and aes-gcm crates, and Java&#39;s javax.crypto.</p><p>The architecture is the idea. The language is just syntax.</p><p><em>Tagged: #cryptography #javascript #ipfs #security #zero-knowledge #encryption #fullstack #webdev</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97b5fe7d8a4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/build-a-zero-knowledge-encrypted-document-vault-complete-developer-guide-97b5fe7d8a4e">Build a Zero-Knowledge Encrypted Document Vault: Complete Developer Guide</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Math Behind Every Blockchain Transaction: A Deep Dive into Cryptographic Signatures]]></title>
            <link>https://medium.com/@muhammadtalha1/the-math-behind-every-blockchain-transaction-a-deep-dive-into-cryptographic-signatures-1044b1133849?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/1044b1133849</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[ecdsa]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 08:57:48 GMT</pubDate>
            <atom:updated>2026-06-03T08:57:48.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3dKp-Rcfv8KS-WW7mvOvg.png" /></figure><p><em>How a wax seal, a one-way street, and some brilliant mathematics keep your crypto safe</em></p><p>You’ve heard the word “crypto” thrown around endlessly crypto markets, crypto wallets, crypto winter. But buried inside that word is something far more foundational: <strong>cryptography</strong>. Not the price charts. Not the speculation. The actual mathematics that makes digital ownership possible.</p><p>This is that story.</p><h3>Why Should You Care?</h3><p>Every time you approve a transaction in MetaMask, every time you interact with a smart contract, every time your ETH moves from one wallet to another a specific sequence of cryptographic operations runs invisibly in the background. These operations answer two critical questions that the blockchain must know with absolute certainty:</p><ol><li>Did this person actually authorize this transaction?</li><li>Has anything been changed since they authorized it?</li></ol><p>Get either of those wrong and the entire system collapses. Billions of dollars of value depend on these two questions having reliable answers. The mechanism that answers them is called <strong>ECDSA</strong> the Elliptic Curve Digital Signature Algorithm and it’s worth understanding.</p><h3>Start With a Letter</h3><p>Before we get into elliptic curves and hexadecimal strings, let’s use an analogy that works surprisingly well.</p><p>Imagine you want to send an important letter to a friend. You write your message, sign it at the bottom with your signature, and seal the envelope with a wax stamp a unique stamp that only you possess. When your friend receives it, they can verify two things instantly: the seal is intact (so no one tampered with the message), and the stamp is yours (so you genuinely sent it).</p><p>That’s exactly what a cryptographic signature does just with math instead of wax.</p><h3>Your Blockchain Identity: Three Layers</h3><p>When you set up an Ethereum wallet, three pieces of data are generated for each account. They form a hierarchy, and understanding this hierarchy is the key to understanding everything else.</p><h3>Layer 1: The Private Key</h3><p>Your private key is the wax stamp from our analogy. It’s a string of 64 hexadecimal characters something like 0x3a7f9c... and it is the master password to your account. With it, you can authorize transactions, move funds, and interact with smart contracts.</p><p>The rule is absolute: <strong>never share your private key with anyone, ever.</strong> If someone has your private key, they have complete control of your account. Not partial control. Complete control. There is no “forgot password” on the blockchain. There is no customer support to call.</p><h3>Layer 2: The Public Key</h3><p>Here’s where the magic begins. Your public key is mathematically derived from your private key using something called scalar multiplication on an elliptic curve the “EC” in ECDSA. The result is a much longer string of characters (128 hex chars, prefixed with “04”).</p><p>You can share this with anyone. Post it publicly. Put it in your email signature if you want. No one can use your public key to steal your funds or steal your private key. This is because the mathematical operation that produces it only runs in one direction.</p><p>Think of it like this: if I gave you the number 55,753, it&#39;s nearly impossible to figure out that it was produced by multiplying 127 × 439. The elliptic curve math is this same principle — but cranked up to the level where it becomes mathematically <em>impossible</em> to reverse, not just difficult.</p><p>Private key → Public key: easy. Public key → Private key: mathematically impossible.</p><p>This one-way relationship is the entire foundation of blockchain security.</p><h3>Layer 3: Your Ethereum Address</h3><p>Your wallet address the 0x742d... string you share when someone wants to send you ETH is actually just a compressed version of your public key. Specifically, it&#39;s derived by running your public key through the Keccak-256 hash function and taking the last 20 bytes (40 hexadecimal characters), then adding a 0x prefix.</p><p>So the derivation chain looks like this:</p><p><strong>Private Key → (elliptic curve multiplication) → Public Key → (Keccak-256 hash + truncation) → Ethereum Address</strong></p><p>Each arrow is one-way. You can go forward, never backward.</p><h3>The Seed Phrase: One Key to Rule Them All</h3><p>Before private keys, there’s one more piece to understand: your <strong>seed phrase</strong> (also called a mnemonic phrase).</p><p>Your seed phrase is 12 or 24 seemingly random words. It might look like: <em>“either today family jar noble window carpet mirror flame bridge crypt sigma”</em></p><p>These words act as the root from which all your private keys are mathematically grown. Each account in your wallet (Account 0, Account 1, Account 2…) is generated by combining your seed phrase with the account index number. The same seed phrase always produces the same private keys, on any device, anywhere in the world. This is what lets you “restore” a wallet on a new phone.</p><p>The implication is significant: <strong>if someone has your seed phrase, they have access to every account you’ve ever created with that wallet.</strong> Not just one all of them. A stolen private key is bad. A stolen seed phrase is catastrophic.</p><p>Never type your seed phrase into a website. Never photograph it. Never put it in a cloud note or a text message. Write it on paper and store it somewhere safe.</p><h3>How Signing Actually Works</h3><p>So when you click “Confirm” in MetaMask, what actually happens?</p><p>Your wallet takes the transaction details the recipient address, the amount, the nonce, the gas settings and treats them as a message. It then uses your private key to run the ECDSA algorithm against this message, producing a <strong>digital signature</strong>: another hexadecimal string, unique to the combination of this exact message and your private key.</p><p>This signature gets broadcast to the network alongside the transaction.</p><p>The network then does something elegant: it uses your <strong>public address</strong> (not your private key that stays secret forever) to mathematically verify that this signature could only have been produced by whoever holds the private key associated with that address. If the verification passes, the transaction is legitimate. If it fails because someone tampered with the transaction details, or because the signature was forged the transaction is rejected.</p><p>You proved you own the account without ever revealing the secret that proves it. This is the genius of asymmetric cryptography.</p><h3>The Tamper-Proof Guarantee</h3><p>Here’s a test that illustrates just how robust this system is.</p><p>Take a signed message: <em>“Please send 1 ETH to Alice.”</em> The signature for this message is a unique cryptographic fingerprint. Now change even a single character <em>“Please send 1 ETH to alice.”</em> (just changing the capital A to lowercase). Run the verification again.</p><p>It fails. Completely. The signature no longer matches.</p><p>This means that once you sign something, the blockchain knows immediately if anyone altered it in transit. The signature is bound not just to your identity but to the exact content of the message. Even a one-character change creates an entirely different fingerprint.</p><p>No one can intercept your transaction and change the recipient address. No one can increase the amount. No one can claim it was actually someone else who signed it. The mathematics makes all of that impossible.</p><h3>Validators Use the Same Math</h3><p>Here’s something that often surprises people: these same signatures aren’t just for your personal transactions.</p><p>On Ethereum (which uses Proof of Stake), the validators who confirm blocks also use ECDSA signatures. When a validator attests that a block of transactions is valid, they sign it with their own private key. Other validators can verify that signature using the validator’s public key. The very same cryptographic principles that protect your $50 swap on Uniswap also protect the entire $400 billion ecosystem.</p><p>Same math. Same algorithm. Applied at every level of the stack.</p><h3>The Golden Rules</h3><p>Understanding the theory is valuable. Practicing good security habits is essential. Here’s what every crypto user should have tattooed somewhere:</p><p><strong>Protect these with your life:</strong></p><ul><li>Your seed phrase</li><li>Your private keys</li></ul><p><strong>Share these freely:</strong></p><ul><li>Your public key</li><li>Your Ethereum address</li></ul><p>Concretely, that means: never type your seed phrase or private key into any website. Never store them in plain text. Never put them in a cloud service, an email, a WhatsApp message, or a screenshot. Hardware wallets exist precisely because the safest private key is one that never touches the internet at all.</p><h3>Why This Matters Beyond Crypto</h3><p>The cryptographic principles described here aren’t unique to blockchain. TLS (the “S” in HTTPS) uses related techniques. Your encrypted messages use them. Digital certificates use them. Every time you submit a form on a secure website, some version of this math is running in the background.</p><p>Blockchain made public-key cryptography newly visible because for the first time it tied those mathematical identities directly to real money. But the underlying science is decades old and battle-tested. That’s actually a good thing. We’re not trusting our value to an experimental idea we’re trusting it to mathematics that has been pressure-tested by every major institution on the internet.</p><h3>Want to See This in Action?</h3><p>Reading about elliptic curves and hash functions is one thing watching them work with your own inputs is another. If you want to truly internalize how all of this fits together, try running through the steps yourself:</p><p>Try the Interactive ECDSA Demo<br>Link: <a href="https://cryptography-app.lovable.app/">https://cryptography-app.lovable.app</a></p><p>Here’s what you can do step by step:</p><ol><li>Generate a seed phrase : See how 12 random words become the root of everything</li><li>Derive multiple private keys : Watch how Account 0, Account 1, and Account 2 are mathematically grown from the same seed</li><li>Generate public keys : Observe the one-way transformation from private to public using elliptic curve multiplication</li><li>Create an Ethereum address : See the Keccak-256 hash and truncation happen in real time</li><li>Sign a message : Type any message, sign it with your private key, and get a real cryptographic signature</li><li>Verify the signature : Change a single character in the message and watch verification fail instantly. Then restore the original and watch it pass.</li></ol><p>Pro tip: Try the tamper test yourself. Sign a message like “Send 1 ETH to Alice,” then change it to “Send 1 ETH to alice” and attempt to verify. The signature will fail and you’ll understand <em>why</em> the blockchain rejects modified transactions.</p><p>Theory makes you informed. Doing it yourself makes you confident.</p><h3>A Closing Thought</h3><p>There’s something philosophically interesting about the fact that possession of a string of characters can constitute ownership of significant value. The blockchain doesn’t know who you are. It doesn’t know your name, your country, your age. It only knows whether the signature on a transaction can be verified by the public key associated with an address. If the math checks out, the transaction is yours to make.</p><p>That’s both the promise and the responsibility of self-custody. The math is unforgiving. It doesn’t distinguish between you and an attacker who stole your private key. Which is why understanding what that key is and what it means to protect it isn’t just academic. It’s practical.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1044b1133849" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker in 2026: From Zero to Production-Ready Containers]]></title>
            <link>https://medium.com/coinmonks/docker-in-2026-from-zero-to-production-ready-containers-63a485daaed5?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a485daaed5</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Thu, 21 May 2026 12:07:34 GMT</pubDate>
            <atom:updated>2026-05-21T14:17:20.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Za5K82pan2fMbqNuU1IXA.png" /></figure><p><strong>A complete, no-fluff guide to containers, images, Dockerfiles, Compose, volumes, and networking with real Go + Gin + PostgreSQL examples.</strong></p><blockquote><strong><em>Reading time:</em></strong><em> ~22 minutes </em><strong><em>Level:</em></strong><em> Developer who knows Go, new to Docker </em><strong><em>Stack used:</em></strong><em> Go (Gin framework) + PostgreSQL + pgAdmin</em></blockquote><h3>Table of contents</h3><ol><li>Why Docker exists the problem it solves</li><li>Images vs containers the distinction that matters</li><li>Docker commands cheatsheet</li><li>Writing your first Dockerfile</li><li>Docker Compose managing multiple containers</li><li>Volumes and data persistence</li><li>Docker networking</li><li>Putting it all together your complete project</li></ol><h3>1. Why Docker exists the problem it solves</h3><p>Every Go developer has lived this moment: you write an API on your MacBook, it compiles and runs perfectly, you push to GitHub, and your teammate pulls it on their Linux workstation. go run main.go panics.</p><p>The database connection string that worked on your machine fails on theirs. The libc version is different. The environment variable you set in your .zshrc six months ago and forgot about it&#39;s not on their machine. The exact libpq version your PostgreSQL driver expects? Wrong.</p><p>Here is why this happens. When you build a Go application, it silently accumulates a set of environmental dependencies:</p><ul><li>A specific version of the Go toolchain (1.21, not 1.20, and definitely not 1.19)</li><li>The gcc compiler for CGO-dependent packages</li><li>System CA certificates for HTTPS calls to external APIs</li><li>Environment variables configured only in your local shell profile</li><li>The exact libpq version your PostgreSQL driver expects</li></ul><p>None of these are in your go.mod. They live invisibly on your machine.</p><p><strong>Docker solves this by packaging your application together with its entire environment into a single portable unit called a container.</strong></p><p>Instead of saying “here is my code, good luck running it”, you now ship: <em>code + Go runtime + system libraries + configuration</em>, all bundled. Wherever that bundle runs your laptop, your teammate’s Windows machine, a CI/CD pipeline, a production server on AWS the behavior is identical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFWg095tKEXQGXgW_wWQVQ.png" /></figure><p>This is especially valuable in teams where onboarding a new developer used to mean half a day of “install Go, configure PostgreSQL, set environment variables, hope glibc versions match.&quot; With Docker, it becomes: docker compose up. Done.</p><h3>2. Images vs containers — the distinction that matters</h3><p>This is where most beginners get confused. Docker has two core entities and understanding their relationship is the foundation of everything else.</p><h3>Docker image</h3><p>A Docker image is a <strong>read-only, static snapshot</strong> of what an environment should look like. It is not a running process. Think of it exactly like a struct definition in Go it holds the blueprint but does not allocate any runtime resources by itself.</p><p>Images are built from a file called a Dockerfile (covered in section 4). Once built, an image can be shared, versioned with tags, and stored in a registry like Docker Hub.</p><h3>Docker container</h3><p>A container is a <strong>running instance created from an image</strong>. Just as you instantiate a struct in Go, you instantiate containers from images. A single image can produce many containers simultaneously, each isolated from the others.</p><pre>Image  ──────────►  Container 1 (running)<br>       ──────────►  Container 2 (running)<br>       ──────────►  Container 3 (stopped)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N006ZcTOhk3pSB-2odZwOA.png" /></figure><h3>Key differences at a glance</h3><p>Property Image Container State Static, read-only Dynamic, has runtime state Resources No CPU/RAM consumed Consumes CPU and RAM Mutability Immutable after build Writable layer on top of image Sharing Pushed/pulled from registries Not directly shareable Go analogy struct type definition struct instance in memory</p><h3>Image layers</h3><p>Every image is composed of stacked, immutable layers. When Docker builds an image, each instruction in the Dockerfile creates a new layer. This layered architecture has a critical performance benefit: <strong>layers are cached and shared</strong>.</p><p>If you have two images both based on golang:1.21-alpine, Docker only stores that base layer once on your machine. When you pull the second image, it reuses the cached layer instead of downloading it again. This is why pulling a second Go-based image shows &quot;Already exists&quot; for several layers — those layers are shared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*DpVuOXyAMIhEmN0SgsfUxQ.png" /></figure><h3>3. Docker commands cheatsheet</h3><p>Before writing any Dockerfiles, you need to be fluent in the core CLI. Here is a complete reference with explanations for every command.</p><h3>Working with images</h3><pre># Pull an image from Docker Hub<br>docker pull golang:1.21-alpine</pre><p>docker pull fetches an image from a registry to your local machine. The format is image_name:tag. If you omit the tag, Docker defaults to latest which can be unpredictable. Always specify a version tag for reproducibility.</p><pre># List all locally available images<br>docker images</pre><p>Shows every image on your machine repository name, tag, image ID, creation date, and size. Watch the SIZE column: a Go binary built with multi-stage builds (section 4) drops from ~350 MB to ~25 MB.</p><pre># Remove an image<br>docker rmi golang:1.21-alpine</pre><p>Deletes an image. Will fail if a container (even a stopped one) is still using it remove the container first.</p><pre># Remove all dangling (untagged) images<br>docker image prune</pre><p>Cleans up &lt;none&gt;:&lt;none&gt; images left behind from failed or replaced builds. Run this periodically to reclaim disk space.</p><h3>Working with containers</h3><pre># Create and start a container from an image<br>docker run golang:1.21-alpine</pre><p>The most fundamental command. It pulls the image if not available locally, creates a container, and runs the default command. For golang:1.21-alpine, that default is go version the container prints it and exits immediately.</p><pre># Run a container in detached (background) mode<br>docker run -d golang:1.21-alpine sleep 3600</pre><p>The -d flag detaches the container so it runs in the background. The sleep 3600 keeps it alive for an hour so you can inspect it.</p><pre># Run a container interactively with a shell<br>docker run -it golang:1.21-alpine sh</pre><p>-i keeps stdin open; -t allocates a pseudo-TTY. Together, -it gives you an interactive shell inside the container. Inside, try go version and cat /etc/os-release to see the isolated environment.</p><pre># Run with port binding<br>docker run -d -p 8080:8080 my-gin-app</pre><p>-p host_port:container_port maps a port on your machine to a port inside the container. Without this, your Gin app running on port 8080 inside the container would be completely unreachable from your browser or curl.</p><pre># Run with an environment variable<br>docker run -d \<br>  -e DATABASE_URL=&quot;host=localhost user=admin password=secret dbname=appdb port=5432 sslmode=disable&quot; \<br>  my-gin-app</pre><p>-e sets an environment variable inside the container at runtime. Go applications read these with os.Getenv(). This is how you inject secrets and configuration without hardcoding them into the image.</p><pre># Give the container a human-readable name<br>docker run -d --name gin-api my-gin-app</pre><p>By default, Docker assigns a random name like peaceful_darwin. Using --name makes subsequent commands much easier.</p><pre># List running containers<br>docker ps</pre><pre># List ALL containers (including stopped)<br>docker ps -a</pre><pre># Stop a running container (graceful SIGTERM, then SIGKILL after 10s)<br>docker stop gin-api</pre><pre># Start a stopped container<br>docker start gin-api</pre><pre># Remove a stopped container<br>docker rm gin-api</pre><pre># Force-remove a running container<br>docker rm -f gin-api</pre><h3>Inspecting and debugging</h3><pre># View logs of a container<br>docker logs gin-api</pre><pre># Follow logs in real time<br>docker logs -f gin-api</pre><p>docker logs is your first stop when a container misbehaves. It captures everything the process wrote to stdout and stderr. For Gin, this includes HTTP request logs and panic stack traces.</p><pre># Execute a command inside a running container<br>docker exec -it gin-api sh</pre><p>docker exec runs an additional command inside an <strong>already running</strong> container you are not creating a new container, you are attaching to an existing one. Try env to see all environment variables, or cat /etc/resolv.conf to see DNS configuration.</p><pre># Inspect detailed container metadata<br>docker inspect gin-api | jq &#39;.[0].NetworkSettings&#39;</pre><p>Returns a JSON payload covering network settings, volume mounts, environment variables, resource limits. Pipe through jq for readable output.</p><pre># Display real-time resource usage (CPU, memory, network I/O)<br>docker stats</pre><h3>Managing networks and volumes</h3><pre># List all Docker networks<br>docker network ls</pre><pre># Create a custom network<br>docker network create app-network</pre><pre># Remove a network<br>docker network rm app-network</pre><pre># List all volumes<br>docker volume ls</pre><pre># Create a named volume<br>docker volume create pg-data</pre><pre># Remove unused volumes<br>docker volume prune</pre><h3>4. Writing your first Dockerfile</h3><p>A Dockerfile is a plain text file containing instructions that Docker executes top-to-bottom to build your image. Each instruction creates a new layer.</p><h3>The application we are dockerizing</h3><p>A minimal Gin REST API that stores and retrieves users from PostgreSQL.</p><p><strong>main.go</strong></p><pre>package main</pre><pre>import (<br>    &quot;net/http&quot;<br>    &quot;os&quot;<br>    &quot;time&quot;</pre><pre>    &quot;github.com/gin-gonic/gin&quot;<br>    &quot;gorm.io/driver/postgres&quot;<br>    &quot;gorm.io/gorm&quot;<br>)</pre><pre>type User struct {<br>    ID        uint      `json:&quot;id&quot; gorm:&quot;primaryKey&quot;`<br>    Name      string    `json:&quot;name&quot;`<br>    Email     string    `json:&quot;email&quot;`<br>    CreatedAt time.Time `json:&quot;created_at&quot;`<br>}</pre><pre>var DB *gorm.DB</pre><pre>func initDB() {<br>    dsn := os.Getenv(&quot;DATABASE_URL&quot;)<br>    if dsn == &quot;&quot; {<br>        dsn = &quot;host=localhost user=admin password=secret dbname=appdb port=5432 sslmode=disable&quot;<br>    }<br>    var err error<br>    DB, err = gorm.Open(postgres.Open(dsn), &amp;gorm.Config{})<br>    if err != nil {<br>        panic(&quot;failed to connect database: &quot; + err.Error())<br>    }<br>    DB.AutoMigrate(&amp;User{})<br>}</pre><pre>func main() {<br>    initDB()<br>    r := gin.Default()</pre><pre>    r.GET(&quot;/users&quot;, func(c *gin.Context) {<br>        var users []User<br>        DB.Find(&amp;users)<br>        c.JSON(http.StatusOK, users)<br>    })</pre><pre>    r.POST(&quot;/users&quot;, func(c *gin.Context) {<br>        var user User<br>        if err := c.ShouldBindJSON(&amp;user); err != nil {<br>            c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>            return<br>        }<br>        DB.Create(&amp;user)<br>        c.JSON(http.StatusCreated, user)<br>    })</pre><pre>    r.Run(&quot;:8080&quot;)<br>}</pre><p><strong>go.mod</strong></p><pre>module gin-docker-demo</pre><pre>go 1.21</pre><pre>require (<br>    github.com/gin-gonic/gin v1.9.1<br>    gorm.io/driver/postgres v1.5.4<br>    gorm.io/gorm v1.25.5<br>)</pre><h3>The Dockerfile — with multi-stage builds</h3><p>Multi-stage builds are the most important Go-specific Docker technique. The core idea: use one stage to <em>compile</em> the binary (needs the full Go toolchain), and a second stage to <em>run</em> it (needs almost nothing). The final image only ships the compiled binary.</p><pre># ── Stage 1: Build stage ──────────────────────────────────────────────<br>FROM golang:1.21-alpine AS builder</pre><p>FROM ... AS builder names this stage. golang:1.21-alpine is the official Go 1.21 image based on Alpine Linux (~350 MB). The AS builder alias lets us reference this stage&#39;s filesystem in stage 2.</p><pre># Install build dependencies<br>RUN apk add --no-cache git ca-certificates</pre><p>Alpine uses apk as its package manager. --no-cache prevents storing the package index in the layer. git is needed for fetching some Go modules; ca-certificates enables HTTPS validation during go mod download.</p><pre>WORKDIR /app</pre><p>Sets the working directory for all subsequent instructions. Think of it as cd /app if the directory doesn&#39;t exist, Docker creates it.</p><pre># Copy dependency files first — critical for layer caching<br>COPY go.mod go.sum ./</pre><p>We copy go.mod and go.sum <em>before</em> the source code. This is deliberate. Docker caches each layer if go.mod hasn&#39;t changed, the next go mod download step will be served entirely from cache, saving 30-60 seconds on every build.</p><pre>RUN go mod download</pre><p>Downloads all modules into the local module cache. Because this layer is cached, subsequent builds where only .go files changed skip this step entirely.</p><pre>COPY . .</pre><p>Now we copy the application source. Changing .go files only invalidates this layer and below not the expensive go mod download step above.</p><pre># Compile a fully static binary<br>RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .</pre><p>This is the key compilation step for Go containers:</p><ul><li>CGO_ENABLED=0 disables CGO, producing a <strong>fully static binary</strong> with zero dynamic library dependencies</li><li>GOOS=linux targets Linux regardless of the build machine&#39;s OS (important if you&#39;re building on macOS)</li><li>-aforces rebuilding all packages for a clean static result</li><li>-installsuffix cgo keeps the build cache separate from CGO builds</li><li>-o mainoutputs the binary named main</li></ul><p>The result: a single executable that runs anywhere without any runtime dependencies.</p><pre># ── Stage 2: Final minimal image ─────────────────────────────────────<br>FROM alpine:latest</pre><p>We start fresh from alpine:latest (~5 MB). No Go toolchain. No source code. No module cache. The final image will only contain what&#39;s needed to <em>run</em> the binary.</p><pre>RUN apk --no-cache add ca-certificates<br>WORKDIR /root/</pre><p>Even a minimal image needs CA certificates for outbound HTTPS calls (payment APIs, webhooks, auth services).</p><pre># Pull the compiled binary from stage 1<br>COPY --from=builder /app/main .</pre><p>--from=builder reaches into the filesystem of stage 1 and copies exactly one file the compiled main binary. That&#39;s it. No source, no compiler, no temporary files.</p><pre>EXPOSE 8080<br>CMD [&quot;./main&quot;]</pre><p>EXPOSE 8080 documents which port the application listens on. CMD in exec form (JSON array) makes your binary PID 1 directly it receives OS signals correctly, enabling graceful shutdown when Docker sends SIGTERM.</p><h3>Full Dockerfile</h3><pre># Stage 1 — Build<br>FROM golang:1.21-alpine AS builder<br>RUN apk add --no-cache git ca-certificates<br>WORKDIR /app<br>COPY go.mod go.sum ./<br>RUN go mod download<br>COPY . .<br>RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .</pre><pre># Stage 2 — Run<br>FROM alpine:latest<br>RUN apk --no-cache add ca-certificates<br>WORKDIR /root/<br>COPY --from=builder /app/main .<br>EXPOSE 8080<br>CMD [&quot;./main&quot;]</pre><h3>Build and verify the size difference</h3><pre># Build the image<br>docker build -t gin-app:1.0 .</pre><pre># See the dramatic size difference<br>docker images<br># REPOSITORY   TAG       SIZE<br># gin-app      1.0       ~25MB     ← multi-stage: tiny<br># golang       1.21      ~350MB    ← full image: huge</pre><pre># Run a container<br>docker run -d \<br>  -p 8080:8080 \<br>  -e DATABASE_URL=&quot;host=localhost user=admin password=secret dbname=appdb port=5432 sslmode=disable&quot; \<br>  --name gin-api \<br>  gin-app:1.0</pre><h3>.dockerignore</h3><pre># .dockerignore<br>*.md<br>.git/<br>.env<br>.env.example<br>tmp/<br>vendor/</pre><p>Without this, Docker sends your entire project directory to the build daemon as the build context, slowing every build. With it, only the files Docker actually needs are transferred.</p><h3>5. Docker Compose — managing multiple containers</h3><p>Running a single container with docker run is manageable. But a real application has multiple services a Go API, a PostgreSQL database, a monitoring UI. Running each with a long docker run command, keeping them on the same network, managing startup order this becomes painful fast.</p><p>Meet Rahul, a backend engineer who just joined your team. On his first day, he clones the repository and runs docker compose up -d. Three minutes later, he has a fully working local environment: the Gin API on port 8080, PostgreSQL on port 5432, pgAdmin on port 8081. No &quot;install PostgreSQL&quot; guide. No &quot;configure your local environment&quot; wiki page. One command.</p><p><strong>Docker Compose</strong> makes this possible by letting you define your entire multi-container application in a single YAML file.</p><h3>The docker-compose.yml file</h3><pre>services:</pre><pre>  # ── Go/Gin API ────────────────────────────────────────────────────<br>  api:<br>    build: .<br>    container_name: gin-api<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      - DATABASE_URL=host=postgres user=admin password=secret dbname=appdb port=5432 sslmode=disable<br>      - GIN_MODE=release<br>    depends_on:<br>      postgres:<br>        condition: service_healthy       # Wait until Postgres healthcheck passes<br>    networks:<br>      - app-network<br>    restart: unless-stopped</pre><pre>  # ── PostgreSQL database ───────────────────────────────────────────<br>  postgres:<br>    image: postgres:15-alpine<br>    container_name: pg-db<br>    environment:<br>      - POSTGRES_DB=appdb<br>      - POSTGRES_USER=admin<br>      - POSTGRES_PASSWORD=secret<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - pg-data:/var/lib/postgresql/data<br>      - ./init.sql:/docker-entrypoint-initdb.d/init.sql<br>    networks:<br>      - app-network<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U admin -d appdb&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 5</pre><pre>  # ── pgAdmin (database UI) ─────────────────────────────────────────<br>  pgadmin:<br>    image: dpage/pgadmin4<br>    container_name: pg-admin<br>    environment:<br>      - PGADMIN_DEFAULT_EMAIL=admin@admin.com<br>      - PGADMIN_DEFAULT_PASSWORD=admin<br>    ports:<br>      - &quot;8081:80&quot;<br>    networks:<br>      - app-network<br>    depends_on:<br>      - postgres</pre><pre>networks:<br>  app-network:<br>    driver: bridge</pre><pre>volumes:<br>  pg-data:</pre><h3>Breaking down the key concepts</h3><p><strong>Service names as hostnames</strong> The key postgres under services automatically becomes a DNS hostname inside the Docker network. This is why DATABASE_URL uses host=postgresCompose resolves postgres to that container&#39;s internal IP address. No hardcoded IPs needed.</p><p><strong>depends_on with </strong><strong>condition: service_healthy</strong> The plain depends_on only guarantees startup <em>order</em>. With condition: service_healthy, Compose actually waits until the healthcheck on the postgres service passes before starting the api. This prevents the Go app from panicking on startup because the database isn&#39;t ready yet.</p><p><strong>healthcheck on postgres</strong>pg_isready -U admin -d appdb probes whether PostgreSQL is actually accepting connections, not just whether the process is running. It retries every 5 seconds up to 5 times.</p><p><strong>restart: unless-stopped</strong> If the api container crashes (e.g., a panic before the database is ready on a very slow machine), Docker restarts it automatically. Combined with the healthcheck condition, this makes the startup bulletproof.</p><p><strong>init.sql mount</strong> The official PostgreSQL image runs every .sql file in /docker-entrypoint-initdb.d/ on first initialization. Mount your schema file there and your tables are created automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HEIx3vtJrpR-32eJ7pW61A.png" /></figure><h3>Core Compose commands</h3><pre># Start all services — builds images if needed<br>docker compose up -d</pre><pre># Show running services and their status<br>docker compose ps</pre><pre># Follow logs across all services<br>docker compose logs -f</pre><pre># Follow logs for a specific service only<br>docker compose logs -f api</pre><pre># Open a psql shell inside the running postgres container<br>docker compose exec postgres psql -U admin -d appdb</pre><pre># Rebuild the api image after code changes<br>docker compose up -d --build api</pre><pre># Stop services (containers preserved)<br>docker compose stop</pre><pre># Stop and remove containers + networks (volumes preserved)<br>docker compose down</pre><pre># Stop, remove containers + networks + volumes<br>docker compose down -v</pre><h3>Environment variables and .env files</h3><pre># .env — never committed to Git<br>POSTGRES_PASSWORD=my_strong_password<br>PGADMIN_PASSWORD=admin_password<br>DATABASE_URL=host=postgres user=admin password=my_strong_password dbname=appdb port=5432 sslmode=disable</pre><pre># .env.example — committed to Git, no real values<br>POSTGRES_PASSWORD=<br>PGADMIN_PASSWORD=<br>DATABASE_URL=host=postgres user=admin password= dbname=appdb port=5432 sslmode=disable</pre><pre># docker-compose.yml — references variables, not values<br>postgres:<br>  environment:<br>    - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}</pre><p>New team members run cp .env.example .env, fill in their own values, and docker compose up -d. Clean, secure, repeatable.</p><h3>6. Volumes and data persistence</h3><p>By default, a Docker container has a writable layer on top of its image. Any files your application writes database rows, uploaded files, logs live in this layer. The problem: when you remove the container with docker rm, that writable layer is permanently deleted. Every restart of your PostgreSQL container means an empty database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbeY6SiRAEg3jv7gxTXJpA.png" /></figure><p><strong>Volumes are Docker’s solution to data persistence.</strong> They exist independently of any container’s lifecycle.</p><h3>The three types of volume mounts</h3><p><strong>1. Named volumes</strong> — recommended for databases</p><pre>volumes:<br>  - pg-data:/var/lib/postgresql/data</pre><p>Docker manages the storage location internally. You reference it by name. Named volumes are the preferred approach for persistent data because Docker handles creation, cleanup, and lifecycle you never need to know the exact host path.</p><pre>docker volume create pg-data<br>docker volume inspect pg-data<br># Shows the actual path: /var/lib/docker/volumes/pg-data/_data</pre><p><strong>2. Bind mounts</strong> — recommended for development</p><pre>volumes:<br>  - ./api:/app</pre><p>Binds a host directory directly into the container. Changes on either side are instantly reflected on the other. Ideal during development edit a .go file in your editor, and a tool like air (Go live reload) picks it up inside the container without rebuilding the image.</p><pre>docker run -d \<br>  -v $(pwd)/api:/app \<br>  -p 8080:8080 \<br>  gin-app:1.0</pre><p><strong>3. Anonymous volumes</strong> — ephemeral temporary storage</p><pre>volumes:<br>  - /app/tmp</pre><p>Docker assigns a random hex name. Removed when the container is removed. Used when you need temporary isolated storage that should not persist.</p><h3>Verifying persistence</h3><pre># Start the stack<br>docker compose up -d</pre><pre># Insert a user<br>curl -X POST <a href="http://localhost:8080/users">http://localhost:8080/users</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;name&quot;: &quot;Alice&quot;, &quot;email&quot;: &quot;alice@example.com&quot;}&#39;</pre><pre># Verify<br>curl <a href="http://localhost:8080/users">http://localhost:8080/users</a><br># [{&quot;id&quot;:1,&quot;name&quot;:&quot;Alice&quot;,&quot;email&quot;:&quot;alice@example.com&quot;,&quot;created_at&quot;:&quot;2026-05-20T10:30:00Z&quot;}]</pre><pre># Tear down containers — volumes are preserved<br>docker compose down</pre><pre># Bring everything back up<br>docker compose up -d</pre><pre># Alice is still there<br>curl <a href="http://localhost:8080/users">http://localhost:8080/users</a><br># [{&quot;id&quot;:1,&quot;name&quot;:&quot;Alice&quot;,&quot;email&quot;:&quot;alice@example.com&quot;,&quot;created_at&quot;:&quot;2026-05-20T10:30:00Z&quot;}]</pre><p>Without the named volume, the second query returns an empty array. With it, Alice survives container deletion.</p><pre># Clean up unused volumes<br>docker volume prune</pre><pre># Nuclear option — remove containers AND volumes<br>docker compose down -v</pre><h3>7. Docker networking</h3><p>Every container you run gets connected to a Docker network. Networking governs how containers communicate with each other, with your host machine, and with the outside world.</p><h3>Default networks Docker creates</h3><pre>docker network ls<br># NETWORK ID     NAME      DRIVER    SCOPE<br># abc123         bridge    bridge    local<br># def456         host      host      local<br># ghi789         none      null      local</pre><p><strong>bridge (default)</strong> Every container without an explicit network joins this. Containers can communicate by IP address but <em>not</em> by name there is no automatic DNS. Always create custom bridge networks instead.</p><p><strong>host</strong>The container shares the host&#39;s network stack directly. No isolation the container&#39;s port 8080 <em>is</em> the host&#39;s port 8080, no -p mapping needed. Useful for performance-sensitive scenarios but sacrifices isolation.</p><p><strong>none</strong>Complete isolation. No network interfaces except loopback. Used for batch containers that should have zero network access.</p><h3>Custom bridge networks — always use these</h3><p>When containers share a custom bridge network, Docker provides automatic DNS resolution. Containers reach each other by service name.</p><pre># Create a custom network<br>docker network create app-network</pre><pre># Run postgres on it<br>docker run -d \<br>  --name postgres \<br>  --network app-network \<br>  -e POSTGRES_PASSWORD=secret \<br>  postgres:15-alpine</pre><pre># Run Gin app on the same network<br># It reaches postgres using the hostname &quot;postgres&quot;<br>docker run -d \<br>  --name gin-api \<br>  --network app-network \<br>  -p 8080:8080 \<br>  -e DATABASE_URL=&quot;host=postgres user=admin password=secret dbname=appdb port=5432 sslmode=disable&quot; \<br>  gin-app:1.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbA8UEX-MiXdSq2jRJcifA.png" /></figure><p>Container ports are internal by default. A Gin app on port 8080 inside a container is unreachable from your browser without explicit binding.</p><pre>docker run -p 8080:8080 gin-app:1.0<br>#              ^     ^<br>#          host  container</pre><pre># Bind a different host port if 8080 is taken<br>docker run -p 9090:8080 gin-app:1.0</pre><p><strong>Critical rule:</strong> Two containers cannot bind the same host port. Starting a second container on port 8080 when one is already using it throws a “port already allocated” error. Each container needs a unique host port, even when their internal container ports are the same.</p><h3>Inspecting networking</h3><pre># See all containers on a network and their IPs<br>docker network inspect app-network</pre><pre># See which networks a container is on<br>docker inspect gin-api | jq &#39;.[0].NetworkSettings.Networks&#39;</pre><pre># Add a running container to an additional network<br>docker network connect app-network my-other-container</pre><pre># Remove it<br>docker network disconnect app-network my-other-container</pre><h3>How Compose handles networking automatically</h3><p>Compose creates a default bridge network named &lt;project-name&gt;_default and connects every service automatically. Service names become resolvable hostnames with no extra configuration.</p><p>Declaring a custom network explicitly (as in section 5) is still recommended it gives a predictable name, makes intent clear, and lets you run docker network inspect app-network to debug connectivity issues.</p><h3>8. Putting it all together — your complete project</h3><p>After working through all seven sections, your project should be organized like this:</p><pre>gin-docker-demo/<br>├── main.go<br>├── go.mod<br>├── go.sum<br>├── Dockerfile<br>├── docker-compose.yml<br>├── .env                   ← not committed to Git<br>├── .env.example           ← template for new developers<br>├── .dockerignore<br>└── init.sql               ← database initialization script</pre><p><strong>init.sql</strong></p><pre>CREATE TABLE IF NOT EXISTS users (<br>    id         SERIAL PRIMARY KEY,<br>    name       VARCHAR(100)        NOT NULL,<br>    email      VARCHAR(255) UNIQUE NOT NULL,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><p>Mounted into docker-entrypoint-initdb.d/, PostgreSQL runs this automatically on first startup. Your schema is always ready before the Go app connects.</p><h3>The complete developer workflow</h3><pre># Clone on any machine<br>git clone https://github.com/you/gin-docker-demo<br>cd gin-docker-demo</pre><pre># Set up environment variables<br>cp .env.example .env<br># Fill in POSTGRES_PASSWORD and DATABASE_URL in .env</pre><pre># Build images and start everything<br>docker compose up -d --build</pre><pre># Verify all services are healthy<br>docker compose ps</pre><pre># Watch the Go app logs — confirm it connected to PostgreSQL<br>docker compose logs -f api<br># [GIN-debug] Listening and serving HTTP on :8080<br># [GIN] 200 | GET /users</pre><pre># Test the API<br>curl <a href="http://localhost:8080/users">http://localhost:8080/users</a></pre><pre># Open pgAdmin<br># <a href="http://localhost:8081/">http://localhost:8081</a><br># Login: admin@admin.com / admin<br># Add server: host=postgres, port=5432, user=admin, password=&lt;from .env&gt;</pre><pre># Rebuild after code changes (only the api service)<br>docker compose up -d --build api</pre><pre># Done for the day<br>docker compose stop</pre><pre># Full cleanup — containers and networks removed, volumes preserved<br>docker compose down</pre><h3>Quick reference card</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*Z2fQczprYchbch6pjc4lSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Q3epqlhgFSTRsktVGKbrKA.png" /></figure><h3>Final thoughts</h3><p>Docker has gone from a niche DevOps tool to a baseline expectation in professional software development. The mental model shift it demands from “software installed on a machine” to “software packaged with its environment” is the only real hurdle. Once that clicks, the rest follows naturally.</p><p><strong>The five principles to internalize:</strong></p><ol><li><strong>Images are blueprints. Containers are instances.</strong> One image, many containers just like a struct type and its instances.</li><li><strong>Layers are your cache.</strong> Order Dockerfile instructions from least to most frequently changed. Dependencies before source code, always.</li><li><strong>Multi-stage builds are non-negotiable for Go.</strong> CGO_ENABLED=0 + a scratch or alpine final stage takes you from 350 MB to 25 MB.</li><li><strong>Networks are how containers talk.</strong> Always use custom bridge networks. Service names resolve automatically in Compose.</li><li><strong>Volumes are how data survives.</strong> Named volumes for databases, bind mounts for development hot-reload.</li></ol><p>Master these five principles and you have everything you need to containerize any Go application, eliminate “works on my machine” incidents, and hand your project to any pipeline CI/CD, staging, or production with confidence.</p><p><em>Found this useful? Share it with a Go developer who is still manually installing PostgreSQL. They will thank you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a485daaed5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/docker-in-2026-from-zero-to-production-ready-containers-63a485daaed5">Docker in 2026: From Zero to Production-Ready Containers</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete End-to-End Guide to System Design]]></title>
            <link>https://medium.com/coinmonks/the-complete-end-to-end-guide-to-system-design-1ff4fd3e1a0b?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ff4fd3e1a0b</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[system-design-course]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Fri, 08 May 2026 05:47:08 GMT</pubDate>
            <atom:updated>2026-05-08T06:42:15.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmry33UCW5jDM_r-dsJPZg.png" /></figure><p><em>From Netflix to WhatsApp everything you need to master High Level Design and Low Level Design for senior engineering interviews.</em></p><p>System DesignHLDLLDBackend EngineeringInterview PrepScalability</p><p>Who this is for: Software engineers targeting SD2+ roles, Tech Leads, and anyone aiming for FAANG/MAANG or highly scalable startups. This guide covers the complete system design curriculum both High Level Design (HLD) and Low Level Design (LLD) in a single, structured read.</p><h3>What Exactly Is System Design?</h3><p>In the simplest terms, system design is the art of architecting the technology-based systems we use every day Netflix, Uber, Instagram, WhatsApp. In an interview setting, you are asked to design one of these systems from scratch.</p><p>For example, an interviewer might say: <em>“Design WhatsApp.”</em> As a software engineer, you need a toolkit of concepts databases, caches, queues, networking protocols to build a coherent, scalable answer. That toolkit is what system design teaches you.</p><blockquote><strong>“It is better to satisfy some of the users than to disappoint all of them.”</strong></blockquote><blockquote><em>— A guiding principle in system design</em></blockquote><p>System design is divided into two major areas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pzYW00cgkJfVGThHJ5iXQ.png" /></figure><h3>Before You Begin: The One Prerequisite</h3><p>Before diving into system design, you need <strong>hands-on development experience</strong>. Jumping in without having built at least a project-level system makes every concept feel abstract and theoretical.</p><p>When you have shipped code, you instinctively understand why a cache matters, or why a database choice is consequential. That real-world grounding is irreplaceable. At minimum, aim for SD1-level work experience, or build substantial personal projects before tackling this material.</p><h3>Part I — High Level Design (HLD)</h3><p>Let’s walk through HLD using a concrete example: <strong>designing Netflix</strong> a service that streams video content to millions of users across different countries, seamlessly.</p><h3>Step 0: Define Requirements</h3><p>Every HLD starts by establishing two classes of requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*586VcxFZ9yjnAMJf8QbUfA.png" /></figure><p>Both sets of requirements must be held in mind throughout the entire design process. They are the compass by which every architectural decision is judged.</p><h3>The HLD Curriculum — Step by Step</h3><h4>1 - Basic Fundamentals :</h4><p>Serverless vs. serverful architecture (AWS Lambda vs. EC2 and when each makes sense). Horizontal vs. vertical scaling vertical means upgrading a single server’s RAM and storage; horizontal means adding more servers behind a load balancer. Also covers: threads, processes, how the internet works, the request-response cycle, and DNS.</p><h4>2 - Databases</h4><p>The core of all programming is data transferring it, manipulating it, and storing it. You must know SQL vs. NoSQL databases (MongoDB, Neo4j), in-memory databases, data replication and migration, and critically <strong>data partitioning and sharding</strong> (horizontal partitioning of data, a very frequent interview topic).</p><h4>3 - Consistency &amp; Availability</h4><p>The CAP theorem states that in a network partition, you must choose between consistency and availability. Consistency means every read gets the most recent write. Availability means the system always responds, even if not with the latest data. Payment systems (like Paytm, PayPal) favor consistency; notification systems (like WhatsApp alerts) favor availability.</p><h4>4 - Caching &amp; CDNs</h4><p>Caches store frequently accessed data for ultra-low-latency delivery. Key concepts: Redis vs. Memcached, write policies (write-back, write-through, write-around), and eviction/replacement policies (LFU, LRU, Segmented LRU). Content Delivery Networks (CDNs) handle static content globally — Netflix can pre-load a popular new episode into CDN nodes worldwide before its release date.</p><h4>5 - Networking</h4><p>TCP vs. UDP differences. HTTP versions 1, 2, and 3 how their implementations differ. WebSockets for real-time bidirectional communication. WebRTC for peer-to-peer video streaming essential for designing a system like Google Meet or Zoom.</p><h4>6 - Load Balancers</h4><p>Load balancers distribute traffic across servers during horizontal scaling. Algorithms include: Round Robin, Least Connections, and Consistent Hashing (a critical CS concept). Also covers stateless vs. stateful load balancing, reverse proxies, and rate limiting which prevents DDoS attacks.</p><h4>7 - Message Queues</h4><p>For asynchronous processing of non-critical tasks, tasks that can be handled with a slight delay without impacting core functionality. Example: the “double-tick” (delivered status) on WhatsApp messages is non-critical; a slight delay is fine. Kafka and RabbitMQ are popular options, both using the Publisher-Subscriber model.</p><h4>8 - Monoliths vs. Microservices</h4><p>Industry practice is to start with a monolith and migrate to microservices as the system and team scale. Key concepts: why microservices are needed, single points of failure, cascading failures, and containerization (Docker). Also covers how to execute the actual migration from monolith to microservices.</p><h4>9 - Monitoring &amp; Logging</h4><p>When millions of users hit your system during a big sale and something breaks, logs are what tell you exactly what went wrong and how to prevent it next time. Tools: AWS CloudWatch, Grafana, Prometheus. Anomaly detection is also a key concept here.</p><h4>10 - Security</h4><p>Only paid Netflix users should access paid content this requires strong authentication and authorization. Covers OAuth tokens, Access Control Lists (ACLs), and encryption. A secure system is a non-functional requirement you cannot afford to neglect.</p><h4>11 - Trade-offs</h4><p>There is no single right answer in system design — only justified trade-offs. Push vs. Pull architecture. Consistency vs. Availability. SQL vs. NoSQL. Memory vs. Latency vs. Throughput vs. Accuracy. Your job in an interview is to articulate <em>why</em> you made each choice, and defend it.</p><h4>Key Insight</h4><blockquote>In system design interviews, <strong>there is no fixed right or wrong answer.</strong> The goal is to demonstrate your thought process ,how you understood the problem, why you made each architectural choice, and how you justify those choices under questioning. Two engineers can design the same system differently and both be correct.</blockquote><h3>The SQL vs. NoSQL Decision</h3><p>One of the most common trade-off questions — when do you use SQL versus NoSQL?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yx1GnUkBdkxfswwhZve8EQ.png" /></figure><h3>Part II — Low Level Design (LLD)</h3><p>Where HLD deals with the architecture of large systems, LLD is about <strong>writing well-structured code</strong> that solves a specific, bounded problem. This is where your actual coding skills are tested.</p><h3>The OOP Foundation</h3><p>LLD is built on object-oriented programming. The four pillars of OOP (Encapsulation, Abstraction, Inheritance, Polymorphism) are the starting point. From there, you need to master the <strong>SOLID Principles</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z73MLCObDaH7W3Ozt3c_uQ.png" /></figure><h3>Design Patterns</h3><p>Design patterns are reusable solutions to common problems. Many engineers are already applying these patterns at work without knowing the formal names. LLD asks you to be deliberate about them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wt1EE8iDuMXQVqWNsYX3Eg.png" /></figure><h3>Concurrency &amp; Thread Safety</h3><p>Concurrency is critical in production systems. This topic covers: thread-safe injection, locking mechanisms, the Producer-Consumer model, race conditions, and synchronization. Much of this was first encountered in Operating Systems courses — LLD asks you to apply it in code.</p><h3>UML Diagrams</h3><p>Class diagrams and component diagrams, some companies require these in interviews, others do not. Check with your recruiter before the interview whether UML is expected. If it is, understand class relationships: association, aggregation, composition, and inheritance.</p><h3>API Design</h3><p>Clean API design is an art. Key concerns include: request and response object modeling, versioning (how do you handle breaking changes?), extensibility, the DRY principle, avoiding God Classes, and applying the Single Responsibility Principle at the API layer.</p><h3>The 10 Systems You Must Practice</h3><p>The fastest way to internalize all the above concepts is to design real systems. Each of the following teaches you a distinct pattern of thinking:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2OvgVuSsBelPOKFc1etdQ.png" /></figure><p>For example, designing <strong>Uber</strong> teaches you to handle two distinct user types riders and drivers each with completely different functional requirements. Designing <strong>WhatsApp</strong> forces you to decide between consistency and availability for different parts of the same system. Designing <strong>Zoom</strong> requires you to understand WebRTC deeply.</p><blockquote>LLD vs. HLD Problem Scale</blockquote><blockquote>In HLD, you design a <strong>large, distributed system</strong> like all of Netflix. In LLD, you design and <em>code</em> a <strong>smaller, bounded system </strong>like a chess game, a notification system, or a URL shortener. No interviewer will ask you to fully implement Netflix in 45 minutes.</blockquote><h3>The Netflix HLD — What It Looks Like</h3><p>After applying all of the above concepts, the final Netflix HLD architecture consists of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_btpUczdeYFNmQ7wRwYSZA.png" /></figure><h3>How Long Will This Take?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zswt6WfTvA1mgE9JyHWrhA.png" /></figure><p>The variable that matters most isn’t your starting point — it’s your practice volume. The more systems you design, the more natural the decision-making becomes. Implement these concepts in personal projects (even as proof-of-concepts) to gain intuition that no amount of passive reading can provide.</p><h3>Final Thoughts</h3><p>System design can feel overwhelming at first. As a working software engineer, you rarely interact with all these layers simultaneously in your daily work. That’s completely normal. But the companies building highly scalable, production-grade systems use every single one of these components and understanding them makes you a dramatically more effective engineer, whether or not you’re actively interviewing.</p><p>The path forward is simple, if not easy:</p><ol><li>Learn the concepts systematically (HLD first, then LLD)</li><li>Practice by designing real systems end-to-end</li><li>Implement at least some of them in code even partially</li><li>Be able to justify every architectural decision you make</li></ol><blockquote><em>“The key to learning system design is always practice, practice, and more practice.”</em></blockquote><p>The more systems you design, the more you internalize where message queues belong, when to reach for a cache, which database fits a given workload, and when to prioritize consistency over availability. That intuition is what separates a good engineer from a great one.</p><p>If this helped you, share it with your network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ff4fd3e1a0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/the-complete-end-to-end-guide-to-system-design-1ff4fd3e1a0b">The Complete End-to-End Guide to System Design</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents, Agentic Workflows & LLMs, Everything Cleared Up in One Read]]></title>
            <link>https://medium.com/@muhammadtalha1/ai-agents-agentic-workflows-llms-everything-cleared-up-in-one-read-4590a7ac0678?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/4590a7ac0678</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 11:12:28 GMT</pubDate>
            <atom:updated>2026-04-30T11:12:28.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMoaiXYkY8I-UdQWRL9iLg.png" /></figure><p><strong>If 2026 has one buzzword, it’s “agents.” But what actually are they?</strong></p><p>Every time someone says “AI agents,” a cloud of confusion follows: <em>Is it the same as an LLM? What’s an agentic workflow? What’s the difference between generative AI and agentic AI?</em> This post cuts through all of it simple, clear, and with visuals to make it stick.</p><p>Let’s go.</p><h3>Part 1: LLMs — The Knowledge-Givers</h3><p>Before agents, we need to talk about what came before them: <strong>Large Language Models (LLMs)</strong>.</p><p>Think of LLMs as your brilliant-but-passive friend. They know <em>everything</em> code, philosophy, travel tips, recipes. You ask them a question, they give you an answer. That’s it.</p><blockquote><strong><em>LLMs give you knowledge. They don’t take action.</em></strong></blockquote><p>If you ask ChatGPT “What’s wrong with my code?”, it’ll tell you. But it won’t go fix it. If you ask for a Mumbai travel itinerary, it’ll list every hotspot but it won’t book your flights or hotels.</p><p><strong>LLM = Knowledge only.</strong></p><h3>Part 2: So What Is an AI Agent?</h3><p>Here’s the simplest definition you’ll ever hear:</p><blockquote><strong><em>Agent = Knowledge + Action</em></strong></blockquote><p>That’s it. The moment an AI system stops just <em>telling</em> you things and starts <em>doing</em> things booking flights, editing files, calling APIs, it becomes an agent.</p><p>An agent uses the brain of an LLM but gives it hands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fozHn6Gz7rwTbIMXedUaQ.png" /></figure><h3>Part 3: Characteristics of an AI Agent</h3><p>Agents don’t just “do more” than LLMs they have distinct characteristics that define them.</p><h4>1. Autonomy</h4><p>An LLM waits for you to ask. An agent decides what to do next on its own. You give it a goal, and it figures out the steps whether that means calling a tool, looping back to the LLM for a better answer, or pausing to ask you for input (called “human-in-the-loop”). You grant it permission to act; it decides <em>how</em>.</p><h4>2. Planning, Iteration &amp; Feedback</h4><p>LLMs respond once. Agents can plan a sequence of steps, execute them, evaluate the results, and try again if something went wrong all on their own. Think of it as the agent having an internal review cycle.</p><h4>3. Coordination (in multi-agent setups)</h4><p>Sometimes one agent isn’t enough. You might have a planning agent, a coding agent, and a testing agent each specializing in one thing. Coordination is the mechanism by which control is handed off from one agent to the next (or skipped, if the situation calls for it).</p><h3>Part 4: What’s Inside an Agent? The Three Components</h3><p>Behind every agent are three building blocks. Without them, an agent is just a chatbot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0Uaj0NY1xqmutY7qL_ehg.png" /></figure><p><strong>Breaking down each component:</strong></p><p><strong>LLM Brain</strong> — Every agent needs an LLM as its thinking engine. Without this, the agent can’t reason, plan, or generate anything. The LLM is the agent’s mind.</p><p><strong>Memory</strong> — This is why startups are racing to solve the memory problem. When you talk to an LLM via API with no memory layer, each message forgets everything before it. An agent with memory keeps track of the conversation history, previous actions, and outputs — so it can build on what it already did instead of starting from scratch every time. Think of it like the difference between a person with amnesia and someone with a notebook.</p><p><strong>Toolbox</strong> — Tools are just functions. createNotionPage(data), bookFlight(destination, date), editFile(path, content) — these are all tools. The big unlock? Thanks to Natural Language Processing (NLP), the agent doesn&#39;t need you to call these functions explicitly. You just say <em>&quot;make me a Notion page&quot;</em> and the agent figures out which function to call. The tool is the agent&#39;s hands.</p><h3>Part 5: What Is an Agentic Workflow?</h3><p>An agentic workflow is the loop that an agent runs through to complete a task. It’s not just “input → output” it’s a full cycle with planning, execution, reflection, and retry.</p><p>Here’s the simplest version of an agentic workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdo7f-J_X3-KPvVJrPWaPA.png" /></figure><p>This loop plan, act, reflect, retry or respond is what makes agentic AI so different from a one-shot LLM call. The agent is essentially its own quality reviewer.</p><h3>Part 6: Multi-Agent Workflows — When One Agent Isn’t Enough</h3><p>Real-world tasks are complex. You might need a <em>planning agent</em>, a <em>coding agent</em>, and a <em>testing agent</em> — each specializing in its domain. This is a multi-agent workflow, and it introduces a few new elements: a <strong>classifier</strong> (which figures out what kind of task is being asked) and an <strong>agent selector</strong> (which routes the task to the right specialist).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lc5gIa88yofKvV94CeuSTA.png" /></figure><p>Each specialist agent runs its own internal loop (plan → execute → reflect → retry). The memory layer at the bottom captures conversation history across all of them so the system remembers what happened in previous turns.</p><p>This is also why memory startups are exploding. Without memory, every session starts from zero. With memory, the system builds an increasingly rich understanding of what it’s been doing and can pick up where it left off.</p><h3>Part 7: Generative AI vs Agentic AI, The Key Distinction</h3><p>People often mix these two up. Here’s the cleanest way to separate them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*Tab5e2XfLUzrGfu8yeEuvQ.png" /></figure><p>The major breakthroughs in Generative AI are largely done. Models are excellent at producing content. Now the world is asking: <em>what do we do with all this generated knowledge?</em> The answer is agents systems that take that knowledge and actually execute things with it.</p><p><strong>This is why everyone is moving to agents.</strong></p><h3>Part 8: Real Examples You Already Use</h3><p>You’ve been using agents longer than you think.</p><p><strong>ChatGPT</strong> is an agent. It has memory, a brain (GPT-4), and tools (web search, code execution, image generation). <strong>Cursor</strong> is a coding agent. It reads your codebase, plans edits, runs the code, and fixes errors — all autonomously. Even an app that sets an alarm for you qualifies as an agent, because it took an action on your behalf based on a natural language instruction.</p><h3>The One-Line Summary</h3><blockquote><em>An </em><strong><em>LLM</em></strong><em> gives you knowledge. An </em><strong><em>Agent</em></strong><em> gives you knowledge </em>and<em> takes action. An </em><strong><em>Agentic Workflow</em></strong><em> is the loop that governs how the agent plans, acts, and improves. A </em><strong><em>Multi-Agent Workflow</em></strong><em> coordinates multiple specialized agents. And </em><strong><em>Agentic AI</em></strong><em> is the evolution of Generative AI from “tell me things” to “do things for me.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4590a7ac0678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Explained: The Complete One-Stop Guide to Retrieval Augmented Generation]]></title>
            <link>https://medium.com/@muhammadtalha1/rag-explained-the-complete-one-stop-guide-to-retrieval-augmented-generation-199677999078?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/199677999078</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 10:43:04 GMT</pubDate>
            <atom:updated>2026-04-29T10:43:04.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWumy4mLhLyPOxn210h1hw.png" /></figure><p>Why the smartest AI systems don’t just rely on memory and how giving them an open book changes everything.</p><p>Imagine getting a personalised AI summary of your blood test results not a generic explanation, but one that reads your specific values, flags your outliers, and gives you tailored suggestions. That capability doesn’t come from ChatGPT or Gemini out of the box. It comes from <strong>RAG</strong>.</p><p>RAG — Retrieval Augmented Generation is one of the most practical and widely deployed AI techniques in the real world today. You’ll find it powering customer support bots, medical report systems, legal research tools, financial compliance engines, and much more. This guide breaks down exactly what it is, why it matters, and how it works from end to end.</p><h3>The Core Idea: Two Students, Two Exams</h3><p>The best way to understand RAG is through a simple analogy.</p><h4>Traditional LLM: Student 1 — Closed Book</h4><p>Studies hard before the exam, memorises everything, and answers questions based purely on what was learned during training. Cannot access new information during the test.</p><h4>RAG-powered model: Student 2 — Open Book</h4><p>Also studies, but gets to bring a book into the exam. Can verify facts in real time, look up the latest information, and give far more accurate and contextual answers.</p><p>That’s RAG in a nutshell. It’s not a single technology it’s a technique that allows your model to access a real-time, up-to-date database while answering a question. The result: answers that are more accurate, more current, and context-aware in a way that generic models simply cannot be.</p><p><strong>Context-aware example:</strong> Ask ChatGPT “why is my flight delayed?” and you get a generic list of reasons. Ask the same question to an airline’s RAG-powered chatbot while logged in and it already knows your flight number, PNR, departure time, and real-time status. That’s context-awareness at work.</p><h3>Why RAG? Four Key Benefits Over Traditional LLMs</h3><ul><li><strong>Reduces hallucination.</strong> LLMs sometimes make up facts when they are uncertain a phenomenon called hallucination. RAG grounds model responses in real, retrieved data, making answers far more reliable and accurate.</li><li><strong>Keeps knowledge up to date.</strong> Every LLM has a knowledge cutoff date. For example, GPT’s cutoff is September 2024. RAG bypasses this limitation by giving the model access to current documents and databases at query time.</li><li><strong>Cost effective.</strong> Without RAG, updating a model’s knowledge requires expensive retraining or fine-tuning. With RAG, you simply update the external database the model itself doesn’t change.</li><li><strong>Preserves data privacy.</strong> Enterprises don’t need to expose their full internal database to a model. RAG only retrieves the specific chunks of data relevant to a query the rest remains private and untouched.</li></ul><h3>The Complete RAG Pipeline</h3><p>The RAG pipeline has two main stages: the <strong>Ingestion Pipeline</strong> and the <strong>Retrieval Pipeline</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3tEVFAIya2h7qHdKAjByw.png" /></figure><h3>Stage 1 — Ingestion Pipeline (preparing the open book)</h3><h4><strong>1 - Collect the data</strong></h4><p>Gather all relevant documents PDFs, Word files, Excel sheets, entire websites, or internal company databases. Any structured or unstructured data can be the source.</p><h4><strong>2 - Split into chunks</strong></h4><p>Rather than processing everything at once, the data is broken into smaller, manageable pieces called chunks. The chunking strategy matters a lot more on that shortly.</p><h4><strong>3 - Convert to embeddings</strong></h4><p>AI models can only process numbers, not raw text. Each chunk is converted into a vector of numbers called a vector embedding using an embedding model. These embeddings capture the semantic meaning of the text.</p><h4><strong>4 - Store in a vector database</strong></h4><p>The embeddings and their original text chunks are stored in a specialised vector database. Unlike regular databases (MySQL, MongoDB) that support keyword search, vector databases support semantic search finding documents by meaning, not just by matching exact words.</p><p><strong>Semantic search in practice:</strong> Search for “heart attack symptoms” in a regular database and you only get documents containing those exact words. Search in a vector database and you also get results about “cardiac arrest” because the meaning is similar, even if the keywords don’t match.</p><h3>Stage 2 — Retrieval Pipeline (using the open book)</h3><h4>R1:User sends a query</h4><p>The user asks a question. This query is also converted into a vector embedding using the same embedding model used during ingestion.</p><h4>R2: Retrieve relevant chunks</h4><p>The query embedding is used to perform a semantic similarity search in the vector database. The top matching document chunks are retrieved this is the retrieval step.</p><h4>R3: Augment the prompt</h4><p>Instead of sending just the original query to the LLM, we build an enriched prompt: the original query plus the retrieved context. This is augmentation the A in RAG.</p><h4>R4: Generate the answer</h4><p>The LLM receives the augmented prompt and generates a final, grounded response. This is the generation — the G in RAG. The answer is returned to the user.</p><p>“<em>RAG is called Retrieval Augmented Generation because the generation is not simple it is augmented by retrieval first.</em>”</p><h3>Technical Implementation: Three Pillars</h3><h4>1. Chunking Strategy</h4><p><strong>Fixed-size chunking</strong> splits text into chunks of a fixed token count (e.g. every 500 tokens). Simple to implement but can break context mid-sentence. <strong>Hierarchical chunking</strong> creates chunks at the paragraph, section, or sentence level. More complex but production-grade. <strong>Semantic chunking</strong> creates new chunks whenever a new topic emerges in the document. Slowest but highest quality. Popular libraries: LangChain, LlamaIndex, Haystack.</p><h4>2. Embedding Models</h4><p>Popular choices include OpenAI’s <strong>text-embedding-3</strong>, <strong>Gemini Embeddings</strong>, and <strong>Sentence Transformers</strong> from the Hugging Face ecosystem. The embedding model you use during ingestion must be the same one used during retrieval the vector spaces must match.</p><h4>3. Vector Databases</h4><p>Leading options: <strong>ChromaDB</strong> (open source, great for prototyping), <strong>FAISS</strong> (Meta’s fast similarity search library), <strong>Pinecone</strong> (managed cloud service), and <strong>Elasticsearch</strong> (hybrid search support). Each has different trade-offs around scale, speed, and cost.</p><h3>Seven RAG Architectures Used in Industry</h3><h4>1. Naive / Standard RAG</h4><p>The basic pipeline described above. Low complexity, great for FAQ bots and simple customer support chatbots with clean documentation.</p><p><em>Use for: Low complexity</em></p><h4>2. Hybrid RAG</h4><p>Combines vector search with traditional keyword search. Best of both worlds semantic meaning plus exact term matching. Very common in production systems.</p><p><em>Use for: E-commerce · Enterprise search</em></p><h4>3. RAG with Memory</h4><p>Adds a memory layer to track conversation history. Without this, a model can’t understand “explain more about it” it doesn’t know what “it” refers to.</p><p><em>Use for: Support assistants · Chatbots</em></p><h4>4. Graph RAG</h4><p>Structures data as a knowledge graph, preserving relationships between entities as nodes and edges. Excellent for knowledge-heavy domains where things are deeply interrelated.</p><p><em>Use for: Fraud detection · Legal · Research</em></p><h4>5. Agentic RAG</h4><p>Handles complex multi-step queries by breaking them into sub-queries, doing multiple retrievals, and using additional tools like web search or finance APIs autonomously.</p><p><em>Use for: Multi-step reasoning</em></p><h4>6. Multimodal RAG</h4><p>Standard RAG only handles text. Multimodal RAG can process images, videos, and audio alongside text enabling use cases in medical imaging and surveillance.</p><p><em>Use for: Medical · Security</em></p><h4>7. Self-Reflective RAG (Self-RAG)</h4><p>Instead of generating a final answer immediately, this architecture first produces a draft response, then critiques and evaluates it checking if more information is needed before producing the final output. Ideal for research-heavy industries and heavily regulated domains where accuracy is non-negotiable.</p><p><em>Use for: Research · Regulated industries</em></p><p><strong><em>Production note:</em></strong><em> In real-world systems, these architectures are often combined. A production system might use Hybrid RAG + Memory + Self-Reflection together for optimal performance.</em></p><h3>Conclusion</h3><p>RAG is not a single product or framework it is a design pattern. At its core, it solves one fundamental problem: LLMs are smart but isolated. They know a lot, but they don’t know your data. RAG bridges that gap by giving the model a structured, real-time window into external knowledge without requiring expensive retraining.</p><p>As AI moves deeper into every domain, RAG will remain one of the foundational techniques that makes enterprise-grade AI systems actually trustworthy and useful in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=199677999078" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an ethers.js-Style SDK for Hyperledger Fabric in Go]]></title>
            <link>https://medium.com/coinmonks/i-built-an-ethers-js-style-sdk-for-hyperledger-fabric-in-go-91064525a5a0?source=rss-bfee9d0fba03------2</link>
            <guid isPermaLink="false">https://medium.com/p/91064525a5a0</guid>
            <category><![CDATA[hyperledger]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[hyperledger-fabric]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Muhammad Talha]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 07:15:54 GMT</pubDate>
            <atom:updated>2026-04-23T07:15:54.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vipMzu9jJ2HS5nYEbsqqdA.png" /></figure><h3>The boilerplate problem that every Fabric developer knows too well</h3><p>If you’ve ever built on Ethereum, you know how clean the developer experience feels:</p><pre>const token = new ethers.Contract(address, abi, signer)<br>const balance = await token.balanceOf(addr)       // read<br>const tx      = await token.transfer(to, amount)  // write<br>await tx.wait()</pre><p>Three lines. The library handles the RPC connection, wallet signing, and confirmation waiting. You focus on your application logic.</p><p>Now try doing the same thing with Hyperledger Fabric in Go.</p><h3>What you actually write today</h3><p>Before you can call a single chaincode function, the official Fabric Gateway SDK requires you to wire up TLS certificates, gRPC connections, identity loading, and gateway configuration manually — every time, in every service:</p><pre>certPEM, _ := os.ReadFile(config.TLSCertPath)<br>cert, _    := identity.CertificateFromPEM(certPEM)<br>pool       := x509.NewCertPool()<br>pool.AddCert(cert)</pre><pre>conn, _ := grpc.Dial(config.PeerEndpoint,<br>    grpc.WithTransportCredentials(<br>        credentials.NewClientTLSFromCert(pool, config.PeerHostOverride),<br>    ),<br>)</pre><pre>id, _   := loadIdentityFromDir(config.CertPath, config.MSPID)<br>sign, _ := loadSignerFromDir(config.KeyPath)</pre><pre>gw, _ := client.Connect(id,<br>    client.WithSign(sign),<br>    client.WithHash(hash.SHA256),<br>    client.WithClientConnection(conn),<br>    client.WithEvaluateTimeout(5*time.Second),<br>    client.WithEndorseTimeout(15*time.Second),<br>    client.WithSubmitTimeout(5*time.Second),<br>    client.WithCommitStatusTimeout(1*time.Minute),<br>)</pre><pre>network  := gw.GetNetwork(config.ChannelName)<br>contract := network.GetContractWithName(config.ChaincodeName, config.ContractName)</pre><p>And that’s just the connection. Every chaincode function is another 15–20 lines on top of that — marshalling, SubmitAsync, commit.Status(), and manually digging through gRPC status details to find the actual chaincode error message buried inside a proto.</p><p>On a real project with multiple chaincodes and multiple services, this becomes hundreds of lines of pure infrastructure duplication.</p><h3>Introducing fabricsdk</h3><p>I spent time abstracting all of this into a single reusable Go package:</p><pre>go get github.com/muhammadtalha198/fabricsdk</pre><p>Here is the exact same setup, rewritten:</p><pre>cfg := fabricsdk.Config{<br>    PeerEndpoint:     &quot;localhost:7051&quot;,<br>    PeerHostOverride: &quot;peer0.org1.example.com&quot;,<br>    TLSCertPath:      &quot;/path/to/peer-tls-ca.pem&quot;,<br>    CertPath:         &quot;/path/to/msp/signcerts&quot;,<br>    KeyPath:          &quot;/path/to/msp/keystore&quot;,<br>    MSPID:            &quot;Org1MSP&quot;,<br>    ChannelName:      &quot;mychannel&quot;,<br>    ChaincodeName:    &quot;mychaincode&quot;,<br>}</pre><pre>fc, err := fabricsdk.New(cfg)<br>if err != nil { log.Fatal(err) }<br>defer fc.Close()</pre><pre>ctx := context.Background()</pre><pre>// Read — no ledger write<br>raw, err := fc.Evaluate(ctx, &quot;GetAsset&quot;, &quot;asset-1&quot;)</pre><pre>// Write — endorse, submit, wait for commit, return txID<br>txID, err := fc.Submit(ctx, &quot;CreateAsset&quot;, string(jsonBytes))</pre><p>That is the entire setup. No manual gRPC wiring. No TLS pool construction. No proto digging.</p><h3>How it maps to ethers.js</h3><p>The concepts translate directly. JsonRpcProvider becomes your Config.PeerEndpoint. Your Wallet private key becomes Config.CertPath and Config.KeyPath — the x509 identity Fabric uses instead of a raw private key. new Contract(address, abi, signer) becomes fabricsdk.New(cfg).</p><p>Reading with token.balanceOf(addr) becomes fc.Evaluate(ctx, &quot;balanceOf&quot;, addr). Writing with token.transfer(to, amt) becomes fc.Submit(ctx, &quot;transfer&quot;, to, amt). The transaction hash is the txID string returned by Submit. And await tx.wait() is already built into Submit — it blocks until the block is committed before returning.</p><p>One thing that is actually simpler than ethers.js: <strong>no ABI file needed</strong>. In Ethereum you need a JSON ABI to describe what functions exist on a contract. In Fabric, chaincode functions are called by name string directly. fc.Submit(&quot;AnyFunctionName&quot;, arg1, arg2) works for any chaincode deployed now or in the future, with zero SDK changes.</p><h3>What else the SDK handles</h3><p><strong>Per-call identity override</strong></p><p>Fabric is permission-based — different org members sign different transactions. The SDK supports this without opening a new TCP connection:</p><pre>// Default identity (from Config)<br>txID, err := fc.Submit(ctx, &quot;CreateAsset&quot;, payload)</pre><pre>// Admin identity for a single call — same gRPC connection, different signer<br>txID, err = fc.WithIdentity(&quot;/admin/signcerts&quot;, &quot;/admin/keystore&quot;).<br>    Submit(ctx, &quot;DeleteAsset&quot;, &quot;asset-1&quot;)</pre><p>This is equivalent to token.connect(adminSigner) in ethers.js.</p><p><strong>Structured errors — no string parsing</strong></p><p>The official SDK buries the real chaincode error message inside nested gRPC status details. The SDK extracts it and returns a typed error with an HTTP-style status code:</p><pre>txID, err := fc.Submit(ctx, &quot;CreateAsset&quot;, payload)</pre><pre>if fabricsdk.IsNotFound(err)     { /* 404 */ }<br>if fabricsdk.IsConflict(err)     { /* 409 — optimistic lock, re-read and retry */ }<br>if fabricsdk.IsUnauthorized(err) { /* 403 */ }</pre><pre>var fabErr *fabricsdk.Error<br>if errors.As(err, &amp;fabErr) {<br>    http.Error(w, fabErr.Message, fabErr.Code) // forward directly to API handler<br>}</pre><p><strong>Chaincode event streaming</strong></p><pre>ctx, cancel := context.WithCancel(context.Background())<br>defer cancel()</pre><pre>events, err := fc.Events(ctx)<br>for ev := range events {<br>    fmt.Printf(&quot;event=%s txID=%s payload=%s\n&quot;,<br>        ev.EventName, ev.TxID, ev.Payload)<br>}</pre><pre>// Replay from a known block after a restart<br>events, err = fc.EventsFrom(ctx, lastKnownBlock)</pre><p><strong>Dynamic multi-chaincode calls</strong></p><p>When you need to call multiple chaincodes from one connection without reconfiguring:</p><pre>dyn := fc.Dynamic()</pre><pre>raw,  err := dyn.Evaluate(ctx, &quot;channelA&quot;, &quot;ccA&quot;, &quot;ContractA&quot;, &quot;GetAsset&quot;, &quot;id-1&quot;)<br>txID, err := dyn.Submit(ctx, &quot;channelB&quot;, &quot;ccB&quot;, &quot;ContractB&quot;, &quot;CreateAsset&quot;, payload)</pre><p><strong>Pluggable logger</strong></p><pre>type zapAdapter struct{ l *zap.SugaredLogger }<br>func (a *zapAdapter) Info(msg string, kv ...any)  { a.l.Infow(msg, kv...) }<br>func (a *zapAdapter) Error(msg string, kv ...any) { a.l.Errorw(msg, kv...) }</pre><pre>cfg.Logger = &amp;zapAdapter{l: logger.Sugar()}</pre><h3>The recommended pattern: thin typed wrappers</h3><p>For production applications, build a small domain-specific wrapper on top of the generic SDK. This is the same typed-wrappers pattern you’d use with ethers.js and TypeScript:</p><pre>// internal/asset/client.go<br>package asset</pre><pre>type Client struct{ fc *fabricsdk.FabricClient }</pre><pre>func NewClient(fc *fabricsdk.FabricClient) *Client { return &amp;Client{fc} }</pre><pre>func (c *Client) Create(req CreateRequest) (string, error) {<br>    b, _ := json.Marshal(req)<br>    return c.fc.Submit(context.Background(), &quot;CreateAsset&quot;, string(b))<br>}</pre><pre>func (c *Client) Get(id string) (*Asset, error) {<br>    raw, err := c.fc.Evaluate(context.Background(), &quot;GetAsset&quot;, id)<br>    if err != nil { return nil, err }<br>    var a Asset<br>    json.Unmarshal(raw, &amp;a)<br>    return &amp;a, nil<br>}</pre><p>A new chaincode becomes one small wrapper file. The connection, identity, and error handling code never gets touched again.</p><h3>The numbers</h3><p>Before the SDK, connecting and calling one chaincode function required roughly 60 lines for setup and 20 lines per function. With fabricsdk, setup is 10 lines and each function is 3–4 lines. Error classification that previously needed manual gRPC proto inspection is now a single predicate call. Identity overrides that previously required rebuilding the entire gateway are now one chained method.</p><h3>Get it</h3><pre>go get github.com/muhammadtalha198/fabricsdk</pre><p>Full documentation: <a href="https://pkg.go.dev/github.com/muhammadtalha198/fabricsdk">https://pkg.go.dev/github.com/muhammadtalha198/fabricsdk</a></p><p>GitHub: <a href="https://github.com/muhammadtalha198/fabricsdk">https://github.com/muhammadtalha198/fabricsdk</a></p><p>MIT licensed. Requires Go 1.21+.</p><p>Issues, feedback, and PRs are welcome. If you’re building on Hyperledger Fabric and have spent time copying the same gRPC boilerplate between services — this was built for exactly that problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91064525a5a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/i-built-an-ethers-js-style-sdk-for-hyperledger-fabric-in-go-91064525a5a0">I Built an ethers.js-Style SDK for Hyperledger Fabric in Go</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>