<?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 Stephen Wayne on Medium]]></title>
        <description><![CDATA[Stories by Stephen Wayne on Medium]]></description>
        <link>https://medium.com/@swayne275?source=rss-3b1c987d9b0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Kj2qrvPTmZfiqswXrncvJA.jpeg</url>
            <title>Stories by Stephen Wayne on Medium</title>
            <link>https://medium.com/@swayne275?source=rss-3b1c987d9b0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:35:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swayne275/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[Messari 2023 Crypto Theses Notes]]></title>
            <link>https://medium.com/@swayne275/messari-2023-crypto-theses-notes-6e2cde06794c?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e2cde06794c</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 17:00:53 GMT</pubDate>
            <atom:updated>2023-04-21T01:35:43.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMy4oMmKEMEBSkKGg8kvFQ.jpeg" /></figure><p>I read through Messari’s <a href="https://resources.messari.io/pdf/messari-report-crypto-theses-for-2023.pdf">theses for crypto in 2023</a> and took notes along the way. The opinions expressed here are not my own, and if parts of these don’t seem correct it’s likely that I misunderstood the source material (so please let me know!). I hope this can be helpful to those who want a detailed summary but don’t have time to read through 168 pages. If you found this useful please Clap so I know to follow up next year!</p><h3>1.0 Top 10 Narratives &amp; Investment Themes</h3><p>We need to retire the term <em>Web3</em><strong><em> </em></strong>as there’s been absolute carnage since we coined it. We need more personal wallets, more privacy, and permissionless financial/social applications.</p><h4>1.1 Winter is Here: It’s Time to Build</h4><p>Many people lost money in 2022, and some poorly managed companies died. We’re left with true believers and long-term builders as many of the gamblers, scammers, tourists have left.</p><p>We now have many options around centralized institutions that previously trapped or took advantage of the populace.</p><p>A litmus test for good tokens: does the token create an early user base and improve the product, or does it make the founders rich? If the latter, it’s an MLM.</p><p>If a crypto product gets <em>better</em> as more people use it, that’s a good sign.</p><h4>1.2 Crypto is (Still) Inevitable</h4><p>Beneath the wreckage is a stronger foundation than ever. Lots of capital, talent, and demographic change has moved crypto forward. Crypto is inevitable because of the buildout that has happened — the genie can’t be put back into the bottle.</p><p>Stablecoin volume rivals global card networks, and NFTs open the door for secure sharing/transactinos of intellectual property, identity, or digital assets.</p><h4>1.3 Surviving Winter, Redux</h4><p>The best way to survive the winter: build! There are fewer distractions, and product-market fit becomes clearer. It’s easier for crypto to get cash now too.</p><h4>1.4 How Low Can We Go</h4><p>MVRV (market value to realized value) that hits 3 has meant “sell right now”, and below 1 has meant “start accumulating” for BTC history</p><p>DeFi is quite low, TVL is ~40B which barely cracks the list of top 50 banks.</p><p>NFTs as a data construct will eventually wrap 10s of trillions of dollars of assets (we’re ~$8B today). <strong>Ryan would rather long infrastructure businesses vs specific projects</strong>. <strong>He’s invested in OpenSea and ENS</strong>.</p><p>DePIN (decentralized physical infrastructure networks) are small but have massive potential. Ryan is personally invested in filecoin (but not helium?)</p><h4>1.5 Bear Market Building</h4><p>We need:</p><ul><li>investments in disclosure standards (proof of reserves, on chain monitoring, crypto version of GAAP accounting)</li><li>investments to solve security issues</li><li>Want to ensure centralized orgs (amazon/google/apple) can’t shut down crypto? <strong>We need decentralized hardware networks</strong></li><li>VCs have <a href="https://alliancedao.notion.site/Crypto-Web3-Startup-Ideas-2023-Edition-48d40ccadeeb42a48056659fcce109b1">published a list of what they want</a></li></ul><h4>1.6 Decoupling of Cryptos: Back to the Basics</h4><p>Valuing a crypto ecosystem has been hard. Now we have quarterly financial statements directly from the blockchain!</p><p>The next cycle will be driven by real usage and sustainable protocol economic models, and the data is freely available.</p><h4>1.7 VC: There’s (Still) Money in the Banana Stand</h4><p>Investment slowed down significantly in 2H 2022. Companies that raised in 2021 and 2022 should have lengthy runways (if they’re smart). Venture markets for more mature companies will likely get more ruthless in 2023 — it’s time to demonstrate businesses are fundamentally sound.</p><h4>1.8 The Macro Rebound vs. The Dumpening</h4><p>It’s a fairly safe bet that the bear market will continue for the foreseeable future with no V-shaped recovery for crypto markets.</p><p>There’s a lot of sell pressure as bitcoin miners sell just about everything they mine to cover operating costs/debt.</p><p>There’s no more mining sell pressure on ETH, but there might be with taxes on stake rewards</p><h4>1.9 Buyouts vs Bankruptcies</h4><p>A lot of companies that looked really hot last year are hurting now. Larger institutions who are long crypto might see this as a compelling entry point (i.e. buy a struggling company). <strong>This could be the bridge that institutions (wall street &amp; big tech) needed to integrate crypto products at scale</strong>.</p><h3>2.0 Top 10 People To Watch</h3><h4>2.1 Changpeng Zhao &amp; Brian Armstrong</h4><p>Binance and Coinbase will be central to any industry rebuild. As their fortunes go, so goes crypto in 2023</p><h4>2.2 Rep. Patrick McHenry</h4><p>Crypto proponent readying to help the House Financial Services committee.</p><ul><li>He promoted SEC Comissioner Hester Peirce’s Safe Harbor proposal</li><li>He co-sponsored a bipartisan bill to regulate stableecoins and establish ground rules for broader financial system integration</li><li>He and Tom Emmer (House Majority Whip) are likely to provide a check on SEC Chair Gary Gensler</li></ul><p><strong>One of the most important politicians to watch this year.</strong> We have a lot of informed leaders in this new Congress.</p><h4>2.3 Sheila Warren</h4><p>A former World Economic Forum executive, she’s got a great staff and positioned the Crypto Council for Innovation (CCI) at the center of DCCPA discussions. CCI is a smaller but high maintenance group of companies (Coinbase, a16z, Paradigm, Fidelity, Block).</p><p>The success of CCI to get good crypto legislation passed will influence the next decade of industry development.</p><h4>2.4 Citizen Journalists: From Molly White to Autism Capital</h4><p>Molly is an informed and savvy crypto skeptic, and Autism Capital is a self-proclaimed “simp account” for SBF before pivoting to investigative journalism. They’ve both outperformed the legacy media.</p><p><em>Web3 Is Going Just Great</em> (Molly) tracks daily crypto dumpster fires, and is a savage reality check. It’s simple and highlights startup failures, hacks, and frauds. Could be useful to recognize real issues and build solutions.</p><p>Autism Capital broke real news on the FTX collapse while the legacy media was busy sucking up to SBF.</p><h4>2.5 Anatoly Yakovenko</h4><p>EVM is the only L1 that seems certain to be a long-term fixture in the crypto industry.</p><p>Scalability can be basically narrowed down to 4 categories: EVM-compatible blockchains (including rollups like Arbitrum, Optimism, and zkSync), Cosmos-stype “app chains”, Aptos/Sui “Move” chains, and Solana.</p><p>Watch Anatoly Yakevenko, Solana’s co-founder. Solana will have to work hard to come back from the FTX position. The team is very strong.</p><h4>2.6 Barry Silbert &amp; The Winklevii</h4><p>Barry has Genesis Capital, Cameron/Tyler Winklevoss have Gemini.</p><p>Genesis ows $900MM to Gemini Earn customers, and creditors want to recoup their funds from Gemini. The fate of DCG (parent company to Genesis Capital) and Gemini hang in the balance.</p><h4>2.7 Stani Kulechov</h4><p>Founded Aave and Lens. Aave pioneered the flash loan (borrow large amounts for specific transactions without providing upfront collateral).</p><p>He also has one of the top in-house DeFi policy people in Europe/DC on his team (Rebecca Rettig).</p><h4>2.8 Alexey Pertsev &amp; Tornado Cash Devs</h4><p>Tornado cash is a DeFi mixing service that uses zk proofs to help users execute fully private transactions on Ethereum. It may have been used to launder over $1b worth of crypto.</p><p>It’s unclear if anything illegal happened, but Alexey is in prison waiting for official charges.</p><h4>2.9 DAO Members</h4><p>We need safeguards for DAO contributors so governments/agencies don’t come after them with legal stuff.</p><p>Ryan guesses these protections will come state by state this year.</p><h4>2.10 IRS Agent Smith</h4><p>The infrastructure bill includes provisions to collect on crypto gains (estimated $28B increase).</p><p>The IRS got a big boost, and it may become easier for authorities to seize crypto assets without any conviction or filing criminal charges.</p><p>Tracking cost basis accurately is nearly impossible. Accounting for fees, trading slippage, and multiple wallets and exchange accounts is hard enough. Add in NFTs, hacks, token farms, and more exotica. The Authorities will come for their pound of flesh wherever crypto is traded.</p><h3>3.0 Top 10 Trends in CeFi</h3><p>3.0 Intro</p><p>FTX self-immolated. Coinbase stock dropped 80%. Western crypto infrastructure laid off hundreds. Crypto lenders from 2018–2020 are basically all dead (or nearly there).</p><p>It’s been a classic credit boom and bust. Much of this stemmed from an over-reliance on unsustainable DeFi yields. Poor risk management + compounding bad bets.</p><p>What remains? How can we build more sustainable infrastructure? Who will lead us?</p><h4>3.1 The Exchanges</h4><p>Biggest risks to monitor:</p><p><strong>Binance:</strong> Global regulation. It operates in a jurisdiction-light manner that may get it into trouble. It’s also got a 75% share of global crypto trading volumes and needs competition.</p><p><strong>Coinbase:</strong> Top global custodian of crypto assets (has about 10% of the crypto market cap). Top USD exchange and the first major crypto IPO. It has $3.5B debt at 15% with a market cap below $10B. Hostile takeover attempts seem unlikely to succeed.</p><p><strong>Bitstamp, Kraken:</strong> European regulatory risk.</p><p><strong>OKX, Huobi, KuCoin, Upbit:</strong> Asian regulatory risk.</p><p><strong>Bitfinex</strong>: Tether risk. Its affiliation with Tether opens it up to multiple regulatory risks.</p><p><strong>Gemini:</strong> Contagion risk.</p><p>The above all have operational risks too — market declines, hacks, deposit losses. The FTX crisis did lead to <strong><em>proof-of-reserves</em></strong> movement, transparency++ for the customer.</p><h4>3.2 The Institutions are Coming</h4><p>Ryan doesn’t seem too excited, although the section was quite entertaining.</p><h4>3.3 Anatomy of a Crypto Credit Crisis</h4><p>The Grayscale Trade (crypto’s “Widowmaker”) was integral in helping create much of the contagion we saw.</p><p>Use common sense in investing: “if you don’t understand the yield, you are the yield”</p><p>Summary:</p><ol><li>Started with Grayscale Trusts. They allow investors to buy GBTC in 401ks through OTC traded securities. But they weren’t ETFs, so there weren’t traditional creation/redemption mechanisms. Accredited investors could create Trust shares with bitcoin, hold for 6 month “seasoning” period, then flip them for a hefty GBTC premium pre-2021</li><li>Flipping and rolling the GBTC Premium got very popular and The Grayscale Trade got crowded in 2020 hitting $40B in AUM peak due to stimulus, BTC halving, and zero interest rates. 3AC and BlockFi accumulated 10% of the Trust’s shares with $4B peak exposure. 3AC then started offloading some of its exposure during the great GBTC Premium Crash</li><li>A good chunk of the seasoning is trapped and underwater with 3AC and BlockFi subject to 6 month holding restrictions. They eat the unrealized losses and lean on lending desks to borrow against their GBTC collateral. Genesis Capital (sister company to Grayscale) is one of the only lenders incentivized to treat GBTC at good money since its affiliate controls the share’s redemption mechanism and Genesis can milk the big borrowers for interest in the interim.</li><li>Exposed lending desks (BlockFi) and funds (3AC) let GBTC ride and now have to push farther out on the risk curve. Not a big deal in 2021 since everyone is making a ton of money, but now the market comes down from November tops. Luna grows and 3AC is a big Luna investor.</li><li>The Luna Foundation buys $1.5B BTC from Genesis with UST, knocking it off the peg. Other funds/trading desks see the peg break and bank run UST. Luna experiences a death spiral. 3AC is now underwater on two mega trades and becomes insolvent. Their GBTC gets liquidated, and Genesis takes possession of 30 million GBTC shares.</li><li>Multiple funds/trading desks with ties to 3AC go under or get bailed out (temporarily) by FTX. Active deposits shrink, lending desks call collateral and yank borrow from funds wherever they can. Credit seizes as everyone accelerates their derisking. This includes Alameda who has external borrow called after genesis realizes they don’t want FTT as collateral.</li><li>Coindesk publishes details on Alameda’s financials and token reserves. They are loaded with illiquid assets (like FTX’s FTT). An analyst sees Binance move $2B worth of FTT on-chain and speculates that CZ is preparing to dump the position. CZ confirms and fully severes ties with FTX days later. This is bad — $2B of an illiquid token just got dumped. FTT crashes. Collateral is worthless and FTX has no liquid accounts or access to other credit. CZ decides not to buy.</li><li>FTX/Alameda have no liquidity and have commingled customer funds. Customers are now at risk, there’s a bank run on FTX, FTX dies.</li></ol><p>The lessons are failry straightforward: Don’t commingle customer assets, cut losses early on bad trades (vs lever them up and pray), maintain internal controls and a fortress balance sheet, split assets across different custodians and counterparties, and only keep on exchange what you can afford to lose.</p><h4>3.4 DCG &amp; Genesis Contagion Risk</h4><p>The most important trend to watch is Digital Currency Group (DCG) and Genesis Capital (its lending arm). Gemini and others apparently have over $2B in frozen deposits at Genesis.</p><h4>3.5 Grayscale: Reflexivity up. Reflexivity down.</h4><p>There’s a case to be made that Grayscale was the most responsible for BTC’s late 2020 ascent (GBTC and ETHE AUM exploded due to the Grayscale trade, ang denerate ~300MM/year in high-margin, sticky annualized revenue).</p><h4>3.6 Custody, Security, Stability</h4><p>Crypto is hard to lend because it can be volatile and illiquid, so it makes bad collateral.</p><p>Three things to note:<br>1. Centralized lending is mostly dead. It’ll likely take years + comprehensive legislation/regulation before lending markets reopen. That’s probably good.</p><p>2. Centralized crypto lenders will behave more like legacy banks in the future, taking full custody of secured collateral, setting market rate terms, and at least pretending to take risk management seriously.</p><p>3. A credit collaps isn’t necessarily a bad thing for the long-term health of the crypto market.</p><p>Ryan is more about DeFi than CeFi crypto lending.</p><h4>3.7 Cloud Infrastructure and Developer Tools</h4><p>DePIN (decentralized physical infrastructure networks) are still nascent. In the mean time, we’re building centralized cloud like everyone else in tech.</p><p>Over half of all staked Ether is controlled by 3 entities, and over half of Bitcoin’s hash rate is provided by three mining pools. Centralized RPC providers are the lowest cost/easiest solution for reading blockchain data. Cloud providers (e.g. AWS) represent nearly 70% of hosted nodes for both ETH and SOL. <strong><em>Users are perpetually at risk of being deplatformed. </em></strong>Geographic concentration of validators could expose networks to geopolitical risks/regulations/acts of nature.</p><p>Expect meaningful upgrades to account abstraction, Proposer Builder Separation, and “Light Clients”.</p><h4>3.8 On-Chain Forensics</h4><p>On-chain fundamentals are getting sexier and more integral to professional traders’ risk scoring. Proof of reserves has become prominent since the FTX collapse.</p><p>Messari is getting iteratively closer to developing the equivalent of GAAP or IFRS reporting standards for crypto protocols. These metrics are available in quarterly reports or real-time, dealer’s choice.</p><h4>3.9 Tax &amp; Compliance</h4><p>Ryan’s base case for 2023 is the IRS will create hell for crypto investors: it is directed to extract higher taxes after a record year (2021) followed by a deep correction (2022) while compliance/tax monitoring tools take down rounds and struggle for new customers.</p><h4>3.10 Research &amp; Data Upgrades</h4><p>Ryan says Messari is the best.</p><h3>4.0 Top 10 Trends in Crypto Policy</h3><p>2023 could be transformational for crypto in terms of permanent law. We should get exchange oversight clarity and stablecoin regulation by law. We should make progress on setting standards for disclosures and consumer protections.</p><h4>4.1 How a Bill Almost Became a Law</h4><p>Ryan thinks SBF is brilliant and manipulative, not negligent or incompetent. He developed a powerful network of friends very quickly. Alameda made their money in sketchy ways, often at the expense of the retail investor/trader. People thought SBF was selling out the crypto industry for an FTX monopoly. Sam knew that a number of people had issues with the DCCPA’s DeFi language, and were planning to either fix or fight the bill.</p><p>It seemed DCCPA was salvageable, and people were trying to work with SBF to improve the DeFi language. Sam then started talking about policy, and lost a lot of goodwill. He threatened to get DCCPA opponents fired, and came after CZ but missed.</p><p>Days later, CoinDesk broke that Alameda’s solvency rested on the value of its own illiquid token balance sheet, CZ announced he’d dump his substantial FTT stake (parting ways with Sam for lobbying against Binance and other crypto firms). Within 2 days the game was up for FTX, Alameda, and Sam himself.</p><p>Two takeaways:</p><ul><li>DCCPA is ow considered a tainted bill. It’s unclear if it would have caught or exasperated the FTX fraud.</li><li>There needs to be justice for Sam’s crimes.</li></ul><p>The forthcoming prosecution in the US is a sign of the integrity in our justice system, and a deterrent for similar future BS. This whole saga has been terrible for crypto, and human lives in general.</p><h4>4.2 How a Bill Becomes a Law</h4><p>To win in D.C. you have to play the D.C. game. Fight the constitutionality of laws, and push back on overreaching regulators while the current administration is in power.</p><p>Read the example in this section. It’s helpful. Basically there are a bunch of gates to get through and financial benefits on the line that make it hard to get something reasonable through.</p><h4>4.3 The SEC vs CFTC Proxy War</h4><p>The Senate Banking Committee (controlled by crypto adversaries) and the House Financial Services committee (controlled by more open-minded crypto proponents) oversee the SEC who’s Chair (Gary Gensler) is crypto public enemy #1 in D.C.</p><p>The Senate Agricutlure Committee and House Agriculture Committee oversee the Commodity Futures Trading Commission (CFTC), which seems like the appropriate regulator of most crypto spot markets today.</p><p>SEC doesn’t really make sense to regulate since most stuff isn’t a security and can’t be listed until it’s either issued a “no action letter” or registered with the SEC. How does a decentralized L1 protocol and its community make centralized reports and disclosures?</p><p>The best case scenario in 2023 is one in which:</p><ul><li>The CFTC regulates the custodial exchanges, “digital commodities” (e.g. BTC, ETH), and carves out DeFi (for now)</li><li>Stabelcoin issuers face new oversight requirements that outline the rules they need to follow to fully integrate with the legacy financial system</li><li>Then and only then can we discuss the SEC’s role in overseeing bona fide crypto securities</li></ul><p>DCCPA never solved the “what is it” problem, and may have made it worse by defining a new category (digital commodity)</p><h4>4.4 MiCA Pros &amp; Cons</h4><p>Markets in Crypto-Assets (MiCA) and Transfer Funds Regulation (TFR) are the law of the land across Europe, going into effect in 2024.</p><p>The good news:</p><ul><li>There’s clarity on how crypto will be treated, and it’s a step forward for consumer protection and market integrity</li><li>Mostly focus on centralized crypto asset service providers (CASPs). DeFi regulations kicked down the road until further study.</li><li>Require CASPs to have real presence/management in the EU, holding them liable for damages/losses caused by hacks or operational failures.</li><li>Mandate client assets are segregated in case of bankruptcy</li><li>Asset issuers responsible for minimum disclosures, and exchanges will have to provide a white paper and other basic info to list assets without any issues (BTC, ETH)</li><li>DeFi: they want to regulate legal entities (rather than protocols), introduce a voluntary framework for DeFi supervision, establish on-chain monitoring, oversee obstacles</li><li>Didn’t ban BTC for its energy intensiveness</li><li>Provide a path to a digital euro stablecoin that isn’t necessarily a CBDC</li><li>NFTs excluded (for now) unless they have a function that makes them a financial instrument</li></ul><p>Problem areas:</p><ul><li>TFR is one of the strictest implementations of the Financial Action Task Force’s “travel rule”. Introduces anti money laundering requirements for CASPs</li><li>There are no exemptions/minimums to TFR for transfers between CASPs</li><li>Algorithmic stablecoins are essentially banned</li><li>Could backdoor to ban proof of work</li><li>Crypto lending isn’t covered</li></ul><h4>4.5 Everybody Hates Gary</h4><p>Chair Gary Gensler’s SEC has never met a company that they didn’t want to sue (except FTX apparently). They’re suing Ripple over XRP’s status as an unregistered security, and it looks more likely they’ll win.</p><p>The SEC also missed most of the major problems happening right under their noses.</p><p>Without clear legislation as to where the SEC’s crypto authority begins and ends, the industry will continue to fight a trench war. A lack of legislation will leave crypto’s fate in the hands of the administrative courts, delay adoption, rack up legal bills, and give oversight advantage to one of the world’s most openly hostile crypto regulators.</p><h4>4.6 Ooki vs. CFTC (DAO Governance)</h4><p>A lot is riding on the CFTC vs SEC question. It matters what authority is bestowed on a regulator by law, not who is in charge at the moment. All regulators will face the temptation to regulate via enforcement.</p><h4>4.8 Protecting Crypto Banking</h4><p>Senator Warren wants to ban banking to crypto companies. Crypto needs banking access, or the U.S. crypto ecosystem will be starved of on/off ramps, liquidity, and customer credibility.</p><p>If you want to red pill good people, do crazy shit. Narcotics “pharmaceutical” companies get big accounts at big bangs, but marijuana dispensaries don’t. Cartels keep bank access, but not truck drivers. Well all know it’s bullshit.</p><h4>4.9 State vs. Federal (Stablecoins)</h4><p>Stablecoins are now the backbone of the crypto economy.</p><ol><li>New House Financial Services Chair (Rep. Patrick McHenry) wants a digital dollar</li><li>Algorithmic stablecoins will be in the crosshairs in both Europe and US. LUNA was a colossal mess.</li></ol><p>The $10T question is whether the future of stablecoins sits under the Paxos model (preferred jurisdiction is New York State) or the USDC model (preferred jurisdiction is federal). Tether will likely not prove an eventual winner.</p><h4>4.10 The Ground Game</h4><p>The thankless, multi-year, never-ending work of educating policymakers, eking out state-by-state progress, and fielding pro-crypto candidates.</p><p>This year is all about reshaping the narrative, setting our own standards as an industry, and building solutions to the problems that plagued the last year.</p><p>Many of those solutions will be built in centralized infrastructure: security, reliability, transparency, proof-of-reserved, segregated customer accounts.</p><h3>Top 10 Crytpocurrency Trends</h3><p>Stablecoins are bridge currencies to a future where nations play a smaller role in centrally managing their economies. A CBDC-led future looks dystopian and authoritarian, but a crypto-lead future looks exciting.</p><h4>5.1 Bitcoin is “Outside Money”</h4><p>According to Zoltan, the deglobalization trend will lead to persistent inflation. Nations outside the US/EU alliance will look to “outside money” (non-sovereign money) rather than G7 “inside money” that slowly loses purchasing power.</p><h4>5.2 Global Regulatory Challenges</h4><p>It’s unlikely global authorities will like tech that makes their jobs harder (e.g. how hard it is to freeze/seize BTC at scale). It’s incompatible with financial surveillance and one-click financial deplatforming that authorities love.</p><p>This is why we hear that BTC is for terrorists, criminals, etc even tho that activity is a rounding error. Those same entities never praise BTC when it lets the good guys get around deplatforming or survive a total currency collapse. BTC couldn’t let Russia get around US sanctions.</p><p>Crypto is a monetary innovation, and those calling it a tool for evil are often projecting their own geopolitical worldview onto a neutral, amoral, and permanent technology.</p><h4>5.3 Bitcoin Mining</h4><p>Last year, miners in Texas could produce BTC for $5–10k and sell for $60k. Now it costs more like $15–20k with a 75% BTC decline.</p><p>Bad facts:</p><ul><li>BTC mining produces a lot of e-waste, about the same amount as a country the size of the Netherlands. Only about 17% is recycled.</li><li>BTC mining can be seen as driving up marginal energy costs in environments with accute energy shortages and high costs</li><li>At the beginning of 2022 only 39% of BTC mining was renewable (nearly 60% from coal/gas)</li></ul><p>Good facts:</p><ul><li>BTC mining costs are fixed and capped by market forces. It doesn’t become more energy intensive as more people use bitcoin. It’s a function of BTC market cap and energy costs. You won’t buy more energy than BTC is worth to mine.</li><li>Mining currently creates a carbon footprint similar to tumble dryers, or about 1/3 of gold mining. It’s significantly less energy intensive than the global banking system.</li><li>BTC miners are the dung beetles of the energy world — they eat energy that no one else wants or can use. The trend towards wasted/stranded energy continues, as miners have been increasingly co-located to capture flared methane, stranded geothermal energy, Cole refuse, and recycled waste tiers.</li></ul><p>Flaring is interesting. Natural gas is a common by-product of crude production, and typically generated in remote locations without pipeline/power infrastructure. It’s often combusted away, and would otherwise leak into the atmosphere and cause a significant greenhouse effect. BTC miners are leveraging wasted energy and reducing the carbon footprint of the oil industry. There is about 69TWh of wasted energy in the US per year due to flaring. The wasted energy from flaring in the US alone is equal to 78% of the global Bitcoin network. <strong>Bitcoin is an ESG (environmental/social/governance) asset.</strong></p><p>The narrative deck is stacked against crypto w.r.t. energy concerns, but we should still push to be greener.</p><h4>5.4 Bitcoin Yield</h4><p>“Bitcoin doesn’t do anything” is a feature (not a bug) of a store of value that is difficult to confiscate or borrow.</p><p>BTC can’t be staked, which is probably a good thing given recent events.</p><h4>5.5 Memes &amp; Ripples</h4><p>Doge, Litecoin, Ripple’s XRP have ben the top 3 performers in Q4.</p><h4>5.6 Privacy Coins &amp; Private Transactions</h4><p>Defaults are powerful for crypto networks. Blockchains like Ethereum are transparent by default and allow for private transactions in specific pools.</p><p>Transparency is kind of necessary for governments to allow this stuff to scale.</p><p>There may be big opportunities for private-by-default Ll1s like Zcash</p><h4>5.7 Stablecoins Should Be Our Leading Export</h4><p>Mega bullish on America and its ongoing leadership in tech, finance, crypto.</p><p>Crypto is a sector in which China simply cannot compete, since open financial architecture is fundamentally incompatible with their model.</p><p>USD is the world’s reserve currency, and there is huge need for USD-pegged stablecoins in countries with mega inflation (eg Argentina).</p><p>If we want to prolong our status as the world’s reserve currency holder, we should export digital dollars without the shackles of a CBDC (something no country will want for national security/privacy reasons).</p><h4>5.8 The Stablecoin Trinity</h4><ol><li><strong>The Majors:</strong> 2 well-regulated stablecoin USD-reserved stablecoin issuers: Circle and Paxos. Circle has ~$45B in USDC and has Blackrock and BNY Mellon as custodians. Paxos issues Binance USD and Paxos dollar, which are ~$20B combined (95% in BUSD). Paxos is regulated by the New York State Department of Financial Services as a trust company , and Circle is a licensed money transmitter. Paxos wants to stay comfy in New York State, Circle is pushing for federal stablecoin legislation.</li><li><strong>The Cowboy</strong>: Tether’s market dominance has declined year over year</li><li><strong>Crypto-Collateralized:</strong> Dai (MakerDAO) and Others.</li></ol><h4>5.9 Algo-Stables: Crypto’s WMDs</h4><p>Terra/LUNA’s failure was swift and savage, inflicting severe pain on investors. Should we keep running high stakes also stablecoins??</p><p>This model can lead to bank runs in down trending markets, but may still be possible to pull off successfully. But just because it <em>could</em> work, <em>should it?</em></p><h4>5.10 CBDCs &amp; Dystopia</h4><ul><li>the case for CBDCs is often framed as a panacea for ills in the banking system that could be solved with policy and rules-based competition, rather than taxpayer-borne science experiements with money</li><li>a CBDC would be tantamount to the FAA flying planes and building jet engines, rather than defining competitive, rules-based safe passage in the skies</li></ul><p>The government could hide the poison with things such as airdrops for certain behaviors (or political allegiances), which is pretty dystopian.</p><h3>6.0 Top 10 Ethereum &amp; L1 Trends</h3><p>2022 was the year of the crypto developer, and the Ethereum Merge was awesome: a giant network ported to a new, scalable architecture with a new security model, in real time, with no hiccups.</p><p>The future looks bright.</p><ul><li>The Merge: part one forked Proof of Work and switched to Proof of Stake. Developers are now ensuring transaction validation is well distributed, allowing stakers to withdraw from staking contracts.</li><li>The Surge: 100,000 tx/sec with a new transaction type called “blobs”: Rollups have a specific allocation of blockspace to post their data. Should reduce fees.</li><li>The Verge: “fully SNARKed Ethereum” — verifying blocks is easier with “Verkle trees”, cryptographic proofs are smaller than their Merkle tree cousins, paving the way for stateless clients (better mobile device support).</li><li>The Purge: Lots of code cleanup to simplify the protocol, eliminate tech debt, limit costs of participating in the network. Generally reduce costs and improve performance.</li><li>The Splurge: “fix everything else”. EVM improvements, account abstractions, quantum-safe Ethereum.</li></ul><p>So generally it’s cleaning up tech debt, improving scalability/security of rollups, and ensuring EVM stays censorship resistant.</p><h4>6.2 Merge Economics</h4><p>The merge was a fundamental economic shift. The environmental footprint was reduced by ~99%, making Ethereum more compelling as an ESG investment. It also reduced new token issuance by 90% and eliminated ~$500MM sell pressure from miners. It also created a net deflationary asset with real yield due to the fee burn mechanism from EIP-1559. The network could have a steady state deflation of 1–2%/year. <strong>No other crypto project has achieved these supply dynamics.</strong></p><p>Yields could range from 5–7% in 2023, setting a sort of “risk-free rate” for Ethereum’s financial system.</p><h4>6.3 MEV &amp; Censorship</h4><p>Maximum Extractable Value (formerly Miner Extractable Value) or MEV is one of the most fascinating tech challenges in all of crypto, and has attracted some of the industry’s top talent.</p><p>MEV is a byproduct of the power dynamic between a blockchain’s security providers (miners/validators) and the network’s users. It can arguably make protocols more liquid, efficient, and antifgragile.</p><p>Block proposers are the validators (previously miners, now stakers). They can potentially be bad actors (e.g. frontrunning transactions), so we should design systems that can control for bad types of MEV to create more equitable protocols.</p><p>Censorship is the primary post-Merge concern with Ethereum right now. Post-Merge, many validators began to censor certain addresses/transaction types (although currently this just results in a longer delay in transaction processing, which isn’t the worst thing). The Scourge is the part of the roadmap to address this.</p><h4>6.4 What Vitalik’s Excited About</h4><ol><li>Privacy-preserving and real-world asset backed stablecoins</li><li>Prediction markets in DeFi.</li><li>Identity modules for things like authentication (sign-in with Ethereum), names (ENS), attestation (decentralized social), proof-of-humanity, etc</li><li>DAOs, which are communities that are decentralized either for robustness, efficiency, or interoperability</li><li>Hybrid applications that use blockchain and non-blockchain systems like voting, auditable services, etc</li></ol><p><strong>For builders:</strong> pick an underdeveloped area that Vitalik likes</p><h4>6.5 Exploding Bridges</h4><p>Today’s bridges have proven… <em>unstable</em>. Rollups are different though. They’re basically blockchains with built in bridges for transferring value and setting transactions across EVM chains. They process their own transactions, but roll up the summary to Ethereum for settlement (and security).</p><p>Users don’t care if their transaction is on L1 directly or routed through an alt-L1, a rollup, etc. You do care that your assets are secure and available. If a rollup has an outage, your funds still live on the parent L1. If L1 has an outage, you’re SOL.</p><h4>6.6 Rollups and Modularity</h4><p>Rollups improve blockchain scalability by processing transactions on a separate blockchain, compressing the data, and putting it on an L1.</p><p>Celestia ushered in the “modular” thesis, allowing developers to mix and match how their protocols handle each step of settle, verify, store.</p><p><strong>Smart Contract Rollups</strong></p><ul><li><strong>Optimistic Rollups</strong>: rely on fraud proofs, and batches are assumed to be valid until a fraud proof is submitted by verifiers (within a challenge period). Arbitrum and Optimism are the two largest, accounting for ~80% TVL.</li><li><strong>Zero-Kowledge Rollups (ZK Rollups)</strong>: rely on validity proofs, and each batch posted to L1 includes such a proof that the smart contract verifies. A long arbitration period isn’t required, but it’s much more technically complex to get EVM compatibility vs optimistic rollups.</li><li>Developers are more excited about zkEVM long term, but it’ll come down to usability. ZK Rollups theoretically have better scaling and lower fees</li></ul><p><strong>Sovereign Rollups</strong></p><p>Similar to the easy of deploying a virtual server via a cloud provider, developers can instantiate a sovereign blockchain with negligible upfront costs. These execute/validate/post to a consensus and data availability layer like Celestia, Polygon Avail, or Ethereum.</p><p>The key difference vs smart contract rollups is these are sovereign in their decision making over transaction validity and rollup state. They can be optimistic, zk, etc. Nodes execute and verify transactions according to their own rules/proofs and don’t rely on the optinions of an udnerlying smart contract layer for final settlement. They use the base layer to store data and refer to the order of past blocks to figure out the next.</p><p><strong>Rollups are great for application development, but it’s unclear if they will compete effectively with alternate L1s like Solana and Avalanche.</strong> They get security benefits from Ethereum, but transaction costs are still &gt;&gt; alt L1s.</p><h4>6.7 Too Close to the Solana</h4><p>Some of the crypto community is migrating from a monolithic architecture (execution/settlement/consensus/data on one chain) to a modular one (different chains for different parts). This is similar to a service oriented architecture (SOA) in software.</p><p>What would it take for an alt L1 like Solana to win against modular blockchains?</p><ol><li>computational advances to make running high-powered nodes cheaper</li><li>delays or security issues with rollups</li><li>user preferences/experience</li><li>product market fit of killer apps on a specific chain</li><li>how much centralization and MEV users are willing to accept</li></ol><p>Monolithic isn’t explicitly worse, it just has different engineering tradeoffs vs modular.</p><p>Solana has continued to improve speed and node decentralization, although server/cloud centralization could remain an issue. Using large cloud providers to run validators gives those providers disproportionate power over the network. Solana has also pushed hard on mobile accessibility — the Solana Mobile Stack represents a big bet on mobile infra to power a generation of new crypto apps. Its web3-native SDK is built on Android, and it has its own phone — the Solana Saga.</p><h4>6.8 Cosmos &amp; Appchains</h4><p>For now, Cosmos will likely remain the top ecosystem for sovereign appchain developers. The flexibility Cosmos offers paired with the value accrual mechanisms Inter-Blockchain Communication (IBC) offers make it an attractive platform for sovereign chain developers to vertically integrate on.</p><p>Unless L2 speeds increase significantly (or more non-financial transactions are pushed off-chain), the apps people use could end up on Cosmos.</p><h4>6.9 Other L1s</h4><p><strong>Cardano </strong>had a big year of technical upgrades, including smart contract capabilities and better scaling. Will slow and steady prove to work?</p><p><strong>Polygon</strong> set new all-time highs in active addresses and NFT wallets in Q3, and has one of the best business development teams in crypto. They got partnerships with Reddit, Meta, Starbucks last year.</p><p><strong>Polkadot</strong> as a chain-of-chains looks like Ethereum post-Merge. They are often a step ahead technically, and the developer community is great.</p><p>The success of any other upstart L1 hinges on business development and developer courtships, which is hard in bull markets and way harder in bears.</p><h3>7.0 Top 10 Trends in DeFi</h3><p>DeFi’s headwinds are still very real. We live to fight another day, but must keep our eyes on the prize. Builders and legislators will have to figure it out and hold bureaucrats in check wrt DeFi oversight.</p><p>It’s time for security and audit standards. Risk waivers and comprehensive disclosures. And apps that are actually useful.</p><h4>7.1 Revenge of the dApps</h4><p>Ethereum fees are way down, and the largest 3 ETH dApps (uniswap, lido, opensea) generate more monthly fees (combined) than the entire Ethereum L1. Volume is shifting off Ethereum to its scaling solutions (Polygon/Optimistic Rollups), or to app chains (dYdX on Cosmos).</p><p>Optimistic on DeFi dominance vs Ethereum in 2023, unless regulation gets in the way.</p><h4>7.2 Uniswap, the Final DeFi Unicorn</h4><p>Uniswap is the only current DeFi unicorn, and kind of only competes with itself. The v3 upgrade is huge.</p><h4>7.3 Real-World Colleteralized DeFi</h4><p>The only customers who weren’t rekt this year used DeFi lenders. Ironically, DeFi lenders seemed to be running much cleaner books than centralized options.</p><p>MakerDAO began dabbling in real-world assets (real estate, invoices, commercial loans, etc) in 2021, and have fully reserved dollar stablecoins backing the Dai stablecoin. They added US Treasuries as risk-free yields went up and DeFi yields collapsed.</p><p>These decentralized lending protocols are more transparent, better collateralized, and seem to have a much firmer grasp on risk management and rotate into the best risk-free assets.</p><h4>7.4 Undercollateralized DeFi Lending</h4><p>Overcollateralized DeFi lenders generate most of their yield from the demand for leverage from margins traders/market makers. Risk appetite as decreased, so those yields have gone down.</p><p>Other DeFi lenders generate riskier yield on undercollateralized positions. This is what brought down a bunch of centralized lenders, but it seems the DeFi lenders are better at risk management.</p><p>It’s doubtful crypto will ever compete with legacy banks at scale without undercollateralized lending. Do we have the right building blocks to make this viable in the short term (credit scores, insurance, etc)? Can we replace loan officers with smart contracts, on-chain data, DeSoc identities, etc? It may be too early.</p><h4>7.5 Superfluid Colleteral &amp; Synthetic Stakes</h4><p>Liquid staking protocols drew people into ETH staking and helped bootstrap the security of Ethereum’s post-Merge PoS blockchain. The Shanghai upgrade should lower the barriers further and attract more staking.</p><h4>7.6 The Perp Walk: dYdX as an Appchain</h4><p>dYdX v4 upgrade will be risky, but could create the highest quality perpetuals product on the market, and compete with centralized alternatives.</p><h4>7.7 On-Chain Asset Managers</h4><p>ETFs were a huge financial innovation, and good active managers could make a killing as memes run out of steam and fundamentals take over. Rules-based asset managers are now much easier to create with code. There are opportunities for specific sector plays, portfolio copy-traders, etc.</p><h4>7.8 New Novel Markets: Two Truths &amp; A Lie</h4><p><strong>ESG:</strong> Some crypto protocols (Nori, Flowcarbon, KlimaDAO, Toucan) are laying the groundwork for corps and individuals to reduce their carbon footprints by revamping the broken carbon trading markets.</p><p><strong>Real Estate:</strong> skeptical that there’s a near-term path for crypto to meaningfully participate in such a heavily regulated and physical asset class. That said, there are pockets that could be interesting. It would be nice to have a crypto-friendly bank where one could deposit holdings and secure loans against your house AND crypto. Crypto protocols that fractionalize NFTs and virtual property are much more exciting.</p><p><strong>Prediction markets:</strong> Feel like a use-case that’s always one year away. Prediction markets generally converge to 2 main use cases: speculating on the price of assets, and sports betting. #1 is already DeFi, but someone might do a sports betting DEX that would require sports-specific oracles.</p><h4>7.9 DeFi Censorship</h4><p>We shouldn’t take for granted that DeFi survives the global regulatory gauntlet of 2023. It is seen as the highest-risk subsector of crypto by Congress, and it will be hard for proponents to tell a different story.</p><p>Front-ends might need to be centralized (CeDeFi) for regulatory purposes, which isn’t a new concept.</p><p>The majority of DeFi users and volume may be KYC’d within the next several years, but non-KYC transactions will always be processed. 30–40% of Ethereum’s blocks are still processing transactions to/from addresses on the U.S.’s naughty list.</p><h4>7.10 Bullish Unlocks -&gt; Down Bad</h4><p>It’s time to take security/sustainable token design more seriously after a year in which we’ve experienced $3B in on-chain hacks. Countless security auditors will keep raking in cash, along with economic security modelers (Gauntlet, Chaos Labs) and network monitors (OpenZeppelin, Blocknative). We’ll also likely see more efforts around developing global security standards.</p><h3>8.0 Top 10 Trends in NFTs &amp; DeSOC</h3><p>NFT infrastructure opportunities are exciting this year, and could be similar to 2013–2015 era Bitcoin.</p><h4>8.1 “Blue Chip” Pixelated Art</h4><p>The size of the NFT market is hard to asses since it’s non-fungible and illiquid. Right now, much of that is locked up in PFPs like BAYC and Punks. They are similar to brandings or gang tattoos — they signify you’re part of a community that’s got your back. There’s also innovation under the surface of what look like toys.</p><h4>8.2 Generative Art</h4><p>Art is art, and its value is in the eye of the beholder and market. Here, we also have innovation beneath the toy exterior.</p><p>You can use generative AI models to create the perfect iteration of some art that expresses a number of things.</p><h4>8.3 The Institutions are Here, Just Not the Ones We Expected</h4><p>Big brands got on board with NFTs (Gucci, Dolce &amp; Gabbana, sports stuff like NBA Top Shorts, F&amp;B companies like Starbucks, etc). Very few of these collections maintained their value, but we’re still seeing strong moves from legacy brands and non-crypto tech companies. Reddit launcehd a collectible avatar program, onboarding 3 million unique users. Meta is building an NFT marketplace to integrate with facebook and insta. We’ll probably see a lot from Elon’s Twitter.</p><p>Fashion may be going digital the fastest — in-game virtual goods/skins is now a $50B market. Digital drip will become more commonplace as gamers demand more customization. This is exciting for brands and artists more than speculators. <strong>NFTs are moving from “investments” to “consumables”.</strong></p><h4>8.4 GameFi</h4><p>Web3 gaming is all about giving players ownership of their in-game digital items and using tokens to create in-game economies (and potentially game governance). Players with a stake in the game will feel more invested in the game’s success and spend more time/money.</p><p>Instead of extracting value from players via DLC/microtransactions, these creators make money as marketplace operators (transaction fees). Users are incentivized to play-to-earn (P2E).</p><p>There are 3 problems though:</p><ol><li>A game needs to be fun to build a sustainable P2E franchise.</li><li>It usually takes a lot of money to make a fun game. Development is timely and expensive, and has art and other complexities to contend with. The higher the quality, the longer the time to build it.</li><li>A lot of these things (like Axie) start off huge and exponentially decline in usage.</li></ol><p>It’s not clear that this financial stuff belongs in gaming (rather than other parts of the real world). Ryan is bearish and will be until he sees evidence that these games won’t suck and the path is viable.</p><h4>8.5 The Cryptoverse</h4><p>It feels like we’re still years away from hardware that makes the cryptoverse not suck (although gaming, teledildonics, gambling might be an exception).</p><p>Ryan remains bullish on the AR/VR future, but it seems far away.</p><h4>8.6 Decentralized Social (DeSo)</h4><p>DeSoc rearchitects Web2 social media on crypto rails. It could serve as the substrate that allows people/capital to organize and exchange value on the internet. It gives people on-chain reputation, organization, and ownership of their content. It also intros new ways for people to better capture value from their online IP. It’s currently split into 3 layers: front end, social graph, content storage.</p><p>Front ends (e.g. Lenster) resemble traditional social media apps, but read/write data to the social graph layer (Lens, Farcaster) and content storage layer (IPFS, Arweave) instead of their own app.</p><p>The social graph is the core piece. It is entirely open and composable. Any developer can create an app on top of a DeSoc social graph to tinker with application/monetization models. Users can use these apps and visualize their social graphs due to the openness of the data.</p><p>With this, you could figure out what’s triggering you and de-amplify it until things calm down (rather than blocking entirely) (this sounds great for election years lol). If you’re having a bad day you could amplify the positive influences. You could change your feed to have business stuff from 9–5 and fun stuff outside of it.</p><p>DeSoc won’t feed the algorithm to exploit your attention, it’ll help you conquor and benefit from social media. Things won’t be locked into a single (and censorable) front end.</p><p>A core infrastructure challenge is the scalability of the base layer networks like Polygon/Ethereum. These are orders of magnitude more constrained than current social network backend infrastructure. DeSoc will need to use cutting edge tech like rollups, parallelization, data availability.</p><p>Investment here might ultimately serve as the comms backbone for many DAOs and guilds.</p><p>If you include digital entertainment/content, the DeSoc addressable market is close to $1T in annual revenue.</p><p><strong>Transparency, user control over the algorithms, portability, revenue shares, 8 billion users. Bullish!</strong></p><h4>8.7 ENS &amp; Identity</h4><p>Proof of humanity doesn’t require you to give up key biometric data or submit to a social credit score.</p><p>Ethereum Name Service (ENS), Lense, and Unstoppable Domains let you add human readable NFT wrappers to your crypto wallets, similar to DNS like AWS Route53. They are much easier to remember (vs an ugly crypto address), and are big business. DeSoc and gaming are great tailwinds for this.</p><p>It feels problematic that ENS and other identifiers are globally searchable by default — it’s a worse version of having public Venmo everything. Could crypto allow you to show different history based on context?</p><p>A number of teams are working on context-dependent history, such as Urbit.</p><h4>8.8 Creator Royalties vs. Monopolist Taxes</h4><p>Apple charges app developers 30%, likewise OpenSea enforces on-chain NFT royalties. Royalty enforcement sucks at the user level, and should be left up to the creators to decide (e.g. creators may decide to let users opt out of royalties when times are tough).</p><p>Apps shouldn’t have to give 30% to Apple, but creators shouldn’t have to give up their agreed-upon income stream because you lost money.</p><h4>8.9 OpenSea’s Down Bad Yarrrr.</h4><p>OpenSea ramped incredibly quickly, and there is no “second best”. It could be a $100B business (or network) if it continues to execute. One could view it as the Coinbase but for NFTs.</p><h4>8.10 OpenAI &amp; ChatGPT</h4><ol><li>Promt writers will inherit the earth.</li><li>The lawyers always win — who really owns the outputs?</li><li>This will be one of the decade’s biggest productivity boons. This might free up good folks to think about the stuff that matters, rather than wordsmithing.</li><li>Your communications could be uploaded to such a system and queried against.</li><li>The imminent demise of Google has been greatly exaggerated. We should decentralize these data silos.</li><li>AI is a reflection of its data sets, and is not necessarily representative of humanity or a global hive mind. It is heavily weighted by who is on the internet, and who produces the most content. AI isn’t good or bad, but its data sets might be.</li></ol><h3>9.0 Top 10 Trends In DAOs &amp; Web3</h3><p>Are we serious about decentralization and open source, or will the same tech giants dominate and provide marginal improvements on what we have today?</p><p>This chapter outlines some of the most important crypto needs, which comes down to hardware, wallets, browsers, secure data pipes, and new governance primitives/social contracts.</p><p>We can’t be reliant on the tech giants for hosting (read: centralizing), but they can help us bootstrap.</p><p>We should consider “Layer-0”: the moral/ethical/cultural underpinnings we use when building technology. We need good governance and social primitives encoded here.</p><h4>9.1 Wallets &amp; Browsers</h4><p>Personal wallets are the backbone of the crypto economy (not exchange-based account). The upgrades this year have been incredible.</p><p>MetaMask added bank-to-crypto transfers. Coinbase plans to expand Coinbase Pay to fund Coinbase Wallets direclty from a bank account, added fiat-to-crypto APIs for dApps, and rolled out support for Ethereum dApps in the standard mobile wallet. Portfolio tools made it easier to track specific wallets in real time and manage portfolios in a single dashboard.</p><p>Better wallet infrastructure moves from wallets being a crypto purist thing to a better experience with more safety and accessiblity.</p><p>The main remaining gaps are in mobile. It’s gonna be a battle to get users unrestricted access to crypto apps on iOS/Android app stores. We may need a crypto native dApp store or better jailbreaking tools. <strong>There are still major censorship risks.</strong></p><h4>9.2 DePIN</h4><p>We need decentralized hardware — the war against censorship will be fought in the cloud. We need things like file storage, wireless access, and cloud computing.</p><p>It’s been possible to incentivize hardware <em>supply</em>, but harder to get <em>demand</em>. The scene is controlled by three of the largest and most reliable tech companies, which means partnerships, business development, and organic demand may be tough to come by. Crypto infra will probably grow fast in areas with high censorship tho (esp from government).</p><p>This is an interesting segment for investors, however. Lots of money to spend building the backbone of a free and open internet, a check on government suppression.</p><p>Things like filecoin will see steady, linear growth (rather than speculation).</p><p><strong>Long term, very bullish here.</strong></p><h4>9.3 Data Integrity</h4><p>Three core types of crypto data: blockchain transactions, off-chain markets (e.g. CEX order book), and “real-world” data for oracles. W need better reliability/standardization of on-chain data, and better access to secure/verified oracle data.</p><p><strong>The Graph is the on-chain leader</strong> here, enabling the developer community to build open APIs of specialized subgraphs that data consumers can query for their apps. Anyone can build and publish APIs (“subgraphs”). This is how we can build accounting tools to report on protocols.</p><p><strong>Chainlink is the leader for off-chain data sources.</strong></p><h4>9.4 Actually Useful DAOs</h4><p>DAOs can loosely be described as subreddits with bank accounts and governance. Blockchains let us run centralized marketplaces on autopilot, giving their contributors more upside and control. e.g. lenders can control a bank’s risk parameters, or drivers/riders in crypto Uber can control pricing tiers and safety standards. <strong>Very bullish!</strong></p><p>DAOs can offer:</p><ol><li>unprecedented control over how money is invested/directed — contributors and workers truly are the owners</li><li>the ability to rage quit a DAO, pull your funds, and fork your own without penalty</li><li>10x speed/cost improvement to spin up/down entities</li></ol><p>There’s a lot of foundational legal work required, however. How do these things actually work in the real world from a tax, contract law, and compliance standpoint.</p><ul><li>Fund raising for rare diseases, and altered incentive structures for solving them</li><li>Small SPACs: a DAO could be used to rescue a sports team or a small business, or fund litigation against a wealthy enemy</li><li>Investment clubs</li><li>Impact DAOs: align values with action</li><li>Social DAOs</li><li>Network states</li></ul><h4>9.5 DAO Management</h4><p>Current DAO management structures are unsustainable, but the list of governance tools to support them is growing. These tools can help you find DAOs, monitor/vote on proposals, discover other top tools, etc.</p><p>Most DAOs can be seen as a board of directors with unequal voting power, except that most don’t show up to meetings. Bribery has been an issue.</p><h4>9.6 The DAO Legal Liabilities are SpOoki</h4><p>Ooki DAO was sued by CFTC for doing offering leveraged and margin trading products without registering as a Futures Commissioner Merchant, and generally being sketchy. They then said that all voting members should be held individually liable for the illegal activities, which would set a very bad precedent for DAOs.</p><p>The CFTC said Ooki is an unincorporated association and the individuals are responsible — going after the organizers. Calling a group a DAO and voting does not reduce legal liability.</p><h4>9.7 DAO “Corporate Actions”</h4><p>We’re seeing DAOs do things like buybacks, corporate restructures, and amend governance bylaws — things we’d also see from corporations.</p><h4>9.8 DAO Treasury Management</h4><p>Most DAOs don’t properly diversify their treasuries or have a coherent community budgeting process, in part due to legal/organizational ambiguities, a lack of tooling, and a blasé attitude towards professional management.</p><p>DAO treasuries now hold only $8.7B, with native tokens representing about 80% of these assets (read: the projects are highly susceptible to market downturns and can become highly illiquid). Communities need to diversify their portfolios during bull markets.</p><p>We need more adversarial thinking in the DAO space — a lot of people there aren’t used to the turbulence of bear markets.</p><h4>9.9 Crypto Talent Marketplaces</h4><p>Ryan agrees with <a href="https://twitter.com/ASvanevik/status/1602177231341883392?s=20">Alex</a> that 2023 will be a crypto startup bloodbath, and it’ll likely be even worse in decentralized communities. The “friends-refer-friends” model is much better than having a bunch of random recruiting emails per day.</p><h4>9.10 Media DAOs</h4><p>Two of the top crypto media franchises (The Block and CoinDesk) might soon be fore sale due as a result of the FTX bankruptcy. <strong>If there ever was a time to build a media DAO, this would be it:</strong></p><ul><li>distressed and potentially conflicted corporate structures leads to talent looking for a potential change of scenery</li><li>The Block/CoinDesk each likely have &gt;$20MM payroll, but that could be trimmed considerably if the core editorial products are spun out</li><li>Innovations like GPT-3 change the economics of media, but you still must own the copyrights and data sources to create good content. You’ll also need professional investigators/fact checkers/analysts to have clean data</li></ul><p>This could allow journalists to make most of the money without feeling conflicted in their coverage. $10MM/year could fund a powerful crypto journalism DAO with some of the industries top journalists and researchers.</p><h3>Bonus: Yo Dre, I Got Somethin’ To Say</h3><h4>10.1 Why You Must Write</h4><p>Reading helps identify blind spots, but writing helps focus and streamline thoughts (me: I’d say writing helps identify blind spots too).</p><p>You must get better at writing to communicate well in this async, global, remote-first world. Be concise and communicate elegantly, comvert missionaries to your cause.</p><p>Get busy writing or become obsolete.</p><h4>10.2 No Idols</h4><p>Avoid main character energy. Stay hungry, humble, disciplined, and hard.</p><h4>10.3 Must Read</h4><p>High Output Management, Shoe Dog, Principles, Crypto, The Federalist Papers.</p><h4>10.4 Tips &amp; Productivity Tricks</h4><p>Surround yourself with good people who are insanely mission-driven, relentless, organized, communicative, and poised.</p><p><strong>Communication:</strong> gmail snooze + multiple inbox. Pinned twitter lists, filter, unsubscribe, report negative messages when you can.</p><p><strong>Meetings:</strong> limit meetings to ≤20% time.</p><p><strong>Mind, Body, Soul:</strong> Books before bed rather than mindless scrolling. Stay fit. Headspace.</p><h4>10.5 Life Advice</h4><p>No one knows what they are doing. But if you can: get married, have kids, move to the burbs (eventually). Your kids will give you valuable perspective at the end of the day, no matter how bad it seemed.</p><p>Value your time, not your money.</p><h4>10.6 Disclaimers</h4><p>Read this yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e2cde06794c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Critique of Becoming a Senior Engineer, I & II]]></title>
            <link>https://medium.com/@swayne275/critique-of-becoming-a-senior-engineer-i-ii-ab19ddceeba4?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab19ddceeba4</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 22:10:06 GMT</pubDate>
            <atom:updated>2023-01-27T22:10:06.027Z</atom:updated>
            <content:encoded><![CDATA[<p>The robots are coming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twJHQdUNVO6N9l0hmI_aZA.jpeg" /></figure><h3><a href="https://medium.com/@swayne275/843ac8bcd3f8">Jasper’s Take</a></h3><p>This was the third prompt. I selected the following options within One-Shot Blog Post:</p><p><strong>Blog Topic</strong>: “Becoming a senior software engineer”</p><p><strong>Tone of voice</strong>: “colloquial and witty”</p><p><strong>Intended Audience</strong>: “engineers”</p><p>Overall, I think it captured a lot of the general points, but only went skin deep. For soft skills it mentioned communication, but didn’t touch on getting alignment between stakeholders, team leadership, or managing up. It mentioned problem solving skills under “time management &amp; planning” which seemed odd since that is more of a “hard skill”, given the context. It also made some grammar errors such as “team rely” rather than “team <strong><em>to</em></strong> rely” in “The ability for others within your organization or team rely on you”.</p><p>All that said, I think it did a pretty good job of assisting me as a writer. I would use the output as a template or outline for the article that I <em>actually</em> want to write, rather than as a rough draft. Jasper seems to be an excellent general-purpose blog post tool, especially given I spent about 15 minutes setting up my account, tweaking the inputs, and reading the output.</p><p>Getting started on a blog post is often the hardest part, and Jasper let me jump right in.</p><h3><a href="https://medium.com/@swayne275/what-it-takes-to-become-a-senior-software-engineer-591bdacb6c75">ChatGPT’s Take</a></h3><p>This was the first take, and I provided the following prompt:</p><p><strong>Prompt</strong>: “write a blog on becoming a senior software engineer using a colloquial and witty tone. the audience is other engineers”</p><p>Overall, I really enjoyed reading this version. It captured a lot of general points, but it also had <em>personality</em> (or <em>robotality? </em>what do we want to call this?). It almost read like <a href="https://www.youtube.com/watch?v=fk8uE3blKco">this HP commercial</a> and has a distinctive tone.</p><p>As for content, I think a lot of the bases were covered. It mentioned the technicals but it also got into the intangibles — an engineer’s attitude and willingness to take risks. It called out being a mentor, and the feedback cycle. Nothing ChatGPT wrote really seemed <em>off</em>, if that makes sense.</p><h3>How they compare</h3><p>If I could only use one tool, it’d be ChatGPT. Not only is it (currently) free, but I think it did a better job of capturing the essence of becoming a senior software engineer. I think Jasper’s take read a bit more like a checklist or spec sheet. It called out things that ChatGPT missed, such as time management and communicating up and down the chain of command, but it didn’t feel like it took me on as much of a journey. I don’t speak (write) for everyone, but the ChatGPT article seemed a bit more <em>human</em>.</p><p>That said, in an ideal world I’d be using both as a starting point, and creatively combining information and themes from each. I’ve also only spent a few minutes with each tool, and I’m sure I could condition each tool to yield different results with a bit of practice.</p><h3>Wrapping Up</h3><p>This whole project took maybe 1 hour, tops. And that’s great! Both tools were able to write reasonable pieces on the basics of becoming a senior software engineer with little user education required.</p><p>I wouldn’t say either technology is <em>scary</em> good at this, just like I wouldn’t describe a hammer as scary good at putting in nails. This is just that — another tool that we humans can add to our tool belt and weild as needed, when appropriate. I think this can help remove a lot of writers block, particularly around outlining the topics that will make their way into the final work. It’s also a great way to quickly get up to speed on a particular topic (just don’t trust everything you read).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab19ddceeba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What it takes to Become a Senior Software Engineer]]></title>
            <link>https://medium.com/@swayne275/what-it-takes-to-become-a-senior-software-engineer-591bdacb6c75?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/591bdacb6c75</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[soft-skills]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 21:50:54 GMT</pubDate>
            <atom:updated>2023-01-27T22:10:29.722Z</atom:updated>
            <content:encoded><![CDATA[<p>Becoming a Senior Software Engineer, Take II</p><p>So, you want to be a senior software engineer, eh? Well, buckle up buttercup, because it ain’t gonna be easy. But, fear not, I’m here to guide you through the journey to becoming a top-notch coder.</p><p>First things first, you gotta have the skills. And I’m not talking about just any old skills, I’m talking about the skills that make a senior engineer stand out from the rest of the pack. You need to be a master of your craft, a true wizard of code. That means you need to be proficient in multiple programming languages, know your way around a variety of frameworks and libraries, and have a deep understanding of computer science concepts.</p><p>But, having the skills is only half the battle. The other half is attitude. You see, a senior engineer isn’t just someone who can write good code, they’re also a leader, a mentor, and a problem solver. You need to have the ability to communicate your ideas effectively, work well in a team, and have the drive to continuously improve and learn.</p><p>So, how do you acquire these skills and attitude? Well, the most important thing is to never stop learning. Read books, articles, and blogs on the latest technologies and trends. Attend meetups and conferences. And most importantly, practice, practice, practice. The more you code, the better you’ll get.</p><p>Another important thing to keep in mind is to be open to feedback and criticism. As a senior engineer, you’ll be working with a lot of different people, and it’s essential to be able to take constructive criticism and use it to improve your skills.</p><p>Finally, don’t be afraid to take risks and try new things. Senior engineers are often called upon to lead projects, and that means taking charge and making decisions. It’s important to be willing to step out of your comfort zone and try new things.</p><p>So, there you have it, folks. If you want to become a senior software engineer, it’s all about skills, attitude, and a never-ending desire to learn and improve. Happy coding!</p><p>Note that all of the above was written by <a href="https://chat.openai.com/auth/login">ChatGPT</a>— you find find the <a href="https://www.jasper.ai/">Jasper.ai</a> rendition <a href="https://medium.com/@swayne275/843ac8bcd3f8">here</a>, along with a wrap-up and <a href="https://medium.com/@swayne275/critique-of-becoming-a-senior-engineer-i-ii-ab19ddceeba4">comparison</a>! There is no art for this work because ChatGPT is unable to generate art at the time of this writing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=591bdacb6c75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What It Takes to Be a Senior Software Engineer]]></title>
            <link>https://medium.com/@swayne275/what-it-takes-to-be-a-senior-software-engineer-843ac8bcd3f8?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/843ac8bcd3f8</guid>
            <category><![CDATA[soft-skills]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Fri, 13 Jan 2023 17:47:20 GMT</pubDate>
            <atom:updated>2023-01-27T22:11:01.171Z</atom:updated>
            <content:encoded><![CDATA[<h3>What It Takes to Become a Senior Software Engineer</h3><p>Becoming a Senior Software Engineer, Take I</p><p>Thinking of taking the plunge and becoming a senior software engineer? It’s an exciting journey that takes dedication, willingness to learn and grow, and a bit of luck. But it’s worth it! With all the knowledge you’ll gain along the way, you can make tangible contributions to your team or company and be a valued mentor for other engineers. Let’s explore what it takes to be a senior software engineer.</p><h3>Developing Soft Skills</h3><p>Though you may have all the technical know-how necessary for coding and developing software applications, don’t forget about the softer skills too! As a senior engineer, you will need to be able to effectively communicate with other developers, managers, and stakeholders in order to ensure your projects succeed. Being able to articulate complex ideas in an organized manner is key to building trust with your colleagues. You should also be able to motivate others on your team and provide them with feedback in order to foster an environment of growth.</p><h3>Time Management &amp; Planning</h3><p>Time management skills are paramount when it comes to becoming a successful senior engineer. You must be able to organize both yourself and your team in order to meet deadlines efficiently. This includes being able to plan out tasks ahead of time so that everyone knows their roles throughout the project timeline. Additionally, having solid problem-solving skills is essential for working through any potential hiccups that come up during the development process.</p><h3>Reliability &amp; Consistency</h3><p>As a senior software engineer, people will look up to you as an authority on software development best practices and processes. Therefore, it is important for you remain consistent in how you approach tasks as well as being dependable when needed most. This means having reliable solutions that can handle anything from minor tweaks in code quality or major changes due unforeseen circumstances down the line. The ability for others within your organization or team rely on you is key when trying maintain high performance levels consistently over time.</p><h3>Wrapping Up</h3><p>Becoming a senior software engineer isn’t easy — but it’s achievable! With enough dedication and hard work, anybody can become one if they have the right mindset and skillset required for success in this field. Developing soft skills such as communication abilities; honing strong time management abilities; cultivating reliability &amp; consistency; all these things are necessary steps towards becoming great at what you do! Good luck!</p><p>Note that all of the above was written by <a href="https://www.jasper.ai/">Jasper.ai</a> — there is a <a href="https://medium.com/@swayne275/what-it-takes-to-become-a-senior-software-engineer-591bdacb6c75">ChatGPT rendition</a>, along with a wrap-up and <a href="https://medium.com/@swayne275/critique-of-becoming-a-senior-engineer-i-ii-ab19ddceeba4">comparison</a>! There is no art for this work because Jasper’s art generator was not available for free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=843ac8bcd3f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Testing a Worker Pool in Go]]></title>
            <link>https://medium.com/better-programming/building-and-testing-a-worker-pool-in-go-bce4c6da4431?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bce4c6da4431</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 17:13:14 GMT</pubDate>
            <atom:updated>2022-11-29T17:13:14.178Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing a concurrency pattern to process tasks using Go</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDBsywRXPkVh91z8VQT7Cw.jpeg" /></figure><h3>Worker Pool Basics</h3><p>A worker pool (also known as a <a href="https://en.wikipedia.org/wiki/Thread_pool">thread pool</a>) is a software design pattern where a set of workers (the “pool”) are created to concurrently process from a queue of tasks.</p><p>In some languages, each worker is a thread (hence the name “thread pool”), but in Go, we have <a href="https://go.dev/tour/concurrency/1">goroutines</a> — lightweight threads managed by the Go runtime that enable concurrent programming.</p><p>There is a queuing system to deliver tasks to workers, and logic for workers to acquire tasks. Often, the queuing system will be a <a href="https://go.dev/tour/concurrency/2">channel</a>, and the idle workers will take tasks on a first-come-first-serve basis.</p><h4>Advantages</h4><p>There are a number of advantages to the worker pool pattern. The first is simplicity and developer experience. By placing the concurrent tool in a package behind an API, developers don’t need to think about the nitty-gritty of properly closing channels, avoiding worker starvation, signaling, synchronization, etc. They just know “I need to process these tasks, and here are a few function calls that help me do it!”.</p><p>Worker pools can also be useful for performance. By using a defined set of workers (rather than spinning off a goroutine for each task), we can limit how many things we’re fanning out to. Many systems have bottlenecks at various levels (whether it be number of network requests, in-flight storage requests, processing speed in other parts of the system, etc), and a worker pool allows us to concurrently process jobs while applying controllable backpressure to avoid over-consuming resources down the line.</p><p>Further, for long-running processing jobs (say, handling incoming API requests) a worker pool avoids the overhead of creating new workers and tearing them down for each job. In Go that process is a little less expensive as goroutines are so light, but in general it’s good to be aware of overhead when using resources.</p><h4>Tuning</h4><p>Worker pool size should be tuned to the specific application. Things to consider are:</p><ul><li>How many tasks are coming in?</li><li>How quickly can tasks come in? Are they bursty, or more steady-state?</li><li>What is down the line from me? How quickly can it handle the results of those tasks (if applicable)?</li><li>How much of my system resources am I willing to put towards processing these tasks? Should processing expand to the maximum the system can handle, or should I limit this to some fraction of the system?</li><li>Should the number of workers be dynamic? (we won’t be building this today)</li></ul><p>Often, the engineer has a reasonable estimate for how many workers they need (within an order of magnitude), and the system can be further tuned based on how it performs under representative integration tests, load tests, or the real world. By incorporating metrics or tracing, the engineer can really hone in on if the worker pool is over- or under-allocated. Perhaps we can explore this in more depth in a future post.</p><h3>Designing Our System</h3><p>Today we’ll be implementing a very simple (and reusable!) worker pool. Tasks will be defined as an interface (the worker pool doesn’t need to care what it’s processing, only how to do it), and idle workers will wait on a channel for additional work. We’ll also need a way to create, start, stop, and add work to the worker pool. We’ll create an interface for this too.</p><p>Below you can see the basic algorithm of how work is sent to the pool and pulled from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v9znVKY3FnBKGk5HkoSSNw.jpeg" /><figcaption>Simple worker pool diagram. The calling code generates Tasks, which are placed in a queue (channel in Go). Idle workers read from this queue and are assigned work as available.</figcaption></figure><p>We’ll start by defining the interface for our worker pool, and the tasks that it can process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e06be63c212487efcda388905814df5d/href">https://medium.com/media/e06be63c212487efcda388905814df5d/href</a></iframe><p>The worker pool really only needs to provide a way to start and stop processing, and a method for adding work to the queue.</p><p>Jobs need a way to run, Execute(), and a way to handle any errors resulting from the job, OnFailure(). With this interface, we leave calling code a lot of flexibility to define what happens without being too prescriptive.</p><p>Okay, now we need to implement something that meets the Pool interface. We’ll do that with SimplePool below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5aa217086dd5c87acb69fa7aba32553b/href">https://medium.com/media/5aa217086dd5c87acb69fa7aba32553b/href</a></iframe><p>The important thing here is that the worker pool has access to a channel from which to consume work (tasks), and it provides a channel (quit) to stop the workers when necessary. Some of the esoteric details include tracking how many workers the pool has and using a <a href="https://pkg.go.dev/sync#Once">Once</a> to ensure the pool can only be started or stopped a single time.</p><p>We’ll add a constructor to inform the calling code that we want to know how many workers are in the pool, and the size of the buffered channels. It will also set up some of the details internal to the implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc261d6c2a1cd43e00b99586308c147c/href">https://medium.com/media/fc261d6c2a1cd43e00b99586308c147c/href</a></iframe><p>Note here that we’ve defined a couple of custom errors — ErrNoWorkers and ErrNegativeChannelSize — this is a technique to make tests easier (which you can check out in workerpool/workerpool_test.go in the <a href="https://github.com/swayne275/go-work">project’s repo</a>).</p><p>Starting and stopping the pool informs the workers to start or stop processing work from the tasks channel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84b321479222c43fc739ab07a89ecfb4/href">https://medium.com/media/84b321479222c43fc739ab07a89ecfb4/href</a></iframe><p>AddWork() provides a method of adding a Task to the worker pool. For this implementation, we’ll have it blocked when the channel is full. As such, we use a select to free any blocked AddWork() goroutines when the worker pool is stopped:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ea293cdba05a66532e1c36ade449601/href">https://medium.com/media/1ea293cdba05a66532e1c36ade449601/href</a></iframe><p>Note that we could have chosen this to be non-blocking with a slight tweak — it’s sort of the dealer’s choice that this point (and could even be a requirement of the interface to include both!):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebab876da9a24ad2ac3c33178ec25760/href">https://medium.com/media/ebab876da9a24ad2ac3c33178ec25760/href</a></iframe><p>Now we’ll implement startWorkers , which will create and start numWorkers workers to read from the tasks channel and process the task:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e6bf65603188d0035f5dc80b61012b/href">https://medium.com/media/d7e6bf65603188d0035f5dc80b61012b/href</a></iframe><p>By using a select statement, an idle worker can wait for either new work on the tasks channel, or a signal that the worker pool is done from the quit channel.</p><p>If it gets something on the tasks channel it’ll perform whatever was defined as the task’s Execute() function, and upon error it’ll call the task’s OnFailure function to handle whatever went wrong.</p><p>Once a worker has finished processing a task, it’ll go back to waiting until there’s a new task, or until the worker pool is stopped.</p><h3>Testing the Package</h3><p>Automated testing is essential when developing code, especially for packages that might become dependencies for other projects. They can also be very helpful for the development process!</p><p>They allow time to pause and consider interfaces and implementations (I’ve changed things here as a result of the testing process), and they might help you find implementation bugs or interface inefficiencies well before they become a problem.</p><p>To that end, I’ve added workerpool/workerpool_test.go to run through a few use cases that should be exercised.</p><p>We’ll start by ensuring our constructor works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b6925623cb0965dbacf348bc5a584b3/href">https://medium.com/media/7b6925623cb0965dbacf348bc5a584b3/href</a></iframe><p>Here we’re mainly testing that the constructor catches common cases of bad input (e.g. negative channel size, 0 workers, etc), and that we actually get a Pool when the input is valid.</p><p>Next, we’ll test our Start() and Stop() implementations do the right thing when called multiple times:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6f3b009f58d34b419ca1c94703b00b0/href">https://medium.com/media/b6f3b009f58d34b419ca1c94703b00b0/href</a></iframe><p>Next, we want to make sure that the worker pool can actually process work. To do that we’ll create a testing implementation that meets our Task interface, and run some of those through the workerpool.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfc3761f3864f1251ef4cb8dd00bf365/href">https://medium.com/media/bfc3761f3864f1251ef4cb8dd00bf365/href</a></iframe><p>Our testTask implements Execute() and OnFailure() to satisfy the Task interface, but also adds tooling to test out Execute() returning an error, determine if we hit the failure case, and also inform the calling code when the task has been processed via a <a href="https://gobyexample.com/waitgroups">WaitGroup</a>.</p><p>As we can see here, sometimes it makes sense to build out specific test infrastructure when we’re trying to exercise code. Because the worker pool operates on interfaces (rather than concrete types), we can just build a new thing that implements that interface rather than trying to get really hacky with otherwise-production code!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a93cb6192ac7cbed817bb40bcb15a43/href">https://medium.com/media/3a93cb6192ac7cbed817bb40bcb15a43/href</a></iframe><p>Here we’re essentially making sure we can create a worker pool, add work to it, and that the work will be processed as intended. workerpool_test.go contains a similar function to validate the error-handling logic, but we’ll skip that here for brevity.</p><p>Finally, let’s make sure that anything waiting on AddWork will be freed if the worker pool is ever stopped (proper resource management is important!):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/041a792342d6fb3abb1766b1267088df/href">https://medium.com/media/041a792342d6fb3abb1766b1267088df/href</a></iframe><p>This test creates a worker pool and a bunch of goroutines to add work to it. There are more tasks than channel capacity, so some of the goroutines will be blocked waiting for tasks to be completed.</p><p>When the goroutines adding tasks are unblocked, they signal by calling Done() on line 18. This means that we can know when all goroutines are unblocked by waiting on the wait group, wg.</p><p>Waiting on this waitgroup will block, however, so we need a way to timeout. We’ll spin up a goroutine to wait until all task-adding goroutines are done, and then signal on a new channel, done. By signaling on this channel, we can use a select to wait for that done signal. Since, in a failure case, done would never happen we can potentially be waiting forever (or at least until our test times out).</p><p>To get around this, we can use a time.After which sends on a channel after the specified duration has passed. In this way, we can say <em>wait until either a second has passed, or all goroutines have completed</em>. In the case where we hit the timeout, we fail (since we still have goroutines waiting to AddWork after our worker pool has been stopped). If we receive a signal on done we’ll know that blocked goroutines have been completed, and the worker pool works as intended.</p><h3>Enhancements</h3><p>Worker pools can range from simple (much simpler than this!) to incredibly complex. Some common enhancements include:</p><ul><li>Adding metrics to get a sense of how long jobs are taking, how much idle time workers have, etc.</li><li>Add a job manager with fair sharing logic to ensure different <em>types</em> of tasks are processed fairly, for some definition of “fair”.</li><li>Add more logging.</li><li>Any additional logic specific to your application.</li></ul><p><em>Some of this can be seen </em><a href="https://github.com/hashicorp/vault/tree/main/helper/fairshare"><em>here</em></a><em> in a fairsharing worker pool that I designed and implemented to solve the most frequent Hashicorp Vault sev1!</em></p><h3>Wrapping Up</h3><p>Worker pools are an essential tool in your concurrency tool belt, and now we understand a bit about how they work. Today we’ve designed and built a reasonably simple (but reusable!) implementation, and figured out how to test it. We’ve thought about how calling code might use it (for example, AddWork() shouldn’t block after the pool has been stopped), and we have left opportunities to enhance it.</p><p>As always, I welcome any feedback and hope this has been helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bce4c6da4431" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/building-and-testing-a-worker-pool-in-go-bce4c6da4431">Building and Testing a Worker Pool in Go</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How and When to Use Context in Go]]></title>
            <link>https://medium.com/better-programming/how-and-when-to-use-context-in-go-b365ddf42ae2?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b365ddf42ae2</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 20:41:13 GMT</pubDate>
            <atom:updated>2022-09-15T20:41:13.999Z</atom:updated>
            <content:encoded><![CDATA[<h3>How and When To Use Context in Go</h3><h4>With a focus on concurrency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCL0eTUe9jVVRFUVKmV5mw.jpeg" /><figcaption>image by author</figcaption></figure><p>When developing code for a concurrent or client/server environment, we can often benefit from having context — information about the system that isn’t necessarily required to perform business logic. Go’s standard library provides an excellent <a href="https://pkg.go.dev/context">context package</a> that includes a number of utilities that can pass this information to functions receiving them. These include the ability to:</p><ul><li>know that the operation has been cancelled</li><li>cancel if an operation isn’t completed by a certain time</li><li>timeout if the operation runs too long</li><li>pass generic data in the form of key/value storage</li></ul><p>We’ll dig into each one and their common use cases below.</p><h3>Empty Context</h3><p>Contexts allow applications to gather additional information about their environments, which they can pass to functions they call. Sometimes a context needs to be created from scratch, or the application developer knows it will be needed but does not yet know where that context will come from or how to generate it.</p><h4>Background context</h4><p>In the first of these cases, an empty context can be created with:</p><p>ctx := context.Background()</p><p>This will generate an empty context that can be passed around and extended with cancel functions, timeouts/deadlines, or values (see the next sections). This context is never cancelled and has no deadline or associated values. Typically this is used for the top-level context or tests.</p><h4>TODO Context</h4><p>Similarly, we can derive a TODO context with the following:</p><p>ctx := context.TODO()</p><p>This returns an empty context that is never cancelled and has no deadline or associated values. This context is used when it’s unclear which context to use, or the function expects a context to be passed in that is not yet available. It is essentially providing a means to compile and pass information around but marking that context as incomplete (similar to a // TODO comment).</p><p>You can see how both can be generated and used in a (somewhat useless) example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a88b2dac92b7037f6b87e8ef6e4c0a1a/href">https://medium.com/media/a88b2dac92b7037f6b87e8ef6e4c0a1a/href</a></iframe><h3>Cancelable Context</h3><p>Cancelation is the most straightforward way of ending a computation path that relies on a context — it allows the calling code to signal to anything downstream that the computation is no longer needed. It is time to clean up resources and exit. This can be useful when processing long-running requests (e.g., stop processing if a client disconnects from a server), and it is a common way of cleanly shutting down an application — when the app receives a stop signal (such as a SIGTERM) it can cancel the top-level context, and anything derived from that context will know to clean up and cease activities.</p><p>We generate contexts with cancel as follows:</p><p>ctx, cancelFunc := WithCancel(parent Context)</p><p>This returns a copy of parent with a new Done channel, along with a cancellation function. When cancelFunc is called, the Done channel on ctx is closed, signaling anything downstream to clean up and cease all activities. Done is also closed if parent is cancellable and has been cancelled.</p><p>In the following example, we generate a cancellable context and check if it’s been cancelled by checking the done channel via Done():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ab397461731106644b1b173bc090b54/href">https://medium.com/media/1ab397461731106644b1b173bc090b54/href</a></iframe><p>When we run the above code, we can see the output as:</p><pre>background long running task launched<br>background long running task still going<br>going to cancel background task<br>long running task bailed because context cancelled<br>some time has elapsed after cancelling</pre><pre>Program exited.</pre><p>If you’d like to experiment with it yourself, you can copy/paste this example (or anything that follows it) into <a href="https://go.dev/play/">Go playground</a>.</p><h3>Context With Deadline</h3><p>Contexts with deadlines are often used when making requests to an external resource that the caller may not know or control the state of, such as a database or API. They say, “I want something to happen at or by a certain time, or else bail.” The Context’s Done channel will close when the deadline expires, signifying to any downstream code that they should stop doing what they are doing.</p><p>These take the form of</p><p>ctx, cancelFunc := WithDeadline(parent Context, deadline time.Time)</p><p>where parent is the context this is based on, and deadline is the time you want the thing to happen. Note that if parent has a deadline that is earlier than deadline. This context will have the same deadline as parent.</p><p>The following example shows how it might be used to end a long-running task:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cab3159b9fa9c4c01ad89963848905f3/href">https://medium.com/media/cab3159b9fa9c4c01ad89963848905f3/href</a></iframe><p>Here, we wrote a function that takes a context and a value for how long to wait. It will return in either case, but print whether it exited due to the context deadline passing or the wait time elapsed. We can see that we will return because the context expired in the first case, and in the second case, we will return well before the context expires. We get the following output:</p><pre>bailed because context deadline passed<br>completed before context deadline passed</pre><pre>Program exited.</pre><p>longRunningTask() also demonstrates a simple case of how code that accepts a context can handle a cancelled context using a select on various channels.</p><h3>Context With Timeout</h3><p>Contexts with timeouts are a convenient feature similar to contexts with deadlines. They are called like this:</p><p>ctx, cancelFunc := WithTimeout(parent Context, dur time.Duration)</p><p>Under the hood, they are calling:</p><p>WithDeadline(parent, time.Now().Add(timeout))</p><p>But hey, we’ll take any simplification we can get!</p><p>Essentially, when we pass a context with a timeout, we say we are willing to wait until the timeout amount of time has passed, and if the call is not complete, it should wrap up and bail out. This reduces the chance that our code might get infinitely (for some value of “infinite”) hung up waiting for some call to complete rather than error out and keep doing its job.</p><p>The following example shows how this might be used to end a long-running task:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7d8f912ab8bf5f4d472f05838ce663f/href">https://medium.com/media/a7d8f912ab8bf5f4d472f05838ce663f/href</a></iframe><p>We get the following output:</p><pre>bailed because context timed out<br>completed before context timed out</pre><pre>Program exited.</pre><p>We can see how similar this is to the above deadline example. When picking between a WithDeadline and a WithTimeout, simply choose the one that fits whatever the calling code has better. If you want it to happen by a certain time, choose deadline! If you want it to happen within a certain duration, choose timeout!</p><h3>Context With Value(s)</h3><p>Contexts also enable request-scoped values to be passed around. To attach a key/value pair to a context, call:</p><p>ctx := WithValue(parent Context, key, val any)</p><p>This returns a copy of parent where the value associated with key is val.</p><p>The provided key must be comparable and should not be a built-in type (such as a string or int) to avoid collisions between different packages using the context. If multiple packages use the same key type with the same value, they can collide when trying to set/get val. Instead, key should be defined as its own properly-scoped type for setting and getting val. That way, even if multiple scopes define a key with the same underlying value, they will not collide within the context. The following example illustrates this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1e0a41ae21b36905a5951434df6049f/href">https://medium.com/media/c1e0a41ae21b36905a5951434df6049f/href</a></iframe><p>Here we define a key type (keyType1) that is scoped to main(). It is constructed with the value &quot;foo&quot;. We now assign the key/value pair &quot;foo&quot;=&quot;bar&quot; within a context. If we try to retrieve a key of type keyType1 (with value &quot;foo&quot;) we get back &quot;bar&quot;, as expected.</p><p>Now, we can define a new function with its own key type. If we assign the same key value to that new key type (&quot;foo&quot;), we can try to get the value from the context:</p><pre>found a value for key type 1: bar<br>no value for key type 2</pre><pre>Program exited.</pre><p>As we can see, since we don’t have access to the proper key <em>type</em>, we cannot access the value, even if the underlying value for the key is the same. Note that we could have also assigned a new value within tryAnotherKeyType() , and it would not be accessible in main() due to the same key type mismatch we’ve discussed thus far. This is how we avoid key/value collisions between packages (or any unit of scope).</p><p>This tool should be used for passing request-scoped data between processes and APIs, not merely for optional function parameters, as this can obfuscate the code. Also, note that the values in the context must be threadsafe — that is, they might be used concurrently by multiple goroutines.</p><h3>Derived Contexts</h3><p>We’ve alluded to it previously in this article, but derived contexts can be very useful. The summary is that child contexts are governed by their parents — they cannot have a longer timeout/deadline than their parents, and they cannot cancel their parents. They also inherit any values stored in their parents. Parents, however, can cancel their children.</p><p>We often use derived contexts as code splits into branches with different lifetimes and functions. For example, we might have one main context that governs the lifetime of our overall application, but a derived context to govern an API request, and perhaps yet another context derived from that to govern a storage call required to handle the request.</p><p>This way, we can choose to end the entire application (by cancelling the main context), the request processing (by cancelling the first derived context), or the storage call (by cancelling the second derived context).</p><h3>Wrapping Up</h3><p>Note that with all of the above, it is best practice to call a context’s CancelFunc when it is no longer needed to free up resources (if it’s a context that includes a cancel function). In the examples above, I generally disregarded the cancel function for simplicity, but it’s important to be efficient with resources for long-running applications. Contexts are generally passed as the first function parameter, so keep that in mind when developing your own context-consuming code!</p><p>Hopefully, this has served as a springboard to learning more about contexts in Go and improving your application development skills. It should start to make more sense now when you see functions that accept contexts (such as calling into a database or API), and you can start to get a sense of how you, as a client, can use contexts to make your own code more predictable and performant.</p><p>We’ve covered the main mechanics of the various context utilities in Go and discussed when and how they might be used. You can leverage this tool in many ways, so treat this as more of a starting bell than a finish line.</p><p><em>Thanks for reading! Stay tuned for more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b365ddf42ae2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-and-when-to-use-context-in-go-b365ddf42ae2">How and When to Use Context in Go</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP/3 Explained]]></title>
            <link>https://medium.com/better-programming/http-3-explained-4bc4e7d31c26?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bc4e7d31c26</guid>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Tue, 30 Aug 2022 14:14:19 GMT</pubDate>
            <atom:updated>2022-08-30T14:14:19.925Z</atom:updated>
            <content:encoded><![CDATA[<h4>What it is, how it’s different, and where it’s going</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uulT6fl_iA8cw1_3QjRpg.jpeg" /></figure><p>Today we’ll be learning about HTTP/3 — where we came from, how it’s different from previous protocols, and where it’s going. I learned most of this information from an <a href="https://www.youtube.com/watch?v=ai8cf0hZ9cQ">excellent talk</a> given by Daniel Stenberg, the inventor of curl. This <a href="https://www.youtube.com/watch?v=ai8cf0hZ9cQ">High-Performance Programming video</a> updated my knowledge on some more recent HTTP/3 stuff.</p><p>The main takeaway is that HTTP/3 operates over a new transport layer (QUIC) and, as a result, improves on legacy HTTP in a few fundamental ways. It is meant to be faster, more secure, and more reliable.</p><h3>Where Did It Come From?</h3><p>Before we can discuss how HTTP/3 improves on prior versions, we should understand the history of the protocol.</p><p>The original HTTP came out in 1991 without a version (it is now referred to as HTTP/0.9). It was quite simple — there were no headers, responses were a single HTML file, and the only method was GET.</p><p>HTTP/1.0 came out in 1996 to make the protocol more extensible. It brought versioning information, status codes, and headers for transmitting metadata. It also expanded beyond simple HTML file returns by adding the Content-Type header we all know and love today.</p><p>HTTP/1.0 left something to be desired, however. Each request/response between a client and server requires a unique TCP connection, which can add significant latency to page loads, especially when multiple resources are required.</p><p>Clients got around this by using multiple TCP connections in parallel, but this was resource intensive. Each connection still had significant latency from having to TLS handshake between client and server.</p><p>HTTP/1.1 came out the next year with the ability to use many parallel TCP connections. Connections could also be reused (avoiding the overhead of having to close and reopen those connections in HTTP/1.0 continually), and pipelining and chunking were added to boost performance further.</p><p>However, this came with a head-of-line (HOL) blocking flavor. As websites got more complex, clients quickly ran out of available TCP connections. As a result, new request/response cycles had to wait for an existing request to complete before it could use the connection.</p><p>HTTP/2 came out in 2015 to improve performance. It switched from transmitting text to sending binary and introduced the concept of streams to improve parallel request performance. By multiplexing a single TCP connection, clients could send many parallel requests without running out of connections and facing the HOL blocking from HTTP/1.1. HOL blocking was still a problem, however. It had just moved from the application layer to the transport layer.</p><p>The protocol will re-send the packets with missing data if data is lost over TCP. As a result, other data (read: other streams) on the TCP connection must wait for these packets to be successfully delivered. Since streams are multiplexed over a single TCP connection, if one stream loses data, all streams must pause and wait for that data to be re-transmitted. Over a lossy network, this can cause real problems.</p><h3>Why Do We Want To Upgrade?</h3><p>HTTP/2 has generally served us well, but it suffers from head-of-line blocking and has a fair amount of overhead due to the HTTPS TLS handshake. This leads to latency or the feeling that a website is not very responsive. As more software moves to the web, it becomes increasingly important to deliver a responsive, fast, almost native-application-like experience to the user.</p><p>Further, these problems are exacerbated anywhere with lossy networks or large distances between client and server. Lossy networks will lose more data, requiring more packet redelivery, intensifying the HOL problem. Long communication hops delay the back-and-forth handshakes that HTTPS requires.</p><p>On top of this, we’re human. We have an insatiable need to build and improve and advance.</p><h3>What Does HTTP/3 Do Differently?</h3><p>HTTP/3 swaps out TCP/TLS as the transport layer and replaces it with QUIC (“Quick UDP Internet Connections”). QUIC gives us streams “for free” (it’s part of the transport layer, not the application layer), and it allows us to build any protocol on top (HTTP is the first example). The HTTP request/response flow is generally the same, but the transport over the wire differs. It is binary over multiplexed QUIC (built on top of UDP), whereas previously, we had binary multiplexed over TCP.</p><p>It also makes HTTP/3 much faster! Handshakes are significantly quicker, and clients can start sending requests and receiving responses faster than they could previously. This significantly cuts down startup latency and makes the webpage feel more responsive. Encryption and authentication are provided by default, and establishing a connection takes one round trip instead of multiple.</p><p>Since HTTP/3 is now “binary over multiplexed QUIC,” the streams are independent of each other. This largely alleviates the head-of-line blocking problem, as an individual stream cannot delay other streams if it suffers packet loss. If a stream loses data, the lost packet will be recovered only in that stream. QUIC can do this since it’s built on top of UDP, which does not force packet re-delivery at the protocol layer.</p><p>As a result, QUIC can be smarter about how and when it chooses to resend data. This also allows for future improvements, such as lossy and non-lossy independent streams on the same connection!</p><p>This combines solid performance improvements under ideal network conditions and massive improvements in compromised situations. The <a href="https://requestmetrics.com/web-performance/http3-is-fast">following benchmarks</a> show how the performance improvements currently scale with website size/complexity and client/server distance.</p><p>Tests were done with a small site (“small”), a content-heavy site (“medium”), and a single-page application (“large”) (more details in the link above). They were done over three distances: “short” being New York to Minnesota, “medium” being New York to London, England, and “long” being New York to Bangalore, India. Below are the speed improvements seen from moving from HTTP/2 -&gt; HTTP/3:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16ca352c0c649803f7c720a84c717a29/href">https://medium.com/media/16ca352c0c649803f7c720a84c717a29/href</a></iframe><p>As client/server distance increases, the speed bumps can get pretty mega. We can also see that content-heavy sites (arguably more representative of the modern web than “small”) benefit the most.</p><h3>Challenges With HTTP/3</h3><p>HTTP/3 doesn’t come without its challenges, which we will briefly discuss here. Note that some of these may have been resolved as this information primarily comes from Daniel’s 2019 talk.</p><h4>Some amount of QUIC requests fail</h4><p>This is largely from various entities blocking UDP traffic. Since QUIC uses UDP under the hood, it can look like a denial-of-service (DOS) attack, which many network administrators block. This will likely be worse on hyper-vigilant enterprise networks to avoid DDOS (distributed DOS) attacks.</p><h4>Clients must be able to fall back on previous HTTP versions</h4><p>QUIC denial will likely be location-based — it may not be a problem at home, but the local coffee shop might block UDP traffic. As a result, clients must be able to fall back on older HTTP versions to communicate successfully.</p><h4>HTTP/3 is CPU intensive</h4><p>As of 2019, HTTP/3 will consume 2–3x CPU to serve the same amount of traffic as previous protocols. This is partly because networking libraries are less optimized for UDP (they’ve had decades to tune for TCP finely) and partly due to a lack of dedicated hardware (think ASICs).</p><h4>UDP stacks are unoptimized</h4><p>This is partly responsible for the aforementioned increased CPU utilization. No one has optimized software and hardware stacks for UDP with the same intensity that they have for TCP. This will improve over time!</p><h4>“Funny” TLS layer</h4><p>We need all relevant TLS libraries to update to support the new standard and new API. This has likely made significant progress since 2019 but is not an easy task.</p><h4>All QUIC stacks are user land</h4><p>QUIC is built on UDP, which means all packets are copied to user space. This increased copying comes with increased resource utilization. Perhaps it could be integrated into the kernel (read: multiple kernels, everywhere), but that could be very difficult.</p><h3>Lack of tooling</h3><p>Wireshark has this down pat, but we need other tools as well. We’ve gotten used to segment numbers and specific window sizes, all replaced by QUIC mechanics.</p><h3>So, Where Are We Today?</h3><p>According to <a href="https://caniuse.com/http3">caniuse</a>, Firefox, Edge, and Chrome all support HTTP/3 by default. Safari doesn’t yet, but it can be enabled in the experimental features. Likewise, various browsers support it by default on Android, and it’s behind a feature flag on iOS. Currently, <a href="https://w3techs.com/technologies/details/ce-http3">about a quarter of websites support HTTP/3</a>, and we can see that trending up.</p><p>HTTP/3 is already making real-world, human-noticeable differences, which will likely improve as UDP stacks are optimized. It brings performance, reliability, and security upgrades but is not without challenges. It’s still early days, but I’m excited for a more secure, performant internet that is more resilient to lossy networks. I’m also excited to see where QUIC goes and the future applications that will be built on top of it.</p><p><em>Thanks for reading. Stay tuned for more!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bc4e7d31c26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/http-3-explained-4bc4e7d31c26">HTTP/3 Explained</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking Command Line Tools Against a Custom Go Line Remover]]></title>
            <link>https://medium.com/better-programming/benchmarking-command-line-tools-7d00ed4813cc?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d00ed4813cc</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Tue, 23 Aug 2022 14:17:17 GMT</pubDate>
            <atom:updated>2022-08-25T06:05:08.501Z</atom:updated>
            <content:encoded><![CDATA[<h4>Testing a text filterer built in Go against the tried and true grep</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGTegLiM1vnbN1OKypOYGw.jpeg" /></figure><p>In this fourth (and final) part of our series, we’ll cover benchmarking our custom Go line remover against an equivalent command in grep. You can find the other parts below:</p><ul><li><a href="https://betterprogramming.pub/how-to-build-a-text-filtering-log-simplifying-tool-in-go-b29d3067e092">Part 1: Building a Text Filtering Tool in Go</a></li><li><a href="https://medium.com/@gourikabang1996/part-2-how-to-prepare-for-your-next-coding-interview-d048b188301e">Part 2: Adding Regular Expression Support</a></li><li><a href="https://betterprogramming.pub/benchmarking-in-go-substrings-vs-regular-expressions-a84de7f0eb02">Part 3: Benchmarking a Program in Go</a></li></ul><p>In the previous three segments we’ve built a tool in Go that can remove matching lines from a file. Then we added regular expression support, and finally compared the performance of the two approaches using built-in Go benchmark testing. Now, we’d like to measure its performance against inverse string matching ( -v or --invert-match) in grep.</p><p>We’ll be using <a href="https://formulae.brew.sh/formula/hyperfine">hyperfine</a> to benchmark, as it’s a highly ranked tool that’s also available via Homebrew for my machine (a MacBook with Apple Silicon). There are various other tools available (such as <a href="https://formulae.brew.sh/formula/bench">bench</a>) that might better fit your needs and architecture.</p><p>We’ll be comparing the same three test cases that we looked at in Part 3 (described below), but with a significantly larger input text to see how the tools perform with more work to do.</p><h3>The setup</h3><p>A fair comparison requires a good setup. To that end, we’ll be benchmarking the Go tool against grep doing three things:</p><ul><li>loading a file into grep</li><li>doing the inverse matching in grep</li><li>writing the results of that inverse match to a file</li></ul><p>We’re using the following version of grep:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffd13e868b7371773ff499f053eed716/href">https://medium.com/media/ffd13e868b7371773ff499f053eed716/href</a></iframe><p>Grep commands will be of the following format:</p><p>grep &quot;&lt;pattern&gt;&quot; &lt;filepath&gt; &gt; &lt;output filepath&gt;</p><p>Lineremover commands will be of the following format:</p><p>./lineremover -file=&quot;path/to/file&quot; -keys=&quot;keys if testing substring search&quot; -pattern=&quot;pattern if testing regular expression search&quot;</p><p>And we can run the benchmarks as:</p><p>hyperfine &#39;&lt;command to benchmark&gt;&#39; --min-runs=10000</p><p>Where &#39;&lt;command to benchmark&gt;&#39; will be running either grep or lineremover as above. To keep things consistent and ensure we have enough data to extrapolate from, we’ll be using hyperfine’s --min-runs option to ensure each test is performed at least 10,000 times. We also need to be conscious of what is running on the machine performing the benchmarks — if it is slowed down during one test relative to another, the benchmark could show that. With that in mind, we’ll keep the machine in the same state across tests as much as possible, with minimal background processes running.</p><p>We’ll be testing against example/inputlong.txt from the <a href="https://github.com/swayne275/lineremover">lineremover repo</a>. This file is essentially the same as example/input.txt, but repeated 2048 times so that program start/stop time will have less impact on our benchmark results relative to the actual string search work.</p><h3>Running the benchmarks</h3><h4>Benchmark matching “hello”</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67a4b03bf194d569c229947a31494c0e/href">https://medium.com/media/67a4b03bf194d569c229947a31494c0e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce4560b7f99423f8e13debbe7e91eabb/href">https://medium.com/media/ce4560b7f99423f8e13debbe7e91eabb/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27998e0e941b6fd96fd0155a2f680d85/href">https://medium.com/media/27998e0e941b6fd96fd0155a2f680d85/href</a></iframe><p>Note that for grep we told hyperfine to ignore errors ( -i) since grep gives a non-zero exit code in the event of no match (which is expected for this test).</p><p>So we can see that grep is quite a bit faster in this test — that’s sort of the expected outcome given it’s a standard in this space and <a href="https://www.google.com/search?client=safari&amp;rls=en&amp;q=when+was+grep+invented&amp;ie=UTF-8&amp;oe=UTF-8">has been out since 1974</a>. Within the lineremovertool, we can see that pattern matching is a bit slower than substring search as well. There’s also quite a bit of variation between runs.</p><h4>Benchmark matching “big”</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f210a9431346d74761a1991212acd6ba/href">https://medium.com/media/f210a9431346d74761a1991212acd6ba/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84889d3ed563990cd6bed63020792df1/href">https://medium.com/media/84889d3ed563990cd6bed63020792df1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ba6295776c2c086964aeb2fa76caab2/href">https://medium.com/media/9ba6295776c2c086964aeb2fa76caab2/href</a></iframe><p>Here, we see that grep is the slowest of the bunch — not what I was expecting! We can also see that pattern match is slightly faster than substring search, but it’s likely not significant and has slightly more variation.</p><h4>Benchmark matching “big”, “brig”, “bight”, “bright”</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02cc10ac4e62d8599694f99995825ad6/href">https://medium.com/media/02cc10ac4e62d8599694f99995825ad6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c49e88aa64a416096f3c5ca8f5cbf176/href">https://medium.com/media/c49e88aa64a416096f3c5ca8f5cbf176/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7f29c5862c612bec5ccea5e6510f827/href">https://medium.com/media/c7f29c5862c612bec5ccea5e6510f827/href</a></iframe><p>As the query gets more complex, we can see that pattern matching slows down significantly compared to substring search. Here again we see that grep is significantly slower than lineremover in both pattern match and substring search modes. It also has way more variance. Again, an unexpected result!</p><h3>Wrapping up</h3><p>Today we learned the mechanics of benchmarking two command line tools against each other, and set up a few tests that might reasonably represent how these tools might be used in the real world. The real value work when benchmarking, however, is figuring out <em>what</em> to benchmark, not necessarily how to run the tests. What tests would give you confidence that some tool is faster <em>for your workload or use cas</em>e? That is the most important question to answer when designing a test. Only then do we design an environment to answer that question.</p><p>As far as this test goes, it was interesting! This was my first time using hyperfine, so that’s pretty cool. Within the tool, I was expecting pattern match to be slower than substring search, but was not expecting the Go tool we built to outperform grep under some search conditions. I’m not yet sure <em>why</em> grep was slower, but one guess is perhaps reading the input file and writing the output file are not as optimized as they were using buffered IO in Go? I also thought perhaps some OS stuff (like caching) might have been at play, but I ran the tests back to back and in various orders and got similar results each time. If you have ideas, please let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d00ed4813cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/benchmarking-command-line-tools-7d00ed4813cc">Benchmarking Command Line Tools Against a Custom Go Line Remover</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking in Go: Substrings vs. Regular Expressions]]></title>
            <link>https://medium.com/better-programming/benchmarking-in-go-substrings-vs-regular-expressions-a84de7f0eb02?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a84de7f0eb02</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 15:10:08 GMT</pubDate>
            <atom:updated>2022-08-26T16:57:39.276Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discussing the pros and cons of these text filtering strategies</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uogrQv6IDZ9xS4ED3QyqQ.png" /></figure><p>In this third part of a four-part series, we’ll cover benchmarking in Go using our text filtering tool as a test subject. You can find the other parts below:</p><ul><li><a href="https://betterprogramming.pub/how-to-build-a-text-filtering-log-simplifying-tool-in-go-b29d3067e092">Part 1: Building a Text Filtering Tool in Go</a></li><li><a href="https://medium.com/@gourikabang1996/part-2-how-to-prepare-for-your-next-coding-interview-d048b188301e">Part 2: Adding Regular Expression Support</a></li><li><a href="https://betterprogramming.pub/benchmarking-command-line-tools-7d00ed4813cc">Part 4: Command-line Benchmarking Against grep</a></li></ul><p>Previously, we <a href="https://betterprogramming.pub/how-to-build-a-text-filtering-log-simplifying-tool-in-go-b29d3067e092">built a Go program to remove unwanted text</a>, and we <a href="https://medium.com/@gourikabang1996/part-2-how-to-prepare-for-your-next-coding-interview-d048b188301e">extended it with regular expression support</a>. Now, we’ll learn about benchmarking in Go by comparing the initial substring search approach against the added regular expression pattern matching. Note that the methods used here are simple and intended to facilitate benchmarking discussions, not prove objectively that one method is strictly faster than another.</p><p>Go’s standard library <a href="https://pkg.go.dev/testing">testing package</a> provides extensive test support (you might have seen functions of the form TestXxx(t *testing.T)), as well as benchmarking support via <a href="https://pkg.go.dev/testing#B">Type B</a>. B facilitates managing benchmark timing, iterations, etc., as well as the typical utility functions to clean up, log, or fail a test.</p><p>Using these tools, we can garner insights on whether the tool runs faster (under these scenarios) using substring or pattern matching.</p><h3>Setting Up the Benchmarks</h3><p>Go benchmarks are functions that live in a &lt;filename&gt;_test.go file, where &lt;filename&gt; is typically the name of the file containing the functions to be tested. Both files are typically in the same package, and benchmark functions take the form of:</p><pre>func BenchmarkXxx(b *testing.B) { // benchmark code }</pre><p>When writing the benchmarks, we typically require some code-specific initial setup and then move to a loop that will run the code under test several times (<a href="https://pkg.go.dev/testing#hdr-Benchmarks">determined by the testing package</a>). In the end, we are told the number of loops that ran and how long it took (on average) to run each loop. From there, we can analyze code performance.</p><p>We will start by setting up a []stringwith a few lines of text — this will be common to substring and pattern match search. We then will build a config that contains either a set of keys or a pattern, and then we’ll run lineMatches()(in the benchmark loop) against the input text and look at how long each iteration takes. We’ll do this with varying amounts of keyphrases and pattern complexity (each built to match the same text) and compare the results.</p><h3>Building the Benchmarks</h3><p>Our benchmarks will be pretty simple: they’ll all use the same input text and generate a config with either a keys or a pattern. We’ll make congruent substring search and pattern matching benchmarks for each query type. Then, we just need to run the tests and compare the results.</p><p>We’ll use the following as our input test (same as in example/input.txt):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/741b78e81868faaec262a5b0e85dd44e/href">https://medium.com/media/741b78e81868faaec262a5b0e85dd44e/href</a></iframe><h4>Benchmark matching “hello” — this will match all lines in our input</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9f91830bc303e05223b185d3202a32c/href">https://medium.com/media/d9f91830bc303e05223b185d3202a32c/href</a></iframe><h4>Benchmark matching “big” — this will match two input lines</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/360bc6da2d41605cfc75eea1c7e5fb6f/href">https://medium.com/media/360bc6da2d41605cfc75eea1c7e5fb6f/href</a></iframe><h4>Benchmark matching “big,” “brig,” “bight,” and “bright” — this will match three input lines</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b91215eae723c1bccaa72dac6bda524/href">https://medium.com/media/3b91215eae723c1bccaa72dac6bda524/href</a></iframe><h3>Running the Benchmarks</h3><p>Finally, we can run all of our benchmarks by running this command:</p><p>go test -bench=.</p><p>in the root directory of the project repo, which yields the following results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/927842e974d12e2789ba9735e8898eb9/href">https://medium.com/media/927842e974d12e2789ba9735e8898eb9/href</a></iframe><p>The first column is the name of the benchmark. The second is how many loops were used (think: the value of b.N), and the third column is the average time it took to run a loop. In our case, each loop was searching through all of inputText for either the substring or pattern matches.</p><p>Note that the -10 appended to each test name indicates the number of CPU cores used for the test (10 in my case).</p><p>We can see that, given the above tests on an Apple Silicon Mac, substring search is anywhere between 3.55x and 83.74x faster than pattern matching as implemented.</p><h3>Wrapping up</h3><p>Does this mean we should always choose substring search? Not necessarily.</p><p>In software, we must select the right tool for the right job. Can you put a screw in with a hammer? Technically yes, but it’s far from ideal. If you can match the text you care about with one or a few substrings, this tool will likely be faster.</p><p>But, there are plenty of benefits to using regular expressions. They will generally translate well between tools and can answer more complex queries than substrings (without significant repetition). One might also consider how much real-world time the performance difference translates to. As we can see, this will depend on query complexity and the input size.</p><p>In many cases, the performance difference may not be significant (fractions of a second to less than a minute).</p><p>Also, note that the above tests are not comprehensive but likely represent a variety of common queries. For example, it would be nice to see how performance scales with input size — that can be left as an exercise to the reader. We also have the option to call b.ResetTimer() just before the b.N loop if the initial setup takes significant time, but there’s no need to do that here. And as usual, there’s much more to the <a href="https://pkg.go.dev/testing#hdr-Benchmarks">benchmarks part of the testing package</a> to dive into!</p><p>If there are additional use cases you’d like to see benchmarked, please let me know in the comments! In the next article (the last of a four-part series), we’ll do some command line benchmarking of this tool against tools like grep (thanks for the idea, Aaron!).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a84de7f0eb02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/benchmarking-in-go-substrings-vs-regular-expressions-a84de7f0eb02">Benchmarking in Go: Substrings vs. Regular Expressions</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Regular Expression Support to an Existing Golang Tool]]></title>
            <link>https://medium.com/better-programming/adding-regular-expression-support-to-an-existing-golang-tool-2dcbdcd3b4ed?source=rss-3b1c987d9b0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dcbdcd3b4ed</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Stephen Wayne]]></dc:creator>
            <pubDate>Mon, 15 Aug 2022 17:42:25 GMT</pubDate>
            <atom:updated>2022-08-26T16:57:10.306Z</atom:updated>
            <content:encoded><![CDATA[<h4>Text Filtering Part 2: Electric Regex Boogaloo</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMBHtDR6vTDegrxzwPwX0Q.jpeg" /></figure><p>This is part two of a four part series (some still in progress). You can find the others here:</p><ul><li><a href="https://betterprogramming.pub/how-to-build-a-text-filtering-log-simplifying-tool-in-go-b29d3067e092">Part 1: Building a Text Filtering Tool in Go</a></li><li><a href="https://betterprogramming.pub/benchmarking-in-go-substrings-vs-regular-expressions-a84de7f0eb02">Part 3: Benchmarking a Program in Go</a></li><li><a href="https://betterprogramming.pub/benchmarking-command-line-tools-7d00ed4813cc">Part 4: Command-line Benchmarking Against grep</a></li></ul><p>Previously, we built an <a href="https://betterprogramming.pub/how-to-build-a-text-filtering-log-simplifying-tool-in-go-b29d3067e092">inverse string matching tool in Go</a>, with the goal of removing noisy logs while debugging. The first iteration accepted one or more keyphrases to match against a source file. This is great for somewhat static, repetitive lines, but what if we want to remove lines matching a particular pattern?</p><p>Enter regular expressions.</p><p>Today, we’ll cover some of the basics of regular expressions in Go, as well as how to extend an existing program to add functionality in a backward compatible manner.</p><h3>What are regular expressions?</h3><p>Regular expressions (regex for short) are a series of characters that specify a search <em>pattern</em>. They are used by string searching algorithms to identify a relevant section of text.</p><p>You’re likely already familiar with wildcards — using * to represent any number of characters (including an empty string). Regex take that a step further.</p><p>They allow you to pattern match much more specifically. You can search for any character <em>other than</em> something using [^&lt;characters to avoid&gt;]. You can search for something <em>beginning with</em> a phrase using ^&lt;phrase&gt;. Likewise, you can search for something <em>ending with</em> a phrase using &lt;phrase&gt;$. There’s a lot more you can do, which you can learn about <a href="https://www.computerhope.com/jargon/r/regex.htm">here</a> and test out <a href="https://regex101.com/">here</a>.</p><h3>Why do we care?</h3><p>Log messages are often well suited to substring match against, but not always. What if we wanted to remove log lines between two specific timestamps, say August 1–4 of 2022? We could do that using the existing tool with substring match by repeating ourselves:</p><pre>-keys=&quot;logcreated-20220801:|logcreated-20220802:|logcreated-20220803:|logcreated-20220804:</pre><p>Or we could search for patterns that match the following regular expression:</p><pre>^logcreated-2022080([1-4]):</pre><p>As the complexity of the query increases, regular expressions become powerful tools for custom, repeatable searches.</p><h3>Adding new functionality</h3><p>As in the <a href="https://betterprogramming.pub/how-to-build-a-text-filtering-log-simplifying-tool-in-go-b29d3067e092">previous article</a>, we should consider how a user will interact with the new feature. For simplicity’s sake, we can assume a user will supply either a set of substrings (-keys) to match against, or a pattern (-pattern), or both. This will make the instructions and error handling logic easy — complain if neither keys nor pattern were given.</p><p>To add inverse pattern matching, we’ll need to do the following:</p><ul><li>update the readme and help instructions</li><li>add the new flag and error handling</li><li>write the regex matching code</li><li>update the processing loop to select between regex and substring match</li></ul><p>Updated help and readme guidance can be viewed in the <a href="https://github.com/swayne275/lineremover">tool repo</a> for brevity.</p><h4>Add the new flag and error handling:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b12defd8247f51284d7ce51d6d1b461/href">https://medium.com/media/7b12defd8247f51284d7ce51d6d1b461/href</a></iframe><p>Because we’re getting user inputs through getUserInput() and storing that config in config, we only need to update these entities to add a new flag. Here, we’re simply defining the new flag on line 11, and verifying that either it or keys has been passed in on line 19.</p><p>For this code we’re using <a href="https://pkg.go.dev/regexp">regexp</a>, another standard library package to handle the regular expression matching. We’re also validating that the provided pattern can actually be used as a regular expression. By doing it here, we can fail early and in one place for user-input-related things.</p><p>Note that Go’s regexpr doesn’t support some functionality, such as <a href="https://stackoverflow.com/questions/26771592/negative-look-ahead-in-go-regular-expressions">negative look-ahead</a>. Doing some quick Googling it seems that there are various implementations of RE2 that should offer additional functionality, but that’s an exploration for another time.</p><h4>Write the regex matching code:</h4><p>Since we’ve already compiled our regular expression and included it in the config, we only need to call MatchString() on the regular expression, passing in the string to check against. This will yield a boolean on whether there was a match. Similarly to substring checking, we can iterate through all lines in the input file, calling MatchString() against them, and save the ones that do not match.</p><p>To simplify the processing logic, let’s add a receiver to config:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db4dccfbd9ed8dede90a658b16607eba/href">https://medium.com/media/db4dccfbd9ed8dede90a658b16607eba/href</a></iframe><p>lineMatches() can be called on a config instance to determine if the given string matches something provided in the pattern, or something provided in the keyphrases.</p><h4>Update the processing loop</h4><p>There isn’t much to change in transformInputImpl(). We are going to take a *config as input (rather than a few variables), and we’ll swap:</p><pre>if !substrInLine(line, keys) {</pre><p>for:</p><pre>if !cfg.lineMatches(line) {</pre><p>A nice side effect of this is now all of the line matching logic is tied up in lineMatches(), which makes further tweaks to the processing clear and centralized.</p><h3>Using the Tool</h3><p>Building on our previous examples, we can now replace:</p><pre>go run main.go -file=&quot;example/input.txt&quot; -keys=&quot;hello&quot;</pre><p>with:</p><pre>go run main.go -file=&quot;example/input.txt&quot; -pattern=&quot;hello&quot;</pre><p>That will accomplish the same thing, but isn’t very exciting or new. How about we do something like:</p><pre>go run main.go -file=&quot;example/input.txt&quot; -pattern=&quot;.*b([r]?)ig([ht]?).*&quot;</pre><p>This pattern can be further explained by using <a href="https://regex101.com/">regex101</a>, but essentially it matches any input lines containing either “big”, “brig”, “bight”, or “bright”. In examples/input.txt this will leave only hello world remaining!</p><p>We can even supply both a set of keyphrases and a pattern if we’d like!</p><pre>go run main.go -file=&quot;example/input.txt&quot; -keys=&quot;hello&quot; -pattern=&quot;.*b([r]?)ig([ht]?).*&quot;</pre><p>Will leave nothing remaining from our input file.</p><h3>Wrapping Up</h3><p>Today, we’ve extended a pre-existing tool to add additional functionality without needing to change too much of the core structure. When building software we must consider the current use cases, but it is prudent to consider future use cases. Thinking about this during the design and build phase can allow software to be extended with minimal changes to existing code, and therefore less room for bugs, headaches, and gotchas.</p><p>Further extending lineremover to accept a path for the destination file is left as an exercise to the reader.</p><p>If you clone the <a href="https://github.com/swayne275/lineremover">repo</a> and follow the above process you can go on a quick and painless side quest to get your hands a bit dirty with Go!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dcbdcd3b4ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/adding-regular-expression-support-to-an-existing-golang-tool-2dcbdcd3b4ed">Adding Regular Expression Support to an Existing Golang Tool</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>