<?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 Kyrylo Sotnykov on Medium]]></title>
        <description><![CDATA[Stories by Kyrylo Sotnykov on Medium]]></description>
        <link>https://medium.com/@comicon2508?source=rss-aabf52d06cc5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IMFn4hXSbizf2Op3-n1Lgw.jpeg</url>
            <title>Stories by Kyrylo Sotnykov on Medium</title>
            <link>https://medium.com/@comicon2508?source=rss-aabf52d06cc5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:23:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@comicon2508/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Sign and Verify Documents in JavaScript with Ed25519]]></title>
            <link>https://levelup.gitconnected.com/how-to-sign-and-verify-documents-in-javascript-with-ed25519-4faa22f65bc1?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4faa22f65bc1</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 17:22:11 GMT</pubDate>
            <atom:updated>2026-08-28T17:22:11.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Rfr58XQEnBdXua3HpVytQ.png" /></figure><p>When an application generates a certificate, invoice, report, contract, or any other digital document, storing the file is only half of the problem. The other half is proving that the document has not been changed after it was issued.</p><p>A filename cannot prove that. A URL cannot prove that either. HTTPS protects data while it travels between systems, but it does not independently prove that a file is still identical to the version that was originally issued.</p><p>This is where cryptographic digital signatures become useful.</p><p>A digital signature allows an application to create mathematical proof that a particular piece of data was signed using a private key. Anyone with the corresponding public key can later verify that proof without having access to the private key.</p><h3>The Basic Signing Model</h3><p>An asymmetric signature system uses two keys:</p><pre>Private Key → creates signatures<br>Public Key  → verifies signatures</pre><p>The private key must remain secret. The public key can be distributed to clients, partners, auditors, or anyone else who needs to verify documents.</p><p>For example, using the <a href="https://www.npmjs.com/package/sign-proof">sign-proof</a> npm package:</p><pre>import {<br>    generateKeyPair,<br>    signData,<br>    verifyData,<br>} from &#39;sign-proof&#39;;<br><br>const {<br>    publicKey,<br>    privateKey,<br>} = generateKeyPair();</pre><p>The private key can now be used to sign a payload:</p><pre>const document = {<br>    id: &#39;CERT-2026-001&#39;,<br>    recipient: &#39;Alice Johnson&#39;,<br>};<br><br>const proof = signData(<br>    document,<br>    privateKey,<br>);</pre><p>The resulting proof can be stored alongside the original document:</p><pre>const signedDocument = {<br>    payload: document,<br>    proof,<br>};</pre><p>Verification only requires the public key:</p><pre>const valid = verifyData(<br>    signedDocument,<br>    publicKey,<br>);<br>console.log(valid);</pre><p>If the payload has not changed and the signature was created by the corresponding private key, verification succeeds.</p><h3>Why Hash the Document Before Signing?</h3><p>A useful signing architecture does not necessarily sign the complete payload representation directly. Instead, it can first create a cryptographic hash of the content and sign that result.</p><p>The flow looks like this:</p><pre>Document<br>   ↓<br>SHA-256<br>   ↓<br>Hash<br>   ↓<br>Ed25519<br>   ↓<br>Signature</pre><p>SHA-256 produces a fixed-size digest regardless of the size of the original input. Whether the source is a small JSON object or a large PDF file, the result is always a 256-bit hash.</p><p>The hash becomes a fingerprint of the content.</p><p>If the original document changes by even one byte, its SHA-256 value changes as well. That causes signature verification to fail.</p><p>For example, imagine that a document originally contains:</p><pre>Amount: $10,000</pre><p>and someone modifies it to:</p><pre>Amount: $100,000</pre><p>The modified document produces a different hash. Because the original digital signature was generated from the original hash, the existing signature no longer validates.</p><h3>Why a Hash Alone Is Not Enough</h3><p>At first, it might seem that publishing a SHA-256 hash would be sufficient.</p><p>For example:</p><pre>import { hashData } from &#39;sign-proof&#39;;<br><br>const hash = hashData(document);</pre><p>The problem is that hashes provide integrity only when the expected hash itself is trusted.</p><p>If an attacker can replace both the document and its stored hash, they can simply compute a new SHA-256 value for the modified document.</p><p>A digital signature prevents that.</p><p>An attacker can compute:</p><pre>SHA256(modifiedDocument)</pre><p>but cannot create:</p><pre>Ed25519Sign(<br>    SHA256(modifiedDocument),<br>    issuerPrivateKey<br>)</pre><p>without possessing the issuer’s private key.</p><p>This is why hashing and asymmetric signatures complement each other. SHA-256 provides a stable fingerprint of the content, while Ed25519 proves that the fingerprint was approved by the holder of the private key.</p><h3>Verifying Real Documents</h3><p>The same approach works for actual files.</p><p>In Node.js:</p><pre>import fs from &#39;fs&#39;;<br><br>const file = fs.readFileSync(<br>    &#39;./certificate.pdf&#39;,<br>);<br>const proof = signData(<br>    file,<br>    privateKey,<br>);</pre><p>Later:</p><pre>const valid = verifyData(<br>    {<br>        payload: file,<br>        proof,<br>    },<br>    publicKey,<br>);</pre><p>If someone edits the PDF after it was signed, the file bytes change, the SHA-256 digest changes, and verification fails.</p><p>This pattern is useful for certificates, invoices, generated reports, audit documents, exported datasets, configuration files, build artifacts, and many other types of content.</p><h3>Signatures and Encryption Are Different</h3><p>Digital signatures are sometimes confused with encryption, but they solve different problems.</p><p>Encryption answers:</p><blockquote><em>Who is allowed to read this data?</em></blockquote><p>Digital signatures answer:</p><blockquote><em>Who signed this data, and has it changed since then?</em></blockquote><p>A document can therefore be signed without being encrypted. This is often exactly what you want for certificates or public documents: anyone can view the content, but anyone can also verify that it is authentic.</p><h3>A Practical Architecture</h3><p>A document verification system might store the original file in S3, IPFS, a database, or a CDN. The cryptographic proof does not need to depend on the storage location.</p><p>Conceptually:</p><pre>                 Public Key<br>                     │<br>                     ▼<br>Document → SHA-256 → Ed25519 Verification<br>                     │<br>                Valid / Invalid</pre><p>The storage layer answers:</p><blockquote><em>Where can I retrieve this document?</em></blockquote><p>The signature answers:</p><blockquote><em>Can I trust that this is still the document that was signed?</em></blockquote><p>Separating those two responsibilities is useful because a file can move between storage providers without changing its cryptographic identity.</p><h3>Installing sign-proof</h3><p>The library is available on npm:</p><pre>npm install sign-proof</pre><p>A minimal example looks like this:</p><pre>import {<br>    generateKeyPair,<br>    signData,<br>    verifyData,<br>} from &#39;sign-proof&#39;;<br><br>const {<br>    publicKey,<br>    privateKey,<br>} = generateKeyPair();<br>const payload = {<br>    id: &#39;DOC-001&#39;,<br>    owner: &#39;Alice&#39;,<br>};<br>const proof = signData(<br>    payload,<br>    privateKey,<br>);<br>const valid = verifyData(<br>    {<br>        payload,<br>        proof,<br>    },<br>    publicKey,<br>);<br>console.log(valid);</pre><p>The API can be used with structured JSON data, text, Buffers, and binary Uint8Array values.</p><h3>Final Thoughts</h3><p>Digital document verification does not need to be complicated. The core model is simple: hash the content, sign that cryptographic fingerprint with a private key, and allow anyone with the public key to verify it later.</p><p>The important part is ensuring that the exact same logical content produces the same signing representation and that binary files are handled as bytes rather than being accidentally transformed into text.</p><p>Those details are where signing systems often become unreliable.</p><p>In the next article in this series, I will focus on one of the most subtle problems in signing structured data: why two equivalent JavaScript objects can generate different signatures, and how canonical JSON serialization solves it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4faa22f65bc1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-sign-and-verify-documents-in-javascript-with-ed25519-4faa22f65bc1">How to Sign and Verify Documents in JavaScript with Ed25519</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why JSON.stringify Can Break Digital Signatures — and How Canonical JSON Fixes It]]></title>
            <link>https://medium.com/it-chronicles/why-json-stringify-can-break-digital-signatures-and-how-canonical-json-fixes-it-0cc8cac15d21?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cc8cac15d21</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 07:44:43 GMT</pubDate>
            <atom:updated>2026-08-24T07:44:43.666Z</atom:updated>
            <content:encoded><![CDATA[<h4>JavaScript Cryptography</h4><h4>Deterministic JSON serialization is essential when signing structured data in JavaScript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrKHtqorutBFHgFr98mPsA.png" /><figcaption>AI-generated illustration created by the author with ChatGPT</figcaption></figure><p>Digital signatures are extremely sensitive to input.</p><p>If a single byte changes, the resulting hash changes. If the hash changes, the signature no longer verifies.</p><p>That is exactly what we want when protecting a document from modification. But it creates an interesting problem when the thing being signed is not a file, but a JavaScript object.</p><p>Consider these two objects:</p><pre>const first = {<br>    name: &#39;Alice&#39;,<br>    age: 30,<br>};<br><br>const second = {<br>    age: 30,<br>    name: &#39;Alice&#39;,<br>};</pre><p>From an application’s perspective, they contain the same information.</p><p>But:</p><pre>JSON.stringify(first);</pre><p>produces:</p><pre>{&quot;name&quot;:&quot;Alice&quot;,&quot;age&quot;:30}</pre><p>while:</p><pre>JSON.stringify(second);</pre><p>produces:</p><pre>{&quot;age&quot;:30,&quot;name&quot;:&quot;Alice&quot;}</pre><p>Those strings are different.</p><p>For normal application logic, this usually does not matter. For cryptography, it matters a lot.</p><h3>Cryptography Works with Bytes, Not Meaning</h3><p>A signature algorithm does not understand that:</p><pre>{<br>    name: &#39;Alice&#39;,<br>    age: 30,<br>}</pre><p>and:</p><pre>{<br>    age: 30,<br>    name: &#39;Alice&#39;,<br>}</pre><p>represent the same logical object.</p><p>It sees two different byte sequences.</p><p>If those sequences are hashed:</p><pre>JSON #1 → SHA-256 → Hash A<br>JSON #2 → SHA-256 → Hash B</pre><p>the hashes differ.</p><p>That means a signature created for the first representation cannot be verified against the second.</p><p>This creates an unpleasant failure mode in real systems.</p><p>A JSON payload may be signed by one service, stored in a database, reconstructed by another application, passed through an API, and then serialized again later. The key order may change even though the actual values remain identical.</p><p>Without deterministic serialization, verification can fail for perfectly valid data.</p><h3>Canonical JSON</h3><p>The solution is to transform structured data into a deterministic representation before hashing it.</p><p>This process is often referred to as canonicalization.</p><p>For example, both of these objects:</p><pre>const first = {<br>    name: &#39;Alice&#39;,<br>    age: 30,<br>};</pre><p>and:</p><pre>const second = {<br>    age: 30,<br>    name: &#39;Alice&#39;,<br>};</pre><p>can be normalized into:</p><pre>{&quot;age&quot;:30,&quot;name&quot;:&quot;Alice&quot;}</pre><p>before hashing.</p><p>Now:</p><pre>Object A<br>   ↓<br>Canonical JSON<br>   ↓<br>SHA-256<br>   ↓<br>Hash X</pre><p>and:</p><pre>Object B<br>   ↓<br>Canonical JSON<br>   ↓<br>SHA-256<br>   ↓<br>Hash X</pre><p>produce the same result.</p><p>The signature is now tied to the actual content rather than to incidental property insertion order.</p><h3>A Simple Canonicalization Function</h3><p>A lightweight implementation can recursively sort object keys while preserving array order.</p><p>For example:</p><pre>export const canonicalize = (<br>    value: unknown,<br>): string =&gt; {<br>    if (value === null) {<br>        return &#39;null&#39;;<br>    }<br>    switch (typeof value) {<br>        case &#39;string&#39;:<br>            return JSON.stringify(value);<br>        case &#39;boolean&#39;:<br>            return value<br>                ? &#39;true&#39;<br>                : &#39;false&#39;;<br>        case &#39;number&#39;:<br>            if (!Number.isFinite(value)) {<br>                throw new TypeError(<br>                    &#39;Cannot canonicalize NaN or Infinity&#39;,<br>                );<br>            }<br>            return JSON.stringify(value);<br>        case &#39;object&#39;: {<br>            if (Array.isArray(value)) {<br>                return `[${value<br>                    .map(canonicalize)<br>                    .join(&#39;,&#39;)}]`;<br>            }<br>            const object =<br>                value as Record&lt;<br>                    string,<br>                    unknown<br>                &gt;;<br>            const keys = Object.keys(object)<br>                .filter(<br>                    (key) =&gt;<br>                        object[key] !== undefined,<br>                )<br>                .sort();<br>            return `{${keys<br>                .map(<br>                    (key) =&gt;<br>                        `${JSON.stringify(<br>                            key,<br>                        )}:${canonicalize(<br>                            object[key],<br>                        )}`,<br>                )<br>                .join(&#39;,&#39;)}}`;<br>        }<br>        default:<br>            throw new TypeError(<br>                `Cannot canonicalize ${typeof value}`,<br>            );<br>    }<br>};</pre><p>The important property is determinism.</p><p>Calling:</p><pre>canonicalize({<br>    name: &#39;Alice&#39;,<br>    age: 30,<br>});</pre><p>and:</p><pre>canonicalize({<br>    age: 30,<br>    name: &#39;Alice&#39;,<br>});</pre><p>returns exactly the same string.</p><h3>Arrays Are Different</h3><p>Object key order generally should not matter.</p><p>Array order usually should.</p><p>These values:</p><pre>[1, 2, 3]</pre><p>and:</p><pre>[3, 2, 1]</pre><p>are normally different data structures.</p><p>Therefore canonicalization should preserve array order:</p><pre>canonicalize([1, 2, 3]);</pre><p>must not equal:</p><pre>canonicalize([3, 2, 1]);</pre><p>This distinction is important because canonicalization should remove irrelevant representation differences without changing the meaning of the data.</p><h3>Canonicalization Before Hashing</h3><p>Once canonical serialization exists, the signing pipeline becomes much more predictable:</p><pre>JavaScript Object<br>       ↓<br>Canonical JSON<br>       ↓<br>SHA-256<br>       ↓<br>Hash<br>       ↓<br>Ed25519 Signature</pre><p>The verifier performs the exact same steps:</p><pre>Received Object<br>       ↓<br>Canonical JSON<br>       ↓<br>SHA-256<br>       ↓<br>Signature Verification</pre><p>This is the approach now used in <a href="https://www.npmjs.com/package/sign-proof">sign-proof</a>.</p><p>For structured objects, data is canonicalized before hashing so that property insertion order does not accidentally invalidate otherwise equivalent signed data.</p><h3>Example with sign-proof</h3><p>Suppose we sign:</p><pre>const original = {<br>    id: &#39;CERT-001&#39;,<br>    recipient: &#39;Alice&#39;,<br>    score: 98,<br>};<br><br>const proof = signData(<br>    original,<br>    privateKey,<br>);</pre><p>Later, the same data arrives from another service:</p><pre>const received = {<br>    score: 98,<br>    recipient: &#39;Alice&#39;,<br>    id: &#39;CERT-001&#39;,<br>};</pre><p>Because both objects are converted to the same canonical representation before hashing, verification can still succeed:</p><pre>const valid = verifyData(<br>    {<br>        payload: received,<br>        proof,<br>    },<br>    publicKey,<br>);</pre><p>The important point is that the object key order changed, but the logical data did not.</p><h3>Why This Matters Across Services</h3><p>This problem becomes more important as systems become distributed.</p><p>A payload may travel through:</p><ul><li>REST APIs;</li><li>queues;</li><li>databases;</li><li>serverless functions;</li><li>browser clients;</li><li>microservices;</li><li>event streams;</li><li>different programming languages.</li></ul><p>Each system may reconstruct objects slightly differently.</p><p>If a signature depends on an arbitrary serialization order, the format becomes fragile.</p><p>A deterministic representation makes the signing protocol much more stable.</p><h3>Canonicalization Becomes Part of the Protocol</h3><p>There is a broader lesson here.</p><p>When you cryptographically sign structured data, serialization is no longer just an implementation detail.</p><p>It becomes part of the protocol.</p><p>A verifier must know exactly how the original signer represented the data before hashing it. If the two systems use different representations, verification fails even if the underlying values are identical.</p><p>That means a signing system should clearly define:</p><ul><li>how object keys are ordered;</li><li>how strings are escaped;</li><li>how numbers are represented;</li><li>how null is handled;</li><li>what happens with undefined;</li><li>how arrays are serialized.</li></ul><p>For interoperability between completely independent systems or programming languages, using a formal canonical JSON specification such as JCS/RFC 8785 is often worth considering.</p><p>For application-level signing inside one ecosystem, even a smaller deterministic serializer can already eliminate many common problems.</p><h3>Final Thoughts</h3><p>Digital signatures are deterministic mathematical operations, but JavaScript objects are not inherently canonical byte sequences.</p><p>That gap is easy to overlook.</p><p>Simply calling JSON.stringify() may appear to work until signed objects are reconstructed in a different order somewhere else in the system.</p><p>Canonical JSON serialization solves that by ensuring equivalent structured data is converted into the same deterministic representation before hashing.</p><p>For any system that signs JSON payloads, certificates, API messages, metadata, or structured records, serialization should be treated as part of the cryptographic design rather than an afterthought.</p><p>The next article in this series covers the other side of the problem: safely signing real binary files such as PDFs and images without accidentally converting their bytes through UTF-8.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cc8cac15d21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/it-chronicles/why-json-stringify-can-break-digital-signatures-and-how-canonical-json-fixes-it-0cc8cac15d21">Why JSON.stringify Can Break Digital Signatures — and How Canonical JSON Fixes It</a> was originally published in <a href="https://medium.com/it-chronicles">IT Chronicles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EIP-712 Explained: Sign and Verify Typed Data with ethers.js and Solidity]]></title>
            <link>https://medium.com/coinmonks/eip-712-explained-sign-and-verify-typed-data-with-ethers-js-and-solidity-ae48d94eddaf?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae48d94eddaf</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 16:43:16 GMT</pubDate>
            <atom:updated>2026-08-17T16:43:16.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5zdyXk1P0II7JWQCpYcUeQ.png" /></figure><p>Imagine your application wants a user to authorize an off-chain action:</p><pre>Transfer 100 USDC<br>to 0x...<br>nonce 42<br>deadline ...</pre><p>You could serialize that data into a string and ask the wallet to sign it. But then subtle questions appear: Which serialization is canonical? Is 100 a string or an integer? Which contract is allowed to consume the signature? Can the same signature work on another chain?</p><p><strong>EIP-712</strong> solves the encoding side of this problem by defining a deterministic way to hash and sign typed structured data. Instead of signing arbitrary JSON text, the wallet signs a digest derived from explicit Solidity-like types, the message, and an application-specific domain.</p><p>That makes EIP-712 particularly useful for permits, meta-transactions, order protocols, delegated actions, and other off-chain authorizations that are later verified on-chain.</p><h3>Why signing plain strings is not enough</h3><p>Ethereum wallets can sign arbitrary messages using mechanisms such as personal_sign. This works well when the thing being signed really is a human-readable message.</p><p>Structured application data is different.</p><p>Suppose two applications serialize this object differently:</p><pre>{&quot;to&quot;:&quot;0x...&quot;,&quot;amount&quot;:&quot;100&quot;}</pre><p>and:</p><pre>{<br>  &quot;amount&quot;: &quot;100&quot;,<br>  &quot;to&quot;: &quot;0x...&quot;<br>}</pre><p>They may represent the same intent to a developer, but they are different byte strings.</p><p>Plain message signing also does not inherently describe Solidity types. A wallet sees bytes or text rather than an explicit structure such as address to, uint256 amount, and uint256 nonce.</p><p>EIP-712 defines a typed encoding and hashing scheme instead. Wallets can use that structure to present meaningful fields to the user rather than an opaque serialized blob.</p><h3>EIP-712 Explained: Domain, Types, and Message</h3><p>Consider a transfer authorization:</p><pre>const domain = {<br>  name: &quot;ExampleApp&quot;,<br>  version: &quot;1&quot;,<br>  chainId: 1,<br>  verifyingContract: &quot;0x1234567890123456789012345678901234567890&quot;,<br>};<br>const types = {<br>  Transfer: [<br>    { name: &quot;to&quot;, type: &quot;address&quot; },<br>    { name: &quot;amount&quot;, type: &quot;uint256&quot; },<br>    { name: &quot;nonce&quot;, type: &quot;uint256&quot; },<br>    { name: &quot;deadline&quot;, type: &quot;uint256&quot; },<br>  ],<br>};<br>const value = {<br>  to,<br>  amount,<br>  nonce,<br>  deadline,<br>};</pre><p>There are four important pieces.</p><p><strong>Domain</strong> identifies the application context in which the signature is valid.</p><p><strong>Types</strong> define the exact structure and Solidity-compatible types being signed.</p><p><strong>Primary type</strong> is the root structure — Transfer in this example.</p><p><strong>Message</strong> is the actual set of values.</p><p>The domain is what gives EIP-712 its <strong>domain separation</strong>. Two applications can sign structurally identical Transfer messages without necessarily producing interchangeable signatures.</p><p>For production authorizations, two domain fields are especially important:</p><pre>chainId<br>verifyingContract</pre><p>chainId binds the signature to a network, while verifyingContract binds it to a particular contract address. Both become part of the EIP-712 domain separator and therefore affect the final digest.</p><p>Without appropriate domain separation, a signature intended for one context may be meaningful in another.</p><h3>How the EIP-712 Hash Is Built</h3><p>EIP-712 does not sign your JavaScript object or its JSON serialization.</p><p>Conceptually, the final digest is:</p><pre>keccak256(<br>  0x1901 ||<br>  domainSeparator ||<br>  hashStruct(message)<br>)</pre><p>The 0x1901 prefix comes from the signed-data encoding scheme used by EIP-712.</p><p>For our Transfer structure, its encoded type is effectively:</p><pre>Transfer(address to,uint256 amount,uint256 nonce,uint256 deadline)</pre><p>Hashing this definition produces the typeHash:</p><pre>keccak256(<br>  &quot;Transfer(address to,uint256 amount,uint256 nonce,uint256 deadline)&quot;<br>)</pre><p>The message’s structHash is then calculated from the type hash and encoded field values.</p><p>Conceptually:</p><pre>keccak256(<br>    abi.encode(<br>        TRANSFER_TYPEHASH,<br>        to,<br>        amount,<br>        nonce,<br>        deadline<br>    )<br>)</pre><p>The domain is hashed using the same EIP-712 struct-hashing rules to produce the domain separator. Finally, the message struct hash and domain separator are combined into one digest.</p><p>This digest — not JSON.stringify(value) — is what ultimately gets signed.</p><p>That distinction is the reason JavaScript and Solidity can independently reconstruct exactly the same value.</p><p>At this point, the full EIP-712 flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*0uZIUXvWIDyzSLFy" /></figure><h3>Signing EIP-712 Typed Data in JavaScript</h3><p>With ethers v6, the high-level API is signer.signTypedData(domain, types, value). ethers handles the EIP-712 encoding and hashing internally.</p><p>A browser example can stay compact:</p><pre>import { BrowserProvider } from &quot;ethers&quot;;<br><br>const provider = new BrowserProvider(window.ethereum);<br>const signer = await provider.getSigner();<br>const chainId = (await provider.getNetwork()).chainId;<br>const domain = {<br>  name: &quot;ExampleApp&quot;,<br>  version: &quot;1&quot;,<br>  chainId,<br>  verifyingContract: &quot;0x1234567890123456789012345678901234567890&quot;,<br>};<br>const types = {<br>  Transfer: [<br>    { name: &quot;to&quot;, type: &quot;address&quot; },<br>    { name: &quot;amount&quot;, type: &quot;uint256&quot; },<br>    { name: &quot;nonce&quot;, type: &quot;uint256&quot; },<br>    { name: &quot;deadline&quot;, type: &quot;uint256&quot; },<br>  ],<br>};<br>const value = {<br>  to: &quot;0x0000000000000000000000000000000000000000&quot;,<br>  amount: 100_000_000n, // 100 USDC with 6 decimals<br>  nonce: 42n,<br>  deadline: BigInt(Math.floor(Date.now() / 1000) + 3600),<br>};<br>const signature = await signer.signTypedData(<br>  domain,<br>  types,<br>  value<br>);</pre><p>Notice that the frontend does not manually hash individual fields. That is intentional.</p><p>Unless you are implementing infrastructure specifically around EIP-712 encoding, use the library implementation instead of recreating the algorithm yourself.</p><p>The important part is that <strong>the frontend schema must exactly match the Solidity schema</strong>.</p><h3>Verifying an EIP-712 Signature in Solidity</h3><p>On-chain, OpenZeppelin’s EIP712 contract reconstructs the domain-aware digest, while ECDSA performs signer recovery. OpenZeppelin explicitly documents the _hashTypedDataV4(structHash) plus ECDSA.recover pattern.</p><p>Here is the Solidity side of the same example:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.20;<br><br>import {EIP712} from<br>    &quot;@openzeppelin/contracts/utils/cryptography/EIP712.sol&quot;;<br>import {ECDSA} from<br>    &quot;@openzeppelin/contracts/utils/cryptography/ECDSA.sol&quot;;<br>contract TransferAuthorizer is EIP712 {<br>    struct Transfer {<br>        address to;<br>        uint256 amount;<br>        uint256 nonce;<br>        uint256 deadline;<br>    }<br>    bytes32 private constant TRANSFER_TYPEHASH =<br>        keccak256(<br>            &quot;Transfer(address to,uint256 amount,uint256 nonce,uint256 deadline)&quot;<br>        );<br>    mapping(address =&gt; mapping(uint256 =&gt; bool))<br>        public usedNonces;<br>    constructor() EIP712(&quot;ExampleApp&quot;, &quot;1&quot;) {}<br>    function authorizeTransfer(<br>        address expectedSigner,<br>        Transfer calldata transfer,<br>        bytes calldata signature<br>    ) external {<br>        require(<br>            block.timestamp &lt;= transfer.deadline,<br>            &quot;Authorization expired&quot;<br>        );<br>        require(<br>            !usedNonces[expectedSigner][transfer.nonce],<br>            &quot;Nonce already used&quot;<br>        );<br>        bytes32 structHash = keccak256(<br>            abi.encode(<br>                TRANSFER_TYPEHASH,<br>                transfer.to,<br>                transfer.amount,<br>                transfer.nonce,<br>                transfer.deadline<br>            )<br>        );<br>        bytes32 digest = _hashTypedDataV4(structHash);<br>        address recoveredSigner =<br>            ECDSA.recover(digest, signature);<br>        require(<br>            recoveredSigner == expectedSigner,<br>            &quot;Invalid signature&quot;<br>        );<br>        usedNonces[expectedSigner][transfer.nonce] = true;<br>        // Execute the authorized business operation here.<br>    }<br>}</pre><p>_hashTypedDataV4 combines the message struct hash with the contract&#39;s EIP-712 domain separator and produces the final digest expected by the signature verification logic.</p><p>Using OpenZeppelin is preferable to manually maintaining EIP-712 domain and ECDSA recovery code. Apart from reducing code, it avoids subtle mistakes around domain construction and signature handling.</p><p>One additional production nuance: ECDSA.recover verifies signatures from EOAs. If your application must support smart contract wallets, account abstraction, or multisigs, you should also account for ERC-1271-style contract signatures rather than assuming every signer has an ECDSA private key.</p><h3>EIP-712 Does Not Prevent Replays for You</h3><p>EIP-712 gives you deterministic structured signing and domain separation. It does <strong>not</strong> automatically make an authorization single-use.</p><p>Consider this perfectly valid signature:</p><pre>Alice authorizes transfer X</pre><p>If the contract accepts it today and nothing in contract state marks it as consumed, an attacker may simply submit the same authorization again.</p><p>That is why production messages commonly contain a nonce:</p><pre>uint256 nonce;</pre><p>and the contract consumes it:</p><pre>mapping(address =&gt; mapping(uint256 =&gt; bool))<br>    public usedNonces;</pre><p>A deadline prevents an authorization from remaining usable indefinitely.</p><p>Meanwhile, chainId and verifyingContract provide domain-level protection against signatures being reused in different EIP-712 domains.</p><p>These controls solve related but different problems:</p><pre>nonce              -&gt; prevents repeated execution<br>deadline           -&gt; limits validity in time<br>chainId            -&gt; binds the domain to a chain<br>verifyingContract  -&gt; binds the domain to a contract</pre><p>The core rule is simple:</p><blockquote><strong><em>A valid signature is not necessarily a valid authorization forever.</em></strong></blockquote><p>Signature verification proves who signed a digest. Your contract still decides whether that authorization is currently acceptable.</p><h3>Common EIP-712 Mistakes in Production</h3><p>Most EIP-712 bugs are not cryptography bugs. They are schema or authorization bugs.</p><p><strong>1. Different field order between frontend and Solidity.</strong><br>Transfer(address to,uint256 amount,...) must match exactly on both sides.</p><p><strong>2. Type mismatches.</strong><br>uint256, address, bytes32, and string are not interchangeable representations.</p><p><strong>3. Different domain name or version.</strong><br>ExampleApp version 1 and ExampleApp version 2 intentionally produce different domains.</p><p><strong>4. Missing nonce.</strong><br>A correctly signed authorization may be replayable if contract state does not consume something unique.</p><p><strong>5. Missing deadline.</strong><br>Without expiration, an unused signature may remain actionable much longer than intended.</p><p><strong>6. Using </strong><strong>abi.encodePacked for the struct hash.</strong><br>The standard EIP-712 struct encoding corresponds to the ABI-encoded values; OpenZeppelin&#39;s documented pattern uses abi.encode.</p><p><strong>7. Incorrect domain assumptions around deployments or proxies.</strong><br>Your frontend must sign against the same effective EIP-712 domain the verification contract reconstructs. Contract addresses, chain changes, and domain-version changes should be treated as protocol changes, not frontend details.</p><h3>Conclusion</h3><p>EIP-712 turns Ethereum signatures from loosely defined byte-string signing into deterministic, typed, domain-separated authorization.</p><p>The flow is straightforward once the layers are separated:</p><pre>JavaScript object<br>    ↓<br>typed EIP-712 structure<br>    ↓<br>domain separator + struct hash<br>    ↓<br>EIP-712 digest<br>    ↓<br>wallet signature<br>    ↓<br>Solidity rebuilds digest<br>    ↓<br>recover signer<br>    ↓<br>apply nonce/deadline/business rules</pre><p>The standard handles <strong>how structured data becomes a signable digest</strong>. Your application still owns <strong>what that signature authorizes, when it expires, and whether it has already been used</strong>.</p><p>That separation is the key to implementing EIP-712 correctly in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae48d94eddaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/eip-712-explained-sign-and-verify-typed-data-with-ethers-js-and-solidity-ae48d94eddaf">EIP-712 Explained: Sign and Verify Typed Data with ethers.js and Solidity</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[Graceful Shutdown in Node.js: Express, Docker, Kubernetes, Databases, and Queues]]></title>
            <link>https://medium.com/engineering-playbook/graceful-shutdown-in-node-js-express-docker-kubernetes-databases-and-queues-3db079614315?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3db079614315</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 00:35:26 GMT</pubDate>
            <atom:updated>2026-08-24T02:02:43.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yZbO6RtlZlqgd8SSP8O0A.png" /></figure><p>A Kubernetes deployment begins replacing a pod. The kubelet starts the termination process and the Node.js process receives SIGTERM. The application immediately calls process.exit(0).</p><p>Three HTTP requests are still running. One is writing an upload, another has opened a PostgreSQL transaction, and a third has already called an external payment provider. A message consumer has received a job but has not acknowledged it. Telemetry is still buffered in memory.</p><p>The process disappears before any of that work finishes. The result can be a 502 or connection reset, an incomplete transaction, a corrupted upload, a redelivered job, duplicate side effects, missing traces, or an inconsistent application state.</p><p>A production-grade Node.js graceful shutdown is therefore not just a SIGTERM listener. It is a coordinated, deadline-bound protocol spanning traffic intake, active requests, background work, databases, Redis, queues, long-lived connections, telemetry, Docker, and Kubernetes.</p><pre>RUNNING → DRAINING → CLOSING_RESOURCES → STOPPED<br>ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ  ↘ deadline exceeded → FORCED_EXIT</pre><h3>What Graceful Shutdown Means</h3><p>Graceful shutdown is a bounded transition in which an application stops receiving new work, gives existing work a limited opportunity to finish, closes resources in dependency order, flushes essential telemetry, and exits with an appropriate status code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSxs9Dil8ICCqGKpylSuuw.png" /></figure><p>Graceful shutdown supports zero-downtime deployment, but it cannot guarantee it. Availability also depends on replica capacity, readiness propagation, load balancers, rolling-update settings, client retries, and idempotent business operations.</p><h3>Signals and Node.js Process Behavior</h3><p>SIGTERM is the normal cooperative termination signal in Docker and Kubernetes. SIGINT usually comes from Ctrl+C and should typically invoke the same coordinator. SIGHUP is often used for terminal disconnects or configuration reloads and should only trigger shutdown when that behavior is intentional.</p><p>Installing a signal listener changes the default behavior: the application becomes responsible for completing shutdown and allowing the event loop to become idle. A listener that only logs SIGTERM may leave the process alive until the orchestrator sends SIGKILL.</p><pre>process.once(&#39;SIGTERM&#39;, () =&gt; void shutdown(&#39;SIGTERM&#39;));<br>process.once(&#39;SIGINT&#39;, () =&gt; void shutdown(&#39;SIGINT&#39;));</pre><p>Do not put asynchronous cleanup in the exit event. At that point Node.js only permits synchronous work to complete reliably. beforeExit is also not a general shutdown hook: it is emitted when the event loop naturally becomes empty and is not guaranteed for explicit or fatal termination paths.</p><p>Avoid calling process.exit() immediately after SIGTERM. It can terminate active responses, pending writes, database operations, queue acknowledgements, and buffered logs. Prefer setting process.exitCode after cleanup and letting the event loop finish. Fatal startup or runtime failures should produce a nonzero code.</p><h3>Use a Shutdown State Machine</h3><p>A state machine makes the protocol observable and prevents duplicate cleanup when several signals or fatal handlers fire.</p><pre>type ShutdownState =<br>  | &#39;RUNNING&#39;<br>  | &#39;DRAINING&#39;<br>  | &#39;CLOSING_RESOURCES&#39;<br>  | &#39;STOPPED&#39;<br>  | &#39;FORCED_EXIT&#39;;</pre><p>The normal path moves from traffic draining to resource cleanup and finally to a stopped process. If the application exceeds its shutdown deadline, it transitions to the forced-exit path instead of waiting indefinitely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/0*vVhMNlrO7YTL1MG8" /><figcaption>Figure 1. Application-level shutdown states and the forced-exit path.</figcaption></figure><p>The shutdown entry point must be idempotent. The first call creates and stores a promise; later calls return the same promise. A second signal may be logged or used as an explicit escalation to forced exit, but it must not start the entire cleanup sequence again.</p><p><em>[Gist: </em><a href="https://gist.github.com/KirillSotnikov/760bc2a54be8fcd80328d1b6bd9dfd93#file-shutdown-coordinator-ts"><em>shutdown-coordinator.ts</em></a><em>] Full reusable TypeScript implementation with phases, priorities, hook timeouts, global timeout, error aggregation, signal handlers, and forced termination.</em></p><h3>HTTP Shutdown: Stop Intake, Then Drain</h3><p>For current Node.js LTS releases, server.close() stops accepting new connections and waits for active HTTP work to finish. Since Node.js 19 it also closes idle keep-alive connections before returning. server.closeIdleConnections() remains useful for libraries supporting older releases. server.closeAllConnections() forcefully closes active HTTP connections and should be reserved for the deadline path; it does not close upgraded WebSocket or HTTP/2 sessions.</p><pre>ready = false;<br>shuttingDown = true;<br><br>await closeHttpServer(server);   // wraps server.close()<br>await waitForActiveRequests();  // bounded by deadline<br><br>// Deadline fallback only:<br>server.closeAllConnections?.();</pre><p>Track both requests and sockets. Request tracking tells you which responses are still active. Socket tracking reveals idle keep-alive connections and gives you a final destruction mechanism. Do not destroy every socket at the beginning; that converts graceful drain into immediate termination.</p><pre>app.use((_req, res, next) =&gt; {<br>  activeResponses.add(res);<br>  const done = () =&gt; activeResponses.delete(res);<br>  res.once(&#39;finish&#39;, done);<br>  res.once(&#39;close&#39;, done);<br>  next();<br>});<br><br>server.on(&#39;connection&#39;, socket =&gt; {<br>  sockets.add(socket);<br>  socket.once(&#39;close&#39;, () =&gt; sockets.delete(socket));<br>});</pre><p>Every long-running operation should already have its own timeout. The pod termination deadline is the final safety boundary, not a replacement for request, upload, upstream, and database timeouts.</p><p><em>[Gist: </em><a href="https://gist.github.com/KirillSotnikov/760bc2a54be8fcd80328d1b6bd9dfd93#file-express-server-ts"><em>express-server.ts</em></a><em>] Complete Express server with health endpoints, request/socket tracking, keep-alive handling, deadline enforcement, and forced socket cleanup.</em></p><h3>Readiness, Liveness, and Startup</h3><p>A startup probe answers whether initialization has completed. A readiness probe answers whether the pod should receive service traffic. A liveness probe answers whether the process is stuck and should be restarted. These are different operational questions and should not share one overloaded endpoint.</p><pre>app.get(&#39;/health/live&#39;, (_req, res) =&gt;<br>  res.status(fatal ? 500 : 200).json({ alive: !fatal })<br>);<br><br>app.get(&#39;/health/ready&#39;, (_req, res) =&gt;<br>  res.status(ready ? 200 : 503).json({ ready })<br>);</pre><p>At shutdown start, readiness should fail immediately. Liveness should normally continue succeeding while the process intentionally drains. This removes the pod from normal routing without classifying expected termination as a crash.</p><p>Endpoint updates, proxies, ingress controllers, external load balancers, and existing client connections do not all change at the same instant. A small drain delay before closing the listener can be justified, but it must be measured and included in the same termination budget.</p><h3>Docker: Make Sure the Signal Reaches Node.js</h3><p>The main process inside a container runs as PID 1. Shell-form commands and wrapper processes can prevent Node.js from receiving signals directly. Use exec-form CMD or ENTRYPOINT and run node directly instead of hiding it behind npm start when possible.</p><pre>STOPSIGNAL SIGTERM<br>CMD [&quot;node&quot;, &quot;--enable-source-maps&quot;, &quot;dist/server.js&quot;]</pre><p>docker stop sends the configured stop signal and waits for its timeout. If the process remains alive, Docker uses SIGKILL. Configure the timeout to cover measured cleanup time. An init process such as Tini is useful when the application spawns children and needs signal forwarding and zombie reaping.</p><p><em>[Gist: </em><a href="https://gist.github.com/KirillSotnikov/760bc2a54be8fcd80328d1b6bd9dfd93#file-dockerfile"><em>Dockerfile</em></a><em>] Multi-stage production image using Node.js 24 LTS, a non-root runtime user, exec-form CMD, and STOPSIGNAL.</em></p><h3>Kubernetes Termination Is a Shared Deadline</h3><p>A simplified pod termination flow is: the pod is marked terminating, the grace-period countdown begins, preStop runs if configured, the container receives its stop signal, the application drains, and the runtime forcefully terminates anything still running when the deadline expires.</p><p>preStop does not provide extra time. The hook and application cleanup share terminationGracePeriodSeconds. A five-second sleep in preStop therefore reduces the time available to finish requests and close dependencies.</p><h4>Coordinated Shutdown Sequence</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K9MGs0nzNMjXw99Z" /><figcaption>Figure 2. Coordinated shutdown across Kubernetes, HTTP traffic, queues, PostgreSQL, Redis, and telemetry.</figcaption></figure><p>Do not model endpoint removal and SIGTERM as a perfect global sequence. Kubernetes components and external routing systems react concurrently. The application should fail readiness, reject new expensive work, stop queue intake, and tolerate a short overlap in which a late request still arrives.</p><pre>terminationGracePeriodSeconds: 40<br>strategy:<br>  rollingUpdate:<br>    maxUnavailable: 0<br>    maxSurge: 1<br><br>lifecycle:<br>  preStop:<br>    exec:<br>      command: [&#39;/bin/sh&#39;, &#39;-c&#39;, &#39;sleep 5&#39;]</pre><p>Choose the grace period from the sum of routing delay, maximum intended request drain, queue drain, telemetry flush, resource close time, and a safety margin. maxUnavailable: 0 favors availability but requires enough cluster capacity for the surge pod.</p><p><em>[Gist: </em><a href="https://gist.github.com/KirillSotnikov/760bc2a54be8fcd80328d1b6bd9dfd93#file-deployment-yaml"><em>deployment.yaml</em></a><em>] Full Deployment fragment with startup, readiness, and liveness probes, rolling update settings, preStop, resource limits, and security context.</em></p><h3>Database and Redis Shutdown</h3><p>Stateful dependencies should remain open until the HTTP requests and jobs that use them have finished. Closing PostgreSQL before draining application work creates a race in which an active handler attempts its final query against a closed pool.</p><p>With node-postgres, stop admitting new application work, wait for tracked operations, let transaction handlers commit or roll back, and then call pool.end(). Long-running queries should be bounded with PostgreSQL statement timeouts and application-level deadlines.</p><pre>// After HTTP requests and queue handlers have drained:<br>await pool.end();</pre><p>For node-redis, stop loops that create new commands, unsubscribe dedicated Pub/Sub clients, end blocking reads, and then perform a graceful close. Use forceful socket destruction only if the shutdown deadline has already been reached. Disable or short-circuit reconnect behavior during intentional termination.</p><pre>await subscriber.unsubscribe();<br>await subscriber.quit();<br>await redisClient.quit();</pre><p><em>[Gist: </em><a href="https://gist.github.com/KirillSotnikov/760bc2a54be8fcd80328d1b6bd9dfd93#file-postgres-resource-ts"><em>postgres-resource.ts</em></a><em> and </em><a href="https://gist.github.com/KirillSotnikov/760bc2a54be8fcd80328d1b6bd9dfd93#file-redis-resource-ts"><em>redis-resource.ts</em></a><em>] Tracked operations, transaction rollback, graceful close, deadlines, Pub/Sub cleanup, and force-close fallbacks.</em></p><h3>Queues and Background Jobs</h3><p>A queue worker should stop acquiring new work before waiting for current handlers. It should acknowledge a message only after successful processing. Incomplete work should remain unacknowledged or be negatively acknowledged according to broker semantics so another worker can retry it.</p><pre>await consumer.stopConsuming();<br>await consumer.waitForInFlight(deadline);<br>await consumer.close();</pre><p>RabbitMQ uses acknowledgements and redelivery, Kafka uses offsets and consumer-group coordination, cloud queues commonly use visibility timeouts, and BullMQ uses Redis-backed locks and stalled-job recovery. All can process the same logical work more than once after failure. Graceful shutdown reduces duplicates but does not eliminate them; business handlers still need idempotency keys or deduplication records.</p><p><em>[Gist: </em><a href="https://gist.github.com/KirillSotnikov/760bc2a54be8fcd80328d1b6bd9dfd93#file-rabbit-consumer-ts"><em>rabbit-consumer.ts</em></a><em>] Complete amqplib consumer with cancel, prefetch, in-flight tracking, ack/nack, deadline handling, channel close, and connection close.</em></p><h3>WebSockets, SSE, Uploads, and Streams</h3><p>Long-lived connections do not fit the ordinary “wait until the request naturally ends” model. WebSocket servers should stop upgrades, send a protocol close frame such as code 1012 for service restart, allow a short reconnect window, and terminate remaining clients at the deadline.</p><p>SSE endpoints can send a final server_shutdown event with a suggested reconnect delay before ending the response. Long polling should return a retryable response. Streaming downloads should support byte ranges when possible. Upload workflows should write to temporary storage and atomically publish only completed artifacts, or use a resumable upload protocol.</p><p><em>[Gist: </em><a href="https://gist.github.com/KirillSotnikov/760bc2a54be8fcd80328d1b6bd9dfd93#file-long-lived-connections-ts"><em>long-lived-connections.ts</em></a><em>] WebSocket and SSE registries with reconnect-friendly close behavior and deadline fallback.</em></p><h3>A Practical Shutdown Order</h3><ol><li><strong>Mark not-ready: </strong>Stop advertising the instance as able to receive new service traffic.</li><li><strong>Stop new work intake: </strong>Cancel queue consumers, schedulers, polling loops, and WebSocket upgrades.</li><li><strong>Close network listeners: </strong>Call server.close() so new HTTP connections are not accepted.</li><li><strong>Drain in-flight work: </strong>Wait for bounded HTTP requests, jobs, transactions, and streams.</li><li><strong>Flush telemetry: </strong>Export essential logs, metrics, and traces with a strict timeout.</li><li><strong>Close resources: </strong>Close queue channels, PostgreSQL, Redis, and other clients in dependency order.</li><li><strong>Exit: </strong>Set the correct exit code and allow the event loop to become idle.</li></ol><p>The dependency graph matters more than a universal list. A queue handler cannot finish after its database pool is closed, and an HTTP request cannot complete session work after Redis is gone.</p><h3>Observability and Forced Termination</h3><p>Log the shutdown reason, signal, deployment metadata, current state, active requests, jobs, sockets, hook duration, cleanup failures, and final exit code. Useful metrics include shutdown duration, forced shutdown count, terminated requests, requeued jobs, and cleanup errors.</p><p>Telemetry should be flushed before exporter shutdown, but it must have a smaller timeout than the remaining global budget. When the deadline expires, record the remaining counts, destroy sockets and long-lived sessions, abort cleanup where possible, and exit nonzero. A forced path is a safety mechanism, not a normal completion strategy.</p><h3>Common Mistakes</h3><ul><li>Calling process.exit(0) immediately after SIGTERM.</li><li>Closing PostgreSQL or Redis before active HTTP requests and jobs finish.</li><li>Waiting forever because there is no global deadline.</li><li>Keeping readiness healthy while the service drains.</li><li>Failing liveness as soon as normal shutdown starts.</li><li>Using Docker shell form so the signal does not reach Node.js directly.</li><li>Letting several signal and error handlers start cleanup independently.</li><li>Waiting for jobs while the consumer continues receiving new ones.</li><li>Ignoring keep-alive sockets, WebSockets, SSE, uploads, or streams.</li><li>Assuming Kubernetes guarantees that all traffic stops before SIGTERM.</li><li>Exiting with code 0 after a fatal startup or unrecoverable runtime error.</li></ul><h3>Testing the Shutdown Protocol</h3><p>Test shutdown while the service is busy and while dependencies misbehave. An idle Ctrl+C test is not enough.</p><pre># Local SIGTERM<br>node dist/server.js &amp;<br>PID=$!<br>kill -TERM &quot;$PID&quot;<br>wait &quot;$PID&quot;<br><br># Docker<br>docker stop --timeout 40 node-api<br><br># Kubernetes<br>kubectl rollout restart deployment/node-api<br>kubectl rollout status deployment/node-api</pre><ul><li>a slow HTTP request and an open keep-alive socket;</li><li>an open WebSocket and SSE connection;</li><li>an active upload or streaming response;</li><li>an unfinished PostgreSQL transaction or long-running query;</li><li>an in-flight queue message;</li><li>a cleanup hook that never resolves;</li><li>repeated SIGTERM signals;</li><li>a Redis, database, or telemetry close error;</li><li>a global deadline that forces socket destruction.</li></ul><p><em>[Gist: </em><a href="https://gist.github.com/KirillSotnikov/760bc2a54be8fcd80328d1b6bd9dfd93#file-test-shutdown-sh"><em>test-shutdown.sh</em></a><em>] Reproducible local, Docker, and Kubernetes commands, including slow-request and repeated-signal tests.</em></p><h3>Production Checklist</h3><ul><li>One idempotent shutdown coordinator handles SIGTERM, SIGINT, fatal errors, and administrative shutdown requests.</li><li>Readiness fails before intake and listener shutdown.</li><li>HTTP requests, sockets, queue jobs, and long-lived connections are tracked.</li><li>Each normal operation has its own timeout, plus hook-level and global shutdown deadlines.</li><li>Queue intake stops before in-flight jobs are awaited.</li><li>Databases and Redis close only after dependent work drains.</li><li>Docker runs Node.js directly with exec-form CMD and an appropriate stop timeout.</li><li>Kubernetes terminationGracePeriodSeconds includes preStop and a safety margin.</li><li>Forced termination is logged, metered, and tested.</li><li>Business side effects are idempotent because retries and redelivery remain possible.</li></ul><h3>Conclusion</h3><p>A reliable Node.js graceful shutdown is a protocol, not a callback. Signals only begin the transition. The application must coordinate traffic draining, active requests, background jobs, stateful dependencies, telemetry, and long-lived connections before the runtime reaches its deadline.</p><p>The core rules are simple: stop intake first, give existing work a bounded opportunity to finish, close resources according to the dependency graph, and maintain an observable forced-exit path. Implemented together, these rules make rolling deployments safer and make failures easier to understand and recover from.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3db079614315" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-playbook/graceful-shutdown-in-node-js-express-docker-kubernetes-databases-and-queues-3db079614315">Graceful Shutdown in Node.js: Express, Docker, Kubernetes, Databases, and Queues</a> was originally published in <a href="https://medium.com/engineering-playbook">ProdRescue Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idempotency Keys in REST APIs: Preventing Duplicate Payments and Requests]]></title>
            <link>https://javascript.plainenglish.io/idempotency-keys-in-rest-apis-preventing-duplicate-payments-and-requests-262b6c2821b0?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/262b6c2821b0</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 10:42:46 GMT</pubDate>
            <atom:updated>2026-07-30T10:42:46.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5D02sWS6lFWPcpZi0jlBQ.png" /></figure><p>A payment API receives a POST /payments request. The card is charged, the database transaction commits, and the server starts returning a successful response. Then the connection disappears.</p><p>The client sees a timeout. It cannot know whether the payment failed before reaching the server or succeeded while the response was lost. Its retry policy sends the same POST again. Without an <strong>idempotency key REST API</strong> contract, the backend may create a second payment for the same purchase.</p><p>Nothing unusual happened. The client retried an uncertain operation, the server processed a valid request, and the network failed at exactly the wrong moment. Duplicate processing is therefore not merely a double-click problem. It is a distributed-systems problem.</p><p>An idempotency key gives several delivery attempts one logical identity. It lets the server recognize retries, coordinate concurrent requests, and return a previously stored outcome without repeating the side effect. The difficult part is not reading a header. The difficult part is defining request equivalence, concurrency behavior, transaction boundaries, failure recovery, expiration, security, and response replay.</p><h3>Why Duplicate Requests Occur in Production</h3><p>Retries are a normal part of resilient systems. A request can be repeated because of network timeouts, mobile connection interruptions, client retry middleware, API gateway retries, reverse proxies, webhook redelivery, message broker redelivery, service-to-service retries, or a user repeating an action after receiving no visible result.</p><p>The critical failure pattern is an unknown outcome:</p><pre>Client                     API                     Payment Provider<br>  |                         |                              |<br>  | POST /payments          |                              |<br>  |------------------------&gt;|                              |<br>  |                         | Create charge                |<br>  |                         |-----------------------------&gt;|<br>  |                         |                              |<br>  |                         | Charge succeeds              |<br>  |                         |&lt;-----------------------------|<br>  |                         | Commit payment record        |<br>  |                         |                              |<br>  |       connection lost   |                              |<br>  |&lt;---------- X -----------|                              |<br>  |                         |                              |<br>  | POST /payments retry    |                              |<br>  |------------------------&gt;|                              |</pre><p>The client must retry because it does not know the result. The server must prevent that retry from creating a second business effect. Eliminating retries would reduce availability; making retries safe is the correct objective.</p><h3>HTTP Idempotency Is Not Business Idempotency</h3><p>HTTP distinguishes safe methods from idempotent methods. GET and HEAD are safe because their intended semantics are read-only. PUT and DELETE are idempotent because repeating the same request is intended to have the same effect as sending it once. POST has no such default guarantee.</p><p>Those method semantics do not automatically create business idempotency. A PUT endpoint can still send a new email on every call, while a POST endpoint can be made application-level idempotent through a durable operation identity.</p><p>It is also important not to oversell the guarantee. An idempotency key does not create absolute exactly-once delivery across networks, databases, queues, and external providers. Requests can still be delivered more than once. The practical goal is effectively-once processing within a defined scope: several attempts are allowed, but the intended business effect is applied no more than once and retries observe the established outcome.</p><h3>Designing the Idempotency Contract</h3><p>The client generates one high-entropy key for one logical operation and reuses it for every retry of that operation:</p><pre>Idempotency-Key: 7e1bcf68–6af4–4c80–93e7–9ab983b68439</pre><p>A UUIDv4 is a practical default. The important rule is that a retry keeps the original key. A genuinely new payment, order, transfer, or registration uses a new key.</p><p>The key should be interpreted inside an authenticated namespace rather than globally. A common uniqueness scope is tenant ID plus operation plus key. This prevents cross-tenant collisions and avoids accidental reuse across unrelated endpoints or API versions.</p><pre>tenant-742 + POST:/v1/payments + 7e1bcf68-…</pre><p>The retention period must be documented. It should cover the real retry window of clients, webhook providers, gateways, and background workers. Once the record expires, a late retry may be treated as a new operation, so high-risk workflows should also have business-level uniqueness constraints such as a unique order reference or provider transaction ID.</p><h3><strong>Use a Request Fingerprint, Not Only a String Key</strong></h3><p>Clients can accidentally reuse keys. A captured key can also be replayed against another request. The server should therefore store a deterministic fingerprint describing the semantic request associated with the key.</p><p>A useful fingerprint normally includes the HTTP method, normalized route, authenticated tenant or user, API version, canonical request body, and selected headers that materially affect the business operation.</p><pre>SHA-256(<br>  method + normalizedRoute + tenantId + apiVersion + canonicalBody<br>)</pre><p>Canonicalization matters because semantically equivalent JSON objects can use different key ordering. Production APIs should either adopt a documented canonical JSON algorithm or convert the incoming payload into a validated internal command and hash that normalized representation.</p><p>When the same scoped key appears with a different fingerprint, the server should return 409 Conflict. It must not replay the old response as though the requests were equivalent, and it must not execute the new payload as a fresh operation.</p><h3>Model the Idempotency Record as a State Machine</h3><p>A production record should have explicit lifecycle states rather than a single cached response field:</p><pre>PROCESSING -&gt; COMPLETED<br>PROCESSING -&gt; FAILED<br>PROCESSING -&gt; EXPIRED</pre><p>PROCESSING means the key has been claimed and the business operation may already be running. COMPLETED means a terminal result is available for replay. FAILED must carry enough classification to distinguish a definite rollback from an unknown outcome. EXPIRED can be explicit for audit-heavy systems or implemented by deleting old terminal records.</p><p>The record typically stores the scoped key, request fingerprint, status, created and locked timestamps, expiration, original HTTP status, response body, selected response headers, business resource ID, and optional error details.</p><p>The following sequence shows the complete lifecycle of an idempotent payment request: the initial claim, business execution, response persistence, and a later replay that bypasses the payment provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5wLFYQ4ajDOcerP8" /><figcaption><strong>Figure 1. Idempotent request lifecycle and response replay</strong></figcaption></figure><p>The critical boundary is the atomic creation of the PROCESSING record. Once the request is completed, subsequent attempts with the same key and matching fingerprint receive the stored response without executing the business operation again.</p><h3><strong>Concurrent Duplicate Requests</strong></h3><p>The central race condition occurs when two identical requests arrive before the first one completes. The following algorithm is unsafe: check whether the key exists, execute the operation when it does not, then save the result.</p><pre>Request A                       Request B<br>---------                       ---------<br>check key: absent<br>                                check key: absent<br>create payment<br>                                create payment<br>save result<br>                                save result</pre><p>The check and claim must be one atomic storage operation. In PostgreSQL, a unique constraint combined with INSERT … ON CONFLICT DO NOTHING lets exactly one request create the PROCESSING record. In Redis, SET key value NX EX performs an atomic claim with a lease.</p><p>A duplicate that finds PROCESSING must not execute independently. The API can wait briefly and poll, return 409 Conflict with Retry-After, or return 202 Accepted with an operation-status URL. The correct behavior depends on whether the endpoint is synchronous, how long operations normally take, and how clients are designed.</p><h3><strong>PostgreSQL as the Source of Truth</strong></h3><p>PostgreSQL is often the strongest default when the business operation already uses the same database. The idempotency row can be protected by a composite primary key and the business mutation can be committed together with the completed replay response.</p><pre>INSERT INTO idempotency_records (<br>  tenant_id, operation, idempotency_key,<br>  request_fingerprint, status, expires_at<br>)<br>VALUES ($1, $2, $3, $4, &#39;PROCESSING&#39;, $5)<br>ON CONFLICT (tenant_id, operation, idempotency_key)<br>DO NOTHING<br>RETURNING *;</pre><p>If the insert returns a row, the current request owns the new operation. If it returns nothing, the handler loads the existing record, compares fingerprints, and either replays the completed response or reports that processing is still in progress.</p><p>For local database operations, the business mutation and transition to COMPLETED should happen in the same transaction. This closes the gap between creating the resource and storing the response used for future retries.</p><p><strong>Full implementation: </strong><a href="https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3#file-01-postgresql-schema-sql"><strong>01-postgresql-schema.sql</strong></a><strong>, </strong><a href="https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3#file-02-fingerprint-ts"><strong>02-idempotency-store.ts</strong></a><strong>, </strong><a href="https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3#file-04-express-payment-route-ts"><strong>04-express-payment-route.ts</strong></a><strong> — </strong><a href="https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3">https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3</a></p><h3><strong>Redis for Fast Coordination</strong></h3><p>Redis provides a low-latency atomic claim and convenient expiration:</p><pre>SET idempotency:{tenant-742}:key-123 value NX EX 300</pre><p>The stored PROCESSING value should contain a random owner token. Completion and lock extension should use an atomic Lua script that first verifies ownership. Otherwise, an old worker could overwrite or delete a key that expired and was acquired by another process.</p><p>A TTL restores availability after a crash, but it does not establish whether the business effect occurred. If a lease expires while a long payment call is still running, another worker may start the same operation. Redis persistence, restart behavior, replication, and cluster failover must also be considered when completed responses are correctness-critical.</p><p>Redis works well as a coordination layer or replay cache when a durable business invariant exists elsewhere. It should not automatically be treated as the only protection against duplicate financial effects.</p><p><strong>Full implementation: </strong><a href="https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3#file-05-redis-idempotency-store-ts"><strong>05-redis-idempotency-store.ts</strong></a><strong> — </strong><a href="https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3">https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3</a></p><h3><strong>The Transaction Boundary Problem</strong></h3><p>The hardest failure occurs when the business operation succeeds but the process crashes before the idempotency response is saved. A record may remain PROCESSING even though the card was charged or the order was created.</p><p>When the business data and idempotency record share a database, commit them in one transaction. External providers require additional protection because a local transaction cannot atomically commit remote state.</p><p>Common solutions include a provider-side idempotency key, a durable payment-attempt record, transactional outbox for asynchronous effects, a workflow engine for long-running operations, and reconciliation of records whose outcome is unknown. A timeout must never be interpreted as proof that a provider operation failed.</p><p>The system should model uncertainty explicitly. Automatic retry is safe only when the previous attempt is known not to have produced the side effect or when the downstream provider guarantees idempotent retries.</p><h3><strong>Response Replay</strong></h3><p>A completed retry should normally return the original HTTP status, response body, created resource identifier, Location header, content type, and other explicitly selected application headers. It should not blindly replay Date, Connection, Transfer-Encoding, stale rate-limit headers, cookies, or request-specific tracing metadata.</p><p>Business timestamps such as paymentCreatedAt should remain unchanged. The retry itself may receive a new trace ID because it is a new transport attempt. A diagnostic header can make replay behavior visible:</p><pre>Idempotency-Replayed: true</pre><h3><strong>Error Handling</strong></h3><p>Authentication and basic schema validation usually happen before allocating an idempotency record, reducing storage abuse from invalid traffic. Permanent business errors can be stored and replayed when they represent a definitive outcome. Transient failures before any side effect begins may allow a controlled retry.</p><p>Unknown outcomes require a different path. A provider timeout, a lost database connection during COMMIT, or a process crash after a remote success cannot safely be reduced to a generic 500 response. The record should remain recoverable, and a reconciliation process should determine whether the resource or provider transaction exists before permitting another execution.</p><h3><strong>Security and Abuse Resistance</strong></h3><p>An idempotency key is not an authentication credential. Every lookup must be scoped by authenticated tenant or user identity. This prevents cross-user replay and accidental exposure of stored responses.</p><p>The implementation should enforce key length and format limits, authenticate before allocating storage, rate-limit unique keys, apply per-tenant quotas, and expire old records. Sensitive responses should be minimized, encrypted at rest where appropriate, and excluded from ordinary logs. Logging a truncated or keyed hash of the idempotency key is usually safer than logging the raw value.</p><p>SHA-256 collision risk is not the practical concern. More realistic failures are inconsistent canonicalization, missing semantic fields, accepting a caller-provided fingerprint, or forgetting tenant scope.</p><h3><strong>Observability</strong></h3><p>Idempotency needs dedicated telemetry because a successful replay can hide retry storms or stuck operations. Useful metrics include new operations, replay rate, fingerprint conflicts, in-progress conflicts, operation latency, lock contention, stuck PROCESSING records, cleanup failures, storage size, and confirmed duplicate payments prevented.</p><p>Structured logs should include the tenant, operation, hashed key, fingerprint, record state, resource ID, current trace ID, original operation ID, record age, and replayed status. Alerts should detect processing records older than the maximum expected duration and any increase in unknown payment outcomes.</p><p><strong>Testing the Failure Modes</strong></p><p>Sequential happy-path tests are not enough. The test suite should send several requests with the same key concurrently and verify that only one business record is created. It should also test a different payload with the same key, replay of successful and permanent-error responses, database rollback, key expiration, Redis lease expiration, provider timeout, and process termination after commit.</p><pre>const responses = await Promise.all(<br>  Array.from({ length: 10 }, () =&gt;<br>    request(app)<br>      .post(&#39;/v1/payments&#39;)<br>      .set(&#39;Idempotency-Key&#39;, key)<br>      .send(body)<br>  )<br>);<br>expect(await countPayments(orderId)).toBe(1);</pre><p><strong>Full implementation: </strong><a href="https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3#file-06-idempotency-integration-test-ts"><strong>06-idempotency.integration.test.ts</strong></a><strong> — </strong><a href="https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3">https://gist.github.com/KirillSotnikov/9d349e6cdf7ff2a121518bd8f74024b3</a></p><h3><strong>When Idempotency Keys Are Not Enough</strong></h3><p>Idempotency keys do not replace database uniqueness constraints, optimistic locking, transaction isolation, or ordered state transitions. A client may generate a new key for every retry, so critical business references such as order IDs, transfer references, and provider transaction IDs still need unique constraints.</p><p>Different idempotency keys can race over shared inventory or account balances. Messages can still be delivered more than once. Downstream services may not support idempotency. Side effects such as email, SMS, cloud API calls, and queue publications may occur outside the local transaction. Each boundary needs its own deduplication, outbox, locking, versioning, or reconciliation strategy.</p><h3><strong>PostgreSQL or Redis?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xOdJLoBajUGrW2JTdJM9-Q.png" /></figure><h3><strong>Production Checklist</strong></h3><ol><li>The client reuses one key for every retry of the same logical operation.</li><li>The key is scoped by authenticated tenant or user and operation.</li><li>The server computes and stores a deterministic request fingerprint.</li><li>Reusing a key with a different fingerprint returns 409 Conflict.</li><li>Claiming a key is atomic and protected by a unique invariant.</li><li>Concurrent PROCESSING requests have an explicit wait, 409, or 202 policy.</li><li>The original status, body, resource ID, and selected headers are replayed.</li><li>Business mutation and completion state share a transaction where possible.</li><li>External side effects use provider idempotency, durable operation records, or reconciliation.</li><li>Unknown outcomes are never treated as definite failures.</li><li>Retention, cleanup, quotas, and key-length limits are defined.</li><li>Tenant isolation, sensitive response storage, and logging are reviewed.</li><li>Metrics detect replays, conflicts, stuck operations, and cleanup failures.</li><li>Concurrency, crash, timeout-after-commit, and expiration tests run in CI.</li><li>Domain-level uniqueness and transaction controls remain in place.</li></ol><h3><strong>Conclusion</strong></h3><p>Duplicate requests are a normal consequence of retries, uncertain networks, process crashes, webhook delivery, and distributed side effects. A robust idempotency key REST API design gives one logical operation a stable identity and persists its progress and result.</p><p>The key itself is only the beginning. Production correctness depends on request fingerprints, atomic claims, explicit lifecycle states, safe response replay, transaction boundaries, downstream guarantees, reconciliation, security, and observability.</p><p>The objective is not to promise magical exactly-once delivery. The practical objective is effectively-once business behavior: requests may arrive several times, but the intended payment, order, transfer, registration, or webhook effect is applied once and every legitimate retry receives a consistent result.</p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=262b6c2821b0" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/idempotency-keys-in-rest-apis-preventing-duplicate-payments-and-requests-262b6c2821b0">Idempotency Keys in REST APIs: Preventing Duplicate Payments and Requests</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gasless Blockchain Transactions: Architecture, Benefits, and Security Risks]]></title>
            <link>https://medium.com/coinmonks/gasless-blockchain-transactions-architecture-benefits-and-security-risks-1d6d26e23068?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6d26e23068</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 08:01:36 GMT</pubDate>
            <atom:updated>2026-07-30T08:01:36.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-B0g8hM6Yl7Fr4U10-V9w.png" /></figure><p>A user opens an application, connects a wallet, and attempts to perform a simple action: register a document, claim a benefit, submit a vote, or confirm ownership of an asset. The action itself may cost only a few cents in network fees. Yet the user cannot proceed because the wallet contains no native token, the selected network is wrong, or the application expects them to understand gas estimation.</p><p>From the protocol’s perspective, nothing is broken. From the product’s perspective, the transaction has failed before it began.</p><p>Gasless transaction architectures address this gap by separating <strong>authorization</strong> from <strong>fee payment</strong>. The user still authorizes an operation cryptographically, but another party submits the on-chain transaction and pays the network fee. This model can reduce onboarding friction, support transaction sponsorship, and make blockchain-backed services behave more like conventional applications.</p><p>The difficulty is that gasless does not mean trustless, free, or operationally simple. It introduces relayers, signed payloads, nonce management, sponsorship policies, infrastructure budgets, and new denial-of-service opportunities. A well-designed system improves usability without weakening the authorization model. A poorly designed one merely moves complexity from the wallet into backend infrastructure.</p><h3>What “Gasless” Actually Means</h3><p>Every blockchain transaction still consumes computational resources, and someone must pay for them. “Gasless” normally means that the end user does not need to hold the native network token or directly broadcast the transaction.</p><p>A typical flow looks like this:</p><ol><li>The client constructs an operation describing the intended contract call.</li><li>The user signs the operation off-chain.</li><li>A relayer or bundler validates the signed request.</li><li>The relayer submits an on-chain transaction and pays the gas.</li><li>A smart contract verifies that the original user authorized the operation.</li><li>The platform may absorb the cost, recover it in another asset, or apply a sponsorship policy.</li></ol><p>This distinction matters. A gasless architecture is not primarily a fee-removal mechanism. It is an <strong>authorization and transaction-submission architecture</strong>.</p><p>There are several major implementation patterns:</p><ul><li>application-specific relayers;</li><li>ERC-2771 meta-transactions;</li><li>permit-based token operations;</li><li>account abstraction through ERC-4337;</li><li>hybrid flows combining these approaches.</li></ul><p>They solve related problems, but they do not provide identical security guarantees or operational characteristics.</p><h3>Relayers and Meta-Transactions</h3><p>A meta-transaction contains a user-authorized action that is submitted on-chain by another account. The user signs structured data rather than a normal blockchain transaction. A relayer verifies the signature, wraps the request in an on-chain transaction, and pays the gas.</p><p>The target contract must distinguish between two identities:</p><ul><li>the account that submitted the blockchain transaction;</li><li>the user who authorized the underlying action.</li></ul><p>Without explicit support, Solidity contracts see the relayer as msg.sender. Any authorization logic based directly on msg.sender would therefore grant permissions to the relayer rather than the original signer.</p><p>A basic signed request may contain:</p><pre>from<br>to<br>value<br>gas<br>nonce<br>deadline<br>callData<br>chainId</pre><p>Each field closes a specific attack surface.</p><p>The target address prevents the same signature from authorizing calls to arbitrary contracts. The nonce prevents repeated execution. The deadline limits how long the request remains valid. The chain identifier reduces cross-chain replay risk. The calldata binds the signature to a specific function and its parameters.</p><p>The relayer does not necessarily need to be trusted with user authority. It may be able to delay, censor, or refuse a request, but it should not be able to change the signed operation. This distinction is important: <strong>a relayer can be operationally privileged without being cryptographically authorized to impersonate users</strong>.</p><h3>ERC-2771 and the Trusted Forwarder Model</h3><p>ERC-2771 standardizes a contract-level approach for native meta-transactions. It defines four primary roles:</p><ul><li>the transaction signer;</li><li>the gas relay;</li><li>the trusted forwarder;</li><li>the recipient contract.</li></ul><p>The forwarder verifies the user’s signature and nonce, then calls the recipient contract while appending the signer’s address to the calldata. The recipient recognizes calls from an approved forwarder and derives an effective sender, commonly exposed through _msgSender(), instead of relying directly on msg.sender.</p><p>This creates a clean separation of responsibilities:</p><ul><li>the relayer operates off-chain infrastructure;</li><li>the forwarder verifies authorization;</li><li>the recipient executes application logic;</li><li>the user retains control of the signing key.</li></ul><p>The word <strong>trusted</strong> in “trusted forwarder” should not be overlooked. The recipient contract accepts the forwarder’s interpretation of the original sender. If an attacker can replace the forwarder, exploit its verification logic, or persuade the recipient to trust a malicious implementation, authorization can collapse.</p><p>Recipient contracts should therefore treat the forwarder address as part of their security configuration. Changes to it deserve the same controls as changes to administrators, upgrade implementations, or signing authorities.</p><p>OpenZeppelin provides ERC2771Context and an ERC2771Forwarder implementation for this pattern. Its current documentation describes ERC2771Forwarder as a production-oriented forwarder, while older MinimalForwarder implementations were explicitly intended primarily for testing and lacked several properties expected from a complete forwarding system.</p><h3>Permit-Based Flows Are Narrower — and Often Simpler</h3><p>Not every gasless workflow requires a general-purpose relayer protocol.</p><p>ERC-2612 extends ERC-20 with permit, allowing a token holder to create or change an allowance through a signed message rather than an on-chain approve transaction. The signature uses EIP-712 structured data and includes an owner, spender, amount, nonce, and deadline.</p><p>A contract can then combine authorization and token use in one submitted transaction:</p><pre>token.permit(<br>    owner,<br>    address(this),<br>    amount,<br>    deadline,<br>    v,<br>    r,<br>    s<br>);</pre><pre>token.transferFrom(owner, recipient, amount);</pre><p>The user signs the approval off-chain. A relayer, application backend, or transaction participant submits the transaction. This removes the separate approval transaction and can substantially improve token-based workflows.</p><p>However, permit does not make arbitrary contract calls gasless. It only changes token allowance state. The submitting account must still pay for the transaction that invokes permit and performs the subsequent operation.</p><p>Permit flows also inherit familiar allowance risks. A signature authorizing an unnecessarily large amount or a distant deadline may expose the user to more risk than the immediate operation requires. Applications should request the minimum practical allowance, use short validity periods, display the spender clearly, and avoid treating a signed permit as an informal login challenge.</p><p>EIP-712 improves the structure and domain separation of signed messages, but the specification does not provide replay protection by itself. The application protocol must enforce nonces, deadlines, or another single-use mechanism.</p><h3>Account Abstraction Changes the Unit of Control</h3><p>ERC-4337 takes a broader approach. Instead of relying on a conventional externally owned account to create a normal transaction, it introduces a higher-level object called a UserOperation. Users submit these objects to a separate mempool, and bundlers package them into transactions that are processed through an EntryPoint contract.</p><p>A simplified ERC-4337 architecture includes:</p><ul><li><strong>smart account:</strong> programmable account logic;</li><li><strong>UserOperation:</strong> the user’s requested action;</li><li><strong>bundler:</strong> collects and submits operations;</li><li><strong>EntryPoint:</strong> coordinates validation and execution;</li><li><strong>paymaster:</strong> optionally sponsors gas;</li><li><strong>factory:</strong> deploys accounts, including counterfactual accounts.</li></ul><p>The paymaster is the component most directly associated with gas sponsorship. It can agree to pay for an operation based on application-specific rules — for example, whether the user is eligible, whether a daily quota remains, or whether the operation calls an approved contract function.</p><p>Account abstraction can also support batched actions, session keys, recovery policies, spending limits, multisignature validation, and alternative authentication mechanisms. This makes it more flexible than a narrow meta-transaction forwarder.</p><p>That flexibility introduces additional moving parts. Teams must reason about smart-account upgrades, bundler compatibility, validation gas, paymaster deposits, simulation behavior, EntryPoint versions, and denial-of-service controls. ERC-7562, for example, defines validation-scope rules intended to limit abuse and protect bundlers from operations that are expensive, unstable, or invalid under changing state.</p><p>Account abstraction is therefore not simply “ERC-2771 with more features.” It changes the account model and moves significant validation logic into programmable contracts and supporting infrastructure.</p><h3>A Production Architecture for Sponsored Transactions</h3><p>A production system should avoid exposing an unrestricted relay endpoint that blindly submits any correctly signed request. Signature validity proves authorization by a key. It does not prove that the platform should spend money executing the request.</p><p>A practical architecture separates authorization, sponsorship, and execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O--fso8gRNnRYb8_" /></figure><p>The API gateway authenticates application traffic and applies coarse rate limits. The policy engine determines whether the platform is willing to sponsor the operation. Signature validation confirms what the user authorized. A durable queue separates request intake from blockchain submission, allowing workers to absorb RPC failures and fee spikes without losing accepted requests.</p><p>The transaction state store should track the full lifecycle:</p><pre>RECEIVED<br>VALIDATED<br>SPONSORSHIP_APPROVED<br>QUEUED<br>SUBMITTED<br>CONFIRMED<br>REVERTED<br>EXPIRED<br>REJECTED</pre><p>This is more useful than returning a transaction hash and assuming the workflow is complete.</p><h3>The Main Security Risks</h3><h4>Replay Across Time, Contracts, or Networks</h4><p>A signed message without an enforced nonce may be reusable. A message without a deadline may remain executable indefinitely. Weak domain separation can allow a signature intended for one contract or chain to be interpreted elsewhere.</p><p>Every signed request should bind at least:</p><ul><li>chain ID;</li><li>verifying contract;</li><li>signer;</li><li>target;</li><li>function calldata;</li><li>nonce;</li><li>expiry;</li><li>relevant value or fee constraints.</li></ul><p>Nonces must be consumed atomically during execution, not merely marked as used in an off-chain database.</p><h4>Relayer Key Compromise</h4><p>The relayer’s key pays for transactions and may hold meaningful native-token balances. An attacker who compromises it may not be able to forge user signatures, but can drain funds through arbitrary transactions or consume the sponsorship budget.</p><p>Relayer keys should be held in a managed key service or hardware-backed signing environment. Balances should be limited, replenishment should be controlled, and withdrawal destinations should be restricted where the platform design allows it.</p><h4>Sponsorship Abuse</h4><p>A valid signature does not make a request economically legitimate. Attackers may create thousands of accounts, repeatedly invoke expensive functions, trigger intentional reverts, or exploit differences between preflight simulation and actual execution.</p><p>Sponsorship decisions should consider the target contract, function selector, estimated gas, user eligibility, per-account quotas, global budgets, and recent failure history.</p><h4>Misleading Signatures</h4><p>Users may technically sign the correct bytes while misunderstanding the action. Generic hexadecimal payloads or unclear typed-data fields weaken meaningful consent.</p><p>EIP-712 provides a standard representation for typed structured data, but applications still need understandable field names and tightly scoped messages. A signature such as Execute(bytes data) may be standards-compliant while remaining difficult for a human to evaluate.</p><h4>Forwarder and Context Errors</h4><p>Contracts supporting ERC-2771 must use the forwarded execution context consistently. Mixing _msgSender() with direct msg.sender checks can produce subtle authorization failures. Delegate calls and calldata manipulation require particular care because the trusted-forwarder model depends on how the original sender is appended and extracted.</p><h3>Operational Trade-Offs</h3><p>Gas sponsorship improves onboarding, but it converts unpredictable user-paid fees into an infrastructure expense. The platform now needs budgets, cost attribution, abuse controls, and policies for fee spikes.</p><p>Relayers also add latency. A direct wallet transaction moves from the user to an RPC provider. A sponsored flow may pass through an API gateway, policy engine, validation service, queue, worker, signer, and RPC provider before reaching the network.</p><p>This additional path can improve control and observability, but it creates more failure modes.</p><p>ERC-2771 is comparatively easy to integrate when a limited set of application contracts can explicitly trust a forwarder. Permit flows are attractive when the main problem is token approval. ERC-4337 is more suitable when programmable accounts, batching, recovery, or flexible sponsorship are central product requirements.</p><p>No option eliminates the need for careful contract design.</p><h3>Production Considerations</h3><p><strong>Make submission idempotent.</strong> Assign an application request ID derived from the signer, nonce, target, and operation hash. Retrying the same API request should return the existing state rather than enqueue a second transaction.</p><p><strong>Separate retryable failures from terminal failures.</strong> RPC timeouts, temporary underpricing, and provider outages may justify retries. Invalid signatures, expired deadlines, consumed nonces, policy rejections, and deterministic contract reverts usually do not.</p><p><strong>Use multiple RPC paths.</strong> A relayer dependent on one provider inherits that provider’s outages and inconsistent transaction propagation. Health-check providers continuously and define rules for switching without broadcasting uncontrolled duplicates.</p><p><strong>Track both infrastructure and protocol metrics.</strong> Queue depth and API latency are not enough. Monitor confirmation time, replacement rate, revert rate by function selector, sponsorship cost per user, nonce gaps, paymaster deposit levels, bundler rejection reasons, and RPC disagreement.</p><p><strong>Preserve decision evidence.</strong> Logs should capture the operation hash, policy version, signer, target, nonce, simulation result, estimated gas, submission transaction, and final receipt. Do not log private keys or sensitive authentication material.</p><p><strong>Prepare an emergency stop.</strong> Teams need a controlled way to pause sponsorship, disable a compromised relayer, rotate trusted infrastructure, and reject vulnerable operation types without unnecessarily disabling unrelated contract functionality.</p><h3>Practical Recommendations for Engineering Teams</h3><h4>1. Sign a Versioned Authorization Envelope</h4><p>Define an explicit EIP-712 schema containing the chain, verifying contract, action, parameters, nonce, deadline, and schema version. Versioning prevents future application changes from silently altering the meaning of old signatures.</p><h4>2. Keep Sponsorship Policy Off the Critical Authorization Path</h4><p>The contract must independently verify user authorization. An off-chain policy engine may decide whether the platform pays, but it should not become the only mechanism preventing unauthorized execution.</p><h4>3. Sponsor Capabilities, Not Arbitrary Calldata</h4><p>Allowlist contract addresses and function selectors. Validate parameter ranges where practical. A sponsorship API that accepts unrestricted calldata is effectively a public interface to the platform’s gas budget.</p><h4>4. Simulate, but Do Not Treat Simulation as Proof</h4><p>Simulate requests before submission to detect obvious reverts and estimate cost. Still assume that blockchain state may change before execution. Contracts and relayers must safely handle operations that become invalid after simulation.</p><h4>5. Bound Every Economic Commitment</h4><p>Set per-operation gas limits, per-user quotas, rolling spending limits, and global circuit breakers. A logically valid transaction can still be economically abusive.</p><h4>6. Design for Transaction Replacement and Reconciliation</h4><p>Persist signed payloads and submission attempts. Detect transactions that remain pending, replace them according to a defined fee policy, and reconcile receipts independently rather than relying only on synchronous RPC responses.</p><h3>Why This Matters Beyond Consumer Applications</h3><p>Gasless execution is often discussed as a convenience feature for decentralized applications, but its broader value is accessibility.</p><p>A government service cannot reasonably assume that every resident understands native tokens. An educational credential platform should not require a student to purchase cryptocurrency before accepting or sharing a record. Enterprise workflows may need predictable billing rather than thousands of employees individually funding wallets. Financial and identity systems may require organizations to sponsor narrowly defined actions while preserving cryptographic user authorization.</p><p>In these settings, the goal is not to hide blockchain at any cost. It is to place protocol complexity behind an architecture that remains auditable, bounded, and secure.</p><p>Gasless systems can help independent organizations interact through shared infrastructure while keeping authorization attributable to individual users. Their value depends less on removing a fee from the interface and more on implementing a reliable boundary between <strong>who authorizes an action, who submits it, and who agrees to pay for it</strong>.</p><h3>Conclusion</h3><p>The safest gasless architecture is not the one with the fewest wallet prompts. It is the one that makes every responsibility explicit.</p><p>Users authorize operations. Contracts enforce that authorization. Relayers transport requests. Policy engines decide which costs the platform will sponsor. Operational systems observe, limit, and recover the transaction pipeline.</p><p>ERC-2771, permit-based flows, and ERC-4337 each offer useful abstractions, but they solve different layers of the problem. The right choice follows from the required account model, supported operations, trust boundaries, and operational capacity.</p><p>The principle worth retaining is simple: <strong>abstract fee payment without abstracting away accountability</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6d26e23068" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/gasless-blockchain-transactions-architecture-benefits-and-security-risks-1d6d26e23068">Gasless Blockchain Transactions: Architecture, Benefits, and Security Risks</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[Digital Signatures Beyond Authentication: Building Verifiable Systems]]></title>
            <link>https://medium.com/@comicon2508/digital-signatures-beyond-authentication-building-verifiable-systems-6f18d5960556?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f18d5960556</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[digital-signatures]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 17:53:16 GMT</pubDate>
            <atom:updated>2026-07-27T17:53:16.791Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rk-YHBP7c_1Y-WELfkW0ag.png" /></figure><p>A user successfully authenticates, submits a financial instruction, and receives a confirmation. Several weeks later, the instruction appears in an audit dispute. The database shows which account was logged in, but the organization cannot prove exactly what data the user approved, whether the record changed afterward, or which cryptographic key authorized it.</p><p>Authentication worked. Verifiability did not.</p><p>This distinction matters whenever information must cross organizational, technical, or time boundaries. A login can establish who controls an account during a session. It does not automatically make every subsequent document, transaction, credential, or API message independently verifiable.</p><p>Digital signatures address that gap, but only when they are treated as part of a larger verification architecture rather than as a cryptographic function added near the end of development.</p><h3>Authentication, Electronic Signatures, and Cryptographic Proofs</h3><p>These concepts are related, but they solve different problems.</p><p><strong>Authentication</strong> establishes that an entity is allowed to act as a particular user, service, or device. Passwords, passkeys, OAuth tokens, client certificates, and short-lived cloud credentials are authentication mechanisms. Their output is typically a session or security context.</p><p>Authentication answers:</p><blockquote><em>Who is interacting with the system right now?</em></blockquote><p>An <strong>electronic signature</strong> is a broader legal and product concept. It may be a typed name, a checkbox, a scanned image, a click recorded by a workflow platform, or a cryptographic signature. Its legal effect depends on applicable law, consent, attribution, record retention, and surrounding evidence — not only on the underlying mathematics.</p><p>A <strong>digital signature</strong> is a cryptographic construction. A private key produces a signature over a message, while the corresponding public key allows another party to verify that signature. Proper verification provides evidence that the signed bytes have not changed and that the signature was produced by the private key associated with the supplied public key. NIST’s Digital Signature Standard describes digital signatures as mechanisms for detecting unauthorized modifications and authenticating the claimed signatory.</p><p>A <strong>cryptographic proof</strong> is the complete verifiable package:</p><ul><li>the signed payload or its canonical representation;</li><li>the signature;</li><li>the algorithm identifier;</li><li>the signer or key identifier;</li><li>the relevant public key or a trustworthy way to resolve it;</li><li>timestamps, validity rules, and domain context;</li><li>revocation or key-status information where required.</li></ul><p>That package can often be verified outside the application that originally created it. This is the point at which a database record becomes portable evidence rather than an assertion that depends entirely on one system’s continued availability and integrity.</p><h3>Why Login Records Are Not Enough</h3><p>Consider an education platform issuing a digital certificate.</p><p>The issuer’s administrator may authenticate through single sign-on before creating the certificate. The platform can log the administrator’s user ID, IP address, and request timestamp. These records are useful, but an external verifier still has to trust the platform’s database and API response.</p><p>A cryptographically signed certificate changes the trust model. The verifier can hash the certificate’s canonical content, validate the signature against the issuer’s public key, and evaluate whether the key was valid when the certificate was issued.</p><p>The same pattern applies to:</p><ul><li>payment instructions exchanged between financial institutions;</li><li>software-release attestations;</li><li>government permits and licenses;</li><li>healthcare referrals;</li><li>supply-chain events;</li><li>enterprise approvals;</li><li>digitally issued academic records.</li></ul><p>The signature does not prove that every statement inside the document is true. It proves something narrower and more technically defensible: <strong>a holder of a specific private key signed a specific byte sequence</strong>.</p><p>The surrounding system must establish who controls that key, what the signer was authorized to approve, and how verifiers determine whether the key remains trustworthy.</p><h3>The Data Representation Is Part of the Security Model</h3><p>Most signature failures in application systems are not failures of elliptic-curve mathematics. They are failures to define what was actually signed.</p><p>Suppose two services process the following logically equivalent JSON objects:</p><pre>{&quot;amount&quot;:100,&quot;currency&quot;:&quot;USD&quot;}</pre><pre>{<br>  &quot;currency&quot;: &quot;USD&quot;,<br>  &quot;amount&quot;: 100<br>}</pre><p>They contain the same fields but produce different byte sequences. Hashing the raw serialization produces different digests. Differences in whitespace, property order, Unicode handling, number formatting, or omitted optional fields can all invalidate a signature.</p><p>The system therefore needs a deterministic representation.</p><p>For JSON, one option is the JSON Canonicalization Scheme defined by RFC 8785. It constrains the data model and defines deterministic serialization rules so that independent implementations can produce the same hashable representation.</p><p>Another approach is to define a narrow binary schema using formats such as Protocol Buffers or CBOR, provided the team specifies deterministic encoding and versioning behavior.</p><p>The signed payload should also include <strong>domain separation</strong>. Signing only a generic hash such as:</p><pre>SHA-256(payload)</pre><p>can create ambiguity if the same key is used in several workflows. A safer message binds the signature to its purpose:</p><pre>signature-input =<br>  &quot;com.example.payment-approval:v1&quot; ||<br>  tenant_id ||<br>  transaction_id ||<br>  issued_at ||<br>  expires_at ||<br>  canonical_payload</pre><p>This prevents a signature created for one context from being interpreted as authorization in another.</p><h3>Ed25519 and ECDSA: Similar Purpose, Different Operational Profiles</h3><p>Ed25519 and ECDSA are both elliptic-curve signature systems, but they should not be treated as interchangeable labels.</p><h4>Ed25519</h4><p>Ed25519 is an EdDSA construction over the edwards25519 curve. RFC 8032 defines Ed25519, Ed448, their variants, and test vectors.</p><p>Its practical advantages include:</p><ul><li>deterministic signature generation;</li><li>compact public keys and signatures;</li><li>strong performance in software;</li><li>fewer configuration choices;</li><li>reduced exposure to nonce-generation mistakes.</li></ul><p>For application-level proofs, signed documents, developer tooling, and systems where both signing and verification libraries support it consistently, Ed25519 is often a straightforward choice.</p><p>Its main limitation is ecosystem compatibility. Some managed key services, hardware security modules, certificate infrastructures, and compliance profiles have historically offered broader support for NIST ECDSA curves than for Ed25519. The decision therefore cannot be based only on algorithm elegance.</p><h4>ECDSA</h4><p>ECDSA is widely used in TLS, hardware-backed keys, cloud key-management services, mobile platforms, and blockchain systems. NIST FIPS 186–5 specifies ECDSA alongside RSA and EdDSA for digital-signature generation and verification.</p><p>ECDSA requires a per-signature value commonly called a nonce. Reusing it, generating it predictably, or leaking partial information about it can expose the private key. RFC 6979 defines deterministic generation for DSA and ECDSA to reduce dependence on runtime randomness during signing.</p><p>Modern cryptographic libraries and managed signing services should handle this correctly. Application teams should not implement nonce generation themselves.</p><p>ECDSA also introduces encoding concerns. Signatures are commonly represented as a pair of integers, r and s, but different systems may use ASN.1 DER or fixed-width concatenation. Some ecosystems additionally enforce low-s normalization to avoid signature malleability. A verification protocol must specify the expected curve, hash function, signature encoding, and normalization rules.</p><h4>Choosing Between Them</h4><p>Choose based on the entire verification environment:</p><ul><li>required compliance profiles;</li><li>browser, mobile, HSM, and cloud support;</li><li>interoperability with existing certificates or protocols;</li><li>library quality in every implementation language;</li><li>offline-verification requirements;</li><li>expected cryptographic agility.</li></ul><p>An algorithm that is secure but inconsistently implemented across five services can create a less reliable system than a slightly more operationally complex algorithm with mature platform support.</p><h3>A Production Verification Workflow</h3><p>A practical architecture separates business authorization, signing, storage, and verification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0tiqJiIhvDMgmTWQ" /></figure><p>A signing request might follow this sequence:</p><ol><li>The API gateway authenticates the caller and applies rate limits.</li><li>The authorization service confirms that the caller may perform the requested action.</li><li>The document service constructs a versioned payload.</li><li>The canonicalization component produces deterministic bytes.</li><li>The system hashes those bytes when the selected signing API expects a digest.</li><li>A dedicated signing service requests a signature from KMS or HSM.</li><li>The application stores the payload, signature, algorithm, key ID, schema version, and relevant timestamps.</li><li>An append-only audit event records the signing decision and cryptographic metadata.</li></ol><p>Verification should be separately deployable. It resolves the public key by an immutable key identifier, reproduces the canonical bytes, validates the signature, and then evaluates policy.</p><p>That last step matters. A cryptographically valid signature may still be unacceptable because the key was revoked, the proof expired, the payload uses an unsupported schema, or the signer lacked authority for that document type.</p><p><strong>Cryptographic validity and business validity are separate results.</strong></p><h3>Key Management Is the Real Security Boundary</h3><p>Private keys should not be stored in source code, container images, ordinary environment variables, application databases, or developer-accessible configuration files.</p><p>A managed KMS or HSM can prevent the application from exporting private key material. The service sends a message or digest to the cryptographic boundary and receives a signature. AWS KMS, for example, supports asymmetric signing keys and allows signatures to be verified either through KMS or externally with the public key. Its documentation also requires the verifier to use the appropriate key, message, and signing algorithm.</p><p>This does not remove operational responsibility. Teams still need to define:</p><ul><li>who may invoke signing operations;</li><li>whether production signing requires workload identity or human approval;</li><li>how key versions are identified;</li><li>how public keys are published;</li><li>when rotation occurs;</li><li>how compromised keys are revoked;</li><li>how historical signatures remain verifiable;</li><li>which logs are retained for investigation.</li></ul><p>NIST SP 800–57 treats key management as a lifecycle covering generation, distribution, storage, use, recovery, revocation, and destruction — not simply key storage.</p><p>Rotation should normally introduce a new key version without deleting the old public key. Removing historical verification material can make valid records unverifiable. The registry should preserve key status and validity intervals even after a key is no longer permitted to sign new payloads.</p><h3>Common Implementation Failures</h3><p>Several mistakes appear repeatedly in otherwise well-designed systems.</p><h4>Signing an Unstable Serialization</h4><p>One service signs compact JSON while another verifies a parsed and reserialized object. Both are correct at the application level but operate on different bytes.</p><p><strong>Mitigation:</strong> Define canonicalization as part of the protocol and test it across every supported language.</p><h4>Trusting a Key Supplied with the Signature</h4><p>An attacker can generate a key pair, sign a forged payload, and attach their own public key. The signature is mathematically valid but proves nothing about the intended issuer.</p><p><strong>Mitigation:</strong> Resolve keys through a trusted registry, certificate chain, pinned identifier, or other authenticated trust mechanism.</p><h4>Omitting Context and Expiration</h4><p>A signed approval may be replayed in another tenant, environment, endpoint, or later transaction.</p><p><strong>Mitigation:</strong> Include tenant, environment, purpose, unique request ID, timestamps, and expiration in the signed content.</p><h4>Treating Verification as a Boolean</h4><p>Returning only true or false makes troubleshooting and policy enforcement difficult.</p><p><strong>Mitigation:</strong> Distinguish errors such as unknown key, unsupported algorithm, malformed signature, canonicalization failure, revoked key, expired proof, payload mismatch, and policy rejection.</p><h4>Rotating Keys Without Preserving History</h4><p>Applications begin signing with a new key and overwrite the old public key record.</p><p><strong>Mitigation:</strong> Use immutable key-version identifiers and maintain historical public verification data.</p><h4>Logging Sensitive Payloads</h4><p>Debug logs may capture complete signed documents, personal data, signatures, authorization headers, or KMS requests.</p><p><strong>Mitigation:</strong> Log proof IDs, key IDs, algorithms, schema versions, digest prefixes, timing, and outcome codes — not sensitive content unless explicitly required and protected.</p><h3>Production Trade-Offs</h3><p>Managed signing creates network latency and dependency on a cloud service. Local signing can be faster, but distributing private keys across application instances increases exposure and complicates rotation.</p><p>Synchronous signing provides immediate results but can make user-facing workflows sensitive to KMS throttling or regional outages. Asynchronous signing through a queue improves resilience for batch issuance, although it requires idempotent jobs, status tracking, and clear handling of partially completed operations.</p><p>Offline verification reduces load and avoids dependency on the issuer’s API. It also means public keys, revocation data, schemas, and policy rules must be distributable and cacheable.</p><p>There is also a cost dimension. Per-operation KMS charges may be negligible for low-volume document issuance but material for high-frequency event signing. Teams should estimate signature volume, test throughput limits, and decide whether every event requires asymmetric proof. Internal high-volume integrity checks may be better served by authenticated logs or MACs, while externally verifiable records require asymmetric signatures.</p><h3>Practical Recommendations for Engineering Teams</h3><p><strong>1. Write a signature profile before writing integration code.</strong><br>Specify the algorithm, curve, hash function, signature encoding, canonicalization method, domain prefix, required fields, timestamp format, and key-resolution process. Treat the profile as a versioned protocol.</p><p><strong>2. Store complete verification metadata with every proof.</strong><br>Persist the algorithm identifier, immutable key version, payload schema, canonicalization version, signature, issuance time, expiration policy, and proof purpose. Do not rely on application defaults that may change after deployment.</p><p><strong>3. Separate authorization from signing permission.</strong><br>The service allowed to call KMS should not independently decide what deserves a signature. Require an authorized business decision from a separate component and include that decision’s immutable identifier in the signed payload.</p><p><strong>4. Build cross-language conformance tests.</strong><br>Create fixed test vectors containing Unicode, decimals, empty values, reordered fields, large identifiers, and boundary timestamps. Require every producer and verifier implementation to generate the same canonical bytes and verification result.</p><p><strong>5. Design key compromise procedures before launch.</strong><br>Document how to disable signing, publish revocation status, rotate credentials, identify affected proofs, preserve forensic logs, and communicate with relying parties. A key-management design without an incident path is incomplete.</p><p><strong>6. Monitor verification outcomes, not only service availability.</strong><br>Track unknown-key rates, malformed proofs, expired signatures, revoked-key attempts, KMS latency, throttling, signing volume by principal, and sudden changes in verification failures. These signals can reveal integration defects, abuse, or compromise earlier than infrastructure metrics alone.</p><h3>Beyond a Single Application</h3><p>Digital signatures become most valuable when information must remain trustworthy outside the system that created it.</p><p>A university record may be verified by an employer. A software attestation may be evaluated by a deployment platform. A government-issued permit may be checked by several independent agencies. A financial instruction may pass through multiple institutions and audit systems.</p><p>In each case, the goal is not to eliminate institutional trust. It is to make critical assertions <strong>portable, tamper-evident, and independently testable</strong>.</p><p>That capability supports more resilient digital infrastructure. It can reduce manual verification, limit certain forms of document fraud, improve cross-organizational workflows, and preserve evidence when individual applications are migrated, unavailable, or no longer operated by their original vendor.</p><h3>Conclusion</h3><p>A digital signature is not an upgraded login event. It is a mechanism for binding a key to an exact message, under an explicitly defined protocol.</p><p>The cryptographic algorithm matters, but it is rarely the hardest part. Reliable verifiable systems depend on deterministic data representation, trusted key discovery, strict domain separation, authorization boundaries, lifecycle-aware key management, observable verification, and policies that distinguish mathematical validity from business acceptance.</p><p>The architectural principle to remember is simple:</p><p><strong>Do not design only for the moment a signature is created. Design for the independent verifier who must understand and trust it years later.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f18d5960556" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Digital Trust Infrastructure Matters More Than Ever]]></title>
            <link>https://medium.com/@comicon2508/why-digital-trust-infrastructure-matters-more-than-ever-9a7beec78c92?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a7beec78c92</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[digital-identity]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 17:59:37 GMT</pubDate>
            <atom:updated>2026-07-19T17:59:37.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWr06QgnjfcgfDKKDQ3Atg.png" /></figure><p>A user signs in with phishing-resistant multi-factor authentication, receives a valid session, and downloads an official-looking document from a trusted application. The authentication layer worked exactly as designed.</p><p>Weeks later, another organization receives a copy of that document through email. It cannot determine whether the file is original, whether a field was modified after issuance, whether the issuing account was compromised, or whether the document has since been revoked.</p><p>This is the boundary between <strong>authentication</strong> and <strong>digital trust</strong>.</p><p>Authentication answers a narrow but important question: <em>Who is interacting with the system right now?</em> Digital trust infrastructure must answer a broader set of questions:</p><ul><li>Who produced this data?</li><li>Has it changed?</li><li>Was the issuer authorized to produce it?</li><li>Is the evidence still valid?</li><li>Can an independent party verify these facts without accessing the issuer’s internal database?</li></ul><p>Many systems treat successful login as the final proof of trust. In reality, authentication is only the beginning of a longer integrity chain.</p><h3>Authentication Does Not Travel with the Data</h3><p>Traditional application security is usually organized around identities, sessions, and authorization policies.</p><p>A user authenticates through a password, passkey, certificate, or identity provider. The application creates a session or accepts a security token. Backend services then evaluate permissions before allowing operations.</p><p>That model works reasonably well while every interaction remains inside one controlled security boundary.</p><p>The difficulty begins when data leaves that boundary.</p><p>A university transcript is downloaded and submitted to an employer. A compliance report is exported from a SaaS platform and sent to an auditor. A medical record is transferred between providers. A supplier presents a certification to a manufacturer. A government document is uploaded to a private financial institution.</p><p>The receiving organization normally does not inherit the original session, database history, authorization context, or internal logs. It receives a PDF, JSON object, image, CSV file, or API response.</p><p>At that point, the receiver may know where the data supposedly came from, but not whether the data itself can be trusted.</p><p>This problem is increasingly important because digital workflows cross organizational boundaries by default. Financial services depend on external identity and risk providers. Healthcare systems exchange records. Educational credentials move between institutions and employers. Government services interact with banks, insurers, contractors, and citizens.</p><p>A centralized database can establish truth inside one organization. It does not automatically establish trust between organizations that operate different systems and may not fully trust one another.</p><h3>Digital Trust Is a Set of Verifiable Properties</h3><p>Digital trust should not be treated as a product category or a single technology. It is an architectural property created by combining several mechanisms.</p><h4>Data integrity</h4><p>Integrity means that a verifier can detect whether protected data has changed.</p><p>A cryptographic hash maps an input of arbitrary size to a fixed-size digest. Even a small change to the input should produce a different digest. Instead of comparing entire documents, systems can compare their hashes.</p><p>However, hashing alone does not establish authorship. An attacker who changes a document can simply compute a new hash.</p><p>A hash becomes useful as trust evidence only when it is bound to an authenticated issuer, stored in a protected system, signed, timestamped, or otherwise anchored in a context the attacker cannot silently rewrite.</p><h4>Digital signatures</h4><p>A digital signature binds data to a private key.</p><p>The issuer calculates a digest of a canonical representation of the data and signs it with a private key. A verifier uses the corresponding public key to validate the signature. Successful verification provides evidence that the signed payload has not been modified and that the signature was created by the holder of the private key.</p><p>NIST’s Digital Signature Standard describes signatures as mechanisms for detecting unauthorized data modification and authenticating the signatory. Current FIPS 186–5 techniques include RSA, ECDSA, and EdDSA.</p><p>This still leaves an important question: <strong>Why should the verifier trust that public key?</strong></p><p>A technically valid signature is not necessarily an organizationally valid signature. The system must bind keys to issuers through a certificate authority, trusted registry, decentralized identifier, preconfigured trust store, or another governed discovery mechanism.</p><h4>Tamper resistance and tamper evidence</h4><p>These terms are often used interchangeably, but they describe different guarantees.</p><p>A tamper-resistant system attempts to prevent unauthorized modification. Examples include hardware security modules, write-once storage, restricted database permissions, and immutable object-retention policies.</p><p>A tamper-evident system assumes that some modification attempts may succeed but ensures that they leave detectable evidence. Hash chains, signed events, append-only journals, and externally anchored checkpoints are common techniques.</p><p>Absolute immutability is rarely a realistic production guarantee. Administrators can be compromised. Cloud accounts can be misconfigured. Signing keys can leak. Retention policies can be changed by sufficiently privileged identities.</p><p>A more defensible design makes unauthorized changes <strong>difficult, observable, attributable, and recoverable</strong>.</p><h4>Audit trails</h4><p>Application logs are not automatically audit trails.</p><p>Operational logs help engineers debug failures and understand runtime behavior. An audit trail records security-relevant actions in a form suitable for investigation and accountability: who performed an operation, which resource was affected, what changed, when it happened, and under which authorization context.</p><p>Cloud audit systems commonly organize events around the practical question, “Who did what, where, and when?” CISA has also emphasized that high-quality audit logs are necessary for detecting and investigating intrusions.</p><p>A useful audit trail should include more than successful operations. It should capture denied requests, policy changes, key-management events, privilege escalation, credential issuance, revocation, and administrative access.</p><p>It also needs protection from the same actors it records. Storing audit events in the application’s primary database under the application administrator’s control creates a weak evidentiary boundary.</p><h3>A Reference Architecture for Verifiable Data</h3><p>Consider a system that issues records which must later be verified by external parties.</p><p>The record could be a certificate, compliance decision, transaction receipt, laboratory result, license, authorization, or signed business document.</p><p>A practical architecture can include the following workflow:</p><ol><li>A client submits data through an authenticated application.</li><li>An API gateway validates the session, applies rate limits, and forwards the request.</li><li>An authorization service verifies that the actor may issue this type of record.</li><li>The issuance service validates the data against a versioned schema.</li><li>The service creates a canonical payload with the issuer, subject, timestamps, schema version, and unique record identifier.</li><li>A digest is calculated from the canonical payload.</li><li>A managed signing service signs the digest using a non-exportable key.</li><li>The record and signature metadata are stored in the operational database.</li><li>An issuance event is written to an append-only audit stream.</li><li>A verification API allows external consumers to validate the signature, issuer status, schema, expiration, and revocation state.</li></ol><p>The architecture should separate ordinary business processing from cryptographic operations. Application containers should not contain raw production signing keys. Instead, they should request signing operations from a managed key service or hardware-backed signing boundary.</p><p>AWS KMS, for example, supports controlled use of keys for encryption and signing, while its integration with CloudTrail provides records of key usage for auditing.</p><p>A queue between issuance and secondary processing can improve resilience. The primary transaction may store the signed record synchronously, while non-critical work — notifications, search indexing, analytics, and external anchoring — runs asynchronously.</p><p>The core trust evidence should not depend on the queue completing successfully.</p><h4>Suggested architecture diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2ebMgs4YsQAqZYqzzHYYA.png" /></figure><p>The most important boundary in this diagram is not the API gateway. It is the separation between application logic, signing authority, audit evidence, and verification policy.</p><h3>Canonicalization Is an Engineering Requirement</h3><p>Signing structured data is harder than signing a static byte array.</p><p>Two JSON documents may be semantically equivalent while differing in whitespace, key ordering, Unicode representation, number formatting, or omitted optional fields. If the issuer and verifier serialize the same logical data differently, signature verification fails.</p><p>The system therefore needs a deterministic representation.</p><p>Options include:</p><ul><li>a formally defined canonical JSON format;</li><li>deterministic Protocol Buffers or CBOR rules;</li><li>signing a fixed binary representation;</li><li>signing a digest generated by a shared canonicalization library;</li><li>using an established envelope format such as JSON Web Signature.</li></ul><p>JWS defines JSON-based structures for content protected by digital signatures or message authentication codes. Implementations still need strict algorithm validation. The JWT Best Current Practices document warns against accepting unsafe algorithm combinations or allowing attackers to influence cryptographic interpretation.</p><p>A production system should version its signing format from the beginning. Otherwise, changing a field name or serialization library can make historical evidence unverifiable.</p><h3>Trust Requires Lifecycle Management</h3><p>A signature may remain mathematically valid long after it should no longer be accepted.</p><p>The issuer could lose authorization. A private key could be compromised. A record could be superseded. An employee could sign data outside an approved role. A certificate could expire.</p><p>Verification must therefore combine <strong>cryptographic validation</strong> with <strong>current policy evaluation</strong>.</p><p>A verification response may need to distinguish between:</p><ul><li>signature valid;</li><li>issuer recognized;</li><li>key active at issuance time;</li><li>record not revoked;</li><li>schema supported;</li><li>record not expired;</li><li>issuer currently authorized;</li><li>evidence incomplete.</li></ul><p>Reducing all of these checks to a green checkmark hides useful risk information.</p><p>Revocation also creates a deliberate trade-off. Fully offline verification is simple and resilient but cannot immediately reflect new revocations. Online verification provides current status but introduces network latency, availability dependencies, privacy concerns, and denial-of-service exposure.</p><p>Some systems use short-lived assertions. Others publish signed revocation lists or periodically downloadable status snapshots. High-value workflows may require a live status check.</p><p>The right choice depends on how quickly trust decisions must react to compromise.</p><h3>Trade-Offs That Architecture Reviews Must Address</h3><p>Digital trust infrastructure adds meaningful guarantees, but it is not free.</p><p><strong>Key management becomes a critical operational dependency.</strong> Teams need policies for generation, access, rotation, backup, recovery, suspension, and destruction. A lost signing key can interrupt issuance. A stolen key can create apparently legitimate fraudulent records.</p><p><strong>Verification adds latency.</strong> Resolving issuer metadata, retrieving public keys, checking revocation, and evaluating policy may involve several services. Caches reduce latency but introduce staleness.</p><p><strong>More evidence creates more sensitive data.</strong> Audit records can reveal identities, access patterns, resource names, and business activity. Logs need access controls, retention limits, encryption, and privacy review.</p><p><strong>Append-only storage complicates correction.</strong> Incorrect records cannot simply disappear. Corrections usually require compensating events, superseding records, or explicit revocations.</p><p><strong>Interoperability requires governance.</strong> Cryptography cannot resolve disagreements about schemas, issuer eligibility, jurisdiction, or the meaning of a verification result.</p><p>Blockchain-based anchoring may be useful when multiple parties require a shared, independently observable ordering of events. It is often unnecessary when one accountable organization controls issuance and a protected audit store is sufficient. Publishing sensitive records directly to a public ledger is usually inappropriate; at most, carefully designed digests or aggregated commitments should be considered.</p><h3>Production Considerations</h3><p>Trust infrastructure should be operated like a security-critical distributed system, not a utility library added near release.</p><p>Monitor signing latency, verification latency, KMS failures, queue lag, rejected signatures, unknown key identifiers, unusual issuance volume, revocation spikes, and administrative policy changes.</p><p>Use idempotency keys for issuance requests. A client retry after a timeout should not create two independently valid records with different identifiers.</p><p>Separate retryable failures from permanent failures. A temporary KMS timeout may be retried with bounded exponential backoff. Invalid canonical data, unsupported schemas, and revoked issuers should fail without automatic retries.</p><p>Protect verification endpoints with rate limiting, but avoid making legitimate public verification dependent on interactive user accounts. Cache public key metadata and signed status lists with explicit expiration rules.</p><p>Disaster-recovery exercises should include cryptographic dependencies. Restoring the database is not sufficient if key references, audit streams, revocation data, and trust registries cannot be restored consistently.</p><p>Security testing should include algorithm-confusion attempts, malformed signatures, substituted key identifiers, replayed issuance requests, stale revocation caches, compromised administrator scenarios, and canonicalization edge cases.</p><p>Finally, incident response procedures must define what happens after suspected key compromise. Teams need a way to suspend issuance, publish key status, identify affected records, rotate keys, and communicate verification consequences.</p><h3>Practical Recommendations for Engineering Teams</h3><h4>1. Define the trust decision before selecting technology</h4><p>Write down exactly what a verifier must prove. Data integrity, issuer identity, issuer authority, freshness, and non-revocation are separate properties. This prevents teams from treating a valid hash or signature as a complete trust decision.</p><h4>2. Sign a versioned canonical envelope</h4><p>Include the payload digest, issuer identifier, schema version, issuance time, record identifier, and signing-key identifier in a deterministic envelope. Version the format so historical records remain verifiable after the application evolves.</p><h4>3. Keep signing keys outside application runtime</h4><p>Use a managed KMS or HSM-backed service with narrowly scoped permissions. Application services should request a signing operation, not retrieve the private key. Record every administrative and cryptographic key operation in a separately controlled audit system.</p><h4>4. Design revocation before the first record is issued</h4><p>Specify who may revoke a record, which reason codes exist, how quickly verifiers receive updates, and what happens when the status service is unavailable. Adding revocation after deployment often creates incompatible verification behavior.</p><h4>5. Separate verification facts from policy outcomes</h4><p>Return structured facts such as signature status, issuer status, timestamps, and revocation state. Let a policy layer decide whether those facts are acceptable for a specific use case. A bank, university, and public information portal may apply different risk thresholds to the same evidence.</p><h4>6. Test the trust chain under partial failure</h4><p>Simulate an unavailable key registry, delayed revocation updates, corrupted audit events, duplicate issuance requests, and regional outages. The system should fail explicitly rather than silently downgrade verification.</p><h3>Why This Matters Beyond One Application</h3><p>Reliable digital infrastructure depends on organizations being able to exchange information without requiring complete access to one another’s internal systems.</p><p>Financial institutions need to validate claims from customers and external providers. Healthcare organizations need integrity and accountability when records move between systems. Educational institutions and employers need portable verification. Government agencies need digital services that remain auditable across contractors, departments, and public-private workflows.</p><p>The goal is not to eliminate institutional trust. Technology cannot determine whether an organization is honest, competent, or legally authorized.</p><p>The goal is to make trust decisions more evidence-based.</p><p>When records carry verifiable provenance, integrity protection, lifecycle status, and auditable history, organizations spend less effort reconstructing trust through screenshots, manual emails, phone calls, and duplicated databases. Fraud becomes harder to scale, investigations become more precise, and system boundaries become easier to reason about.</p><h3>Conclusion</h3><p>Authentication proves that an identity passed a security check at a particular moment. It does not guarantee that exported data remains authentic, unchanged, authorized, and valid after it leaves the application.</p><p>Digital trust infrastructure extends security beyond the login session. It combines signatures, key governance, deterministic data formats, audit evidence, revocation, and explicit verification policy into an end-to-end trust chain.</p><p>The architectural principle worth remembering is simple:</p><p><strong>Do not ask downstream systems to trust data merely because it once came from a trusted application. Give them the evidence required to verify it independently.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a7beec78c92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Gasless Academic Credential System on Hedera]]></title>
            <link>https://medium.com/coinmonks/building-a-gasless-academic-credential-system-on-hedera-a79b317e85a4?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a79b317e85a4</guid>
            <category><![CDATA[digital-identity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ipfs]]></category>
            <category><![CDATA[decentralization]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 22:50:57 GMT</pubDate>
            <atom:updated>2026-07-21T14:04:58.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPDq97C1qO5R6dxArdj5mw.png" /></figure><h3>Introduction</h3><p>Universities around the world still issue academic credentials as static PDF documents or paper diplomas. While these formats are familiar, they introduce several problems. Verifying a diploma often requires manual communication with the issuing institution, which can take days or even weeks. At the same time, diploma fraud remains a global issue, with fake or altered documents appearing in job applications and professional licensing processes.</p><p>In a digital-first world, this system feels outdated.</p><p>What if academic credentials could be verified instantly, shared globally, and owned directly by the people who earned them?</p><p>This idea led to the creation of <strong>D-Certify</strong>, a decentralized credential issuance and verification system built on the <strong>Hedera</strong> network. The system allows universities to issue diplomas as verifiable digital assets while providing instant and tamper-proof verification for employers and institutions.</p><p>By combining blockchain infrastructure with modern storage systems, D-Certify transforms academic credentials from static documents into verifiable digital assets.</p><h3>Why Blockchain for Academic Credentials?</h3><p>Traditional credential systems rely on centralized databases controlled by universities or credential verification services. While these systems function, they introduce several structural weaknesses:</p><ul><li><strong>Centralized trust</strong> — verification depends on the availability and cooperation of the issuing institution.</li><li><strong>Slow verification</strong> — manual verification processes can take days or weeks.</li><li><strong>Fraud risk</strong> — digital documents can be edited, copied, or forged.</li><li><strong>Limited portability</strong> — credentials are often difficult to verify across countries or institutions.</li></ul><p>Blockchain infrastructure addresses these problems by introducing several key properties:</p><p><strong>Immutability</strong><br>Once a credential record is written to the ledger, it cannot be altered.</p><p><strong>Transparency</strong><br>Verification can be performed independently without contacting the issuing institution.</p><p><strong>User ownership</strong><br>Credentials can exist as digital assets held directly by students.</p><p><strong>Global accessibility</strong><br>Anyone with access to the network can verify the authenticity of a credential.</p><p>In this model, academic credentials become <strong>verifiable digital assets</strong>, rather than static files stored in institutional databases.</p><h3>Why Hedera?</h3><p>D-Certify is built on <strong>Hedera</strong>, a distributed ledger designed for high throughput, predictable costs, and enterprise-scale applications.</p><p>Several characteristics make Hedera particularly suitable for credential infrastructure:</p><ul><li><strong>Very low transaction fees</strong></li><li><strong>High transaction throughput</strong></li><li><strong>Fast consensus finality</strong></li><li><strong>Predictable network costs</strong></li></ul><p>Two native Hedera services are central to the architecture of D-Certify:</p><p><strong>Hedera Token Service (HTS)</strong><br>Used to mint diplomas as NFTs and assign ownership to students.</p><p><strong>Hedera Consensus Service (HCS)</strong><br>Used to create immutable audit logs of credential issuance events.</p><p>Together, these services allow the system to represent both <strong>ownership</strong> and <strong>verification history</strong> on-chain.</p><h3>System Architecture</h3><p>The architecture of D-Certify is designed to balance decentralization with usability.</p><p>The system consists of four primary layers.</p><h4>Frontend</h4><p>The system provides three user interfaces designed for different roles in the credential lifecycle.</p><p><strong>University Dashboard</strong></p><p>Used by universities or educational institutions to:</p><ul><li>issue new academic credentials</li><li>upload diploma documents</li><li>manage issued certificates</li></ul><p>This interface is used by authorized issuers only.</p><p><strong>Student Dashboard</strong></p><p>Students use this dashboard to:</p><ul><li>view pending credentials issued to them</li><li>accept and claim ownership of their diploma NFT</li><li>access their verified academic records</li></ul><p>When a student accepts a credential, the NFT representing the diploma is transferred to the student’s account.</p><p><strong>Verification Dashboard</strong></p><p>This interface is used by employers, institutions, or third parties to verify credentials.</p><p>Verification can be performed by:</p><ul><li>uploading a diploma document</li><li>entering a credential issuance ID</li></ul><p>The system then validates the credential using on-chain records and metadata.</p><h4>Backend</h4><p>The backend manages several critical processes:</p><ul><li>document hashing</li><li>metadata creation</li><li>interaction with Hedera SDK</li><li>NFT minting</li><li>consensus logging</li></ul><p>This layer ensures that credential issuance follows a deterministic and verifiable workflow.</p><h4>Storage Layer</h4><p>Credential metadata and documents are stored using IPFS (InterPlanetary File System), a decentralized storage network.</p><p>This ensures that credential data remains accessible even if the application infrastructure changes.</p><h4>Blockchain Layer</h4><p>The blockchain layer consists of two Hedera services:</p><ul><li><strong>HTS for credential ownership</strong></li><li><strong>HCS for issuance audit logs</strong></li></ul><p>This combination allows the system to track both <strong>who owns a credential</strong> and <strong>when it was issued</strong>.</p><h3>Credential Issuance Flow</h3><p>Issuing a diploma through D-Certify involves several steps designed to ensure both authenticity and verifiability.</p><h4>Step 1 — Document Upload</h4><p>A university administrator uploads the diploma document through the issuance dashboard.</p><p>This document may be a PDF containing the student’s academic credential.</p><h4>Step 2 — Document Hashing</h4><p>Instead of manually hashing the document, the system uploads the credential file directly to IPFS.</p><p>IPFS generates a <strong>Content Identifier (CID)</strong> based on the file’s content. This CID acts as a unique fingerprint of the document.</p><p>Because the CID is derived from the file data, any modification to the document would produce a completely different identifier.</p><p>This property allows the system to detect document tampering without requiring manual hashing in the application layer.</p><h4>Step 3 — Metadata Storage on IPFS</h4><p>Credential metadata is stored on IPFS.</p><p>An example metadata structure may look like this:</p><pre>{<br>  &quot;type&quot;: &quot;diploma&quot;,<br>  &quot;issuer&quot;: {<br>    &quot;name&quot;: &quot;University at Buffalo&quot;,<br>    &quot;email&quot;: &quot;university-at-buffalo-123@gmail.com&quot;,<br>    &quot;accountId&quot;: &quot;0.0.7992656&quot;<br>  },<br>  &quot;customer&quot;: {<br>    &quot;name&quot;: &quot;Kyrylo Sotnykov&quot;,<br>    &quot;email&quot;: &quot;kyrylo.sotnykov@gmail.com&quot;,<br>    &quot;accountId&quot;: &quot;0.0.7992657&quot;<br>  },<br>  &quot;credential&quot;: {<br>    &quot;title&quot;: &quot;Blockchain Specialization Certificate&quot;,<br>    &quot;cid&quot;: &quot;bafybeicekcmwcwmbk3l7yq3rajkzppg7cbqmy66kuwf6ac37cevtkogk2m&quot;,<br>    &quot;issuedAt&quot;: &quot;2026-03-10T22:06:41.581Z&quot;<br>  },<br>  &quot;storage&quot;: {<br>    &quot;file&quot;: &quot;https://ipfs.io/ipfs/bafybeicekcmwcwmbk3l7yq3rajkzppg7cbqmy66kuwf6ac37cevtkogk2m&quot;<br>  }<br>}</pre><p>Storing metadata on IPFS ensures the information remains decentralized and accessible.</p><h4>Step 4 — NFT Minting via HTS</h4><p>Next, the system uses the Hedera Token Service to mint an NFT representing the diploma.</p><p>Each NFT represents a unique academic credential and contains a reference to the metadata stored on IPFS.</p><p>Ownership of this NFT is then transferred to the student’s account.</p><p>This step establishes <strong>user ownership</strong> of the credential.</p><h4>Step 5 — Consensus Logging via HCS</h4><p>Finally, the issuance event is recorded using Hedera Consensus Service.</p><p>The message recorded in the consensus topic may include:</p><ul><li>the credential hash</li><li>token ID</li><li>issuer identifier</li><li>timestamp</li></ul><p>Because Hedera provides a consensus timestamp, this record becomes a permanent and verifiable audit log of the credential issuance event.</p><h3>Student Credential Claim Flow</h3><p>After a university issues a credential, the student must claim ownership of the diploma NFT.</p><p>This step ensures that credentials are ultimately controlled by the people who earned them.</p><h4>Step 1 — Credential Notification</h4><p>The student receives a notification that a new credential has been issued for them.</p><p>The credential appears in the <strong>Student Dashboard</strong> as a pending record.</p><h4>Step 2 — Student Review</h4><p>The student can review:</p><ul><li>diploma details</li><li>issuing university</li><li>issuance date</li><li>credential metadata</li></ul><h4>Step 3 — Credential Acceptance</h4><p>When the student accepts the credential:</p><ul><li>the system executes a token transfer transaction</li><li>the NFT representing the diploma is transferred to the student’s Hedera account</li></ul><p>This establishes <strong>student ownership of the credential</strong>.</p><h4>Step 4 — Ownership Confirmation</h4><p>Once the transfer is confirmed:</p><ul><li>the credential appears in the student’s wallet</li><li>the ownership record becomes publicly verifiable on the ledger</li></ul><p>From this moment, the student fully controls their diploma as a digital asset.</p><h3>Instant Credential Verification</h3><p>One of the key benefits of this system is the ability to verify credentials instantly.</p><p>Verification can be performed in two ways:</p><ol><li><strong>Document verification</strong> — uploading a diploma file.</li><li><strong>Credential lookup</strong> — entering a credential issuance ID.</li></ol><p>Both methods validate the credential against:</p><ul><li>IPFS metadata</li><li>NFT records</li><li>Hedera consensus logs.</li></ul><p>The verification process follows a simple sequence.</p><h4>Step 1 — Upload the Credential</h4><p>An employer or institution uploads the diploma document to the verification portal.</p><h4>Step 2 — Hash Calculation</h4><p>The system computes the <strong>Content Identifier (CID)</strong> of the uploaded document.</p><h4>Step 3 — Cross-Reference</h4><p>The calculated hash is compared against:</p><ul><li>metadata stored on IPFS</li><li>issuance records stored via HCS</li><li>NFT ownership records on HTS</li></ul><h4>Step 4 — Verification Result</h4><p>If all values match, the credential is verified as authentic.</p><p>If the hashes do not match, the system flags the document as potentially altered.</p><p>This verification process typically takes only seconds.</p><h3>Gasless User Experience</h3><p>One of the biggest barriers to blockchain adoption is user experience.</p><p>Universities and employers typically do not want to manage:</p><ul><li>wallets</li><li>private keys</li><li>transaction fees</li><li>blockchain onboarding</li></ul><p>To address this, D-Certify implements a <strong>gasless architecture</strong>.</p><p>The backend infrastructure manages blockchain transactions on behalf of users. This allows universities to issue credentials and students to receive them without directly interacting with blockchain wallets.</p><p>As a result, the user experience remains simple and familiar while still benefiting from decentralized infrastructure.</p><h3>Security Model</h3><p>Security is a critical consideration for any credential system.</p><p>D-Certify uses several mechanisms to protect the integrity of the system.</p><p><strong>Controlled Issuer Permissions</strong><br>Only authorized university accounts can issue new credentials.</p><p><strong>Cryptographic Hash Verification</strong><br>Document hashes ensure that any modification to a credential can be detected.</p><p><strong>Immutable Audit Logs</strong><br>HCS provides consensus timestamps that prevent retroactive modification of issuance records.</p><p><strong>Decentralized Metadata Storage</strong><br>IPFS ensures that credential data remains accessible without relying on a single server.</p><p>Together, these mechanisms create a robust and tamper-resistant credential infrastructure.</p><h3>Real-World Impact</h3><p>A decentralized credential system has practical benefits for several groups.</p><h4>Universities</h4><ul><li>automate credential issuance</li><li>protect institutional reputation</li><li>reduce verification workload</li></ul><h4>Students</h4><ul><li>gain ownership of their academic credentials</li><li>share verifiable diplomas globally</li><li>verify credentials instantly</li></ul><h4>Employers</h4><ul><li>eliminate manual verification processes</li><li>detect credential fraud immediately</li><li>reduce hiring delays</li></ul><p>In a global job market where credentials often cross borders, instant verification can significantly improve efficiency and trust.</p><h3>Hackathon Context</h3><p>D-Certify was developed during <strong>ETHDenver 2026</strong> as an exploration of how decentralized infrastructure can modernize academic credential systems.</p><h3>Conclusion</h3><p>Academic credentials are a fundamental part of professional identity, yet the systems used to issue and verify them remain outdated.</p><p>By combining decentralized storage, cryptographic verification, and distributed ledger infrastructure, D-Certify demonstrates how academic credentials can evolve into <strong>verifiable digital assets owned directly by students</strong>.</p><p>Using Hedera’s native services for tokenization and consensus logging, the system provides both ownership and tamper-proof verification.</p><p>In the long term, infrastructure like this could form the foundation for a global, interoperable credential network — where diplomas, certifications, and professional achievements are instantly verifiable and securely owned by the people who earned them.</p><h3>Try It Yourself</h3><p>D-Certify is open-source and available for free. You can examine the code, run your own instance, or contribute ideas on <a href="https://github.com/KirillSotnikov/d-certify-hedera-sdk">GitHub</a>.</p><p>👉 Check out the <a href="https://d-certify.sotnykov.com/">live demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a79b317e85a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/building-a-gasless-academic-credential-system-on-hedera-a79b317e85a4">Building a Gasless Academic Credential System on Hedera</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[How I Built a Patent-Pending Client-Side Feature Unlocking System That Works Offline]]></title>
            <link>https://medium.com/@comicon2508/how-i-built-a-patent-pending-client-side-feature-unlocking-system-that-works-offline-7c0ccfdce75d?source=rss-aabf52d06cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c0ccfdce75d</guid>
            <category><![CDATA[patents]]></category>
            <category><![CDATA[offline-apps]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[app-optimization]]></category>
            <dc:creator><![CDATA[Kyrylo Sotnykov]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 20:40:53 GMT</pubDate>
            <atom:updated>2025-08-10T20:40:53.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8XUFsIXeD6lv1oQk37pWA.jpeg" /></figure><p>Most applications rely on servers for even simple things — like whether or not a feature is available to you. That also means that if you lose your internet connection, you can lose access to features you’ve paid for. It’s frustrating, slows down development, and costs money to maintain.</p><p>I wanted to do something different.</p><p>I have recently filed a patent with the United States Patent and Trademark Office (USPTO Application №63/861,081) for an offline client-side feature unlocking system. The system supports multiple unlocking mechanisms, stores progress locally, and works seamlessly in web and mobile applications.</p><h3>The Problem</h3><p>Feature unlocking is a common pattern in modern software — especially in onboarding, gamification, and trial-based SaaS offerings. Most implementations, though, are server-dependent, which has several drawbacks:</p><ul><li>Infrastructure overhead: servers, databases, and API endpoints are not just costly to set up but also to maintain.</li><li>Network dependency: no internet, no access.</li><li>Slower MVP development: backend infrastructure slows down early releases.</li><li>Scalability problems: centralized servers become bottlenecks.</li></ul><p>This dependency is unnecessary for the majority of use cases — especially those that can be executed entirely on the client’s device.</p><h3>The Idea</h3><p>The concept is simple: move the unlocking logic entirely to the client. My implementation:</p><ul><li>Works offline.</li><li>Includes four unlocking methods: time-based, usage-based, interval-based, and code-based.</li><li>Stores all progress in <em>localStorage</em> (web) or <em>AsyncStorage</em> (mobile).</li><li>Obfuscates stored data to dissuade tampering.</li></ul><p>The result is a light, scalable, and privacy-friendly way of managing feature access with zero server call.</p><h3>Architecture — How It Works</h3><p>The architecture is made simple yet flexible. It has four main layers:</p><ol><li>Storage Layer — Saves feature states between sessions using <em>localStorage</em> (web) or <em>AsyncStorage</em> (mobile).</li><li>Logic Engine — TypeScript-based evaluation system that decides if a feature meets its unlocking conditions.</li><li>UI Integration — React components that display feature states and permit interaction.</li><li>Obfuscation Layer — Base64-encoded keys with a prefix to make direct tampering harder.</li></ol><p>The data flow is straightforward: user actions update stored values → logic engine evaluates conditions → UI updates in real time — without ever hitting a server.</p><h3>Unlock Mechanisms</h3><p>The system provides four unlocking strategies, which can be used individually or in any combination:</p><ul><li>Time-based — Unlock a feature after a specific duration.</li></ul><pre>{ type: &#39;time&#39;, delayMs: 86400000 } // 24 hours</pre><ul><li>Usage-based — Unlock after another feature is used X times.</li></ul><pre>{ type: &#39;usage&#39;, feature: &#39;basic_export&#39;, count: 5 }</pre><ul><li>Interval-based — Require a cooldown period between uses.</li></ul><pre>{ type: &#39;interval&#39;, cooldownMs: 3600000 } // 1 hour</pre><ul><li>Code-based — Unlock with a secret code.</li></ul><pre>{ type: &#39;code&#39;, code: &#39;PREMIUM123&#39; }</pre><h3>Real-World Use Cases</h3><p>Some places where this system shines are:</p><ul><li><strong>EdTech</strong> — Progressively unlock lessons as students complete prior modules.</li><li><strong>SaaS Trials</strong> — Gradually reveal premium features during trial demos to enhance engagement.</li><li><strong>Mobile Onboarding</strong> — Introduce features progressively instead of overwhelming new users.</li><li><strong>AI Apps</strong> — Unlock advanced AI features as users demonstrate skill or engagement.</li><li><strong>Offline Tools</strong> — Provide complete functionality in low-or-no-connectivity situations.</li></ul><h3>Why Not Servers?</h3><p>So why skip servers entirely? Here’s the contrast:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kysRPFOKL0XzNm2d-E0r9Q.png" /></figure><p>Servers are great if you need centralized control or real-time updates, but for most applications, they’re an unnecessary cost.</p><h3>Patent &amp; Innovation</h3><p>This technique is not a coding workaround — it is patent pending.</p><p>Filed with the United States Patent and Trademark Office (USPTO Application №63/861,081) on August 10, 2025, the invention protects:</p><ul><li>A unified architecture for client-side progressive feature unlocking.</li><li>Support for multiple unlocking mechanisms.</li><li>Full offline support.</li><li>Cross-platform support.</li></ul><p>To my knowledge, there is no existing solution that supports this combination without a backend.</p><h3>Conclusion</h3><p>Working on this system helped me understand that the best solution is often the simplest — and, in this case, removing servers opened up new possibilities:</p><ul><li>Faster MVP launches.</li><li>Better offline user experience.</li><li>Lower operational costs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c0ccfdce75d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>