<?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 Vihaan on Medium]]></title>
        <description><![CDATA[Stories by Vihaan on Medium]]></description>
        <link>https://medium.com/@vihaan1016?source=rss-7fbc1a994815------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Vihaan on Medium</title>
            <link>https://medium.com/@vihaan1016?source=rss-7fbc1a994815------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:26:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vihaan1016/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[Your Rust Benchmarks Are Lying to You]]></title>
            <link>https://medium.com/@vihaan1016/your-rust-benchmarks-are-lying-to-you-f52f7ae8848e?source=rss-7fbc1a994815------2</link>
            <guid isPermaLink="false">https://medium.com/p/f52f7ae8848e</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[flamegraphs]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[criterion]]></category>
            <dc:creator><![CDATA[Vihaan]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 21:45:00 GMT</pubDate>
            <atom:updated>2026-06-30T21:45:00.511Z</atom:updated>
            <content:encoded><![CDATA[<p>I want to start with a confession: the first time I tried to benchmark a piece of Rust code, I wrote this.</p><pre>let start = std::time::Instant::now();<br>do_work();<br>let elapsed = start.elapsed();<br>println!(&quot;{elapsed:?}&quot;);</pre><p>I ran it a few times, eyeballed the numbers, and called it a day. It felt scientific. It was not. That single Instant::now() measurement is a snapshot of one moment in a deeply noisy system: your CPU&#39;s clock speed, the scheduler&#39;s mood, what&#39;s sitting in cache, and almost none of that noise has anything to do with the code you actually wrote. The number it spits out can vary by 2x between two runs of the exact same binary, and you&#39;d have no way of knowing whether a &quot;10% improvement&quot; you just measured is real or just static.</p><p>So how do engineering teams actually measure performance? And how do you do it properly in Rust? That’s what this post is about, mostly the criterion crate, and flamegraphs, the visualization that tells you <em>where</em> your time is going. By the end you should understand not just which commands to run, but why each one exists. I highly recommend getting a overview of certain systems terms as they are introduced in this blog simultaneously to get a better learning experience.</p><h3>Why benchmarking is a real discipline, not an afterthought</h3><p>Here’s the problem with performance: it’s <strong>non-compositional</strong>. You can’t look at two individually fast functions and assume that calling one after the other is also fast. Cache eviction, branch predictor pollution, TLB thrashing, and allocator fragmentation are all properties that show up only when components interact, not properties of any single function in isolation.</p><p>That has a frustrating consequence: none of your normal quality-control tools can catch performance regressions. Code review can spot an obviously bad algorithm, but it can’t spot the 15% slowdown caused the allocator pressure from a .collect() into a fresh Vec inside a loop that gets called ten million times a second. Unit tests check correctness, not speed, so a function that takes 10x longer than before still returns the right answer. And manual testing is hopeless here too, because humans can’t perceive the difference between 274 nanoseconds and 315 nanoseconds per operation, even though that’s a real and meaningful regression at scale.</p><p>The only thing that actually works is automated, statistically rigorous measurement baked into your workflow. That’s the gap Criterion and flamegraphs fill.</p><h3>Why Criterion, and how it actually works</h3><h3>The problem with naive timing</h3><p>We already saw why a single Instant::now() call lies. Let’s now know about the technical culprits. Your CPU runs under Dynamic Voltage and Frequency Scaling (DVFS), which means it might be at 800 MHz when your timer starts and at 4+ GHz by the time it stops, and the same instructions take wildly different wall-clock time at different frequencies. On top of that, the OS scheduler can use your thread mid-measurement to go run something else entirely like fetching a packet over Wi-fi, adding delay that has nothing to do with your code. And then there&#39;s cache state: was your data sitting in L1 (a few cycles) or did it have to come all the way from DRAM? A cold-cache and warm-cache run of the identical function can differ by an order of magnitude or more.</p><p>The fix isn’t “be more careful with Instant::now().&quot; It&#39;s a mental shift: <strong>a benchmark result is not a number, it&#39;s a confidence interval over a distribution.</strong></p><h3>How Criterion Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcFRQ6HXh2vaY9DvbPVaYg.png" /></figure><h3>Warm-up, and why 3 seconds isn’t arbitrary</h3><p>Criterion’s default warm-up phase runs for about 3 seconds before it records anything. That’s not padding, it’s doing real hardware work. It gives the CPU governor time to ramp from idle frequency up to its boost clock, it saturates your instruction and data caches with the benchmark’s actual working set, and it gives branch predictors like Intel’s TAGE predictor time to learn your code’s branch patterns. Skip warm-up and your first several measurements are sampling a CPU that hasn’t woken up yet.</p><h3>Slope, not average</h3><p>Here’s Criterion’s central trick. Instead of looping N times and dividing total time by N, which smears any single outlier across every iteration, Criterion runs your function in groups of increasing size (N, 2N, 3N, …), records total time for each group, and fits a line through the points. cirterion uses a straight line for the regression solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*N1H8hmSSsm9DNEL5aTPtIw.png" /></figure><ul><li>y is the total time mesaured.</li><li>x is the Number of iterations.</li><li>m (the slope) is the per-iteration cost</li><li>b is the Overhead (time required for setup and time required to stop)</li></ul><p>A single OS preemption during one group just nudges that one point off the line, and the slope barely moves. Division-by-N has no such protection.</p><h3>Cleaning up and characterizing the data</h3><p>Once samples are in, Criterion hunts for outliers using a version of <strong>Tukey’s fences</strong>: compute the interquartile range (IQR) between the 25th and 75th percentiles, then flag anything beyond 1.5×IQR as a mild outlier and 3×IQR as severe. A high rate of severe outliers is basically Criterion telling you your environment is too noisy to trust, which is exactly what happens on shared CI runners.</p><p>Then it estimates the shape of your timing distribution using <strong>kernel density estimation (KDE)</strong>, which is smoother and less arbitrary than picking histogram bin widths. A clean unimodal curve means your function behaves consistently. A bimodal curve is a real signal: some iterations hit cache and some don’t, and a plain mean computed across both peaks describes a speed your code never actually runs at.</p><p>Finally, confidence intervals come from <strong>bootstrap resampling</strong>: draw samples with replacement from your cleaned data, compute the mean, repeat 100,000 times, sort the results, and take the 2,500th and 97,500th values as your 95% CI bounds. Because CPU timing distributions are skewed and have a hard physical floor, this approach beats assuming a nice symmetric Gaussian.</p><h3>black_box: a deliberate blindfold for the compiler</h3><p>LLVM is good at its job, which is exactly the problem. If you benchmark a lookup on the same key every time, the optimizer might notice and <strong>constant-fold</strong> the whole thing at compile time, so you’d end up timing a register load, not your data structure. If you never use the return value, LLVM might <strong>dead-code-eliminate</strong> the call entirely, leaving you with a benchmark of nothing. And if your input is loop-invariant, <strong>Loop-Invariant Code Motion (LICM)</strong> can take the real work out of the loop and run it once, then reuse the result for every “iteration.”</p><pre>black_box(tree.get(black_box(&amp;42u32), &amp;txn).unwrap())</pre><p>black_box is the fix: an opaque inline-asm barrier that tells the optimizer &quot;this value is used, stop trying to prove otherwise,&quot; without doing anything at runtime. Wrap the input so it can&#39;t be constant-folded, and wrap the output so it can&#39;t be discarded.</p><h3>iter_batched: separating setup from the thing you actually care about</h3><p>Imagine a factory worker whose job is hammering nails. If you time them “from walking to the toolbox” you’ll get a number dominated by walking, not hammering. iter_batched is how you hand them a pre-loaded nail gun and only start the clock once they pull the trigger. The setup closure, creating an empty store, say, runs once per batch and isn&#39;t measured; the routine closure is the only thing timed.</p><pre>b.iter_batched(<br>    || setup_index(0),<br>    |(idx, _dir)| {<br>        for i in 0u32..1000 {<br>            let k = black_box(i.wrapping_mul(2654435761));<br>            black_box(idx.insert(&amp;k, &amp;(i * 7), &amp;auto()).unwrap());<br>        }<br>    },<br>    BatchSize::SmallInput,<br>)</pre><p>BatchSize controls how Criterion manages that setup cost: SmallInput pre-allocates a batch of cheap setups, LargeInput sets them up one at a time to avoid holding many large structures in memory at once, and PerIteration rebuilds fresh state for every single call, which is necessary when the routine is destructive, like a delete. Skip iter_batched on an insert benchmark and you&#39;re often timing 100x more setup overhead than actual insert cost, which buries the signal entirely.</p><h3>What flamegraphs actually show you</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rD8WPfKraL5ILuieWFSPA.png" /></figure><p>Once you know that something is slow, you need to know <strong><em>where</em></strong>. That’s a flamegraph’s job. Brendan Gregg invented them at Netflix to visualize sampled call stacks: perf periodically interrupts your program via the CPU&#39;s hardware Performance Monitoring Unit, grabs the current call stack, and records it. Do that thousands of times and you&#39;ve got a statistical map of where the CPU spends its time.</p><p>Reading one correctly means trusting three axes, and getting any of them wrong leads people astray constantly. The <strong>Y-axis is call depth, not slowness</strong>: a tall stack of narrow frames is just deep nesting, not a problem. The <strong>X-axis is sample population, not time</strong>: frames are sorted alphabetically within their parent purely so identical sub-stacks can merge, which means there’s no left-to-right timeline to read. Frame width tells you what fraction of total samples included that function. The actual rule of thumb is to hunt for the <strong>widest frame near the top</strong>, something called often and doing real work itself, not just delegating to children. And <strong>color is usually meaningless.</strong></p><p>Sampling rate matters more than it seems like it should. perf record -F 99 samples at 99 Hz rather than a round 100 Hz on purpose: sampling at exactly 100 Hz risks syncing with kernel timers that also fire at common round frequencies, biasing your samples toward whatever the kernel happens to be doing on every tick. Prime-ish frequencies like 99 or 999 avoid that aliasing. Higher rates buy resolution at the cost of overhead: 99 Hz costs roughly 0.5%, while 999 Hz can run 2-5%, and at very fast functions the profiler can start showing up in its own flamegraph.</p><p>Then there’s the part that trips people up the most: <strong>frame pointer omission</strong>. By default, Rust release builds let LLVM repurpose the RBP register as a general scratch register instead of maintaining it as a frame pointer, because one extra usable register is a small but real win. The cost is that perf can no longer follow the linked-list-of-frame-pointers it normally uses to reconstruct a call stack. Without it, your flamegraph collapses into a wall of [unknown] frames with only the leaf function correctly attributed. The breadcrumb trail is gone. The fix is one build flag:</p><pre>RUSTFLAGS=&quot;-C force-frame-pointers=yes&quot; cargo build --release</pre><p>This costs roughly 1–3% in raw performance from giving up that register, which is a completely reasonable trade for a profiling build. The alternative is DWARF-based unwinding, which works without recompiling but parses debug sections to reconstruct the stack on every sample, far more expensive per sample (and can fail on deeply inlined code), which makes frame pointers the better default whenever you can recompile.</p><h3>Try it yourself</h3><p>Use this <a href="https://github.com/vihaan1016/benchmarking-intro">github repo</a> to try it yourself.</p><p>Reading about this is fine, but the only way it really sticks is watching these effects show up in numbers on your own machine. There’s a companion exercise built around three small key-value store implementations, a sorted Vec, a BTreeMap, and a HashMap, benchmarked across eight workloads that each isolate a different access pattern.</p><h3>Further reading</h3><p>If you want to go past what’s in this post, these are worth your time: Brendan Gregg’s original flamegraph writing and tooling, the <a href="https://bheisler.github.io/criterion.rs/book/">Criterion.rs documentation</a>, and TiKV’s engineering blog for more on how they run benchmark gating in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f52f7ae8848e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the scary world of EVM!!]]></title>
            <link>https://blog.blockmagnates.com/exploring-the-scary-world-of-evm-6c78c67a3557?source=rss-7fbc1a994815------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c78c67a3557</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Vihaan]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 18:39:24 GMT</pubDate>
            <atom:updated>2026-07-03T08:06:02.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vr9af8gKIcWwnCYqipGMRQ.jpeg" /></figure><h3>Introduction</h3><p>Most developers just write their smart contracts in Solidity and stop there. But behind the scenes, Ethereum translates that code into a machine language called bytecode. To truly understand how your contracts work, you need to look past the Solidity code and learn what happens at this deeper level. <br>This article summarises several technical aspects of the EVM and explains:</p><ul><li>What <strong>bytecode and opcodes</strong> are</li><li>How <strong>function calls and calldata</strong> work</li><li>How the <strong>EVM stack</strong> operates</li><li>How Solidity uses <strong>memory during execution</strong></li><li>How <strong>storage slots</strong> are structured</li><li>How <strong>slot packing</strong> optimizes storage usage</li></ul><p>Together these concepts form the foundation of how Ethereum programmes run.</p><h3>Bytecode and Opcodes</h3><p>When you prepare your Solidity code for the Ethereum network, it turns into &quot;bytecode&quot;, a long string of data the system can actually read. This data is made up of small instructions called &quot;opcodes&quot;. These opcodes are the most basic, single-step actions the network can take, like:</p><ul><li>arithmetic operations</li><li>memory access</li><li>storage reads and writes</li><li>control flow operations</li></ul><p>Each opcode is represented by <strong>one byte</strong>. Since a byte has <strong>256 possible values</strong>, the EVM can theoretically support <strong>256 different opcodes</strong>.</p><p>All of these 256 spaces are not yet used. Some of these slots remain unused for future development so that Ethereum can introduce new upgrades without breaking compatibility.</p><p>For example, Ethereum upgrades have introduced new opcodes, such as the following:</p><ul><li>REVERT – allows transactions to fail without consuming all remaining gas</li><li>STATICCALL – enables read-only contract calls</li><li>CHAINID – returns the chain identifier</li></ul><h3>Function Signatures and Calldata</h3><p>When a user calls a smart contract function, the transaction includes a data field known as <strong>calldata</strong>.</p><p>Calldata contains:</p><ol><li>the function identifier</li><li>the encoded arguments</li></ol><p>The first <strong>4 bytes</strong> of calldata represent the <strong>function selector</strong>, which identifies which function should execute.</p><p>This selector is derived from the <strong>Keccak-256 hash</strong> of the function signature.</p><p>Example function:</p><pre>transfer(address, uint256)</pre><p>Hashing this string produces a 32-byte hash. The <strong>first four bytes</strong> become the function selector.</p><p>Example calldata layout:</p><pre>| 4 bytes | 32 bytes | 32 bytes |<br>|selector | argument | argument |</pre><p>When the EVM receives a transaction, the contract reads these bytes and determines which function to execute and which parameters to use.</p><h3>EVM Call Stack</h3><p>Ethereum Virtual machine is a stack-based machine.</p><p>Most instructions:</p><ol><li><strong>pop values from the stack</strong></li><li><strong>perform an operation</strong></li><li><strong>push the result back onto the stack</strong></li></ol><p>Example:</p><pre>PUSH1 0x02<br>PUSH1 0x03<br>ADD</pre><p>Execution:</p><pre>Initial stack:<br>(empty)<br>After: PUSH1 0x02<br>Stack: [2]<br>After: PUSH1 0x03<br>Stack: [2, 3]<br>After: ADD</pre><p>The ADD opcode:</p><pre>Pops 3<br>Pops 2<br>Computes 2 + 3<br>Pushes result<br>Final Stack: [5]</pre><h3>Memory in EVM:</h3><p>Memory is a <strong>temporary data area</strong> used during contract execution.</p><p>The EVM provides three main instructions for interacting with memory:</p><ol><li>MLOAD: Reads <strong>32 bytes</strong> from a memory location.</li><li>MSTORE: Writes <strong>32 bytes</strong> to memory.</li><li>MSTORE8: Writes <strong>a single byte</strong> to memory.</li></ol><h4>Solidity’s Memory Layout:</h4><pre>Memory Layout<br><br>0x00 – 0x3f   Scratch space<br>0x40          Free memory pointer<br>0x60          Zero slot</pre><h4>Free Memory Pointer</h4><p>The address 0x40 stores the <strong>next available memory location</strong>. When Solidity allocates new memory, it reads the pointer, stores the new data, and then updates the pointer.</p><h4>Zero Slot</h4><p>The zero slot, is used as an initial value for dynamic memory arrays and should never be written to.</p><h4>Dynamic Memory Allocation</h4><p>Dynamic arrays are stored in a linear order in memory.</p><pre>Memory layout:<br>| length | element1 | element2 | element3 |<br>Memory diagram:<br>Memory Address<br>0x80 → length = 2<br>0xA0 → arr[0]<br>0xC0 → arr[1]</pre><p>Steps performed by Solidity:</p><ol><li>Read the free memory pointer</li><li>Store the array length</li><li>Allocate space for array<strong> </strong>elements</li><li>Update the free memory pointer</li></ol><p>This allows easy access to elements of an array.</p><h3>Storage in Ethereum</h3><p>While memory is temporary, storage is permanent in blockchain. Each smart contract running in the Ethereum Virtual Machine (EVM) maintains state in its own permanent storage. This storage can be thought of as a very large array, initially full of zeros. Each value in the array is 32-bytes wide, and there are 2²⁵⁶ such values.</p><p>Conceptually: storage[slot] → 32-byte value</p><p>Solidity assigns storage slots to variables in the order that they are declared.</p><p>For fixed-size variables, Solidity assigns storage as follows:</p><pre>uint256 a;<br>uint256 b;<br><br>Storage:<br>slot[0] -&gt; a<br>slot[1] -&gt; b</pre><p>Each 32 byte variable occupies the entire storage slot unless it can be packed with other variables. Dynamic arrays and mappings are stored in a different way as the size of such data structures is not already known. To understand their slot allocation, <a href="https://programtheblockchain.com/posts/2018/03/09/understanding-ethereum-smart-contract-storage/">read this</a>.</p><h3>Slot Packing</h3><p>We finally arrive at one of the most important concepts of the low level EVM storage allocation methods. Since each slot is 32 bytes, solidity tries to pack as many smaller variable with sum of their size being less than 32 bytes into the same slot. This optimization reduces the storage usage and saves gas during deployment. but modifying one packed value requires loading the entire slot, masking the old value, inserting the new one, and writing the whole slot back with SSTORE. Hence, it is advisable to not pack variables that would change frequenty and instead assign entire storage slots in order to reduce the number of opcodes and binary operations; more on this ahead in the article.</p><h4>Updating Packed Variables</h4><p>Since the EVM can only write on entire storage slots it becomes quite difficult to update packed variable while making sure that unwanted variables are not changed. To tackle this problem we use a series of opcodes and binary operations to only change the desired variables.</p><pre>SLOAD(slot)<br>mask_value = ~(0xffffffff &lt;&lt; offset)<br>cleared_slot = old_slot AND mask_value<br>shifted_new_value = new_value &lt;&lt; offset<br>updated_slot = cleared_slot OR shifted_new_value<br>SSTORE(slot, updated_slot)</pre><p>What is happening is basically as follows:</p><ol><li>Loading the slot with SLOAD</li><li>Clearing the bits corresponding to the target variable using a <strong>bitmask</strong></li><li>Shifting the new value into the correct position</li><li>Combining values using a <strong>bitwise OR</strong></li><li>Writing the updated slot using SSTORE</li></ol><p>This process ensures that the other packed variables remain unchanged.</p><h4>Reading Packed variables</h4><p>Reading a packed variables means extracting only the desired part consisting of the required variable. This can very easily be conceptualised as following: value = (slot &gt;&gt; offset) &amp; mask</p><p>The process involves:</p><ol><li>Loading the slot with SLOAD</li><li>Shifting the slot value to align the target variable</li><li>Applying a bitmask using a <strong>bitwise AND</strong></li></ol><h3>Conclusion</h3><p>Understanding important concepts such as calldata encoding, memory allocation, storage slot layout, and slot packing is vital to writing gas-optimised and secure code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c78c67a3557" width="1" height="1" alt=""><hr><p><a href="https://blog.blockmagnates.com/exploring-the-scary-world-of-evm-6c78c67a3557">Exploring the scary world of EVM!!</a> was originally published in <a href="https://blog.blockmagnates.com/">Block Magnates</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Segregated Witness(SegWit): The update that quietly fixed Bitcoin.]]></title>
            <link>https://medium.com/@vihaan1016/segregated-witness-segwit-the-update-that-quietly-fixed-bitcoin-b5d058168315?source=rss-7fbc1a994815------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5d058168315</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Vihaan]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 14:43:03 GMT</pubDate>
            <atom:updated>2026-02-24T14:43:03.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*P8RgyhP20Xi-RwfYC55rZA.png" /></figure><h3>Abstract:</h3><p>This article explains the Segregated Witness (SegWit) upgrade introduced to Bitcoin in 2017 and why it was a turning point for the network’s scalability and reliability. We analyze how legacy Bitcoin transactions worked, the core limitations they introduced such as transaction malleability, inefficient block usage, and quadratic hashing. We then explore how SegWit restructured transaction to solve these problems.</p><h3>Introduction:</h3><p>Segregated Witness or SegWit is a soft fork described in the series of BIPS (141,142,143,144,145), whose main target was to optimize the transactions in bitcoin by separating the signatures from the transactions to a separate structure. Not only does it reduces the size of transaction hence increasing the number of transactions that can be accommodated in a single block but also solves the problem of transaction malleability which is very important for the existence of layer 2 solution like Lightning network.</p><h3>Before we Begin:</h3><p>In order to understand the need for change to segregated witness we must first understand how the legacy transactions worked.</p><p>At the top level we need to understand that SegWit fundamentally changed how a bitcoin transaction is created. In a legacy transaction the following two main components exist:</p><ul><li>The transaction data itself, which includes information about how much bitcoin is being moved, where it came from, and the new destinations.</li><li>The data related to the cryptographic signatures that were required to approve the transaction.</li></ul><p>This is how a legacy bitcoin transaction looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*rTK8Iz4_4SmqhiRSbeb5dA.jpeg" /></figure><p>The pubkey script in the output section of the transaction is also called as the locking script as it makes sure that only the owner of the receiving address can spend this transaction. The signature script section of the transaction is also known as the unlocking script.</p><p>SegWit is a soft fork which means that it is backward compatible. A soft fork occurs when the consensus rules are made stricter. Previously valid blocks may be considered invalid but previously considered invalid blocks will stay invalid.</p><h3>Why was SegWit needed?</h3><h4>Transaction Malleability:</h4><p>Before SegWit the transaction id (<strong>txid</strong>) was calculated by hashing the entire transaction including the signature scripts. The main problem with such a hashing was that it was very easy for a malicious party to add empty operators like OP_NOP (non operational operators) and change the signature script which would in turn change txids. Even though the same funds were moved to their respective destinations the unpredictability broke chains of unconfirmed transactions which made the rise of <a href="https://chain.link/education-hub/bitcoin-layer-2#:~:text=Enter%20layer%202s.-,A%20Bitcoin%20layer%202%20is%20any%20offchain%20network%2C%20system%2C%20or,and%20programmability%20through%20smart%20contracts.">Layer 2</a> solutions like <a href="https://medium.com/softblocks/lightning-network-in-depth-part-1-payment-channels-b943607950dd">Lightning Network</a> impossible.</p><h4>Block Capacity Limit:</h4><p>Bitcoin had a hardcoded block size of 1MB. As the adoption of bitcoin grew the blocks started to be always full which led to increase in transaction fees and delays. Simply raising the 1MB block size would make it a hard fork meaning was highly debatable.</p><h4>Quadratic Hashing Vulnerability:</h4><p>In legacy bitcoin transactions, verifying a signature required hashing the entire transaction. The time complexity of this legacy hashing system was O(n²) . If the time to verify the transaction with two inputs is 1 ms, it will take 4 ms to verify a transaction with four inputs. Double the number of inputs again, and you have 16 ms. A transaction with 1,024 inputs would take more than 4 minutes! This weakness can be exploited by creating a large transaction with a lot of inputs. All nodes verifying the transaction will be occupied for minutes, making them unable to verify other transactions and blocks during this time. The Bitcoin network as a whole would slow down.</p><h4>Rigid Scripting Language:</h4><p>Bitcoin’s original code was very strict and adding new features was risky. If developers tried to add a new command older nodes on the network wouldn’t understand it. They would just see an error and reject the transaction. This left developers with two equally bad choices. They could force a risky hard fork where everyone had to upgrade their software at the exact same time. Or they could use the old OP_NOP codes that were left by satoshi in the original bitcoin code which were only 10 and clunky. Both options made it very hard for Bitcoin to grow and improve.</p><h3>SegWit’s Solutions:</h3><h4>Segregation of witness data:</h4><p>SegWit separates the the witness data (signature scripts) from the main transaction body. This means that:</p><ul><li>The new transaction id(txid) is calculated without the witness data.</li><li>Because the witness data is no longer a part of the txid the changes made to the witness data does not affect the txid. The transaction id remaining the same from the moment it is created and does not change giving rise to complex, multi-step smart contracts like Lightning Network to exist.</li></ul><h4>Introduction of Block Weight:</h4><p>SegWit bypassed the 1 MB limit without a hard fork by introducing a new measurement called <strong>Block Weight</strong>, capped at 4,000,000 Weight Units (WU). Let’s call the block excluding the witnesses the base block:</p><ul><li>1 byte of base block data is counted as 4 WU.</li><li>1 byte of witness data is counted as 1 WU.</li></ul><p>Suppose the witnesses in a block account for ratio r of the data in a block. The maximum block weight is 4,000,000, and a total block size T gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*y5O0-s0KHaxDEXiea80JiA.png" /></figure><p>Inserting various values of r into this formula gives different maximum total block sizes.</p><p>As the relative amount of witness data increases in the block, we can squeeze in more transactions. The effect is an actual maximum block size increase. The witness discount is implemented for several reasons:</p><ul><li>The signature scripts and witnesses don’t go into the <a href="https://www.investopedia.com/terms/u/utxo.asp">UTXO</a> set. Data that goes into the UTXO set has higher costs because the UTXO set should preferably be stored in RAM for fast transaction verification.</li><li>It gives wallet developers, exchanges, and smart contract developers more incentive to make fewer outputs, which reduces the UTXO set’s size. For example, an exchange can choose to consolidate its many outputs into a few outputs.</li><li>The witnesses don’t have to be sent to a lightweight wallet.</li></ul><h4>BIP 143:</h4><p><a href="https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki">BIP 143</a> breaks down the entire transaction into components. It hashes the common items exactly once and reuses them. The node now with segwit calculates 3 <a href="https://scispace.com/pdf/double-sha-256-hardware-architecture-with-compact-message-2gncxmfv28.pdf">double-SHA256</a> hashes at the start:</p><ul><li><strong>hashPrevouts</strong>: A of all the previous outputs (the funds being spent) across every input.</li><li><strong>hashSequence</strong>: A single hash of all the sequence numbers for every input.</li><li><strong>hashOutputs</strong>: A single hash of all the new outputs (where the funds are going) created by this transaction.</li></ul><p>When it is time to verify the signature for Input 1, the node no longer hashes the whole transaction. Instead it joins together a much smaller, fixed-size set of data:</p><ol><li>The version number of the transaction.</li><li>The pre-hashed <strong>hashPrevouts</strong>.</li><li>The pre-hashed <strong>hashSequence</strong>.</li><li>The specific data for Input 1 (its outpoint, its value, and its script code).</li><li>The pre-hashed <strong>hashOutputs</strong>.</li><li>The locktime.</li></ol><p>When verifying these transactions the node is now only calculating the 32 bytes output of these pre-hashed expressions with the specific data of a given input. This changes the verification time from quadratic O(n²) to linear and manageable O(n). This neutralizes the threat of DDoS attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NDNbBXeTakZAp5nRWOEfyg.jpeg" /></figure><h4>Versioning System:</h4><p>SegWit introduced a versioning system for unlocking scripts. A SegWit output starts with a version byte (e.g., OP_0).</p><ul><li>If a new cryptographic feature needs to be added in the future, developers can simply release it under OP_1, OP_2, etc.</li><li>Older nodes are programmed to read any unknown version as an “anyone-can-spend” transaction, meaning they will just accept it as valid without needing to understand the new rules. This makes future upgrades easily deployable as soft forks (which is exactly how the Taproot upgrade was later rolled out using OP_1).</li></ul><h3>SegWit Controversy?!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmEKe9Cgsf1VCtAR-OuIYQ.png" /></figure><p>The main arguments against SegWit’s rollout include:</p><ul><li>Bitcoin’s increased throughput of 7–10 transactions per second is still nowhere near high enough for a decentralized, global payment system.</li><li>Fees would remain relatively high, making things like microtransactions financially unfeasible.</li><li>Miners can still process legacy transaction blocks, meaning malleability is still a threat.</li></ul><h3>Conclusion:</h3><p>While it is quite possible that some of the issues that were solved by SegWit may have better solutions, we still believe that at the present moment it is an excellent way to increase the scalability of the network and to enable the implementation of such technologies as the Lightning Network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5d058168315" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>