<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Hamza on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Hamza on Medium]]></description>
        <link>https://medium.com/@hamza.00dev1?source=rss-3e8a873d6060------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NtvYLQM6825wnGYZ</url>
            <title>Stories by Muhammad Hamza on Medium</title>
            <link>https://medium.com/@hamza.00dev1?source=rss-3e8a873d6060------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:32:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamza.00dev1/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[From Theory to Pull Request: Lessons from Three Months of Bitcoin and Lightning Contributions]]></title>
            <link>https://medium.com/@hamza.00dev1/from-theory-to-pull-request-lessons-from-three-months-of-bitcoin-and-lightning-contributions-c5a6b5860fcf?source=rss-3e8a873d6060------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5a6b5860fcf</guid>
            <category><![CDATA[open-source-contribution]]></category>
            <category><![CDATA[bitcoin-lightning]]></category>
            <category><![CDATA[btrust-builders]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[btrust]]></category>
            <dc:creator><![CDATA[Muhammad Hamza]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 13:45:23 GMT</pubDate>
            <atom:updated>2026-11-29T09:36:25.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49WnBLnnBFS1RB8De2Q0NQ.png" /></figure><h3>Introduction</h3><p>Three months ago I had a general interest in contributing to open-source Bitcoin projects, but very little concrete knowledge of either the underlying theory or the practical process of making useful contributions. I knew that reading code and opening pull requests was the goal, yet I did not have a clear picture of how to move from theory to actual work, or how maintainers review and merge changes.</p><p>The foundation for that progression was laid by the BTrust Fellowship. The programme provided a structured path from theory, through hands-on work with an existing codebase, to opening and iterating on pull requests. Without that framework the move from general interest to useful contributions would have been far less clear.</p><p>What changed over the three months was not a single breakthrough. It was a gradual sequence: first building a solid theoretical foundation, then spending deliberate time inside an existing codebase by building it, running it, and reviewing other people’s work, and only later choosing a project and opening pull requests. The most useful parts of the experience were the habits that made that progression possible: understanding the review culture of a project before trying to contribute, testing changes locally, communicating clearly, and paying attention to what the maintainers were currently focused on.</p><p>This article is written for someone who is in a similar position. It describes what I actually did, what turned out to matter, and what I would do differently if I were starting again.</p><p>The first weeks were spent on theory. I started with the Bitcoin white paper and the ideas that shaped it, then moved into how the system works at a high level: transactions, how blocks are connected, and the basic security assumptions. From there I spent time on Lightning. I looked at how payment channels are constructed, how the different transaction types inside a channel function, and why certain design choices exist around security and updates.</p><p>At the time this stage felt slow. Looking back, it was the part that later made code reviews and design discussions intelligible. When I eventually looked at routing logic or wallet code, I already had a model of what the code was trying to achieve and what problems it needed to handle carefully. Without that background, much of the later code would have been difficult to reason about.</p><p>A practical habit that helped during this period was discussing the material regularly with another person. Talking through concepts, comparing understanding, and seeing the same ideas from a different angle made the knowledge stick and also improved how I later explained technical points to others.</p><h3>Working Inside Bitcoin Core</h3><p>Once the theoretical base was in place, the next step was to get Bitcoin Core running locally. The practical starting point was straightforward: clone the repository, build it from source, and make sure the tests passed. Doing this removed a large amount of friction. With a working build, it became possible to check out other people’s pull requests, run them, and see exactly what had changed.</p><p>I also wrote a short guide on the process of building and running Bitcoin Core. Writing it forced me to organise the steps clearly enough that someone else could follow them, and it turned out to be useful both for myself and for others who were starting from a similar place. If you want to read the article, you can find the link <a href="https://medium.com/@hamza.00dev1/under-the-hood-of-bitcoin-core-a-hands-on-guide-to-building-testing-and-contributing-196b27c6d3f7">here</a>.</p><p>From there the work moved into reviewing. I looked at both already-merged pull requests and open ones. Merged pull requests were especially helpful because they showed the full cycle the original change, the comments that came back, how the author responded, and what the final version looked like. Open pull requests showed the live process. In Bitcoin Core the way reviewers communicate is specific. Learning the common acknowledgement terms and seeing how they were used made it much easier to understand what a reviewer was actually asking for and how to respond usefully.</p><p>I checked out many of those pull requests locally and tested them myself. In several cases the act of testing and commenting surfaced issues the original author had not noticed. A couple of the pull requests I reviewed were later merged. The more important outcome, though, was the practice itself: reading carefully, testing changes locally, and writing comments that were specific enough to be useful. This period also included studying how the project handles documentation, commit messages, and review policies, which made later contributions smoother.</p><h3>Moving to LDK and Opening Pull Requests</h3><p>After gaining practical experience with Bitcoin Core, I chose the Lightning Dev Kit (LDK) as the project I wanted to contribute to for a longer period. A mentor helped me think through the decision. I already had a reasonable understanding of the Lightning concepts from the earlier theory work, and the codebase felt like a natural place to apply the contribution habits I had practised.</p><p>I already had one pull request open on LDK before the fellowship began (#4892). During the fellowship I opened two more. One of them (#5579) was merged. The work included:</p><ul><li>A change that added a configuration option so that routing can ignore forwarding fees from specific nodes. This is useful for organisations that run nodes behind other nodes and do not want those fees to affect their own routed payments. Link: <a href="https://git.rust-bitcoin.org/lightningdevkit/rust-lightning/pulls/4892">PR #4892</a></li><li>Work on improving how the wallet selects coins when it must spend locked outputs. The issue already contained a suggested approach and a reproducing test. I evaluated the options, wrote a design document, and opened a pull request with the change. Links: <a href="https://git.rust-bitcoin.org/lightningdevkit/rust-lightning/issues/5435">Issue #5435</a> and <a href="https://git.rust-bitcoin.org/lightningdevkit/rust-lightning/pulls/5515">PR #5515</a> (open)</li><li>A small fix for a flaky test that sometimes failed because of wall-clock timing. Link: <a href="https://git.rust-bitcoin.org/lightningdevkit/rust-lightning/pulls/5579">PR #5579</a> (merged)</li></ul><p><strong>Walkthrough: Forced Conflicting Coin Selection (</strong><a href="https://git.rust-bitcoin.org/lightningdevkit/rust-lightning/issues/5435"><strong>PR #5515</strong></a><strong> / </strong><a href="https://git.rust-bitcoin.org/lightningdevkit/rust-lightning/issues/5435"><strong>Issue #5435</strong></a><strong>)</strong></p><p>When a Lightning node must fund an on-chain claim and all free UTXOs are already locked, the wallet is allowed to double-spend locked coins. The existing code in Wallet::select_confirmed_utxos_internal sorted those coins only by individual effective value in ascending order. With a target of 1,800 sats, this could select a 1,000 sat coin from one claim and a 1,100 sat coin from another, displacing two claims.</p><p><a href="https://git.rust-bitcoin.org/lightningdevkit/rust-lightning/issues/5435">Issue #5435</a> was opened by core maintainer Jeffrey (jkczyz). The issue already described the problem clearly and suggested the richest-claim-first approach: group the locked UTXOs by ClaimId and prefer the claim with the highest total effective value. It also included a concrete reproducing test case and listed three possible policies. I focused on evaluating those options, choosing the richest-claim-first heuristic, and turning it into a local, well-tested change.</p><p>The implementation groups the locked UTXOs by ClaimId, sorts the groups so the richest claim comes first (with a deterministic tie-break), and then runs the existing selection loop. Because the coins of the richest claim are now together, the 1,800 sat target is satisfied from a single claim (the 3,000 sat coin) instead of two. I added a unit test based on the example from the issue. Before the change the test failed; after the change it passes and only the 3,000 sat coin is selected. I also wrote a design document that compares the three approaches, records the chosen policy, and covers testing and risks. The change is limited to the wallet utilities and does not alter public interfaces.</p><p><strong>Key takeaway:</strong> The issue already contained a solid suggested approach and a reproducing test. The useful work was to carefully validate that suggestion against the actual selection loop, compare the three policy options (especially the trade-offs around churn and deadline risk), and make a clear recommendation. This reinforced that good contributions often start by fully understanding and testing what is already proposed, then applying judgment on the open design questions rather than starting from scratch.</p><h3>Habits That Made Progress Possible</h3><p>Several habits turned out to matter more than any single technical skill.</p><p>Discussing ideas regularly with another person helped. Being able to explain a concept or a piece of code to someone else, and hearing how they understood it, improved both my own clarity and my ability to communicate with reviewers and maintainers later. I currently working on an IDE for open contribution projects, which support this flow.</p><p>Weekly check-ins with mentors were also useful. Having someone look at what had been done, ask questions, and give feedback on progress created a rhythm and made it harder to drift. The feedback was practical: what was working, what needed more attention, and how to approach the next step.</p><p>Writing forced clearer thinking. In addition to the Bitcoin Core build guide, I researched and wrote about <a href="https://medium.com/@hamza.00dev1/frost-how-it-works-how-it-compares-to-multisig-and-musig2-and-when-to-use-it-b96dad31195a">FROST</a> (a threshold signature scheme). Preparing the material for a presentation and then turning it into a written explanation changed how I understood the topic. The act of organising the ideas so that someone else could follow them made the knowledge more solid. Writing technical articles in general turned out to be a useful way to deepen understanding while also producing something others could use.</p><p>Finally, following the project’s own process carefully mattered. Learning how reviews are expected to happen, what kinds of comments are useful, and when to ask for human review time made contributions more effective. Testing changes locally before commenting, and making the intent of a change clear in both the code and the tests, reduced the amount of back-and-forth.</p><p>The structure of the <strong>BTrust Fellowship</strong> itself was an important part of making the progress accountable. Weekly discussions, regular check-ins with mentors, and the expectation of steady, visible work created a rhythm that made it difficult to stall. The programme did not replace the need to learn the code or follow each project’s review process, but it supplied the external structure that turned individual effort into consistent contribution.</p><h3>Feedback Received</h3><p>The most useful feedback from maintainers and mentors reinforced the habits above.</p><p>One maintainer advised that I should finish addressing comments from the automated review tools before assigning human reviewers. The point was simple: follow the project’s expected order and do not rush to request human time. Respecting that process saves maintainers’ attention for the moments when it is actually needed.</p><p>Mentors suggested paying attention to what the maintainers are currently focused on and trying to contribute in those areas. Work that is relevant to the project’s present priorities is more likely to receive attention and feedback. They also emphasised making the intent of a change visible, especially in tests, so that reviewers can quickly understand what is being verified and why.</p><p>From observing and participating in reviews, two further points stood out. Always acknowledge the time people spend reviewing your work. And avoid vague comments. Explain the issue or the suggestion in clear, simple terms so that others can follow the reasoning without having to guess the intent.</p><h3>What I Would Do Differently</h3><p>Looking back, a few adjustments would have made the early stages smoother.</p><p>I would have paid closer attention earlier to what the maintainers were prioritising in a given period. Starting reviews and contributions with that context in mind would have helped the work stay relevant and receive feedback faster.</p><p>I would have been more deliberate about when I started reviewing. Understanding the project’s review expectations and communication style first, rather than jumping in immediately, would have made the early comments more useful.</p><p>I would have strengthened earlier the habit of explicitly connecting the theory I had studied to the specific code I was reading or changing. That connection proved valuable once I started doing it consistently, and doing it from the beginning would have reduced some of the initial friction.</p><p>These are refinements rather than major course corrections. The overall sequence theory, then hands-on work inside an existing project, then opening my own changes worked well. The main lesson is that the habits around process, communication, and visibility matter as much as the code itself.</p><h3>Closing</h3><p>The three months moved from learning the fundamentals, to working inside Bitcoin Core by building it and reviewing other people’s changes, to opening and iterating on pull requests in LDK. The progression was gradual, and the most useful parts were the repeatable habits: building a working local environment, testing changes myself, learning how a project expects reviews to happen, communicating clearly, and paying attention to what the maintainers are focused on.</p><p>If you are starting from a similar place, the practical sequence that helped me was: spend time on the theory until the design choices make sense, get the project building and the tests running, review existing pull requests carefully (both merged and open) while testing them locally, and only then open your own changes. Along the way, write down what you learn, discuss it with someone else, and follow the project’s review process rather than trying to shortcut it.</p><p>I plan to continue with the open pull requests, further reviews, and work in the areas the LDK maintainers are currently prioritising. The experience so far has shown that a clear progression and careful attention to process turn general interest into useful contributions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5a6b5860fcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FROST: How It Works, How It Compares to Multisig and MuSig2, and When to Use It]]></title>
            <link>https://medium.com/@hamza.00dev1/frost-how-it-works-how-it-compares-to-multisig-and-musig2-and-when-to-use-it-b96dad31195a?source=rss-3e8a873d6060------2</link>
            <guid isPermaLink="false">https://medium.com/p/b96dad31195a</guid>
            <category><![CDATA[frost]]></category>
            <category><![CDATA[multisig]]></category>
            <category><![CDATA[bitcoin-security]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[musig]]></category>
            <dc:creator><![CDATA[Muhammad Hamza]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 16:24:58 GMT</pubDate>
            <atom:updated>2026-11-17T16:24:58.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YO5_tVGBnHxj6KmCtna_AA.png" /></figure><p>FROST stands for Flexible Round-Optimized Schnorr Threshold Signatures. In plain language, it is a way for a group of people to share control of one private key without the full key ever existing in one place. The group decides beforehand how many of them must agree before a signature can be created. That number is called the threshold. For example, in a group of five people the threshold might be three. Any three of the five can work together to produce a valid signature, but one or two people alone cannot.</p><p>The most important idea in FROST is that the full private key never exists in one place. Each person only holds a small piece of the key, called a share. When enough people (the threshold number) combine their shares in a special way, they can create one normal-looking signature. On the blockchain this signature looks exactly the same as a signature made by a single person. No one looking at the chain can tell that several people were involved or how many people were needed.</p><p>FROST is built on Schnorr signatures. Bitcoin started using Schnorr signatures with the Taproot upgrade. Schnorr signatures have a mathematical property that makes it easy to add signatures together. This property is what allows FROST to work so cleanly.</p><h3>Why We Need Something Like FROST</h3><p>A single private key is a single point of failure. If the device that holds the key is lost, stolen, or destroyed, the funds can be lost forever. If the owner dies, no one else can move the money. If someone forces the owner to hand over the key, everything is gone.</p><p>FROST removes this single point of failure by spreading the power across several people. Losing or compromising one share is not enough to steal the funds, and one missing person is not enough to lock the group out, as long as the threshold number of shares still exist.</p><h3>The Two Main Parts of FROST</h3><p>FROST has two clear stages:</p><ol><li><strong>Key Generation: </strong>done only once when the group is first set up.</li><li><strong>Signing: </strong>done every time the group wants to approve a transaction or a message.</li></ol><p>These two stages are completely separate. The hard work of creating the shares happens only once. After that, the group can sign as many times as it needs.</p><h3>Key Generation and How the Shares Are Created</h3><p>There are two different ways to create the key shares.</p><h4>Trusted Dealer Generation (TDG)</h4><p>One trusted person or computer creates a normal private key, splits it into shares using a method called Shamir’s Secret Sharing, and sends one share to each member of the group. After the shares are sent, the dealer is supposed to delete the original key.</p><p>This method is simple and easy to understand, but it has a clear risk: for a short time the full private key exists in one place. If the dealer is dishonest or the computer is compromised during that short window, the whole system is broken.</p><p>In code (using the official Zcash FROST library), the process looks like this:</p><pre>let (max_signers, min_signers) = (3, 2);<br><br>let (shares, group_public_key) = frost::keys::generate_with_dealer(<br>    max_signers,<br>    min_signers,<br>    IdentifierList::Default,<br>    rng,<br>)?;</pre><p>After the dealer generates the shares, each participant must turn their share into a usable key package:</p><pre>let mut key_packages: HashMap&lt;_, _&gt; = HashMap::new();<br><br>for (k, v) in shares {<br>    let key_package = frost::keys::KeyPackage::try_from(v)?;<br>    key_packages.insert(k, key_package);<br>}</pre><p>This creates a 2-of-3 threshold. Each participant receives one share and converts it into a KeyPackage that they will later use for signing.</p><h4>Distributed Key Generation (DKG)</h4><p>In this method the members of the group work together to create their shares. The full private key is never created anywhere, not even for a second. This is much safer, but it is also more complicated and requires several rounds of communication between the members. Most serious users prefer DKG.</p><p>In the distributed method each member creates a secret polynomial. A polynomial is just a mathematical expression that looks like a curved line. The secret is hidden in the constant term of that polynomial. For a member numbered iii, the polynomial looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1h4qqkLYPkueekG6HN_iw.png" /></figure><p>What each part means in plain language:</p><ul><li>f_i(x) is the secret polynomial that belongs only to member iii.</li><li>a_{i0} is the secret number that member iii contributes. This is the most important part of the polynomial.</li><li>a_i1,a_i2,…, are random numbers that the member chooses.</li><li>t is the threshold (the number of people needed to sign).</li><li>The highest power is t−1. This is what makes any group of ttt people able to work together while any smaller group learns nothing about the secret.</li></ul><p>Each member also creates public commitments. A commitment is a way of proving that you know a secret without showing the secret itself. On an elliptic curve this is done by multiplying the secret by a fixed public point called the generator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*Gxyp-ZeIygN_fDlR60EjEQ.png" /></figure><ul><li>ϕ_ij is the public commitment for the coefficient a_ij​.</li><li>G is the fixed generator point of the elliptic curve. Everyone knows this point.</li><li>Multiplying a secret by G hides the secret. It is computationally impossible to go backwards from the point to the secret number.</li></ul><p>After the public commitments are shared, each member privately sends small pieces of their polynomial to the other members. Each person adds up all the pieces they received and ends up with their final private key share, written as sis_isi​. The group public key is simply the sum of everyone’s public contributions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*OY0s8-9-_1w2Q-91liLZMA.png" /></figure><p>No one ever holds the private key that matches Y. That is the core safety property of distributed key generation.</p><p>In the Zcash FROST library the DKG process is split into three clear parts:</p><p><strong>Part 1: Each participant generates their first package</strong></p><pre>let (round1_secret_package, round1_package) = frost::keys::dkg::part1(<br>    participant_identifier,<br>    max_signers,<br>    min_signers,<br>    &amp;mut rng,<br>)?;</pre><p>The round1_secret_package stays private. The round1_package is sent to all other participants.</p><p><strong>Part 2: Each participant processes the packages from the others</strong></p><pre>let (round2_secret_package, round2_packages) = frost::keys::dkg::part2(<br>    round1_secret_package,<br>    round1_packages,<br>)?;</pre><p><strong>Part 3: Finalization</strong></p><pre>let (key_package, pubkey_package) = frost::keys::dkg::part3(<br>    round2_secret_package,<br>    round1_packages,<br>    round2_packages,<br>)?;</pre><p>This final step produces the actual KeyPackage (the private share the participant will use for signing) and the PublicKeyPackage (the group public key that everyone shares).</p><h3>Signing, How the Group Creates a Signature</h3><p>Once the shares exist, the group can create signatures. Signing normally takes two rounds of communication.</p><p><strong>Round 1: Commitments</strong><br> Each signer who wants to take part creates two secret random numbers called nonces and publishes only the public versions of those nonces. Nothing sensitive is revealed at this stage.</p><p><strong>Round 2: Signature shares</strong><br> Each signer uses their private key share, their secret nonces, and some public information to create a signature share. These shares are then added together to make one final signature.</p><p>Here are the main equations, explained simply.</p><p>Each signer i creates two secret nonces did_idi​ and eie_iei​ and publishes the public commitments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*WxE-KoQVU_vApSfAiMx9iw.png" /></figure><p>A binding value is calculated so that no one can trick the others into signing a different message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*H-yqc2EIjnwKpLx99B206g.png" /></figure><ul><li>ρ_i is the binding factor for signer iii.</li><li>H is a cryptographic hash function.</li><li>i is the identity number of the signer.</li><li>m is the message being signed (usually the hash of a Bitcoin transaction).</li><li>B is the complete list of all the public commitments from this signing session.</li></ul><p>The group nonce is formed by combining everyone’s commitments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*kjh3LZKasDtJWstQnhtEKw.png" /></figure><p>The challenge number is calculated in the same way as a normal Schnorr signature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*BuxIlPMS5Wjy8B9q31g4Dw.png" /></figure><p>Each signer then creates their own signature share:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*vdxZp_aZrjas1fzUjSw-Mg.png" /></figure><ul><li>λ_i​ is the Lagrange coefficient. This number depends on which exact set of people are signing. It allows any threshold number of shares to act as if the full secret was used, without ever putting the full secret together in one place.</li><li>s_i is the private key share belonging to signer i.</li></ul><p>All the signature shares are added together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*TUTpIyoadnQ8JBnmeuoJHw.png" /></figure><p>The final signature is simply the pair (R,z). Anyone can check it with the ordinary Schnorr equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*xrz8L2N5SGbPOxGWR9dWbg.png" /></figure><p>This final check looks exactly like a normal single-person Schnorr signature. That is why FROST signatures are private and small on the blockchain.</p><p>In code the final aggregation step looks like this:</p><pre>let group_signature = frost::aggregate(<br>    &amp;signing_package,<br>    &amp;signature_shares,<br>    &amp;pubkey_package,<br>)?;</pre><p>One important practical point: the FROST mathematics only guarantees that everyone signed the same message. It does not guarantee that the message is the correct transaction. Each signer must still examine the full transaction on their own device (the destination address, the amount, the fees, and the change output) before they create their signature share. If a signer only looks at a hash, they can be tricked into signing something they did not intend.</p><h3>Different Approaches and Their Trade-offs</h3><p>FROST offers choices at two levels: how the key shares are created and how the signing is performed.</p><p>For key generation the two approaches are Trusted Dealer Generation and Distributed Key Generation. Trusted Dealer Generation is simple and fast. It requires almost no communication between members. The clear disadvantage is that the full private key exists in one place for a short time. Distributed Key Generation removes that risk completely because the full key never exists. The cost is higher complexity and more rounds of communication. Most serious deployments prefer Distributed Key Generation.</p><p>For signing there are also two approaches. The standard method uses two rounds of communication. The first round can be done in advance (this is called preprocessing). When preprocessing is used, the actual signing needs only one online round. This is very useful when some signers are offline, air-gapped, or on slow networks. The trade-off is that the nonces must be carefully stored and never reused. Reusing a nonce allows an attacker to calculate the private key share.</p><p>Another practical choice is whether to use a coordinator. A coordinator is a party that simply relays messages between the signers. It has no special power over the keys and cannot create a signature by itself. The advantage of a coordinator is that communication becomes easier. The disadvantage is that a dishonest coordinator can refuse to relay messages and therefore block the signing process. It is possible to run FROST without any coordinator if the signers can communicate directly with each other over secure channels.</p><p>FROST is designed for efficiency rather than maximum robustness. A malicious participant can disrupt a signing session. The protocol can detect who caused the problem and exclude that person from future sessions. An extra layer called ROAST can be added on top of FROST if stronger robustness is required, but it is not part of the basic FROST protocol.</p><h3>Alternatives That Exist and Their Differences</h3><p>Three main alternatives are commonly discussed when talking about FROST.</p><p><strong>Classic Bitcoin script multisig</strong> (the older OP_CHECKMULTISIG or the newer OP_CHECKSIGADD). In this system each participant has their own independent private key. The blockchain itself checks that enough signatures are present. The advantage is that the signatures can be created independently and the system is very robust. The disadvantages are larger transaction size, higher fees, and the fact that the threshold and the public keys are visible on the blockchain. Anyone looking at the chain can see how many people are required and which keys are involved.</p><p><strong>MuSig2</strong>. MuSig2 is also built on Schnorr signatures and produces a single small signature that looks like a normal single-key signature. The big difference is that MuSig2 is only n-of-n. Every single member of the group must take part in every signature. There is no threshold flexibility. If one person is offline or refuses to sign, the whole group is stuck. FROST allows any threshold (2-of-3, 3-of-5, 5-of-7, and so on), so it can continue even if some members are missing.</p><p><strong>Pure Shamir’s Secret Sharing</strong> without a threshold signature scheme. In this approach the private key is split into shares and the shares are simply brought together when needed. The problem is that the full private key is reconstructed in one place at the moment of signing. That creates a moment of high risk. FROST never reconstructs the key.</p><p>In short: Classic multisig reveals the threshold and the keys on chain, produces larger transactions, and allows independent signing. MuSig2 keeps everything private and small but requires every member to participate every time. FROST keeps everything private and small, supports any threshold, and never reconstructs the private key.</p><h3>Real-World Use Cases</h3><p>FROST is useful in any situation where a group of people need shared control without giving any single person full power.</p><p>In Bitcoin it is especially attractive for Taproot wallets. Because the signature looks like a normal single-key spend, the transaction is smaller and cheaper, and the privacy of the group is protected. Companies that hold large amounts of bitcoin can use FROST so that several executives must agree before funds can move. Families can use it for inheritance planning so that children or trusted relatives can access funds only when enough of them agree. Decentralized organizations and DAOs can use FROST to authorize decisions without putting a single private key in one person’s hands.</p><p>Outside Bitcoin, the same idea can be used for any group decision that needs cryptographic proof: a board of directors approving a document, a set of servers authorizing a software update, or a group of guardians controlling a digital identity.</p><h3>Conclusion</h3><p>FROST solves a real and important problem. It gives the privacy and efficiency of a single signature while still spreading control across several people. The fact that the full private key never exists is a strong security property that classic multisig and pure Shamir sharing do not offer.</p><p>The main cost is complexity. Setting up Distributed Key Generation and running the signing protocol correctly requires good software and careful operational practices. Nonce management must be perfect. For small groups that already trust each other and do not mind larger on-chain footprints, classic multisig may still be simpler. For groups that need both privacy and threshold flexibility, FROST is currently the strongest practical option available on Bitcoin.</p><p>When stronger resistance to disruption is needed, ROAST can be added on top of FROST. Together they give teams a powerful and flexible way to share control without creating a single point of failure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b96dad31195a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the Hood of Bitcoin Core: A Hands-On Guide to Building, Testing, and Contributing]]></title>
            <link>https://medium.com/@hamza.00dev1/under-the-hood-of-bitcoin-core-a-hands-on-guide-to-building-testing-and-contributing-196b27c6d3f7?source=rss-3e8a873d6060------2</link>
            <guid isPermaLink="false">https://medium.com/p/196b27c6d3f7</guid>
            <category><![CDATA[bitcoin-study]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[bitcoin-contribution]]></category>
            <category><![CDATA[bitcoin-core]]></category>
            <category><![CDATA[bitcoin-learn]]></category>
            <dc:creator><![CDATA[Muhammad Hamza]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 17:27:07 GMT</pubDate>
            <atom:updated>2026-11-23T18:16:52.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYzA_P5sOeVl7oOHs3bk2g.png" /></figure><p>If you want to really understand Bitcoin, reading articles and whitepapers is only the first step. You only get the full picture when you open your terminal, download the code, build it yourself, and start testing it on your own computer.</p><p>A lot of people think the Bitcoin Core code is scary because it is written in C++. But if you have even a little background in basic C, the code is surprisingly easy to follow line by line. Even better, all the main integration tests are written in Python. That means if you know Python, you already have what you need to test how Bitcoin works.</p><p>In this guide, you will learn how to set up your tools, build Bitcoin Core, run your own private test chain, and run the tests so you can start contributing.</p><h3>Why Bitcoin Core Development Differs</h3><p>Bitcoin Core is not your typical open-source software project, it is arguably one of the most critical open-source codebases in existence, I believe. It powers a decentralized, leaderless financial system.</p><p>When you write web applications or enterprise software, bugs can be patched behind a deployment pipeline. In Bitcoin Core, a bug in consensus rules can split the network, cause a hard fork, or lead to catastrophic financial loss. It is strictly built and maintained around security, deliberate thought, and broad consensus agreement before implementing major or even minor changes. When contributing, the primary mindset is defensive: <strong>make sure no one loses money</strong>.</p><h4>High-Level Subsystem Breakdown</h4><p>To navigate the codebase without feeling overwhelmed, I learn to keep this architectural mental model in mind:</p><ul><li><strong>src/validation.cpp: </strong>The beating heart of the node. It validates blocks and transactions against consensus rules, updates the <strong>UTXO</strong> set, and maintains the active chainstate.</li><li><strong>src/net_processing.cpp &amp; src/net.cpp:</strong> The networking boundary. It handles peer connections, message serialization/deserialization, and P2P gossip.</li><li><strong>src/node/ </strong>&amp;<strong> src/init.cpp</strong>: Node lifecycle management, argument parsing, startup routines, and thread orchestration.</li><li><strong>src/rpc/</strong>: The JSON-RPC server interface that external clients use to communicate with the node.</li><li><strong>src/wallet/</strong> : Descriptor-based wallet logic, key derivation, coin selection, and transaction signing.</li></ul><h3>Building Bitcoin Core</h3><h4>Environment Prerequisites</h4><p>I am currently working inside <strong>Ubuntu via WSL2 on Windows</strong>. While native Ubuntu Linux is widely considered the gold standard for C++ and open-source contribution (and I plan to transition to native Ubuntu down the line), WSL2 has proven completely dependable for compiling and testing. If you are on native Linux or macOS (Intel/Apple Silicon), the core workflow remains identical.</p><p>Make sure your environment has the basic compiler and dependency toolchain installed:</p><pre># Ubuntu / Debian / WSL2 Dependencies<br>sudo apt update<br>sudo apt install build-essential libtool autotools-dev automake pkg-config \<br>                 bsdmainutils python3 libevent-dev libboost-dev libsqlite3-dev cmake</pre><p><strong>Documentation References:</strong> Detailed per-platform installation instructions are maintained in <a href="https://github.com/bitcoin/bitcoin/blob/master/doc/build-unix.md">doc/build-unix.md</a> and <a href="https://github.com/bitcoin/bitcoin/blob/master/doc/build-osx.md">doc/build-osx.md</a>.</p><h4>Cloning and the First-Time Build</h4><p>Bitcoin Core modern builds use <strong>CMake</strong>. Clone the repository, create a build directory, and compile:</p><pre># 1. Clone the repository<br>git clone https://github.com/bitcoin/bitcoin.git<br>cd bitcoin<br><br># 2. Configure the build directory<br>cmake -B build<br><br># 3. Compile the targets across all available CPU cores<br>cmake --build build -j$(nproc)</pre><p>(Note: On macOS, replace $(nproc) with $(sysctl -n hw.logicalcpu)).</p><h4>Incremental Builds &amp; Pulling Updates</h4><p>When pulling new commits from master or switching branches, you do not need to clean or reconfigure everything from scratch. Just pull the changes and re-run your build command:</p><pre>git pull upstream master<br>cmake --build build -j$(nproc)</pre><p>CMake intelligently recompiles only the modified translation units and re-links the binaries.</p><h4>Key Binary Artifacts</h4><p>Inside <strong>build/bin/</strong>, you get two primary backend executables:</p><ol><li><strong>bitcoind</strong>: The headless Bitcoin node daemon. It handles peer networking, validation, and storage.</li><li><strong>bitcoin-cli</strong>: The command-line client used to issue RPC commands to <strong>bitcoind</strong>.</li></ol><p><em>I omitted </em><strong>bitcoin-qt</strong><em>, the graphical desktop client, because backend engineering and testing focus purely on </em><strong>bitcoind </strong><em>and </em><strong>bitcoin-cli</strong><em>.</em></p><h3>Runtime Environments &amp; Local Sandboxing with Regtest</h3><p>Bitcoin Core supports four network modes: Mainnet, Testnet4, Signet, and <strong>Regtest (Regression Test)</strong>.</p><p>For local development, <strong>Regtest</strong> is essential. It lets you run a completely private, localized blockchain where you can mine blocks instantly on demand with zero proof-of-work delay. That is a good testing network you can work with.</p><h4>Configuring bitcoin.conf</h4><p>You can a run your bitcoin-cli command using the following:</p><pre>bitcoin-cli -regtest &lt;RPC Command&gt;</pre><p>The above method might make the command to long or feel repeatateive, rather than typing <strong>-regtest </strong>on every single command, configure it once in your configuration file:</p><pre># ~/.bitcoin/bitcoin.conf<br>regtest=1<br>fallbackfee=0.0002<br>server=1<br>txindex=1<br><br>[regtest]<br>rpcuser=testuser<br>rpcpassword=testpassword</pre><h4>Spinning Up the Node &amp; Controlling via CLI</h4><p>To start the daemon in the foreground (which lets you watch operational stdout logs directly):</p><pre>./build/bin/bitcoind</pre><p>If you prefer it running in the background, start it with daemon mode:</p><pre>./build/bin/bitcoind -daemon</pre><h4>Creating a Wallet and Minting Spendable Coins</h4><p>Because regtest starts as a blank chain with zero blocks, you must create a wallet, generate an address, and mine blocks to fund it:</p><pre># 1. Create a local test wallet<br>./build/bin/bitcoin-cli createwallet &quot;test_wallet&quot;<br><br># 2. Generate a receiving address<br>./build/bin/bitcoin-cli -rpcwallet=test_wallet getnewaddress<br># Returns: &lt;your_regtest_address&gt;<br><br># 3. Mine 101 blocks to make the coinbase rewards spendable<br>./build/bin/bitcoin-cli -rpcwallet=test_wallet generatetoaddress 101 &quot;&lt;your_regtest_address&gt;&quot;<br><br># 4. Check your balance<br>./build/bin/bitcoin-cli -rpcwallet=test_wallet getbalance</pre><p><strong>Why exactly 101 blocks?</strong></p><p>Under Bitcoin consensus rules (<strong>COINBASE_MATURITY</strong>), newly minted coinbase outputs cannot be spent until they have received <strong>100 confirmations</strong>. Mining 101 blocks matures the coinbase reward of the very first block, giving you an immediately spendable balance.</p><p>To verify the chain state:</p><pre>./build/bin/bitcoin-cli getblockchaininfo</pre><h3>The Testing Framework (The Core Journey)</h3><p>Testing is the bedrock of Bitcoin Core. Without exhaustive automated verification, no patch can be trusted.</p><h4>1. Unit Tests (C++)</h4><p>The unit test suite lives in <strong>src/test/</strong> and exercises isolated algorithmic logic, serialization formats, script parsing, and cryptographic operations.</p><p>Run the entire unit test suite directly using the compiled binary:</p><pre>./build/bin/test_bitcoin</pre><p>To isolate and run a single test suite without running the whole suite:</p><pre># arith_uint256_tests is just an example f test file<br>./build/bin/test_bitcoin --run_test=arith_uint256_tests</pre><h4>2. Functional Tests (Python)</h4><p>The functional tests live in <strong>test/functional/ </strong>and test real, integration-level node behavior. The test runner starts actual temporary <strong>bitcoind</strong> nodes in sandbox environments, sends commands over RPC, and asserts network behaviors.</p><p>To run the entire functional test suite:</p><pre>python3 build/test/functional/test_runner.py</pre><p><em>Note on test results:</em> When you run the entire suite, you might see some tests marked as [SKIP] . This is completely expected, certain tests require specific dependencies that might be disabled in your build. As long as all executed tests pass with zero failures, your build is solid.</p><p>To run a specific test (for example, the basic wallet test):</p><pre>python3 build/test/functional/test_runner.py test/functional/wallet_basic.py</pre><p>In a case where any test fails after try pulling the latest changes from upstream and rebuilding with CMake, that should resolve the issue immediately.</p><h4>3. Fuzz Testing</h4><p>Beyond unit and functional tests, Bitcoin Core maintains an extensive fuzz testing engine located in <strong>src/test/fuzz/</strong>. Fuzzing bombards internal parsers, deserializers, and network message handlers with millions of randomized, semi-valid inputs. It acts as an automated adversary designed to flush out buffer overflows, memory leaks, and edge-case assertion crashes that standard test suites easily miss.</p><h4>How to Build and Run a Fuzz Test</h4><p>Fuzz builds require Clang rather than GCC. Set up the compiler, configure using the official CMake preset, and run:</p><pre># 1. Install Clang if you haven&#39;t<br>sudo apt update &amp;&amp; sudo apt install clang<br><br># 2. Configure and build using the libFuzzer preset<br>CC=clang CXX=clang++ cmake --preset=libfuzzer<br>cmake --build build_fuzz -j$(nproc)<br><br># 3. (Optional) Clone seed inputs to test deeper code branches<br>git clone --depth=1 https://github.com/bitcoin-core/qa-assets<br><br># 4. Run the target<br>FUZZ=process_message build_fuzz/bin/fuzz qa-assets/fuzz_corpora/process_message</pre><h3>Contribution Workflow, Review, and PR Best Practices</h3><p>After cloning and building the bitcoin core, the most inspiring part of Bitcoin Core is that anyone can contribute. But contributing requires learning its review culture.</p><h4>The Peer Review Hierarchy</h4><p>In the Bitcoin Core repository, pull requests are governed by a specific review vocabulary. Because nobody “owns” Bitcoin Core and code isn’t merged on personal authority alone, the project relies on <strong>rough consensus</strong>. Contributors use standardized acronyms to communicate their level of review and agreement:</p><ul><li><strong>Concept ACK:</strong> You agree with the general idea and believe the feature/fix belongs in Bitcoin Core.</li><li><strong>Approach ACK:</strong> You agree with the general technical direction and design used to implement the idea.</li><li><strong>Review / Code ACK:</strong> You have reviewed the code line by line, verified logic and style, and confirmed no regressions exist.</li><li><strong>Tested ACK:</strong> You built the PR branch locally, ran unit/functional tests, verified reproduction steps, and confirmed that the patch functions as intended.</li><li><strong>NACK: </strong>You disagree with the pull request. a bare NACK is never accepted, it must always be accompanied by clear technical reasoning that explain why the change introduces bugs, breaks consensus rules, creates security or privacy risks.</li><li><strong>Nit: </strong>A minor comment or suggestion (such as fixing a typo, renaming a variable for readability, or adjusting formatting) that is non-blocking. You are telling the author: <em>“This doesn’t stop your PR from being merged, but consider changing it if you touch this code again.”</em></li></ul><h4>Testing Existing PRs Locally Using the GitHub CLI (gh)</h4><p>When you want to review someone else’s pull request on your local machine, you have two options: standard git or the GitHub CLI (<strong>gh</strong>).</p><p>While you can fetch PR refs manually using standard git:</p><pre># Fetching a PR branch manually using git<br>git fetch upstream pull/&lt;PR_ID&gt;/head:pr-&lt;PR_ID&gt;<br>git checkout pr-&lt;PR_ID&gt;</pre><p>I strongly recommend using <strong>gh (the GitHub CLI)</strong> instead. It saves you a lot of manual steps, handles the remote refs automatically, and makes reviewing and testing PRs locally much smoother. If you want to see all the useful things it can do, you can simply run:</p><pre>gh help</pre><p>This prints out a full list of commands available to you. If you haven&#39;t installed it yet make sure you have gh installed on your machine, you can follow the <a href="https://cli.github.com/">official installation guide</a> to install the gh cli program.</p><p><strong>Authenticate with GitHub:</strong> Once installed, run this one-time login command in your terminal and follow the prompt:</p><pre>gh auth login</pre><h4>Checking Out and Testing a PR with gh</h4><p>Once gh is ready, checking out any open PR to test it locally takes just one command:</p><pre># Checkout a PR branch directly into your local repo<br>gh pr checkout &lt;PR_ID&gt;<br><br># Recompile the modified files<br>cmake --build build -j$(nproc)<br><br># Run the relevant functional or unit tests associated with the change<br>python3 test/functional/test_runner.py test/functional/&lt;relevant_test&gt;.py</pre><p>Testing existing PRs and reproducing open issues locally is the most effective way to build credibility in the repository before writing large patches of your own.</p><h4>Best Practices for Submitting PRs</h4><ol><li><strong>Atomic Commits:</strong> Every commit in a PR must build cleanly and pass tests on its own. Never combine refactoring, code movement, and bug fixes into a single commit.</li><li><strong>Clear Commit Messages:</strong> Write precise, descriptive messages explaining <em>why</em> a change was made, not just <em>what</em> changed.</li><li><strong>Strict Policy Against AI / LLM Generation:</strong> Bitcoin Core requires strict developer accountability. Maintainers will close pull requests if there is reasonable doubt that the author does not fully understand or cannot defend their own changes. Never submit mass AI-generated refactors, bot-generated PR descriptions, or synthetic commits. Human comprehension and manual verification are non-negotiable.</li></ol><h3>Conclusion</h3><p>You only learn how Bitcoin works when you open your terminal and try it out. Reading about it gives you the idea, but building the code, creating your own test blocks, and running the tests brings it to life.</p><p>Do not let the code scare you. It is just careful, well-written code meant to keep people’s money safe. If you follow the steps, test issues on your machine, and take it one step at a time, you have everything you need to contribute.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=196b27c6d3f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Hash Time-Locked Contracts in Lightning]]></title>
            <link>https://medium.com/@hamza.00dev1/understanding-hash-time-locked-contracts-in-lightning-885de1444160?source=rss-3e8a873d6060------2</link>
            <guid isPermaLink="false">https://medium.com/p/885de1444160</guid>
            <category><![CDATA[commitment-transaction]]></category>
            <category><![CDATA[htlc]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[lightning-channel]]></category>
            <dc:creator><![CDATA[Muhammad Hamza]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 14:17:38 GMT</pubDate>
            <atom:updated>2026-11-23T18:01:18.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAZ8T2k_HmxWJCmeL3yYqQ.png" /></figure><h3>Introduction</h3><p>Today I want to talk about HTLC, Hash Time-Locked Contract, and how we use it as a contract-based feature in off-chain transactions, especially inside Lightning channels.</p><p>If we break the name down, <strong>Hash</strong> means something is hashed, <strong>Time-Lock</strong> means something is locked until a specific time, and <strong>Contract</strong> simply means an agreement between two parties. When we put them together, an HTLC is a special kind of agreement that locks money with both a hash and a time limit.</p><p>In simple terms, it works like this: I tell the other person, “I will give you this amount of satoshis if you can show me the secret that matches this hash before the deadline. If you can’t show the secret in time, the money comes back to me and you can never claim it.” That is the whole idea. It is atomic, either the person claims the money with the secret, or the money is refunded. There is no middle ground.</p><h3><strong>How an HTLC Sits Inside a Lightning Channel</strong></h3><p>To open a channel in Lightning, the process starts with a funding transaction. This is the first on-chain transaction and it is a 2-of-2 multisig. The commitment transactions are created and exchanged during the channel setup, before the funding transaction is broadcast. Once the funding transaction is confirmed, the channel is open and the commitment transactions can be used. These commitment transactions show how the money in the channel is currently divided. Each commitment has a <strong>to_local</strong> output (money going back to yourself) and a <strong>to_remote</strong> output (money going to the other person). When we add an HTLC, we create an extra output inside that commitment transaction for the HTLC amount.</p><p><strong>Commitment Transaction with an HTLC Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkXOMz3eRvb9BQGN6f-oaw.jpeg" /></figure><p>Because of the way Lightning works, the two parties hold slightly different versions of the commitment transaction. This asymmetry is important. It helps us know who published what, and it allows the other person to revoke (cancel) an old state if needed. The tool that makes revocation possible is the revocation key. If someone tries to publish an old commitment, the other person can use the revocation key to take the money.</p><p>There is also something called `<strong>to_self_delay</strong>`. This is a relative time delay that forces you to wait before you can spend your own output. It gives the other person enough time to react and use the revocation path if you are cheating.</p><h3>The Three Ways an HTLC Output Can Be Spent</h3><p>Now let’s look at how the HTLC itself is built inside the commitment. There are basically three ways the HTLC output can be spent:</p><ol><li>The receiver shows the preimage (the secret) and claims the money.</li><li>The time expires and the money goes back to the sender.</li><li>Someone uses the revocation key if the other party is trying to cheat.</li></ol><p><strong>Three Spending Paths of an HTLC</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHF60F1joOUPOwPuWeYQzA.jpeg" /><figcaption><strong>Three Spending Paths of an HTLC</strong></figcaption></figure><h3>Why Second-Stage Transactions Are Needed</h3><p>Because of the `<strong>to_self_delay</strong>` rule, we cannot put all these conditions in one simple output. Both the absolute timeout and the relative delay must be able to work without blocking each other. If they were combined in a single output, one timeout could delay the other and weaken the protection it is supposed to give. That is why Lightning uses two extra second-stage transactions which are:</p><ul><li><strong>HTLC-timeout transaction</strong> (used by the person who sent the HTLC)</li><li><strong>HTLC-success transaction</strong> (used by the person who is claiming with the preimage)</li></ul><p><strong>Second-Stage HTLC Transactions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjrA_KB-zKIMQXJ0YgrxXQ.jpeg" /></figure><p>These second-stage transactions let us enforce the delay properly without giving anyone extra time.</p><p>Here is a simplified look at the script used in the HTLC-timeout transaction output:</p><pre>OP_IF<br> &lt;revocationpubkey&gt;<br>OP_ELSE<br> &lt;to_self_delay&gt;<br> OP_CHECKSEQUENCEVERIFY<br> OP_DROP<br> &lt;local_delayedpubkey&gt;<br>OP_ENDIF<br>OP_CHECKSIG</pre><p>This script says: either the other person can take the money immediately with the revocation key, or after the delay the original sender can take the refund.</p><p>When the HTLC succeeds, the two parties swap the preimage. Once the preimage is known, the old version of the commitment can no longer be used safely, and a new commitment transaction is created that reflects the updated balances. That is how the channel state moves forward.</p><h3>Summary</h3><p>So to summarise in plain language: <br>An HTLC is a temporary lock on some money inside a channel. The money can only be taken by showing a secret before a deadline. If the secret is not shown in time, the money returns to the sender. All of this happens off-chain through commitment transactions, protected by revocation keys and time delays, so neither side can cheat the other.</p><p>That is the core of how HTLCs work and why they are so important for moving money safely across Lightning channels.</p><h4><strong>References:</strong></h4><p><a href="https://www.ellemouton.com/posts/htlc-deep-dive/">https://www.ellemouton.com/posts/htlc-deep-dive/</a> <br><a href="https://medium.com/summa-technology/bitcoins-time-locks-27e0c362d7a1">https://medium.com/summa-technology/bitcoins-time-locks-27e0c362d7a1</a> <br><a href="https://medium.com/chainside/understanding-payment-channels-4ab018be79d4">https://medium.com/chainside/understanding-payment-channels-4ab018be79d4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=885de1444160" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inefficiency of Bitcoin’s Legacy Block Relay]]></title>
            <link>https://medium.com/@hamza.00dev1/inefficiency-of-bitcoins-legacy-block-relay-ba93698ef6e6?source=rss-3e8a873d6060------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba93698ef6e6</guid>
            <category><![CDATA[bitcoin-bandwith]]></category>
            <category><![CDATA[p2p-network]]></category>
            <category><![CDATA[bitcoin-network]]></category>
            <dc:creator><![CDATA[Muhammad Hamza]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 14:44:35 GMT</pubDate>
            <atom:updated>2026-09-05T14:44:35.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*b6Ow-tnfbqLreU0ukVmiYA.png" /></figure><p>We know that normal transaction propagation and block propagation consume high bandwidth. Some changes have been proposed to reduce the bandwidth consumed by the network itself, and the primary method is by sending peers “sketches,” which is called a <strong>compact block</strong> (BIP 152).</p><p>These sketches are sent to receiving peers, and each sketch includes:</p><ul><li>The <strong>80-byte header</strong> for the new block.</li><li>Shortened transaction identifiers (<strong>short txids</strong>), which are specifically designed to prevent Denial-of-Service (DoS) attacks.</li><li>Some <strong>full transactions</strong> that the sending peer predicts the receiving peer does not have in its mempool or in its own blocks yet.</li></ul><p>We basically have the legacy relaying mechanism to compare against alongside two operating modes for compact blocks. But before moving to those modes, it is important to understand how the receiving peer works when it receives this data from the sending peer.</p><p>When the receiving peer receives the propagated data, it tries to reconstruct the block locally. It does not construct a separate block, but the exact same block that the sending peer has, using the sketch data combined with the valid transactions already sitting in its local memory pool (mempool). In case there are any missing transactions, it requests those specific transactions using the getblocktxn request and receives them via the blocktxn message response.</p><p>The major advantage of this approach is that transactions only need to be sent across the wire once in the best-case scenario. This drastically reduces overall bandwidth. Under standard propagation, transactions are announced, and the receiving node has to check if the transaction already exists in its own pool or memory. If it already does, re-downloading that transaction inside a raw block is completely wasted data.</p><p>With compact blocks, the receiving node only requests the specific transactions that are actually missing. On the transmitting side, the sender uses prefilled transactions to predict what the receiver is missing upfront. If the receiver still lacks any part of the block, it requests only those missing items using getblocktxn. This achieves block propagation without consuming unnecessary network bandwidth.</p><p>To understand the mechanics, we have the <strong>legacy relaying mode</strong> to compare against, followed by the two compact block modes: <strong>High-Bandwidth Relaying Mode</strong> and <strong>Low-Bandwidth Relaying Mode</strong>.</p><p><strong>Legacy Relaying Mode</strong></p><p>In legacy relaying mode, a block must always be fully validated by a node before it is announced.</p><p>To illustrate this, consider two nodes: <strong>Node A</strong> (the transmitting peer) and <strong>Node B</strong> (the receiving peer). When Node A receives a new block, it must first fully validate that block. Once verified, it announces the block to Node B using an inv (inventory) or headers message. If Node B does not have the block, it sends a getdata request back to Node A asking for the full payload. Finally, Node A transmits the entire raw block.</p><p><strong>High-Bandwidth Relaying Mode</strong></p><p>In high-bandwidth relaying mode, the receiving node (Node B) signals Node A in advance that it wants to receive new blocks immediately without an announcement round trip, using the sendcmpct(1) message.</p><p>When a new block arrives at Node A, it performs only basic validation — such as verifying the 80-byte block header and proof-of-work — and then immediately begins sending the compact block sketch (cmpctblock) directly to Node B without fully validating every transaction inside the block first.</p><p>Node B attempts to reconstruct the full block using the sketch and its mempool. If any transaction is missing, Node B sends a getblocktxn request to Node A, and Node A responds with the missing data via blocktxn. In the background, both nodes complete full validation before appending the block to their respective chains. This flow cuts latency down drastically, though bandwidth can increase if multiple peers push the same compact block simultaneously.</p><p><strong>Low-Bandwidth Relaying Mode</strong></p><p>In low-bandwidth relaying mode, the goal is strictly to avoid redundant data transfer across peers. Node B initiates this mode by sending a sendcmpct(0) message to Node A.</p><p>Here, Node A must fully validate the block before doing anything. Once validated, Node A does not push the compact block immediately; instead, it sends an inv or header announcement to Node B. If Node B has not received this block from any other peer, it explicitly requests the compact block using getdata(CMPCT).</p><p>Node A then transmits the compact block sketch. If Node B is missing any transactions needed to complete the block, it sends a getblocktxn request to Node A, and Node A returns the missing transactions in a blocktxn message. Once Node B reconstructs the block, it validates it fully.</p><p><strong>Trade-Off Summary</strong></p><ul><li><strong>Legacy Relaying Mode:</strong> Involves fewer round trips than low-bandwidth compact relay, but bandwidth consumption is extremely high because it retransmits 100% redundant transactions that nodes already have in their mempools.</li><li><strong>High-Bandwidth Mode (</strong>sendcmpct(1)<strong>):</strong> Delivers the lowest latency and fewest round trips (0.5 RTT in the best case), but can consume extra bandwidth if multiple peers send unsolicited compact blocks at the same time.</li><li><strong>Low-Bandwidth Mode (</strong>sendcmpct(0)<strong>):</strong> Involves more message round trips (headers/inv —&gt; getdata — &gt;cmpctblock — &gt; getblocktxn — &gt;blocktxn), but guarantees minimal bandwidth consumption by preventing nodes from downloading duplicate blocks from multiple peers.</li></ul><p>This forms the core architecture of compact block propagation on the Bitcoin peer-to-peer network. In upcoming articles, I will be exploring deeper concepts around this topic including the trade-offs between propagation latency and bandwidth consumption</p><p><strong>References:<br>* </strong><a href="https://bitcoincore.org/en/2016/06/07/compact-blocks-faq/">https://bitcoincore.org/en/2016/06/07/compact-blocks-faq</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba93698ef6e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chained Conditions: How Rust’s Where Clause Actually Works]]></title>
            <link>https://medium.com/@hamza.00dev1/chained-conditions-how-rusts-where-clause-actually-works-6a14ae72bb9f?source=rss-3e8a873d6060------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a14ae72bb9f</guid>
            <category><![CDATA[trait-binding-rust]]></category>
            <category><![CDATA[bitcoin-contribution]]></category>
            <category><![CDATA[rust-bitcoin]]></category>
            <category><![CDATA[rust-projects]]></category>
            <category><![CDATA[bitcoin-news]]></category>
            <dc:creator><![CDATA[Muhammad Hamza]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 20:32:11 GMT</pubDate>
            <atom:updated>2026-06-24T20:32:11.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2BW23aXEicK27esWJ3izw.png" /></figure><p>I was reading through some Bitcoin Rust source code when I hit a wall. Not the kind of wall where you don’t understand the syntax. The worse kind — where you <em>think</em> you understand it, move on, then twenty minutes later realize you understood nothing at all.</p><p>The code looked something like this:</p><pre>impl&lt;C&gt; Emitter&lt;C&gt;<br>where<br>    C: Deref,<br>    C::Target: RpcApi,<br>{<br>    pub fn new(<br>        client: C,<br>        last_cp: CheckPoint&lt;BlockHash&gt;,<br>        start_height: u32,<br>        expected_mempool_txs: impl IntoIterator&lt;Item = impl Into&lt;Arc&lt;Transaction&gt;&gt;&gt;,<br>    ) -&gt; Self {<br>        // ...<br>    }<br>}</pre><p>My first read: <em>“Okay. Two conditions on C. Got it.”</em></p><p>My second read: <em>“Wait. What exactly is</em> C::Target<em>? And why does it only appear after</em> C: Deref<em>?&quot;</em></p><p>That question — small as it sounds — turned out to be the key to understanding one of Rust’s most powerful patterns. This article is about what I discovered.</p><h3>What Is a Where Clause, Really?</h3><p>Before we get to the interesting part, let’s establish the basics.</p><p>In Rust, when you write a generic function or implementation block, you’re saying: <em>“I don’t care what specific type you give me — as long as it satisfies certain conditions.”</em> Those conditions are called <strong>trait bounds</strong>, and the where keyword is how you express them cleanly when there are multiple.</p><p>Think of it like this. Imagine you’re writing a function that needs to receive some kind of container. You don’t care if it’s a box, a bag, or a crate — but you have two requirements: it needs to be openable, and whatever is inside needs to be edible.</p><p>In plain English: <em>“Give me anything that can be opened, and whatever is inside must be food.”</em></p><p>That’s exactly what a where clause expresses — but in Rust&#39;s type system.</p><p>Here is a simple example before we touch Bitcoin code:</p><pre>fn process&lt;T&gt;(value: T)<br>where<br>    T: Display + Clone,<br>{<br>    let copy = value.clone();<br>    println!(&quot;{}&quot;, copy);<br>}</pre><p>The compiler friend reads this and says:</p><p>But the example from the Bitcoin codebase above is doing something more interesting than a simple list.</p><h3>The Part Most Tutorials Skip: Chained Conditions</h3><p>Let’s look at those two bounds again:</p><pre>where<br>    C: Deref,<br>    C::Target: RpcApi,</pre><p>At first glance this reads like two independent conditions — C must implement Deref, <em>and</em> C&#39;s target must implement RpcApi. But they are not independent. They are <strong>chained</strong>. The second condition cannot exist without the first, and understanding why is the heart of this article.</p><p>Deref is a Rust trait that smart pointer types implement. When a type implements Deref, it means you can dereference it — you can &quot;unwrap&quot; it to get at what&#39;s inside. Types like Box&lt;T&gt;, Arc&lt;T&gt;, and &amp;T all implement Deref. When you dereference them, you get their inner value — their <strong>target</strong>.</p><p>And that brings us to C::Target.</p><p>Target is an <strong>associated type</strong> defined on the Deref trait. It represents whatever type you get <em>after</em> dereferencing. So C::Target is not just some field or property of C — it is a concept that only exists <em>because</em> C implements Deref. Without the first bound, C::Target is meaningless. The compiler would have no idea what you&#39;re referring to.</p><p>This is the dependency:</p><p><strong>Step 1:</strong> Establish that C can be dereferenced → this gives us the concept of C::Target</p><p><strong>Step 2:</strong> Now that C::Target exists as a meaningful type → constrain it to implement RpcApi</p><p>You cannot ask the second question without first answering the first. The compiler evaluates them in order, and the second bound literally depends on the first being satisfied. This is what makes it a chain, not a list.</p><p>The compiler friend, in this case, is doing something like:</p><blockquote><em>Programmer: </em>“Yes, it wraps a BitcoinClient that implements RpcApi.”</blockquote><blockquote>“Then we’re building. Come through.”</blockquote><p>Now imagine the programmer had passed in a plain u32 instead:</p><blockquote>“Can I dereference a u32? No. u32 doesn’t implement Deref. I’m not even asking the second question. We’re done here.”</blockquote><p>The chain collapses at step one. The second condition never gets evaluated.</p><h3>Why This Pattern Exists in Bitcoin Rust Code</h3><p>This isn’t an academic pattern. It solves a real problem in production Bitcoin software.</p><p>Consider what the Emitter struct is doing — it needs to talk to a Bitcoin node via RPC. It needs to call methods like getblock, getblockcount, getblockhash. Those methods are defined on the RpcApi trait.</p><p>But here’s the constraint: the code also needs to work with different kinds of wrappers. You might want to wrap your RPC client in an Arc so it can be shared across threads. You might want to wrap it in a Box for heap allocation. You might be working in a test environment where you pass a reference directly.</p><p>If the code required a specific type — say, BitcoinClient directly — it would be rigid and unusable across different deployment contexts. By accepting any C where C: Deref and C::Target: RpcApi, the code is saying:</p><p><em>“I don’t care about the wrapper. Wrap your RPC client in whatever makes sense for your architecture. As long as I can dereference it and find something that speaks RPC on the other side, I can work with it.”</em></p><p>This is generic Rust at its most practical. The where clause is not complexity for its own sake — it is flexibility with guarantees.</p><p>A concrete example of what this allows:</p><pre>// All of these are valid because Arc&lt;T&gt;, Box&lt;T&gt;, and &amp;T all implement Deref<br>// and BitcoinClient implements RpcApi</pre><pre>let client1: Arc&lt;BitcoinClient&gt; = Arc::new(BitcoinClient::new());<br>let client2: Box&lt;BitcoinClient&gt; = Box::new(BitcoinClient::new());<br>let client3: &amp;BitcoinClient = &amp;BitcoinClient::new();</pre><pre>// The same Emitter::new() accepts all three<br>let emitter1 = Emitter::new(client1, ...);<br>let emitter2 = Emitter::new(client2, ...);<br>let emitter3 = Emitter::new(client3, ...);</pre><p>Without the chained where clause, you would need three separate implementations. With it, you write the logic once and the type system handles every valid combination.</p><h3>The Three Layers of This Pattern</h3><p>When you encounter a where clause like this in real Rust code, it helps to read it in three distinct layers:</p><p><strong>Layer 1 — Trait Bounds</strong> (C: Deref): What behaviors must the type support? This is the entry gate.</p><p><strong>Layer 2 — Associated Type Constraints</strong> (C::Target: RpcApi): Given those behaviors, what must the <em>output</em> of those behaviors look like? This is the chained condition.</p><p><strong>Layer 3 — The Implication</strong>: Together, these two layers define not just what C is, but what C <em>leads to</em>. You’re constraining a type and its derivative in one coherent statement.</p><p>Most Rust tutorials explain Layer 1 well. Associated types get covered eventually. But the dependency relationship between them — the chain — is rarely made explicit. That gap is exactly what caused my confusion when I first read the Bitcoin code.</p><h3>What I Got Wrong Before — And What Actually Clicked</h3><p>My initial mental model was flat. I read where C: Deref, C::Target: RpcApi and thought: <em>two conditions, both must be true, moving on.</em> That&#39;s not wrong — but it&#39;s incomplete in a way that matters.</p><p>The flatness of that reading hides the fact that C::Target is not a property C happens to have. It is a <em>consequence</em> of C implementing Deref. The Target associated type is <em>defined by</em> the Deref trait. It doesn&#39;t exist on types that don&#39;t implement Deref. So the second bound isn&#39;t just another requirement — it&#39;s a requirement that becomes <em>expressible</em> only because of the first.</p><p>The moment this clicked for me was when I stopped reading the bounds left-to-right as a list and started reading them top-to-bottom as a chain. The first bound opens a door. The second bound walks through it and asks a question of what’s on the other side.</p><p>Once I saw it that way, a large class of Rust generic code became readable where it had previously felt opaque.</p><h3>Closing</h3><p>The where clause in Rust is more expressive than it looks. When you see trait bounds combined with associated type constraints, you are not looking at a checklist — you are looking at a sequence of logical steps, each one dependent on the last.</p><p>In the Bitcoin Rust ecosystem specifically, this pattern appears everywhere smart pointer flexibility meets protocol-level constraints. Learning to read it fluently is not optional if you want to contribute meaningfully to crates like BDK, LDK, or rust-bitcoin.</p><p>The next time you see a where clause with more than one condition, ask yourself: <em>are these independent? Or does the second one only exist because the first one is true?</em></p><p>Chances are, it’s a chain.</p><p><em>If you found this useful, follow me here on Medium for more articles on Rust, Bitcoin development, and open source contribution. I write from the perspective of someone actively contributing to the Bitcoin Rust ecosystem — mistakes included.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a14ae72bb9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>