<?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 Mohammad Khezer on Medium]]></title>
        <description><![CDATA[Stories by Mohammad Khezer on Medium]]></description>
        <link>https://medium.com/@mamk13?source=rss-5348cf74cf4f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jaC2q0iRwM-UB03IQA1I-A.jpeg</url>
            <title>Stories by Mohammad Khezer on Medium</title>
            <link>https://medium.com/@mamk13?source=rss-5348cf74cf4f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:03:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mamk13/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[Prove the Recipient, Measure the Receipt: Two Boundaries in Token Distribution]]></title>
            <link>https://mamk13.medium.com/prove-the-recipient-measure-the-receipt-two-boundaries-in-token-distribution-dde485225ca4?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dde485225ca4</guid>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 12:01:01 GMT</pubDate>
            <atom:updated>2026-11-18T12:01:01.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Conceptual illustration for Prove the Recipient, Measure the Receipt: Two Boundaries in Token Distribution" src="https://cdn-images-1.medium.com/max/1024/1*08CHGOvGCLYfF_eleUX51Q.png" /><figcaption>AI-generated conceptual illustration.</figcaption></figure><p>A proof can establish that an allocation exists while failing to establish who should receive it. A successful transfer can move tokens while failing to deliver the amount that the receiving application credits. Both problems begin when one observation is asked to prove more than it actually establishes.</p><p>This educational article was prepared with AI writing assistance. Its examples use locally tested Python fixtures, not live tokens, Ethereum proofs or a reconstruction of an incident.</p><p>The two boundaries are distinct. A claim proof must bind the settlement fields that the application trusts. Deposit accounting must identify the assets actually received under the supported token model. Combining a cryptographic-looking proof with a transfer call does not remove either obligation.</p><h3>Requested units and received units</h3><p>Suppose Alice requests a deposit of 100 integer units. The teaching token charges a 1% fee, delivering 99 units to the vault and recording one unit in its fee ledger. If the vault credits Alice with 100, it has created a one-unit liability without backing.</p><p>Lab 13 compares that requested-amount negative control with a received-amount path. The corrected path measures the vault’s balance immediately before and after the transfer, then credits the positive difference.</p><pre>before = token.balance_of(vault)<br>require(token.transfer_from(owner, vault, requested))<br>received = token.balance_of(vault) - before<br>require(received &gt; 0)<br>require(received &gt;= min_received)<br>credit(owner, received)</pre><p>This is explanatory pseudocode, not a safe universal token adapter. The executable fixture is much narrower: synchronous, non-rebasing, honest balances, integer units and no callbacks. Under those assumptions, the measured delta belongs to the deposit being processed.</p><p><a href="https://eips.ethereum.org/EIPS/eip-20">ERC-20</a> requires callers to handle a false return. That is one check in the model. The synthetic fee behavior is an explicit test assumption, not a statement that every ERC-20 implementation behaves this way or that interface conformance establishes transfer economics.</p><h3>A minimum protects the depositor’s expectation</h3><p>Correct vault backing does not by itself protect Alice’s expectation. If Alice intended to receive 100 units of credit, silently crediting 99 may be unacceptable even though the vault remains solvent.</p><p>The min_received parameter makes that expectation explicit. The tests attempt a 100-unit deposit with a minimum of 100 and require rejection. They then use a minimum of 99 and require success.</p><p>For the rejected attempt, the test inspects all fixture ledgers: Alice’s balance, vault assets, fee balance and deposit credits. The model explicitly restores those ledgers. An exception alone would not reverse an earlier Python dictionary mutation.</p><p>The units are raw integers, not display amounts. The fee calculation floors requested * fee_bps / 10_000. For small inputs, rounding changes the fee. Tests cover amounts around the 100-unit boundary and multiple fee values, with conservation checks over all token balances.</p><h3>A balance delta has assumptions too</h3><p>Measuring a balance delta avoids crediting a preexisting donation to Alice. Lab 13 places 50 units in the vault first, then processes the 100-unit request with the 1% fee. Vault assets become 149, but Alice receives 99 of credit.</p><p>That does not make delta accounting universally safe. A rebase during the operation, a dishonest balance query, unrelated concurrent changes or callbacks can invalidate the inference that the whole difference belongs to this depositor. Outbound transfer fees create a separate redemption problem that this deposit fixture does not model.</p><p>The correct review question is therefore not “Did we use before and after balances?” It is “Under which token behaviors does this difference measure the quantity we are promising to credit?” Unsupported assets need an explicit policy; a familiar interface is not that policy.</p><h3>Membership is not payment authorization unless the leaf binds payment</h3><p>Lab 14 moves to the outgoing allocation boundary. Its two-leaf teaching tree contains Alice’s 10-unit claim and Bob’s 20-unit claim. Each corrected leaf commits to campaign, allocation index, account and amount.</p><p>The negative control omits the account. Eve can then submit the same campaign, index and amount while replacing Alice as the recipient. The proof still matches because the omitted field never influenced the leaf.</p><p>The corrected leaf includes the account, so recipient substitution changes the hash and fails verification. The application records payment to the proven account. A relayer may submit the claim, but the submitter does not get to rewrite the recipient.</p><p>The lesson is not that a particular hash function is broken. It is that the application verified the wrong proposition. “This amount is in the tree” is weaker than “This account owns this amount in this campaign.”</p><p>The implementation uses SHA-256, tagged leaf/node inputs and JSON arrays solely to make the test deterministic and inspectable. It is not Keccak, Ethereum ABI encoding or an OpenZeppelin-compatible tree. <a href="https://docs.openzeppelin.com/contracts/5.x/api/utils/cryptography#MerkleProof">OpenZeppelin’s MerkleProof documentation</a> is background for verification and encoding review, not an installed dependency.</p><h3>A root update should not erase payment history</h3><p>Root rotation introduces another boundary. Suppose Alice has already claimed index 0. An administrator updates Bob’s amount from 20 to 30 and publishes a new root. If the application clears all consumed indices whenever the root changes, Alice may collect again from the updated tree.</p><p>Lab 14 retains consumption across roots within the same campaign. Alice’s old index stays spent; Bob can claim the updated allocation under the new proof. The model assumes allocation indices preserve their meaning across rotations. An administrator cannot safely reuse a spent index for a different person and then blame the replay guard for refusing payment.</p><p>Campaigns have separate consumption scopes. A genuinely new campaign can allocate to Alice again. The campaign identifier is bound into the leaf, while each distributor accepts only its own campaign. This avoids confusing a legitimate new allocation with replay of an old one.</p><p>The root administrator remains trusted in this model. Proof verification cannot protect recipients from an administrator who publishes a malicious allocation set. The model also records credits rather than performing funded token transfers, so it establishes neither solvency nor callback safety.</p><h3>Test the rejected path before the happy path</h3><p>For a bad proof, assert that the index remains unused. Then submit the correct proof and require one successful claim. For a deposit below the minimum, assert that no fee, debit or credit survives, then retry with a supported minimum. Recovery tests reveal whether failure has become a denial-of-service primitive.</p><p>On October 15, 2026, <a href="https://github.com/mamk13/blockchain-security-labs/tree/7aec1fadfcee43538de8dfa599e568138e1a2d97/labs/13-received-amount-credit">Lab 13</a> passed 8 tests and <a href="https://github.com/mamk13/blockchain-security-labs/tree/7aec1fadfcee43538de8dfa599e568138e1a2d97/labs/14-merkle-claim-binding">Lab 14</a> passed 7 tests using pinned CPython 3.12.14, standard-library dependencies and separate local suite processes. The collection passed 137 tests locally, and <a href="https://github.com/mamk13/blockchain-security-labs/actions/runs/38708110272">hosted CI</a> succeeded for the linked commit.</p><p>No live token, wallet, RPC, EVM execution or historical exploit was used. There is no asserted incident date, affected address, loss or deployed remediation. The practical output is a pair of reproducible questions: does the proof bind the recipient being paid, and does the credited quantity equal the supported operation’s actual receipt?</p><p>Disclosure: AI-assisted research, writing, educational-model preparation and cover illustration. The image is conceptual, not incident evidence. Historical test dates and model limitations are retained; no new execution or production-security validation is claimed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dde485225ca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Payment Can Be Safe to Repeat and Still Impossible to Finish]]></title>
            <link>https://mamk13.medium.com/a-payment-can-be-safe-to-repeat-and-still-impossible-to-finish-6d0e7f2a62e7?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d0e7f2a62e7</guid>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 12:01:01 GMT</pubDate>
            <atom:updated>2026-11-17T12:01:01.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Conceptual illustration for A Payment Can Be Safe to Repeat and Still Impossible to Finish" src="https://cdn-images-1.medium.com/max/1024/1*g-Ors81twhkOSsTnTb9rTg.png" /><figcaption>AI-generated conceptual illustration.</figcaption></figure><p>A payment system has at least two obligations: prevent someone from collecting more than they are owed, and let eligible recipients collect despite another recipient’s failure. Passing the first test does not establish the second.</p><p>This educational article was prepared with AI writing assistance. The examples are deterministic Python models, with explicit execution assumptions and test results; they are not Solidity contracts or an exploit replay.</p><p>Imagine a distributor holding 20 units: 10 for Alice and 10 for Bob. Alice’s receiver calls back into the withdrawal path. In one implementation, Alice collects twice and uses the cash that should back Bob’s claim. In another design, neither recipient can collect because an unrelated receiver rejects a batch payment. Both outcomes are failures, but they require different specifications and different tests.</p><p>The first is an accounting safety problem at an interaction boundary. The second is a progress problem created by sharing a failure boundary. Treating both as “add a reentrancy guard” hides the distinction.</p><h3>What a callback can observe</h3><p><a href="https://docs.soliditylang.org/en/latest/security-considerations.html#reentrancy">Solidity’s security guidance</a> explains why external interactions require care and motivates checks-effects-interactions. A receiver may execute code before the original operation has finished. The relevant question is what state that code can observe and use.</p><p>Lab 11 deliberately represents a withdrawal in two orders. The negative control transfers the modeled cash and invokes the callback before clearing the claim. The corrected order clears the claim first.</p><p>The essential difference is:</p><pre># Negative control<br>transfer_to_ledger(owner, amount)<br>callback()<br>claims[owner] = 0</pre><pre># Corrected ordering for this model<br>claims[owner] = 0<br>transfer_to_ledger(owner, amount)<br>callback()</pre><p>This sketch is not a production implementation. It omits caller authentication, token adapters and many possible shared-state relationships. Its purpose is to expose exactly one question: is the same claim still payable when control reaches the receiver?</p><h3>Test the other recipient’s backing</h3><p>The callback in the negative control withdraws Alice’s claim again. Because the first call has not cleared it, the nested call sees another payable 10 units. Alice receives 20. Bob still has a 10-unit claim, but cash is now zero.</p><p>An assertion on Alice’s final claim alone would miss the insolvency: her claim is zero in both implementations. A stronger assertion compares remaining cash with remaining liabilities. In the vulnerable trace, cash is less than the sum of claims. In the corrected trace, the nested call rejects, Alice receives 10 and Bob’s 10 remains funded.</p><p>Lab 11 then executes Bob’s withdrawal to show that the intended positive path survives. Rejecting every withdrawal would prevent the attack too, but would not satisfy the system’s function.</p><p>This is the advantage of a paired negative control. The same scenario produces the prohibited result under a deliberate defect and the intended result under the correction. It demonstrates that the regression is sensitive to the specific ordering mistake.</p><h3>Failure is not one undifferentiated event</h3><p>Callback failure raises a second question: which effects survive?</p><p>The model implements a snapshot of its claims, cash and received-credit dictionaries for each withdrawal. If a callback failure propagates out of that call, those dictionaries are restored. This is explicit code, not a property supplied automatically by a Python exception.</p><p>One test lets Bob’s nested withdrawal succeed, then makes Alice’s outer callback fail. The outer snapshot restores both operations’ ledger changes. Another test makes Bob’s nested withdrawal fail but catches that failure in the outer callback. Bob’s inner effects are restored while Alice’s outer withdrawal can complete.</p><p>These traces distinguish failure propagation from failure recovery. A test that simply expects “some exception” cannot tell whether the outer operation committed, whether an inner operation partially survived, or whether a recipient can safely retry.</p><p>The rollback boundary is narrow. Arbitrary callback side effects outside the model’s dictionaries are not restored. No real EVM transaction, gas behavior, cross-contract storage or external system was executed. Translating the lesson requires testing the target environment’s actual semantics.</p><h3>A rejecting recipient can block a batch without stealing</h3><p>Lab 12 isolates liveness. It has three allocations: Alice 10, Eve 5 and Bob 7. Its receiver-acceptance fixture is side-effect-free; it is intentionally not a reentrant external call.</p><p>The push_all negative control puts every recipient in one all-or-nothing transaction model. Alice&#39;s payment is attempted, Eve rejects, and the snapshot restores the batch. Bob is never paid. Repeating the same batch repeats the same failure.</p><p>Accounting can remain perfectly consistent throughout. No recipient gets too much. No money disappears. Yet cooperative recipients cannot make progress because their success depends on Eve accepting payment.</p><p><a href="https://docs.soliditylang.org/en/latest/common-patterns.html#withdrawal-from-contracts">Solidity’s withdrawal-pattern documentation</a> provides the conceptual alternative: recipients withdraw independently. Lab 12’s independent claim calls let Alice and Bob collect while Eve’s rejected allocation remains pending and funded.</p><p>The guarantee is deliberately limited. It says Eve’s rejection does not prevent other willing recipients from using their independent paths. It does not force Eve to accept payment, guarantee a transaction will be included, or supply gas and incentives for a recipient who never acts.</p><h3>Failure isolation has costs</h3><p>Pull payments change who initiates settlement. A recipient may need an extra transaction and a way to discover the pending claim. An application may require a relayer, expiry rule or recovery path. Those mechanisms introduce new authority and availability questions.</p><p>The model makes none of those decisions. Its recovery test simply changes the acceptance fixture from rejection to success and verifies that Eve can collect the retained claim exactly once. Repeated failed attempts must not burn that entitlement.</p><p>Conservation is checked after different claim orders: remaining cash equals unpaid allocations, and remaining cash plus received credits equals the original total. This complements the progress test. A path that lets everyone claim but quietly overpays is not an acceptable liveness improvement.</p><h3>Reproduce the two boundaries separately</h3><p>On October 15, 2026, <a href="https://github.com/mamk13/blockchain-security-labs/tree/7aec1fadfcee43538de8dfa599e568138e1a2d97/labs/11-callback-settlement">Lab 11</a> passed 6 tests and <a href="https://github.com/mamk13/blockchain-security-labs/tree/7aec1fadfcee43538de8dfa599e568138e1a2d97/labs/12-payment-liveness">Lab 12</a> passed 6 tests under CPython 3.12.14. Each ran in a separate process using only the standard library. All 137 collection tests passed locally; <a href="https://github.com/mamk13/blockchain-security-labs/actions/runs/38708110272">hosted CI run 38708110272</a> succeeded for the linked commit.</p><p>There were no RPC calls, wallets or live transactions. No affected deployment, loss or production remediation is claimed. These are educational models with exercises and solutions, not security certificates.</p><p>When reviewing a payment path, keep two assertions visible: “No one receives more than their allocation” and “One recipient’s rejection does not block another independent recipient.” Then write the state transitions that make each statement meaningful. Safety and progress meet at settlement, but neither proves the other.</p><p>Disclosure: AI-assisted research, writing, educational-model preparation and cover illustration. The image is conceptual, not incident evidence. Historical test dates and model limitations are retained; no new execution or production-security validation is claimed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d0e7f2a62e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Upgrade Path Is Part of Your Security Boundary]]></title>
            <link>https://mamk13.medium.com/the-upgrade-path-is-part-of-your-security-boundary-19d45c9b508f?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d45c9b508f</guid>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 12:01:02 GMT</pubDate>
            <atom:updated>2026-11-16T12:01:02.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Nested architectural gates linked to an upper control mechanism, illustrating how upgrade authority can change an application security boundary." src="https://cdn-images-1.medium.com/max/1024/1*zVdhotNfn5n9oGMc5rOnvw.png" /><figcaption>AI-generated conceptual illustration.</figcaption></figure><p><strong>Historical review, with an editorial update on November 16, 2026.</strong> The original evidence cutoff was September 28. Response and custody statements below are attributed to the dated September reports, not asserted as current recovery status. Cosmos Labs later added a September 29 postmortem link; references to a forthcoming report have been corrected. This remains a preliminary engineering review, not a complete updated forensic reconstruction.</p><p><em>A preliminary review of the September 22, 2026 Neutron governance incident, with a tested educational upgrade model.</em></p><p>An application can enforce its permissions perfectly and still lose its security boundary when another authority can replace those permissions — or the application itself.</p><p>That is the engineering question behind this review: <strong>who can change the code that enforces your invariant?</strong> A contract audit is incomplete if that answer stops at the first administrator address.</p><p>This is a preliminary analysis, not a complete exploit reconstruction. It separates the available primary response account from original engineering analysis. The code below demonstrates an independent failure mode in upgrade authorization; it does not assert that this exact bug caused Neutron’s incident.</p><h3>What the available primary evidence establishes</h3><p>The <a href="https://forum.cosmos.network/t/hub-weekly-update-17-september-24-2026/17364">Hub Unit’s September 24 update</a> reports a September 22 governance attack on Neutron, administrative takeover and asset extraction, followed by movement of stolen ATOM to Cosmos Hub over IBC. It says the Hub was a destination for stolen funds, not the exploited network. Validators used Gaia v28.3.0 for a recovery intervention.</p><p>Cosmos Labs’ September 25 response account describes proposal execution, contract-admin acquisition, malicious code and draining on Neutron. It names Astroport and identifies Drop among the affected response participants. Its scope is the Hub response; the original draft described Neutron’s detailed postmortem as forthcoming. The source was edited on September 29 to link that published report. This historical review does not independently reconstruct that later postmortem.</p><p>Those are attributable statements by response participants. Reading their reports independently is not equivalent to replaying the chain or validating each transfer.</p><h3>Dates: incident, response and publication</h3><p>The following timeline is attributed to <a href="https://forum.cosmos.network/t/neutron-governance-attack-cosmos-hub-response-and-recovery-update/17369">Cosmos Labs</a>; times are UTC.</p><ul><li><strong>Date/time:</strong> September 22, approximately 02:25–07:44; <strong>Reported event:</strong> Neutron attack sequence and halt; referenced height 61,635,573</li><li><strong>Date/time:</strong> September 22, approximately 11:18; <strong>Reported event:</strong> Hub halted at height 33,086,740</li><li><strong>Date/time:</strong> September 23, 12:00–12:06; <strong>Reported event:</strong> Hub restart and recovery change at height 33,086,741</li><li><strong>Date/time:</strong> September 24; <strong>Reported event:</strong> Hub Unit recap published</li><li><strong>Date/time:</strong> September 25; <strong>Reported event:</strong> Detailed Hub response account published</li><li><strong>Date/time:</strong> September 28; <strong>Reported event:</strong> This preliminary review prepared</li></ul><p>The event date is September 22, not September 25 or today. This case was selected for the original September 28 review. It is historical material, not a claim about the latest incident.</p><h3>Financial impact: containment is not repayment</h3><p>The <a href="https://forum.cosmos.network/t/neutron-governance-attack-cosmos-hub-response-and-recovery-update/17369">Cosmos Labs account</a> reports approximately 1.73 million ATOM reaching the Hub, 1,227,121.37 ATOM moved into recovery custody, and a later 168,990.9 ATOM refund escaping containment. These are Hub-side flows, not a complete loss balance sheet.</p><p>The <a href="https://forum.cosmos.network/t/hub-weekly-update-17-september-24-2026/17364">Hub Unit recap</a> identifies the recovery address as <a href="https://www.mintscan.io/cosmos/address/cosmos1z8pq5cn7tdrwwzlwm0e44fgq07e43ner6vph64">cosmos1z8pq5cn7tdrwwzlwm0e44fgq07e43ner6vph64</a> and the source address as <a href="https://www.mintscan.io/cosmos/address/cosmos1dd25c4sshelrpfs0433apg24c5phrhk8m96c4n">cosmos1dd25c4sshelrpfs0433apg24c5phrhk8m96c4n</a>. It describes a 4-of-6 validator multisig and a pending recovery plan. These addresses were checked against that published account, not independently reconciled against chain state in this review.</p><ul><li><strong>Accounting category:</strong> Gross extraction across all affected protocols; <strong>What this edition can responsibly report:</strong> Not independently reconciled; no definitive dollar total asserted</li><li><strong>Accounting category:</strong> Funds secured in Hub recovery custody; <strong>What this edition can responsibly report:</strong> Attributed ATOM amount above; custody does not establish user repayment</li><li><strong>Accounting category:</strong> Attacker’s net proceeds; <strong>What this edition can responsibly report:</strong> Unknown; gross transfers, swaps and later refunds cannot simply be added</li><li><strong>Accounting category:</strong> Actual user repayments; <strong>What this edition can responsibly report:</strong> Not verified here</li><li><strong>Accounting category:</strong> Synthetic token face value; <strong>What this edition can responsibly report:</strong> Not used as a measure of realized losses</li></ul><p>A rigorous ledger needs one row per asset and movement, transaction identifiers, denomination, valuation timestamp and recovery status. A bridged asset appearing on two chains is not automatically two losses. A swap is not automatically a new extraction. This accounting discipline is a requirement for the final postmortem, not an optional footnote.</p><h3>Root cause: the authority path matters</h3><p>The supported incident-level mechanism is governance-enabled administrative control followed by malicious replacement behavior. The exact deployed code path, proposal payload, affected contract list and migration transactions have not been independently established in this review. I therefore do not attribute the incident to a particular Solidity bug, a compromised signing key, a flash loan or the toy queue below.</p><p>The security interpretation is broader: application permissions depend on the authorities that can rewrite them. “Only the admin can migrate” offers limited protection if an attacker can become that admin through a higher-level control path.</p><p>For a real review, build an authority map from the asset-holding application upward:</p><ul><li><strong>Layer:</strong> Application; <strong>Question to answer with deployed-state evidence:</strong> Which operations release assets or change backing?</li><li><strong>Layer:</strong> Implementation/migration authority; <strong>Question to answer with deployed-state evidence:</strong> Who can replace that logic or change its admin?</li><li><strong>Layer:</strong> Governance executor; <strong>Question to answer with deployed-state evidence:</strong> What exact messages can a passed proposal dispatch?</li><li><strong>Layer:</strong> Governance configuration; <strong>Question to answer with deployed-state evidence:</strong> Who can change voting rules, delays, membership or emergency powers?</li><li><strong>Layer:</strong> Chain-level authority; <strong>Question to answer with deployed-state evidence:</strong> Can a module or coordinated chain upgrade override the application-level restriction?</li></ul><p>Do not assume every Cosmos chain has the same authority structure. Do not infer a deployed permission from a framework’s default. The relevant evidence is the specific chain version, module configuration and contract state at the incident height.</p><h3>Two invariants that should not be confused</h3><p>The first is an <strong>economic security objective</strong>: asset-control authority should not be replaceable through a path outside the protocol’s declared governance and response assumptions. This is an original interpretation of the incident, not a formally proven Neutron invariant.</p><p>The second is an <strong>implementation invariant</strong> that can be demonstrated locally:</p><blockquote><em>An upgrade execution must apply the exact queued action, after its required delay, while that action remains pending.</em></blockquote><p>The second invariant is necessary for a meaningful review window, but it cannot establish the first. Correctly executing a harmful, legitimately approved operation is still harmful.</p><p><a href="https://docs.openzeppelin.com/contracts/5.x/access-control">OpenZeppelin’s access-control guidance</a> explains this distinction between restricting callers and constraining administrators through delayed operations. It also warns about the liveness implications of timelock administration and requires delay changes to pass through the timelock itself. That documentation is general background; OpenZeppelin is not a dependency of this lab or a claimed Neutron component.</p><h3>Vulnerable educational example: the label survives, the intent disappears</h3><p>Language/runtime: <strong>CPython 3.12.14</strong>. Dependencies: <strong>Python standard library only</strong>. No Solidity compiler or CosmWasm compiler was used.</p><p>The deliberately vulnerable queue stores readiness against a proposal label but discards the action that was reviewed:</p><pre>class VulnerableQueue:<br>    def __init__(self):<br>        self.ready = {}<br>        self.applied = []</pre><pre>    def queue(self, proposal, approved_action, now, delay):<br>        self.ready[proposal] = now + delay</pre><pre>    def execute(self, proposal, supplied_action, now):<br>        if now &lt; self.ready[proposal]:<br>            raise Rejected(&quot;too early&quot;)<br>        del self.ready[proposal]<br>        self.applied.append(supplied_action)</pre><p>Suppose p1 was reviewed with code A at time 100 and becomes ready at time 110. At 110, the executor supplies code B under p1. The time check succeeds because it refers to the label. Nothing connects that label to the original code.</p><p>This is a synthetic counterexample. No production endpoint, exploit payload or asset transaction is involved.</p><h3>Corrected educational example: store and compare the action</h3><p>The companion implementation uses an immutable action record. Its fields are chain, executor, target, code identifier, migration-argument bytes and nonce. The queue stores that complete action together with its readiness time.</p><p>The correction’s execution method is reproduced below. validate rejects malformed records and mutable arguments; queue creation validates the execution domain, checks the proposer role and prevents proposal reuse. The complete definitions and tests are in the linked lab.</p><pre>def execute(self, caller, proposal, supplied_action, now):<br>    self._time(now)<br>    validate(supplied_action)<br>    if caller != &quot;executor&quot;:<br>        raise Rejected(&quot;not executor&quot;)<br>    record = self.pending.get(proposal)<br>    if record is None:<br>        raise Rejected(&quot;not pending&quot;)<br>    approved, ready_at = record<br>    if supplied_action != approved:<br>        raise Rejected(&quot;action changed&quot;)<br>    if now &lt; ready_at:<br>        raise Rejected(&quot;too early&quot;)<br>    # The synthetic effect cannot call back or fail after this point.<br>    del self.pending[proposal]<br>    self.applied.append(approved)</pre><p>This is an illustrative correction to our toy bug, not an upstream remediation. In a production contract, the commitment must use canonical encoding and cover all relevant execution context. A descriptive title, a mutable web page or an arbitrary proposal number cannot stand in for executable intent.</p><p>The model trusts caller labels and timestamps supplied by the test harness. It has no signature verification, voting logic, storage durability, concurrent executor, reentrancy or external-call rollback. A real migration has more failure modes than appending a Python object to a list.</p><h3>Regression tests and results</h3><p>The new lab ran locally on September 28, 2026:</p><pre>cd labs/02-upgrade-intent<br>python3 --version<br>python3 -m unittest -v test_upgrade</pre><p>Result: <strong>CPython 3.12.14; 12 tests passed in 0.001 seconds; exit code 0</strong>.</p><p>The tests cover changed fields, premature execution, exact readiness, repeated execution, duplicate queueing, cancellation, role separation, foreign domains, mutable arguments, invalid time and missing proposals. Every rejection test compares the complete model state before and after the attempted action.</p><p>One passing test intentionally demonstrates that malicious approved code executes after the delay. That result is a documented limit of the defense. Removing it would make the test suite sound more reassuring while teaching less.</p><p>The existing backing-and-replay lab was also rerun unchanged: <strong>14 tests passed in 0.017 seconds, exit 0</strong>. Its earlier validation dates remain in the repository. The two suites contain 26 local tests in total.</p><p>The hosted <a href="https://github.com/mamk13/blockchain-security-labs/actions/runs/36461321611">GitHub Actions run</a> completed successfully for commit 26377497c1e8ebe0611e577564ce0e0c28967078; the API reported both named test steps successful. Local timings above are not CI timings. No live-chain transaction or historical exploit replay was performed.</p><p><strong>Companion:</strong> <a href="https://github.com/mamk13/blockchain-security-labs/tree/26377497c1e8ebe0611e577564ce0e0c28967078/labs/02-upgrade-intent">Lab 02 at the tested publication commit</a>. Start with the exercise, then compare your explanation with the separate solution. No tagged release or open-source license is claimed.</p><h3>Remediation questions for developers and responders</h3><p>These are review recommendations, not verified Neutron fixes:</p><ol><li><strong>Enumerate every path to replacement.</strong> Include admin transfer, migration, module authority, role grants and emergency procedures. Protecting only the ordinary upgrade function leaves alternate paths unresolved.</li><li><strong>Bind reviewed intent.</strong> Commit to the actual operation and domain, preserve the approved bytes, and reject substitutions before state changes.</li><li><strong>Make the delay usable.</strong> Publish a decoded operation and code reference early enough for review. Monitor changes in authority as well as transfers. A long timer with no watcher or response path provides little practical benefit.</li><li><strong>Constrain emergency powers.</strong> Define which actions can bypass ordinary delay and how they expire. A broad emergency executor can become the shortest path to permanent control.</li><li><strong>Test governance changes as security changes.</strong> Changing a threshold, voter set or executor changes the assumptions behind every protected application.</li><li><strong>Model pending cross-chain work.</strong> A halt freezes local execution, not necessarily every refund, acknowledgment or asset already elsewhere. Recovery plans need explicit treatment of late-arriving state and separate mandates for each action.</li></ol><h3>Evidence still needed for a final postmortem</h3><p>This edition has no independently verified affected-contract address list, proposal transaction hash, malicious migration hash, implementation checksum or incident-height chain binary. A protocol-specific patch has not been verified. These omissions prevent a claim of complete reconstruction.</p><p>The next update should obtain the original proposal messages and vote snapshot, reconstruct the precise authority changes, associate each affected contract with its old and new code, reconcile token flows without double counting, and verify whether held funds actually reached affected users. Any conclusion about which control would have prevented the incident must be tested against that full authority map.</p><p>The engineering exercise remains useful while those questions are open: prove that execution preserves reviewed intent, then identify every authority capable of replacing that guarantee.</p><p>Correction policy: original version September 28, 2026; historical framing updated November 16, 2026. Material evidence changes will be dated and retained. The lab illustrates a separate security property; it must not be cited as proof of the Neutron exploit mechanism.</p><p>Disclosure: AI-assisted research, writing, educational-model preparation and cover illustration. The image is conceptual, not incident evidence. Historical test dates and model limitations are retained; no new execution or production-security validation is claimed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d45c9b508f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Upgrade Can Succeed While the State Becomes Wrong]]></title>
            <link>https://mamk13.medium.com/an-upgrade-can-succeed-while-the-state-becomes-wrong-01b6f01bd815?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/01b6f01bd815</guid>
            <category><![CDATA[blockchain-security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 10:11:01 GMT</pubDate>
            <atom:updated>2026-10-26T10:11:01.655Z</atom:updated>
            <content:encoded><![CDATA[<h4>Packed-field compatibility and atomic migration are separate security properties.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FJKvudnw0LYwCQjlBBa-g.png" /></figure><p>An upgrade has multiple success conditions.</p><p>The implementation pointer can change correctly while old storage acquires the wrong meaning. A migration can return normally while assigning balances to the wrong accounts. A rejected migration can leave the system halfway between versions if the surrounding process commits those changes separately.</p><p>Those are different defects. One “upgrade succeeded” assertion cannot distinguish them.</p><p>Two new educational labs examine a restricted packed layout and a populated version-to-version migration. They use Python dictionaries and integers, not Solidity bytecode or a live proxy. The examples are deliberately small enough to inspect completely.</p><h3>The bytes stay; their interpretation moves</h3><p>Start with two unsigned 128-bit fields:</p><pre>v1: balance, debt<br>v2: debt, balance</pre><p>Both schemas occupy one 256-bit word in the teaching model. Both fields have the same width. The total allocation has not grown.</p><p>Yet the layouts are incompatible with preserving the old field meanings.</p><p>Write balance=100 and debt=3 using v1. The model places balance in the lower 128 bits and debt in the upper 128 bits. The word is therefore:</p><pre>word = 100 + 3 * 2^128</pre><p>Decode that unchanged word with v2, and the names refer to the opposite portions: balance=3, debt=100. No corrupted write is needed. Changing the interpretation is enough.</p><p><a href="https://docs.soliditylang.org/en/latest/internals/layout_in_storage.html">Solidity’s storage-layout documentation</a> describes lower-order alignment and packing for applicable value types. The inspected page was the current development documentation; this work did not generate compiler-version-specific layout output. The example above is a restricted hand-modeled unsigned layout, not a general compiler validator.</p><h3>Allocation size is a weak invariant</h3><p><a href="https://github.com/mamk13/blockchain-security-labs/tree/0293f95a3abdc3234ede6ce34c1d1f5b19238389/labs/17-packed-layout-compatibility">Lab17: packed-layout compatibility</a> contains a negative control that compares only total slot allocation. It accepts the reordered fields.</p><p>The corrected educational check compares each preexisting field’s complete location:</p><pre>stable field identity → (slot, bit offset, bit width)</pre><p>That is why a test should populate distinct nonzero values before changing schemas. Initializing everything to zero would hide the swap. Values 100 and 3 make the reinterpretation obvious without implying any real token amount or decimal convention.</p><p>Additional tests change a width, insert a field before existing fields, remove a field, and rename a field. The model treats names as stable identity, so a rename requires review even if the bytes could remain compatible. That conservative false positive is intentional; a name-based teaching check cannot decide semantic equivalence.</p><p>Appending a field preserves prior positions in this restricted flat layout, including when unused packed space exists. This is not permission to append blindly to an arbitrary production inheritance hierarchy. The model excludes inheritance, structs, arrays, mappings, signed types, gaps, namespaced storage, and custom base slots.</p><p>For real upgrades, compare the relevant compiler-generated layouts and the project’s supported upgrade validation. <a href="https://docs.openzeppelin.com/upgrades-plugins/writing-upgradeable">OpenZeppelin’s upgrade guidance</a> explains why declaration order and type changes need care, and why initialization requires explicit handling. A general-purpose validator must account for considerably more structure than this lab.</p><h3>A metadata slot is not an application schema</h3><p><a href="https://eips.ethereum.org/EIPS/eip-1967">EIP-1967</a> standardizes particular proxy metadata storage locations, including the implementation address. That helps locate the code pointer; it does not prove that the code interprets every application field consistently.</p><p>A useful review separates two questions:</p><ul><li>Did the proxy select the intended implementation?</li><li>Does that implementation interpret the existing application state according to the upgrade specification?</li></ul><p>The first can be correct while the second is wrong. The packed-field example demonstrates the second independently of governance, signatures, or the mechanism used to set a code pointer.</p><p>There is another distinction: byte-layout compatibility does not by itself establish business compatibility. Keeping a field in place while changing its unit, scale, or economic meaning requires a semantic migration specification, even if a structural checker accepts the layout.</p><h3>Migration is a state transition, not just a callback</h3><p><a href="https://github.com/mamk13/blockchain-security-labs/tree/0293f95a3abdc3234ede6ce34c1d1f5b19238389/labs/18-atomic-upgrade-migration">Lab18: atomic upgrade migration</a> starts with a populated fixture:</p><pre>implementation = v1<br>version = 1<br>owner = Alice<br>balances = {Alice: 70, Bob: 30}<br>total = 100</pre><p>The specified upgrade installs v2, records version 2, and adds limit=100. It must preserve the owner and every existing account balance.</p><p>The deliberately split variant installs v2 before running a migration that fails. In this Python model, the exception alone does not restore prior assignments. The fixture is left with implementation=v2 and version=1.</p><p>The corrected model snapshots the entire represented proxy state before starting. It installs the new implementation, runs migration, and validates postconditions. Any rejection restores that snapshot. Successful completion must satisfy the full transition policy.</p><p>This is a local simulation of a desired all-or-nothing boundary. It is not an implementation of UUPS, a transparent proxy, or an on-chain upgrade-and-call operation.</p><h3>Total conservation can hide reassignment</h3><p>A migration changes Alice’s 70 and Bob’s 30 into Alice’s 0 and Bob’s 100. The total still equals 100.</p><p>A test asserting only total conservation passes. A test asserting the specified per-account preservation fails.</p><p>This is not a universal rule that every migration must preserve every balance byte-for-byte. Some legitimate migrations deliberately convert units or redistribute a documented entitlement. In that case, the correct invariant is the explicitly approved mapping from old rights to new rights.</p><p>For this exercise, unchanged balances are the specification. The test therefore compares the entire balances dictionary, not just its sum. It also checks owner, total, implementation, version, and the newly required limit.</p><p>An apparent-success fixture returns without setting the new version or limit. It is rejected despite returning normally. Other fixtures corrupt individual required fields. These make “callback returned” demonstrably weaker than “transition established the required state.”</p><h3>Failure must leave a usable retry path</h3><p>A failed attempt should not consume the migration’s right to run unless that is explicitly part of the design.</p><p>The lab fails once with a no-op migration, then retries the correct migration. The retry succeeds because the state returned to v1. A second attempt after successful completion rejects without mutation.</p><p>Unauthorized callers are rejected before their callback runs. The model uses the trusted string “governance” for that role; it does not implement or audit governance authentication. It also does not prove that arbitrary authorized code is safe. An approved malicious implementation remains outside the protection of a small migration postcondition set.</p><p>The most important limitation test mutates a Python list outside the modeled proxy dictionary, then raises an exception. The proxy state is restored; the external list is not.</p><p>That passing test intentionally documents a missing guarantee. A deep copy of one ledger cannot restore unrelated external effects. Production reasoning must identify the actual transaction boundary and every effect that can escape it, including off-chain actions. Do not infer that Python exceptions provide EVM-like atomicity.</p><h3>A practical acceptance matrix</h3><p>For a concrete upgrade, write down four independent acceptance conditions:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FVOdsU%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FVOdsU%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FVOdsU%2Fplain-s.png%3Fv%3D2&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="266" frameborder="0" scrolling="no"><a href="https://medium.com/media/3463e7e52182b8ef27f47df436d85de1/href">https://medium.com/media/3463e7e52182b8ef27f47df436d85de1/href</a></iframe><p>Labs17–18 address restricted parts of the last three rows. They do not prove the first. Earlier queue-intent and initialization exercises answer different questions; rerunning them is not a substitute for migration-specific tests.</p><p>Before deployment, populate a representative pre-upgrade state. Include distinct packed values, multiple users, nonzero debts, and any version-dependent units. Then test both the expected migration and deliberate deviations. A validator result and an application invariant test are complementary evidence, not interchangeable certificates.</p><h3>Reproduction and evidence</h3><p>On October 19, 2026, CPython 3.12.14 ran 12 Lab17 tests and 10 Lab18 tests, all passing. The complete repository’s 18 suites passed 182 tests, including the 137 existing tests retained from Labs01–14.</p><p><a href="https://github.com/mamk13/blockchain-security-labs/actions/runs/39225429275">Hosted CI run 39225429275</a> succeeded for commit 0293f95a3abdc3234ede6ce34c1d1f5b19238389. The work used the standard library only, with no RPC requests, live financial transactions, Solidity compilation, or exploit replay.</p><pre>git clone https://github.com/mamk13/blockchain-security-labs.git<br>cd blockchain-security-labs<br>git checkout 0293f95a3abdc3234ede6ce34c1d1f5b19238389<br>(cd labs/17-packed-layout-compatibility &amp;&amp; python3 -m unittest -v test_layout)<br>(cd labs/18-atomic-upgrade-migration &amp;&amp; python3 -m unittest -v test_migration)</pre><p>Use CPython 3.12.14 for the recorded environment. The READMEs, exercises, and separate solutions describe the exclusions and proposed extensions.</p><p>An upgrade is not complete merely because the new code runs. It is complete only relative to a specification of what the old state means, what the new state must become, and what must remain true if the transition fails.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01b6f01bd815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Code Ran. Whose State Changed?]]></title>
            <link>https://mamk13.medium.com/the-code-ran-whose-state-changed-ae48803b13ff?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae48803b13ff</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 21:54:05 GMT</pubDate>
            <atom:updated>2026-10-24T21:57:32.136Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two reproducible exercises distinguish execution identity, storage ownership and transaction lifetime.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTOrKeY2bdJ3DQH79q71BA.png" /></figure><p>A test can call the expected function, receive the expected return value and still inspect the wrong account.</p><p>That is a particularly expensive mistake around proxies. The code being executed and the account whose state is being changed are separate dimensions. Add transient storage, and a third dimension appears: how long that state should remain meaningful.</p><p>Two new educational labs isolate those questions. They are synthetic Python models, not an EVM implementation, incident reconstruction or production patch. Their purpose is to make a misleading test fail for a specific reason.</p><h3>Start with identities, not function names</h3><p>Consider three fixtures: Alice, a proxy, and an implementation. The implementation’s program writes the integer 42.</p><p>In the first test, Alice calls the implementation directly. The program writes 42 into implementation storage. A test that checks only that account passes. It has said nothing about whether the proxy forwards correctly.</p><p>In the second test, Alice calls the proxy, which uses an ordinary call to the implementation. The program again writes implementation storage. The implementation sees the proxy as its immediate caller. The operation can return normally while the proxy’s value remains zero.</p><p>In the third test, the proxy delegates execution. The implementation supplies the program, but the modeled storage owner remains the proxy, and the sender remains Alice. This separation is grounded in <a href="https://eips.ethereum.org/EIPS/eip-7">EIP-7’s DELEGATECALL specification</a>; the lab models only selected context properties, not every instruction&#39;s semantics.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FmYhSR%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FmYhSR%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FmYhSR%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="264" frameborder="0" scrolling="no"><a href="https://medium.com/media/264fc4e56189d4180855446dd60df31b/href">https://medium.com/media/264fc4e56189d4180855446dd60df31b/href</a></iframe><p>The practical regression is therefore a paired assertion. Seed the implementation with 99, run through the proxy, and require both proxy=42 and implementation=99. Add a second proxy with independent state. A correct result on one account should not conceal an unexpected mutation on another.</p><p>These numbers are invented fixtures. No contract addresses, balances or incident transactions are implied.</p><h3>Make the wrong route pass the weak test</h3><p><a href="https://github.com/mamk13/blockchain-security-labs/tree/0293f95a3abdc3234ede6ce34c1d1f5b19238389/labs/16-code-storage-context">Lab16: code and storage context</a> contain an intentionally wrong forwarder for a specification that requires delegation. It calls normally instead.</p><p>The negative control is useful precisely because the write succeeds. “Did it revert?” is the wrong distinguishing question. The test must ask who owned the write and which caller identity reached the implementation.</p><p>The model represents a frame as code, storage, sender and a static flag. Nested delegation preserves the existing owner and sender; an ordinary call inside a delegated frame establishes a different context. Tests also reject a modeled static write and restore modeled state after failure.</p><p>There are important exclusions. This model does not implement ABI encoding, value transfer, gas, opcode execution, precompiles or EIP-7702 authorization. Frame identities are trusted test inputs. Its diagnostic trace retains failed frames; it is not a transaction receipt. A nested ordinary call must be given the static flag explicitly in this toy API. Those are reasons to follow the exercise with implementation-level tests, not reasons to describe the Python result as an EVM proof.</p><h3>A transaction boundary is not a function boundary</h3><p>Transient state makes lifetime errors easier to hide.</p><p><a href="https://eips.ethereum.org/EIPS/eip-1153">EIP-1153</a> specifies transaction-scoped transient storage. Frames belonging to the same owner can share it; delegated execution uses the caller’s owner, while ordinary calls use the callee’s. Reverting a frame also reverts its transient writes and those of descendants. End-of-transaction cleanup does not mean end-of-function cleanup.</p><p>Suppose a guard sets a transient lock when a protected operation begins. It rejects entry while that lock is set. The vulnerable teaching variant never clears the lock on successful return, relying entirely on transaction-end disposal.</p><p>A nested callback is rejected. A test ending the transaction immediately afterward looks green.</p><p>But now put two legitimate sequential calls in the same transaction. The first returns successfully. The second sees the leftover lock and rejects, even though no protected call is currently active. The guard has accidentally implemented “at most once per transaction,” not “no nested entry.”</p><p>The distinction is also called out in <a href="https://docs.soliditylang.org/en/v0.8.28/contracts.html#transient-storage">Solidity 0.8.28’s transient-storage guidance</a>. A guard intended to allow sequential composition needs to release its lock after successful completion.</p><h3>Test three lifetimes separately</h3><p><a href="https://github.com/mamk13/blockchain-security-labs/tree/0293f95a3abdc3234ede6ce34c1d1f5b19238389/labs/15-transient-frame-lifetime">Lab15: transient frame lifetime</a> makes three tests explicit:</p><ol><li><strong>Nested entry</strong>: while the callback runs, the outer guard still holds the lock. Reentry must reject.</li><li><strong>Sequential entry</strong>: after the first protected call returns, a later independent call within the same transaction must succeed.</li><li><strong>Transaction completion</strong>: even the deliberately uncleared negative control must leave no transient state for the next transaction.</li></ol><p>Each is a different proposition. Passing the third does not establish the second; passing the second does not establish the first.</p><p>The corrected path clears the lock after the callback returns. That does not permit nested reentry: the callback runs before the clear. The intended invariant concerns active nesting, not whether the transaction has previously touched the function.</p><p>The lab also separates failure cases. If an inner call fails and the outer callback catches that failure, restoration must retain the lock held by the outer call. If the outer failure propagates, restoration returns to the earlier unlocked checkpoint. A successful child write must still disappear when its parent later reverts.</p><p>This is why “successful call” should not be treated as “final state” until the relevant enclosing execution has committed.</p><h3>Combine the questions without merging the models</h3><p>A useful review worksheet has four columns:</p><ul><li>Code selected for execution.</li><li>Account that owns persistent and transient state.</li><li>Caller or authority context relied on by the operation.</li><li>Boundary at which each state change becomes disposable or committed.</li></ul><p>The two labs do not integrate into a full VM. Lab15 trusts the supplied owner name; Lab16 does not implement transient opcodes. Their combination is a review method, not a claim that an integrated proxy/transient-storage system has been tested.</p><p>For an actual implementation, the next tests should exercise the actual entry path and target VM version. Include two instances sharing code, nested delegation, a caught callback failure, a parent revert after child success, and two sequential calls inside one transaction. Check the intended account and relevant untouched accounts, not just return data.</p><h3>What actually ran</h3><p>On October 19, 2026, CPython 3.12.14 ran all 18 repository suites in isolated subprocesses: 182 tests passed. The new context/lifetime pair contributed 23 tests: 12 in Lab15 and 11 in Lab16. These use only the Python standard library.</p><p><a href="https://github.com/mamk13/blockchain-security-labs/actions/runs/39225429275">GitHub Actions run 39225429275</a> also completed successfully for commit 0293f95a3abdc3234ede6ce34c1d1f5b19238389. Local results and hosted CI are separate observations. Neither includes live transactions, a historical fork or Solidity compilation.</p><p>To reproduce:</p><pre>git clone https://github.com/mamk13/blockchain-security-labs.git<br>cd blockchain-security-labs<br>git checkout 0293f95a3abdc3234ede6ce34c1d1f5b19238389<br>(cd labs/15-transient-frame-lifetime &amp;&amp; python3 -m unittest -v test_transient)<br>(cd labs/16-code-storage-context &amp;&amp; python3 -m unittest -v test_context)</pre><p>Use CPython 3.12.14 to match the recorded runtime. Read each README’s exclusions before extending the model.</p><p>The core question is small enough to ask in every review: the code ran — but whose state changed, and until when?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae48803b13ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Nonce Is Not a Boundary: Separating Replay, Cancellation and Domain Scope]]></title>
            <link>https://mamk13.medium.com/a-nonce-is-not-a-boundary-separating-replay-cancellation-and-domain-scope-5c4bc4ed559e?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c4bc4ed559e</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 12:41:29 GMT</pubDate>
            <atom:updated>2026-10-19T12:41:29.873Z</atom:updated>
            <content:encoded><![CDATA[<h4>An unused nonce can belong to a permission that was cancelled yesterday — or to a permission issued for a different contract. “Not used before” answers only one part of the authorization question.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGs9RVtztDvmoQZDiS3MfA.png" /></figure><p>Consider a permit that authorizes an operation once. A reviewer sees a nonce check and concludes that replay is handled. But replay is not a single global property. The same message may reach a second consumer with its own empty nonce store. A wallet may cancel all previously issued permits. An application may change the meaning of an operation while retaining the same identifier. A local consumed-nonce set cannot describe all those boundaries.</p><p>The useful specification has three questions: where does the authority apply, which generation of authority remains valid, and has this particular authorization already been consumed?</p><h3>Start with the policy, not the data structure</h3><p><a href="https://eips.ethereum.org/EIPS/eip-712">EIP-712</a> provides structured signing and domain context; it explicitly does not supply application replay protection. Domain fields can distinguish a chain, verifying contract and version. Separately, <a href="https://eips.ethereum.org/EIPS/eip-1271">ERC-1271</a> allows a contract wallet’s validation to depend on context, including state. Neither standard decides what cancellation should mean for every application.</p><p>That decision is consequential. Some systems intentionally create a durable commitment when they accept an order. Others merely queue an instruction whose authority must still exist at execution. A generation check is appropriate only if bulk cancellation is part of the intended policy. Adding it to an irrevocable commitment system could violate the promise that acceptance made.</p><p>The examples here choose a narrow policy: a trusted owner can cancel all outstanding permits in the current generation. Future permits use a new generation. No old generation can become current again.</p><h3>A generation is a cancellation boundary</h3><p>In Lab 09, a permit contains an owner, epoch and nonce. Grants are trusted fixture entries, not signatures. An epoch is simply a monotonically increasing integer associated with the owner.</p><p>The negative control advances that integer when cancellation is requested, but execution only checks whether the permit was once granted. Updating cancellation state is ineffective when the settlement path never consults it.</p><p>The corrected rule is compact:</p><pre>if permit not in grants or permit in used:<br>    reject()<br>if permit.epoch != current_epoch[permit.owner]:<br>    reject()<br>used.add(permit)</pre><p>This is an explanatory sketch; the executable model and its input assumptions are linked below. Crucially, rejection happens before consumption. An obsolete permit should not burn a newly issued permit that happens to reuse the same nonce number.</p><p>Take Alice’s nonce 7 in epoch 0. Alice cancels all outstanding permits, moving to epoch 1. She then grants nonce 7 again. The new permit can execute once. The old one remains invalid. The replay key includes the generation, so the two permits are different authorizations even though their displayed nonce is identical.</p><p>That choice has a trade-off: nonce reuse is allowed across generations. An application that needs globally unique operation identifiers should retain a separate global identifier rule. An epoch is not a substitute for deciding what an operation’s identity means.</p><h3>Cancellation must have a scope</h3><p>The lab cancels Alice’s permits without cancelling Bob’s. This is easy to miss when a first implementation stores one global epoch. A global value may be intentional for emergency shutdown, but it is a very different authority from per-owner cancellation.</p><p>The trusted cancellation method also matters. A public method that lets anyone advance Alice’s epoch would turn cancellation into denial of service. The model assumes authenticated governance of grants and epochs; it does not implement access control. This is a boundary to test in the real adapter, not a claim that the local fixture proves it.</p><p>Monotonicity is another assumption. Python integers do not wrap. A bounded on-chain counter needs explicit behavior at its maximum. Resetting an epoch to a prior value is especially dangerous if old signed permits remain available: the system can accidentally make a historical generation current again.</p><h3>A domain is an execution-context boundary</h3><p>Lab 10 asks a different question. Its authority fixture grants an exact pair: a domain and an order. The domain has a chain identifier, verifier identifier and schema identifier. The order has recipient, amount and nonce.</p><p>The vulnerable consumer searches for any grant matching the order, regardless of domain. A permit intended for chain 1, vault A, payment schema v1 is then accepted by a separate consumer for chain 2, vault B, schema v2. Its nonce store is empty, so local replay prevention offers no resistance.</p><p>The corrected consumer requires the entire domain and order to match. The test changes one domain dimension at a time. Testing only a case where all three fields change would establish rejection, but would not show that each boundary is independently enforced.</p><p>The positive counterpart matters too. If an owner deliberately grants the same payload in two domains, both domains may execute it. Rejecting that outcome would impose a global single-use rule that the policy never promised. Security testing must preserve intended behavior as well as reject unintended behavior.</p><h3>Rejection state is part of the result</h3><p>An exception is not the complete assertion. After a wrong-domain or old-generation attempt, the test must inspect consumed identifiers and recipient credits. Otherwise, a rejecting request might still prevent a later legitimate operation from succeeding.</p><p>Likewise, a valid domain does not permit a second execution in the same consumer. Lab 10 grants a second, different order using an already consumed nonce and checks that it cannot settle. Domain binding and nonce consumption work together; neither replaces the other.</p><p>Likewise, a valid domain does not permit a second execution in the same consumer. Lab 10 grants a second, different order using an already consumed nonce and checks that it cannot settle. Domain binding and nonce consumption work together; neither replaces the other.</p><h3>What was actually executed</h3><p>On October 15, 2026, Lab 09 passed 7 tests, and Lab 10 passed 7 tests under pinned CPython 3.12.14. Every suite ran in a separate local process with standard-library dependencies only. The complete collection passed 137 tests locally, and hosted CI succeeded for <a href="https://github.com/mamk13/blockchain-security-labs/commit/7aec1fadfcee43538de8dfa599e568138e1a2d97">commit 7aec1fad</a>, <a href="https://github.com/mamk13/blockchain-security-labs/actions/runs/38708110272">run 38708110272</a>.</p><p>Read <a href="https://github.com/mamk13/blockchain-security-labs/tree/7aec1fadfcee43538de8dfa599e568138e1a2d97/labs/09-authorization-epochs">Lab 09</a> and <a href="https://github.com/mamk13/blockchain-security-labs/tree/7aec1fadfcee43538de8dfa599e568138e1a2d97/labs/10-domain-separated-permits">Lab 10</a>. Each includes an exercise and a separate solution.</p><p>No cryptographic signature, EIP-712 encoding, ERC-1271 call, chain fork, transaction rollback, or concurrent executor was tested. These models use equality and trusted grants to isolate policy errors. They are not a deployed patch or proof of an integration’s security. No incident date, affected contract, transaction reference, or loss is asserted because this is an evergreen lesson rather than an incident report.</p><p>For a real review, write down the intended answers to all three questions — context, cancellation generation and consumption — then construct a failing test for each boundary. A nonce can enforce single use within its scope. The specification must define that scope first.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c4bc4ed559e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Valid Yesterday, Revoked Today: Why Cached Authorization Is Not Execution Permission]]></title>
            <link>https://mamk13.medium.com/valid-yesterday-revoked-today-why-cached-authorization-is-not-execution-permission-29d4030ac1f1?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d4030ac1f1</guid>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 09:49:37 GMT</pubDate>
            <atom:updated>2026-10-13T09:50:30.724Z</atom:updated>
            <content:encoded><![CDATA[<p>A request can keep the same bytes while losing its authority. If a system promises that a wallet may revoke permission before execution, remembering that permission existed yesterday does not satisfy that promise today.</p><figure><img alt="Cached Authorization Is Not Execution Permission" src="https://cdn-images-1.medium.com/max/1024/1*UwD1_SypLuih0OP7nB0afw.png" /></figure><h3>The question before the signature check</h3><p>Suppose a wallet authorizes a payment, a service accepts it into a queue, and the wallet changes its authorization policy before settlement. Should the payment still execute?</p><p>There are at least two coherent answers. Admission may create an irrevocable commitment with explicitly defined cancellation rules. Or admission may merely queue a request whose authority must still exist when it executes. Neither answer follows from the presence of a signature alone. The application must choose and communicate its policy.</p><p>This article chooses the second policy: settlement requires current wallet authorization. Under that policy, replacing an execution-time decision with a cached admission result is a security error. Under a deliberately different commitment policy, the same cache might represent a valid business rule — but that rule needs its own state, cancellation semantics, and tests.</p><p>The primary-source basis is narrow. <a href="https://eips.ethereum.org/EIPS/eip-1271">ERC-1271</a> defines a contract signature-validation interface and allows validation to depend on context. OpenZeppelin’s <a href="https://docs.openzeppelin.com/contracts/5.x/api/utils/cryptography#SignatureChecker">SignatureChecker documentation</a> explicitly explains that a contract signature’s validity may change across blocks. Those references establish that validity need not be a permanent property of the submitted bytes. They do not establish a vulnerability in any particular deployed application.</p><h3>A five-step synthetic failure</h3><p>Our example uses integer units, one wallet, one consumer, and an intent containing a domain, recipient, amount, nonce, and deadline. “Proof-A” is a test label, not a cryptographic signature.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FD1wUy%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FD1wUy%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FD1wUy%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="537" frameborder="0" scrolling="no"><a href="https://medium.com/media/24e26f94711fa93d1ef0a0be8dcb8db1/href">https://medium.com/media/24e26f94711fa93d1ef0a0be8dcb8db1/href</a></iframe><p>No forged signature is needed in this model. The submitter simply retains a once-valid request. No amount modification, deadline extension, or repeated nonce is necessary either. This matters because a suite focused only on altered message fields and replay can pass while missing authorization lifecycle changes.</p><p>The root cause is the meaning assigned to a stored result: a historical observation becomes continuing permission. The queue’s acceptance and the wallet’s current decision are different facts.</p><h3>What the companion actually implements</h3><p><a href="https://github.com/mamk13/blockchain-security-labs/tree/efc6dfd8f3b77cc38d6c48775675b4d006436935/labs/07-revocable-authorization">Lab 07 at the published commit</a> provides a deliberately small model. A trusted fixture maintains a set of exact intent/proof pairs. Its grant and revoke operations stand in for authenticated wallet governance. They are not public production APIs and do not model who is allowed to change owners or permissions.</p><p>The vulnerable consumer stores an admission result and later consults that cache:</p><pre>def execute(self, intent, proof, now):<br>    self.check(intent, now)<br>    if (intent, proof) not in self.cache:<br>        raise Rejected(&#39;not admitted&#39;)<br>    self.settle(intent)</pre><p>The corrected educational consumer asks the current policy fixture before settling:</p><pre>def execute(self, intent, proof, now):<br>    self.check(intent, now)<br>    if not self.wallet.valid_now(intent, proof):<br>        raise Rejected(&#39;authorization no longer valid&#39;)<br>    self.settle(intent)</pre><p>Both excerpts come from the tested model. check enforces the consumer domain, an unexpired deadline, an unused nonce, and sufficient balance. settle consumes the nonce, debits the balance, and credits the modeled recipient. No external call occurs between the successful checks and settlement in this sequential Python example.</p><p>The change is intentionally modest. It does not make a general-purpose wallet verifier. It moves the authorization decision to the boundary where this particular policy requires it.</p><h3>Test the rejection’s consequences</h3><p>A rejection assertion is only half the test. If a denied request consumes its nonce or changes accounting, retry and recovery behavior can still be wrong.</p><p>The lab snapshots three values before a rejected execution: balance, used nonces, and recipient payments. It asserts that all three remain unchanged. That requirement applies to revocation, wallet unavailability, altered fields, the wrong proof, an expired deadline, and insufficient funds.</p><p>The most useful regression is a paired negative control. The same admitted request is revoked; the vulnerable consumer pays 10 units, while the corrected consumer rejects it without mutation. This demonstrates that the test distinguishes the two policies rather than merely exercising a happy path.</p><p>Recovery is separate. If the fixture is unavailable, the consumer rejects without consuming the nonce. When the fixture becomes available again and still authorizes the request, execution succeeds. A transient failure must not become cached permission, but this model also avoids permanently burning a request merely because verification was temporarily unavailable.</p><p>Another test deliberately re-grants the same pair after revocation. The corrected consumer accepts it if its nonce remains unused. That is a chosen policy, not a universal definition of revocation. If a real system requires irrevocable cancellation, it needs a separate cancellation state or epoch rule that a later approval cannot undo accidentally.</p><h3>Boundaries that deserve their own assertions</h3><p>The deadline test uses 99, 100, and 101 against a deadline of 100. Equality is accepted deliberately. A different product may choose another boundary; an undocumented comparison is the problem to avoid.</p><p>Field-mutation tests independently change the domain, recipient, amount, nonce, and deadline. The fixture authorizes an exact immutable intent, so none of those changes inherit the original permission. This is a semantic binding exercise, not a demonstration of EIP-712 encoding or cryptographic domain separation.</p><p>Nonce scope also matters. Here, nonces belong to a single wallet/consumer instance. A second otherwise-valid intent with an already-consumed nonce is rejected. A multi-wallet implementation would need an explicit namespace; copying a global set from this teaching model could give unrelated wallets an unintended shared cancellation surface.</p><p>The balance is measured in abstract integer units. There are no token decimals, transfer fees, rebasing balances, or external asset callbacks. Those are additional integration boundaries, not properties proved by this suite.</p><h3>Where a production review must go further</h3><p>The model does not call isValidSignature, decode its return value, hash typed data, verify ECDSA, execute Solidity, or meter gas. A real contract integration must handle the actual verifier’s return and failure behavior, including malformed responses and unavailable verification, according to its policy. It must also reason about the state that remains observable during settlement.</p><p>Checking immediately before execution is not a blanket concurrency proof. This model has no threads, external callbacks, database commits, chain reorganizations, or cross-process workers. If an external interaction can occur between validation and consuming authorization, the reviewer must analyze that interval separately. “We recheck” is not enough unless the recheck and the protected action sit inside the correct consistency boundary.</p><p>Conversely, this article does not recommend revoking settled obligations retroactively. Once an application intentionally commits to an order, its cancellation and settlement rules may differ from a wallet’s present willingness to sign. The review question is whether implementation, user expectations, and documented commitment semantics agree.</p><h3>Reproduce the evidence</h3><p>Use CPython 3.12.14 and the standard library; the suite needs no dependencies, RPC endpoint, wallet, or financial transaction.</p><pre>cd labs/07-revocable-authorization<br>python3 --version<br>python3 -m unittest -v test_authorization</pre><p>On October 12, 2026, the local Lab 07 suite passed 12 tests in 0.001 seconds, exit 0. The separate initialization-boundary Lab 08 also passed 12 tests. All six earlier published suites were rerun: 96 tests across eight suites passed, including 24 new tests. These are local measurements; execution duration is not a performance benchmark. Hosted CI status is recorded separately in the editorial package and linked Actions run.</p><p>The source, exercise, solution, and limitations are pinned in <a href="https://github.com/mamk13/blockchain-security-labs/commit/efc6dfd8f3b77cc38d6c48775675b4d006436935">commit efc6dfd</a>. No historical exploit was replayed. There is no affected deployment, transaction hash, loss figure, recovery amount, or upstream remediation to report for this synthetic example.</p><h3>A review question to keep</h3><p>For every stored approval, ask: <strong>Is this a record of what was true, or a right that the application has deliberately made durable?</strong></p><p>Then test a policy change between acceptance and use. Predict the expected outcome first, execute both the permitted and rejected paths, and check the resulting state. That exercise often reveals more than another test that changes one byte of an otherwise static request.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d4030ac1f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fresh Is Not Synchronized: The Oracle Checks a Timestamp Alone Cannot Prove]]></title>
            <link>https://mamk13.medium.com/fresh-is-not-synchronized-the-oracle-checks-a-timestamp-alone-cannot-prove-c8513e30b328?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8513e30b328</guid>
            <category><![CDATA[chain-link]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 18:21:07 GMT</pubDate>
            <atom:updated>2026-10-09T18:21:07.931Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why a reliable oracle consumer must validate units, age, cross-feed timing and failure policy separately.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xR4UL-Xz3bWB7Gs2Qx0npg.png" /></figure><p>A smart contract can read two valid oracle answers, check that neither is stale, and still compute a price from two different market moments.</p><p>That is the failure mechanism this article examines.</p><p>It is not a report about a newly confirmed exploit. I did not find enough primary forensic evidence during the October 1–8 review window to support a complete new incident postmortem with verified transactions, affected implementations and financial impact. This is therefore an evergreen educational review, supported by public specifications and a synthetic local model.</p><p>The core invariant is:</p><blockquote>A derived price is accepted only when every input is valid in its own units and the observations are temporally compatible under an explicit application policy.</blockquote><p>That sentence contains four separate obligations: identity, value, time and combination. Treating them as one generic “oracle check” makes important gaps easy to miss.</p><h3>What the primary documentation establishes</h3><p>Chainlink’s EVM Data Feeds guide shows that a consumer can read decimals() and latestRoundData(). The latter returns the answer together with metadata including updatedAt. The same guide also demonstrates deriving a new denomination by combining two feeds and normalizing their decimals.</p><p>Source: <a href="https://docs.chain.link/data-feeds/using-data-feeds">https://docs.chain.link/data-feeds/using-data-feeds</a></p><p>The guide also warns that contracts reading feeds on L2 networks need to consider sequencer uptime. That is a separate availability and market-state boundary; a price timestamp alone does not establish that the surrounding execution environment is safe.</p><p>Those facts tell us what data is available. They do not define one universal staleness threshold, one universal cross-feed skew limit, or one universal fallback policy for every protocol. Those are application decisions.</p><h3>A synthetic example: correct integers, wrong economic result</h3><p>Assume a consumer derives BASE/QUOTE from two */USD feeds.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F5fpZv%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F5fpZv%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F5fpZv%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="214" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5f547c60935998ec51b13e5e95419bf/href">https://medium.com/media/d5f547c60935998ec51b13e5e95419bf/href</a></iframe><p>If the consumer silently assumes both answers use the same decimals, it calculates:</p><p><strong>200,000,000,000 / 1,000,000 = 200,000</strong></p><p>The intended economic ratio is 2,000.</p><p>Both integers are positive. Both observations are recent. The arithmetic operation succeeds. The result is still wrong by a factor of 100 because the units were not normalized.</p><p>The corrected sequence is:</p><ol><li>Verify the expected feed identity, chain and denomination.</li><li>Read each feed’s declared decimals.</li><li>Reject nonpositive or malformed answers under the application’s policy.</li><li>Reject future or over-age timestamps.</li><li>Reject a pair whose update-time difference exceeds the allowed cross-feed skew.</li><li>Normalize each answer into explicit units.</li><li>Apply a defined rounding rule and an economic sanity policy.</li></ol><p>The order matters. Scaling an invalid or temporally incompatible observation only produces a precisely formatted invalid result.</p><h3>Freshness is a policy, not a property hidden inside updatedAt</h3><p>An updatedAt value answers a narrow question: when was this observation last updated according to the feed interface?</p><p>It does not answer:</p><ul><li>whether this feed is appropriate for the protocol’s use case;</li><li>whether the address is correct for the current chain;</li><li>whether the market is open;</li><li>whether a deviation or heartbeat policy is appropriate for the asset;</li><li>whether an L2 sequencer outage affects safe consumption;</li><li>whether two feeds describe sufficiently close market moments;</li><li>whether the protocol should pause, fall back or continue when a check fails.</li></ul><p>A consumer must turn metadata into explicit acceptance rules.</p><p>For one application, 60 seconds may be too long. For another, rejecting after 60 seconds may create an unnecessary availability failure. The threshold should follow the feed behavior, market, chain, protocol exposure and failure consequence. Copying a number from another integration is not evidence that the same risk policy applies.</p><h3>The cross-feed skew that two age checks miss</h3><p>The cross-feed skew that two age checks miss</p><ul><li>BASE/USD updated at 11:59:50.</li><li>QUOTE/USD updated at 11:59:25.</li></ul><p>Each observation is individually fresh: 10 seconds and 35 seconds old.</p><p>But the pair has 25 seconds of update skew. During a volatile move, the numerator may reflect a new market state while the denominator still reflects an older one.</p><p>This does not prove that 25 seconds is unsafe for every pair. It proves that independent age checks and pairwise temporal compatibility are different invariants.</p><p>A useful boundary test is:</p><pre>accept if:<br>    now - base.updated_at &lt;= max_age<br>    now - quote.updated_at &lt;= max_age<br>    abs(base.updated_at - quote.updated_at) &lt;= max_skew</pre><p>Then test max_skew — 1, max_skew, and max_skew + 1. The equality rule should be deliberate, not an accident of &lt; versus &lt;=.</p><h3>Failure behavior is part of the security design</h3><p>Rejecting a price is not the end of the design. It changes what the protocol can do next.</p><p>Possible policies include:</p><ul><li>pause the affected operation;</li><li>use a separately validated fallback source;</li><li>continue only for risk-reducing actions;</li><li>apply exposure or price-impact limits;</li><li>require governance or operator intervention.</li></ul><p>Each option changes trust and availability. A fallback that is never tested may fail exactly when the primary path is unavailable. A cached value can prevent immediate downtime while silently extending stale-price exposure. A permissioned override can restore operations while adding a governance boundary.</p><p>The correct question is not “Do we have a fallback?” It is “Which actions remain safe under each failure state, and what evidence authorizes the transition?”</p><h3>What to test</h3><ol><li><strong>Unit boundaries</strong></li></ol><ul><li>feeds with equal decimals;</li><li>feeds with different decimals;</li><li>maximum supported decimal value;</li><li>unsupported or malformed decimal metadata;</li><li>an output that requires deterministic rounding.</li></ul><p>2. <strong>Time boundaries</strong></p><ul><li>age = max_age — 1;</li><li>age = max_age;</li><li>age = max_age + 1;</li><li>updatedAt &gt; now;</li><li>one stale input while the other remains fresh.</li></ul><p>3. <strong>Combination boundaries</strong></p><ul><li>skew = max_skew — 1;</li><li>skew = max_skew;</li><li>skew = max_skew + 1;</li><li>large market movement between otherwise acceptable updates.</li></ul><p>4. <strong>State-change boundaries</strong></p><ul><li>rejected reads leave accounting unchanged;</li><li>a failed fallback does not silently reuse an unsafe cached value;</li><li>risk-reducing actions remain possible only if the policy intentionally allows them;</li><li>recovery does not replay or double-apply an operation attempted during the pause.</li></ul><p><strong>Reproducible companion lab</strong></p><p>Lab 05 provides a deliberately small CPython model with a vulnerable derived-price function and a corrected age/skew/unit gate:</p><p><a href="https://github.com/mamk13/blockchain-security-labs/tree/0d10721580ee48f35028160309b785a52fc35d86/labs/05-oracle-age-skew-units">blockchain-security-labs/labs/05-oracle-age-skew-units at 0d10721580ee48f35028160309b785a52fc35d86 · mamk13/blockchain-security-labs</a></p><p>The 12 Lab 05 tests passed locally on CPython 3.12.14 on October 8, 2026. Hosted GitHub Actions run 37752211603 also completed successfully for the exact commit and all five then-published lab suites:</p><p><a href="https://github.com/mamk13/blockchain-security-labs/actions/runs/37752211603">Add oracle age, skew and unit validation lab · mamk13/blockchain-security-labs@0d10721</a></p><p>A separate Lab 06 extends the week’s practical work into ERC-4626-style share accounting and rounding. Its 14 focused tests passed locally, and the six-suite hosted run completed successfully for commit 3e0c85fb467d87c89833245b52c4d5e9bb81a6e5:</p><ul><li><a href="https://github.com/mamk13/blockchain-security-labs/tree/3e0c85fb467d87c89833245b52c4d5e9bb81a6e5/labs/06-share-accounting-rounding">blockchain-security-labs/labs/06-share-accounting-rounding at 3e0c85fb467d87c89833245b52c4d5e9bb81a6e5 · mamk13/blockchain-security-labs</a></li><li><a href="https://github.com/mamk13/blockchain-security-labs/actions/runs/37752570747">Add share accounting and rounding lab · mamk13/blockchain-security-labs@3e0c85f</a></li></ul><p>These are educational models. They do not read live feeds, prove feed suitability, reproduce an incident, implement a production adapter, or replace review of the actual protocol and official documentation.</p><h3>Review checklist</h3><p>Before approving an oracle consumer, ask:</p><ul><li>Is the feed address correct for this chain and denomination?</li><li>Are the answer and decimal fields validated independently?</li><li>Is the maximum age defined per feed or feed class?</li><li>Is cross-feed skew bounded when deriving a pair?</li><li>Are L2 sequencer and market-status conditions handled where applicable?</li><li>Is rounding direction explicit?</li><li>Does rejection preserve state?</li><li>Is fallback behavior tested as a state machine rather than a comment?</li><li>Can an operator explain which actions remain safe during oracle failure?</li><li>Do tests cover the exact equality boundaries?</li></ul><p>The key lesson is simple: “fresh” is not a complete oracle invariant. Safe consumption requires explicit units, explicit clocks, explicit combination rules and explicit failure behavior.</p><p>Evidence classification: Chainlink interface and derived-pair behavior are attributed to the official documentation linked above. The synthetic values, cross-feed acceptance model, test design and engineering conclusions are original educational analysis. No affected protocol, transaction, loss or attacker profit is asserted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8513e30b328" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Smart Contract Sandbox Is Only as Strong as Its Compiler Boundary]]></title>
            <link>https://mamk13.medium.com/a-smart-contract-sandbox-is-only-as-strong-as-its-compiler-boundary-e48ed3c01e61?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e48ed3c01e61</guid>
            <category><![CDATA[sandbox]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 11:11:35 GMT</pubDate>
            <atom:updated>2026-10-05T11:12:38.174Z</atom:updated>
            <content:encoded><![CDATA[<h4>An evidence-based engineering review of CWA-2026–006, disclosed September 28, 2026, with two tested, non-weaponized educational labs.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGBNN0UcLrmH3ruY-yi9hA.png" /></figure><p>A smart contract can obey every rule in its source language and still become dangerous if the runtime that enforces those rules miscompiles it.</p><p>That is the uncomfortable lesson in <a href="https://github.com/CosmWasm/advisories/blob/main/CWAs/CWA-2026-006.md">CWA-2026–006</a>, a critical vulnerability in the Wasmer Singlepass compiler embedded by <em>wasmvm</em>. The official advisory says a specially crafted WebAssembly contract could escape the execution boundary, run controlled native instructions in the node process, and mint native tokens without authorization.</p><p>This was a vulnerability disclosure, not a reported production exploit. The maintainers say they received no reports of exploitation in production. This article therefore presents no attacker transaction, drained contract, realized loss, or recovery amount.</p><p>The distinction matters. “Critical” describes potential impact and reachability under affected configurations; it does not prove that an attack occurred.</p><h3>Executive summary</h3><ul><li><strong>Disclosure date</strong>: September 28, 2026.</li><li><strong>Original report date</strong>: August 18, 2026, through the Cosmos bug-bounty program.</li><li><strong>Affected component</strong>: the Wasmer Singlepass compiler used by wasmvm to execute CosmWasm contracts.</li><li><strong>Supported impact</strong>: crafted guest code could escape the WebAssembly boundary, execute controlled native instructions inside the node process, and mint native tokens without authorization.</li><li><strong>Reachability</strong>: exploitation required an attacker-controlled contract to be stored and instantiated. On permissionless configurations, an ordinary funded account could reach that path without governance or privileged keys. Previously stored attacker code remained relevant even after upload restrictions.</li><li><strong>Known production loss</strong>: none reported by the maintainers as of the reviewed advisory. This is not the same as proof that exploitation never occurred.</li><li><strong>Official remediation</strong>: upgrade to the matching patched wasmd and wasmvm release pair. The patch is consensus-breaking and requires coordinated chain upgrades.</li><li><strong>Temporary mitigation limit</strong>: restricting or disabling code upload and instantiation raises the delivery barrier but does not remove the vulnerable runtime or neutralize already stored code.</li></ul><h3>What is confirmed, inferred, and still unknown</h3><p><strong>Confirmed by primary sources</strong></p><p>The <a href="https://github.com/CosmWasm/advisories/blob/main/CWAs/CWA-2026-006.md">CosmWasm advisory</a> identifies a code-generation defect in Wasmer Singlepass. It lists the affected and patched wasmd/wasmvm versions, states that unauthorized native-token minting is possible, explains the store-and-instantiate prerequisite, and says there were no known production exploit reports.</p><p>The <a href="https://forum.cosmos.network/t/hub-weekly-update-18-october-1-2026/17397">Cosmos Hub Unit’s October 1 account</a> says the Hub’s production versions were affected but not exploited. It documents an interim mitigation, a full patch, the governance upgrade, and the later public disclosure. That is evidence about the Cosmos Hub response; it is not a complete inventory of every CosmWasm chain.</p><h3>Original analysis in this review</h3><p>The broken security invariant can be expressed as:</p><blockquote>Guest-controlled contract execution must not cross into host-native execution or mutate native bank state except through explicitly authorized, validated host capabilities.</blockquote><p>This wording is an engineering interpretation of the disclosed behavior. It is not quoted from the advisory and is not a formal proof of the Wasmer defect.</p><p>The deployment corollary is:</p><blockquote>A source dependency declaration is not enough; the deployed binary must load the patched wasmvm version paired with its maintained wasmd release line.</blockquote><h3>Unknown or deliberately not reproduced</h3><p>This review does not identify the reporter, malicious byte sequence, compiler-internal trigger, proof-of-concept payload, vulnerable instruction sequence, or an exploitable production contract. It does not replay the escape or execute untrusted native code.</p><p>The advisory says more technical detail may be added after chains have had time to upgrade. Until then, claims beyond the disclosed code-generation defect and impact should remain qualified.</p><h3>Timeline: vulnerability, patch, and disclosure are different dates</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fmwrrz%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fmwrrz%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fmwrrz%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="518" frameborder="0" scrolling="no"><a href="https://medium.com/media/162a0bbb5644c04f7aacf22fabcec390/href">https://medium.com/media/162a0bbb5644c04f7aacf22fabcec390/href</a></iframe><p>Calling September 28 the “incident date” would be misleading. It is the public disclosure date. The defect was reported in August, private remediation began in September, and no production exploitation is reported.</p><h3>Affected versions and verified patch matrix</h3><p>The advisory lists these affected ranges:</p><ul><li>wasmd ≤ v0.70.3, ≤ v0.61.14, ≤ v0.60.8, and ≤ v0.54.9.</li><li>wasmvm ≤ v3.0.7, ≤ v2.3.4, and ≤ v2.2.8.</li></ul><p>The required maintained-line pairs are:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FK0zzQ%2F3%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FK0zzQ%2F3%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FK0zzQ%2Fplain-s.png%3Fv%3D3&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="186" frameborder="0" scrolling="no"><a href="https://medium.com/media/2959c6ca4dd79deb71dbc58d7e38b84d/href">https://medium.com/media/2959c6ca4dd79deb71dbc58d7e38b84d/href</a></iframe><p>The line pairing is important. A check such as “wasmvm is at least 2.2.9” is not sufficient: 3.0.7 is numerically greater than 2.2.9 but is still listed as affected. Security automation must select the maintained release line first, then apply that line’s patched floor.</p><p>The advisory also tells operators to query the runtime directly:</p><pre>&lt;appd&gt; query wasm libwasmvm-version</pre><p>The returned version must be one of the patched versions and match the wasmvm version in go.sum. This checks the binary that is actually running, not only the repository’s intended dependency.</p><h3>Affected chains and contracts</h3><p>This is a runtime-level vulnerability, not a bug in one application contract. The potentially affected population is therefore defined by dependency versions and reachability, not one contract address.</p><p>The official advisory covers chains running the affected wasmd/wasmvm versions. Exploit delivery required attacker-controlled code to be stored and instantiated. Permissionless upload and instantiation made the path reachable without privileged credentials; restricted configurations reduced immediate reachability but did not correct the compiler defect.</p><p>The Cosmos Hub Unit confirms that the Hub ran affected versions and patched before public disclosure without known exploitation. This review does not assert that every CosmWasm chain was affected, upgraded on the same date, or shared the Hub’s configuration.</p><p>There are no verified attacker addresses, affected application-contract addresses, or exploit transaction hashes to list because the primary sources report no production exploit.</p><h3>Root cause versus exploit mechanism</h3><p>The root cause is the disclosed code-generation defect in the Wasmer Singlepass compiler. The compiler is part of the mechanism that turns guest WebAssembly into executable behavior while preserving the sandbox boundary. A defect at that layer can invalidate assumptions made by the contract language, the chain module, and application auditors.</p><p>The exploit mechanism, at the level made public, is:</p><ol><li>An attacker stores and instantiates a specially crafted contract on a chain running an affected runtime.</li><li>The compiler defect lets the contract escape the WebAssembly execution boundary.</li><li>Controlled native instructions execute inside the node process.</li><li>The attacker can create unauthorized native-token balances that look ordinary and survive node restart.</li></ol><p>This sequence does not involve a flash loan. Financing primitives are irrelevant to the disclosed root cause.</p><h3>Why restart and configuration controls are insufficient</h3><p>The advisory says the unauthorized balances are indistinguishable from ordinary balances and survive restart. Restarting the node does not reconstruct the legitimate ledger state.</p><p>It also says there is no configuration-only mitigation that removes the vulnerability. Restricting code_upload_access and instantiate_default_permission, or disabling the relevant store/instantiate messages, can block new delivery. Those controls do not repair the compiler and do not neutralize attacker-controlled code already stored on chain.</p><p>This yields a useful response hierarchy:</p><ol><li><strong>Contain delivery</strong>: restrict or disable new storage and instantiation if the patch cannot be deployed immediately.</li><li><strong>Inventory existing reachability</strong>: determine whether untrusted code is already stored and who can instantiate it.</li><li><strong>Deploy the matching patch pair</strong>: upgrade the maintained wasmd line and its required wasmvm version.</li><li><strong>Verify the running artifact</strong>: confirm lock-file intent, binary checksum/signature, and the runtime-reported library version.</li><li><strong>Coordinate consensus</strong>: because the patch is consensus-breaking, nodes must upgrade through the chain’s authorized process.</li></ol><h3>Financial impact: do not turn potential loss into an invented loss total</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FRbbGg%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FRbbGg%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FRbbGg%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="341" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be04355fbf6cc45c47145c8b00a4de5/href">https://medium.com/media/9be04355fbf6cc45c47145c8b00a4de5/href</a></iframe><p>“Could mint native tokens” describes impact capability. It is not permission to multiply token supply by a market price and call that number a realized loss.</p><h3>Educational vulnerable code: a guest-selected host capability</h3><p>The following <strong>Python 3.12.14 educational model</strong> is intentionally vulnerable. It is not Wasmer code and does not reproduce native execution. It represents only the boundary failure: guest-controlled input can select a host-only effect.</p><pre>class VulnerableBoundaryModel:<br>    def __init__(self):<br>        self.state = HostState()<br>        self._dispatch = {<br>            &quot;guest_write&quot;: self._guest_write,<br>            &quot;host_mint&quot;: self._host_mint,<br>        }<br><br>    def execute(self, actions):<br>        for action in actions:<br>            self._dispatch[action.operation](action)<br><br>    def _host_mint(self, action):<br>        self.state.bank_supply += action.value</pre><p>If an untrusted action selects host_mint, the model changes host-native supply. The vulnerable design confuses “operation exists in the host” with “operation is a capability available to the guest.”</p><h3>Corrected educational code: explicit capabilities and atomic rejection</h3><p>The corrected model exposes one narrow operation, constrains its namespace, validates the complete batch before mutation, and verifies that rejected input leaves all modeled state unchanged.</p><pre>class CapabilityBoundary:<br>    @staticmethod<br>    def _validate(action):<br>        if type(action) is not GuestAction:<br>            raise Rejected(&quot;invalid action&quot;)<br>        if action.operation != &quot;guest_write&quot;:<br>            raise Rejected(&quot;operation is outside the guest capability set&quot;)<br>        if type(action.target) is not str or not action.target.startswith(&quot;guest/&quot;):<br>            raise Rejected(&quot;target is outside the guest namespace&quot;)<br>        if type(action.value) is not int or action.value &lt; 0:<br>            raise Rejected(&quot;invalid value&quot;)<br><br>    def execute(self, actions):<br>        if type(actions) not in (list, tuple):<br>            raise Rejected(&quot;actions must be a fixed batch&quot;)<br>        for action in actions:<br>            self._validate(action)<br>        for action in actions:<br>            self.state.guest_store[action.target] = action.value</pre><p>This fixes the toy model’s dispatch flaw. It does not fix Wasmer, implement a WebAssembly sandbox, or replace the official dependency upgrade.</p><h3>Second lab: turn the advisory into a deployment gate</h3><p>The companion version exercise encodes the four official release pairs and adds a declared-versus-loaded parity check. Its unsafe counterexample uses one global minimum; the corrected gate fails closed on unknown lines and rejects a running library that differs from the dependency declaration.</p><p>That lab teaches a different skill from the sandbox model: converting security-release data into a deterministic deployment condition.</p><h3>Regression-test results</h3><p>All commands ran in an isolated local workspace with Python standard-library dependencies only.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FaeXNn%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FaeXNn%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FaeXNn%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="378" frameborder="0" scrolling="no"><a href="https://medium.com/media/774547c8af52706db24230f8c5009acf/href">https://medium.com/media/774547c8af52706db24230f8c5009acf/href</a></iframe><p>One initial combined command ran Lab 03 successfully and then tried to import Lab 04 from Lab 03’s directory, producing ModuleNotFoundError. Each suite was rerun from its correct documented directory and passed. That setup mistake is retained in the validation record rather than silently rewritten as a clean first attempt.</p><p>No Wasmer/wasmvm compiler was executed. No native escape, chain fork, RPC call, wallet operation, exploit replay, or financial transaction was attempted.</p><p>The tested local commit is c19cf6061c9d43c5b836d2ddb2fd616c66a107cf. It has not been published to GitHub in this handoff because the command-line environment lacked credentials and the browser’s final public commit action required action-time confirmation. Do not cite a hosted CI result or GitHub permalink until the remote commit is verified.</p><h3>Developer and operator lessons</h3><ol><li><strong>Audit below the contract</strong>. A secure contract language cannot compensate for a broken compiler, runtime, native library, or host-function boundary.</li><li><strong>Write the boundary as an invariant</strong>. “Guest code cannot create host-privileged effects” is more testable than “the sandbox is secure.”</li><li><strong>Separate reachability mitigation from remediation</strong>. Disabling uploads can buy time; it is not the patch.</li><li><strong>Inventory stored code</strong>. A delivery restriction applied today says nothing about code admitted yesterday.</li><li><strong>Gate exact release pairs</strong>. Parallel maintained lines invalidate one global version threshold.</li><li><strong>Verify the running library</strong>. Source metadata, static-library selection, build output, and runtime state can diverge.</li><li><strong>Treat consensus-breaking security upgrades as operational incidents</strong>. The security patch, validator coordination, artifact signatures, rollout height, and rollback plan belong in one response record.</li><li><strong>Preserve negative evidence carefully</strong>. “No reports received” is not equivalent to exhaustive proof of non-exploitation.</li></ol><h3>What a mature patch-verification record should contain</h3><ul><li>advisory identifier and reviewed revision;</li><li>affected and patched release line;</li><li>source commit and dependency lock file;</li><li>toolchain version and reproducible build command;</li><li>binary checksum and release signature;</li><li>runtime-reported wasmvm version;</li><li>activation height and validator adoption;</li><li>temporary configuration changes and when they were removed;</li><li>inventory of already stored code and instantiation authority;</li><li>monitoring for anomalous supply changes;</li><li>explicit statement of what was not verified.</li></ul><h3>Final assessment</h3><p>CWA-2026–006 is not a story about a careless application developer or a missing require statement. It is a reminder that smart-contract security is stacked: contract, VM, compiler, native runtime, node binary, consensus upgrade, and operations.</p><p>The source contract can be correct while the execution boundary is wrong.</p><p>The immediate engineering action is simple: follow the official release matrix and verify the library that is actually loaded. The deeper lesson is broader: every sandbox claim depends on the compiler and host boundary that make “inside” and “outside” real.</p><h3>Primary sources</h3><ul><li><a href="https://github.com/CosmWasm/advisories/blob/main/CWAs/CWA-2026-006.md">CWA-2026–006: Sandbox escape in the Wasmer Singlepass compiler</a>, disclosed September 28, 2026.</li><li><a href="https://forum.cosmos.network/t/hub-weekly-update-18-october-1-2026/17397">Cosmos Hub Weekly Update #18</a>, published October 1, 2026.</li><li><a href="https://github.com/cosmos/gaia/releases/tag/v28.1.1">Gaia v28.1.1</a>, <a href="https://github.com/cosmos/gaia/releases/tag/v28.2.1">v28.2.1</a>, and <a href="https://github.com/cosmos/gaia/releases/tag/v28.3.1">v28.3.1</a> release pages, operational context for the Hub only.</li></ul><p>Correction policy: version 1, October 5, 2026. Material evidence changes should be added with dates. The educational labs must not be described as the upstream patch or an exploit reproduction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e48ed3c01e61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Deposit, Two Valid Requests: The Backing Invariant an Amount Check Cannot Prove]]></title>
            <link>https://mamk13.medium.com/one-deposit-two-valid-requests-the-backing-invariant-an-amount-check-cannot-prove-917230f79e10?source=rss-5348cf74cf4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/917230f79e10</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[vulnerability]]></category>
            <dc:creator><![CDATA[Mohammad Khezer]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 10:38:02 GMT</pubDate>
            <atom:updated>2026-09-28T10:39:50.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9bpFGkoIRWPqDbqr8NiCQ.png" /></figure><p>Educational review, not a new incident disclosure or a forensic reconstruction.</p><p>A mint request can pass its amount check and still increase liabilities beyond the funds backing them. The failure appears when we inspect the history of requests rather than one request in isolation.</p><p>Imagine a verified source deposit worth 100 units. The authorized fee is 1 unit, so a mint of 99 is valid under the route’s arithmetic policy. Now submit that same request again. The numbers still fit. Two successful executions would create 198 units against one 100-unit deposit.</p><p>The arithmetic did not fail. The accounting identity did.</p><p>This week, I did not establish a sufficiently verified new smart-contract incident from September 14–21 to support a fresh postmortem. That is a statement about this review’s evidence, not a claim that no incidents occurred. Instead, this article develops an original, isolated teaching model of duplicate consumption. It complements the existing fee-validation example without asserting that replay caused the Symbiosis incident.</p><h3>What the evidence supports</h3><p>The previously covered Symbiosis event occurred on September 11, 2026. BlockSec published its analysis on September 17, placing the reported defect in off-chain deposit validation and estimating the impact at 9.97 BTC. A new article publication date does not make the underlying incident new<a href="https://blocksec.com/blog/web3-security-liquid-network-symbiosis-exploits">—blockSec</a><a href="https://blocksec.com/blog/web3-security-liquid-network-symbiosis-exploits"> analysis</a>.</p><p>The existing analysis remains available as <a href="https://mamk13.medium.com/symbiosis-bitcoin-bridge-when-a-valid-signature-carries-an-invalid-amount-b84f3b0dd01b">Symbiosis Bitcoin Bridge: When a Valid Signature Carries an Invalid Amount</a>. Its incident claims are attributed and evidence-limited. This review adds no newly verified exploit transaction hashes, affected contract addresses, implementation revisions, or recovery transfers. There is no new evidence here that warrants republishing that case as an updated forensic postmortem.</p><p>The general architecture matters: Symbiosis describes a lock-and-mint system using Portal and Synthesis contracts. That documentation explains a backing relationship; it does not independently prove how a particular deployed Bitcoin route behaved during an incident. <a href="https://docs.symbiosis.finance/crosschain-liquidity-engine/synthesizing-process">Official architecture.</a></p><p>For another relevant primary source, EIP-712 defines typed structured data signing and domain separation while explicitly excluding replay protection from its scope. Applications must decide what a repeated authorization does. <a href="https://eips.ethereum.org/EIPS/eip-712">EIP-712.</a></p><h3>Evidence and dates</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FeRUhw%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FeRUhw%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FeRUhw%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="327" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea220dcee73f121ad115409c51befca2/href">https://medium.com/media/ea220dcee73f121ad115409c51befca2/href</a></iframe><p>The first-party disclosure timestamp, exact exploit execution times, containment sequence, and deployed patch revision remain unresolved in this review. Full incident pages were not uniformly accessible. Source retrieval limitations are not filled with inferred identifiers.</p><h3>State the invariant at the right level</h3><p>For one full-consumption deposit, define D as the independently verified amount, F as an authorized fee, and M as issuance, all in the same unit. For a nonsubsidized route that rejects zero issuance:<br>0 &lt;= F &lt; D, and M = D — F.<br>The resulting amount must satisfy 0 &lt; M &lt;= D. These are local conditions. They say nothing about whether the source event was already used.</p><p>The historical condition is stronger: the sum of successful issuance attributed to one source event must not exceed its authorized net amount. If the product permits exactly one full claim, this becomes two requirements: at most one successful consumption, and that consumption has the expected amount.</p><p>A protocol permitting partial claims needs a remaining-balance ledger instead of a simple boolean. A protocol distributing issuance across multiple destinations needs a global allocation rule. The data structure should express the actual economic policy, not force it into a convenient nonce counter.</p><h3>Three identities that should not be confused</h3><p>A source-event identity answers which economic event provides backing. For our Bitcoin teaching model, it contains a network identifier, a canonical transaction ID, and an output index. The test transaction ID is synthetic. Format validation cannot prove a deposit exists, belongs to the protocol, or has sufficient confirmations.</p><p>A message identity answers which authorization was signed. It can include the source event, amount, recipient, asset, destination, contract and policy version. Those bindings prevent an authorization from being accepted in the wrong context, but a changed message should not magically create new backing.</p><p>An execution identity answers whether a particular destination has already applied an authorized operation. Destination execution needs its own idempotency check. A source-side worker lock does not stop a submitted transaction from being retried elsewhere.</p><p>These identities serve different checks. In particular, putting a destination or policy version into a global source-consumption key can accidentally allow the same deposit to be claimed once per destination or version. Bind those fields to the authorization while keeping source-allocation accounting faithful to the deposit’s identity.</p><h3>Vulnerable educational code</h3><p>The following is original Python teaching code. It assumes the input evidence and fee have already been authenticated; it demonstrates only a missing consumption check. checked_net is the fee-validation function in the companion artifact.</p><pre>class VulnerableLedger:<br>    def __init__(self):<br>        self.issued = 0<br><br>    def consume(self, event, deposit, fee):<br>        amount = checked_net(deposit, fee)<br>        self.issued += amount<br>        return amount</pre><p>Calling consume(event, 100, 1) twice returns 99 twice. The aggregate becomes 198. The amount function can be perfectly correct while this ledger violates the backing property.</p><h3>Corrected educational model</h3><p>A single-process model can make the membership check, consumption mark and accounting change one critical section:</p><pre>from threading import Lock<br><br>class GuardedLedger:<br>    def __init__(self):<br>        self.issued = 0<br>        self.consumed = set()<br>        self.lock = Lock()<br><br>    def consume(self, event, deposit, fee):<br>        # Full artifact additionally validates canonical event input fields.<br>        amount = checked_net(deposit, fee)<br>        with self.lock:<br>            if event in self.consumed:<br>                raise ValueError(&quot;source event already consumed&quot;)<br>            self.consumed.add(event)<br>            self.issued += amount<br>        return amount</pre><p>This excerpt deliberately has no external mint call. The full model includes a frozen event record and input checks. The arithmetic guard accepts exact integers, excludes booleans, requires a positive deposit within an illustrative monetary bound, and rejects negative or excessive fees before subtraction.</p><p>The lock protects the modeled transition against concurrent threads in one process. It is not a durable database transaction, a cross-chain atomicity mechanism, or a production repair. Starting a fresh process creates an empty consumed set. Applying this code directly to a bridge would leave a restart replay problem.</p><p>No corrected Symbiosis source or upstream release is asserted. There is no smart-contract compiler involved: runtime CPython 3.12.14; dependencies Python standard library only.</p><h3>Tests that challenge the property</h3><p>The companion archive contains the complete code, README and tests. Run from its repro directory:</p><pre>python3 -m unittest -v fee_guard_example test_replay</pre><p>On September 21, this command completed with exit code 0: 14 tests passed in 0.017 seconds.</p><p>Eight tests exercise the existing fee model, including negative fees, excessive fees, the nonzero-mint policy, type checks, amount bounds, exhaustive small inputs and 10,000 seeded valid cases. Six new tests exercise the state model:<br>- Two unsafe consumptions demonstrate aggregate issuance of 198.<br>- A second guarded consumption is rejected, with issuance and the consumed set unchanged.<br>- Invalid fee input does not consume the event; a later valid request succeeds.<br>- Two distinct output indices remain distinct events.<br>- Noncanonical or invalid event fields are rejected.<br>- Eight threads synchronize before attempting one event: one succeeds and seven are rejected.<br>The concurrent test covers one local interleaving scenario under Python’s threading runtime. It does not exhaust possible schedules or establish multi-process correctness. The suite does not test cryptographic signatures, Bitcoin scripts, chain finality, database crash recovery, distributed consensus, token transfer behavior, or deployed contracts.</p><h3>Carry the property into a real design</h3><p>A durable design should commit its allocation record and issuance intent consistently. The record needs a uniqueness constraint for the source event, an immutable authorized destination, and enough state to reconcile retries. A separate worker can submit an already-recorded intent, but it must reuse the same identity rather than generate a fresh claim after a timeout.</p><p>There is an unavoidable boundary between recording an intent locally and observing a destination-chain effect. A timeout does not prove a transaction failed. Before retrying, the worker must reconcile with destination state, and destination logic must reject duplicate consumption of the same authorization. A local lock alone cannot solve that boundary.</p><p>Reorganizations introduce another dimension. The system must define when source evidence becomes eligible, what to do if it later disappears, and who can intervene. Clearing a consumed flag after a reorganization can be dangerous if the corresponding destination issuance remains outstanding. Recovery should preserve a reconciled liability history.</p><p>Unit conversion also belongs in the specification. A source satoshi and a destination token base unit need not be interchangeable. Define scaling and rounding explicitly, check the fixed-width destination range, and include converted amounts in the signed payload. Passing Python’s arbitrary-precision arithmetic tests does not demonstrate correct EVM encoding.</p><h3>Impact, response and unresolved evidence</h3><p>This teaching model caused no financial loss: it was run locally without chain access or transactions. Its 198 issued units are in an invented state, not attacker proceeds or counterfeit tokens with a market value.</p><p>For the previously covered incident, the attributed loss estimate is not an independently reconciled gross-loss ledger. Exact recoveries, net unrecovered loss, attacker proceeds, and completed compensation remain unverified here. Unknown recovery must not be entered as zero. Forged token face value must not be substituted for realized loss.</p><p>Likewise, this review makes no claim that a specific containment action or remediation deployment has been completed. A rigorous incident update would need complete source reports, validated traces, implementation mapping, a response timeline, and recovery evidence. Until then, keep the educational recommendations separate from statements about what a protocol actually changed.</p><h3>The review question to carry forward</h3><p>Ask whether the system can show that every successful issuance consumes a unique, authorized share of verified backing. Then test invalid inputs, duplicates, concurrent attempts, restarts, and uncertain transaction outcomes against that statement.</p><p>Amount checks protect one calculation. A trustworthy ledger must also preserve the relationship between that calculation and its entire execution history.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=917230f79e10" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>