<?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 Juan Carlos Garcia on Medium]]></title>
        <description><![CDATA[Stories by Juan Carlos Garcia on Medium]]></description>
        <link>https://medium.com/@deadkennedyx?source=rss-d715ad084863------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KbxyZ3ZxrqVFjnbmQLU1NA.jpeg</url>
            <title>Stories by Juan Carlos Garcia on Medium</title>
            <link>https://medium.com/@deadkennedyx?source=rss-d715ad084863------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:53:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deadkennedyx/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[log-loss.md]]></title>
            <link>https://medium.com/@deadkennedyx/log-loss-md-5e2de3d097c0?source=rss-d715ad084863------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e2de3d097c0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[prediction-markets]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[predictions]]></category>
            <dc:creator><![CDATA[Juan Carlos Garcia]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 17:31:02 GMT</pubDate>
            <atom:updated>2025-12-22T17:36:56.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TWZCV5ew_8Usi85f.png" /></figure><p>When you’re forecasting real-world events (like Polymarket questions), you shouldn’t just predict <strong>yes/no</strong>. You should predict a <strong>probability</strong>. Log loss is a scoring rule designed for exactly that. It rewards you for being confidently right, and punishes you hard for being confidently wrong.</p><p>For a binary event (YES/NO), if your model predicts (p) and the outcome is ∈{0,1}, log loss is:</p><p>−(ylog(p)+(1−y)log(1−p))</p><p>Intuition:</p><ul><li>If the event happens ((y=1)) and you predicted (p=0.9), log loss is small (good).</li><li>If it happens and you predicted (p=0.1), log loss is large (you were confidently wrong).</li><li>If you predict (p \approx 0.5), you’re “hedging,” and the penalty is moderate either way.</li></ul><p>That’s why log loss is popular for forecasting systems. It pushes your model toward <strong>calibrated probabilities</strong>, not just bold guesses.</p><h4>Polymarket as labels, GDELT + OSINT as signals</h4><p>A practical way to think about building a model here:</p><ul><li><strong>Polymarket</strong> provides clean targets:</li><li><strong>Outcome label:</strong> does the event resolve YES by the deadline?</li><li><strong>Movement label:</strong> will the market probability move by ≥X points in the next 24h?</li><li><strong>GDELT</strong> gives structured, time-stamped “news activity” signals:</li><li>spikes in coverage volume around entities</li><li>acceleration in mentions (rate-of-change matters)</li><li>spread across regions/outlets</li><li><strong>OSINT datasets</strong> add public indicators that sometimes lead headlines:</li><li>official statements, public documents, verified updates</li><li>cross-source corroboration patterns</li><li>contradictions (official denial vs accumulating evidence)</li></ul><p>Your model learns a mapping like:</p><p>P(event∣signals so far)</p><p>and log loss tells you whether those probabilities match reality over time.</p><h4><strong>Why log loss matters for “predicting decisions”</strong></h4><p>You’re not predicting a specific person’s mind. You’re predicting how <strong>a crowd</strong> (traders + attention + incentives) and the world update probabilities as evidence arrives. Log loss is useful because it evaluates exactly what you care about:</p><ul><li>Were you <strong>right with the right confidence</strong> (good calibration)?</li><li>Or were you right but consistently <strong>overconfident</strong> (and would eventually get punished)?</li></ul><p>Two models can have similar accuracy, but the one with lower log loss is usually the one you can trust more as a probability engine.</p><h4><strong>The latency angle: where profit would actually come from</strong></h4><p>Even if you find predictive signals, turning that into profit typically depends on <strong>speed</strong>. In practice, any edge is often about reacting to new information before the market fully incorporates it. That means the pipeline isn’t just:</p><p><strong>signals to model to decision</strong></p><p>It’s:</p><p><strong>signals to model to place order</strong></p><p>and it has to run fast.</p><p>If the goal is to capture short-lived mispricings, you’d likely need:</p><ul><li>signal ingestion and feature generation in near real-time</li><li>model inference that’s effectively instantaneous</li><li>order placement that happens, ideally before the market reacts</li></ul><p>Otherwise, even a correct prediction can be unprofitable because the price updates by the time you act.</p><p>Forecasting projects fail when they accidentally use information that wasn’t available at prediction time (data leakage). To use log loss correctly, you want:</p><ul><li>strict time-based splits (train on past, test on future)</li><li>features computed only from data available up to that timestamp</li><li>calibration checks (not just “did it pick the right side”)</li></ul><p>That combination, clean timestamps plus probabilistic predictions plus log loss, gets you something closer to <strong>reliable belief updates</strong>, which is what markets are really measuring.</p><h4><strong>Disclaimer</strong>:</h4><p>This is <strong>research and experimentation</strong> I’m doing to see what’s possible with public data (Polymarket, GDELT, OSINT-style signals). I’m <strong>not claiming</strong> this already works, or that it reliably “beats” prediction markets. Markets can be efficient, regimes change, and it’s easy to fool yourself without strict evaluation. The goal here is to build a careful pipeline, measure it honestly (log loss + calibration), and learn what, if anything, holds up out-of-sample.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e2de3d097c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polymarket edge hunting: what? it did work!]]></title>
            <link>https://medium.com/@deadkennedyx/polymarket-edge-hunting-what-it-did-work-e68509990126?source=rss-d715ad084863------2</link>
            <guid isPermaLink="false">https://medium.com/p/e68509990126</guid>
            <category><![CDATA[polymarket]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[Juan Carlos Garcia]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 22:27:55 GMT</pubDate>
            <atom:updated>2025-12-16T22:34:05.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KP2cdLGRXsm6uybL.png" /></figure><p>Three weeks ago I set out to answer a simple question: are Polymarket binaries ever mispriced enough to lock in profit, or at least to front-run slow market makers? The result is a small Rust daemon that fans into hundreds of markets, checks both legs, and yells when it finds an edge. Along the way it uncovered an odd straddle strategy on 15 minute Bitcoin markets.</p><p>This is a writeup of what I built, why it works, and where it still bites us.</p><ul><li>Language/runtime: Rust + Tokio.</li><li>Market data: Polymarket CLOB websocket (wss://ws-subscriptions-clob.polymarket.com/ws/market), chunked subscriptions.</li><li>Discovery: a Gamma API crawl to list open, orderbook‑enabled markets, filtered to a token cap (env-configurable).</li><li>Processing: one fan‑in channel (tokio::mpsc) feeding an engine that maintains top-of-book per asset.</li><li>Throughput: ~1000+ markets per run (~10,000 tokens), sub‑second processing; per-quote work is O(1).</li></ul><p><strong>THE RULES/CONSTRAINTS</strong></p><p>We only evaluate edges when both legs are:</p><ul><li>Fresh as a pair: |tsA - tsB| &lt;= pair_stale_ms (default 500 ms).</li><li>Low lag: each leg’s lag &lt;= max_lag_ms (default 1500 ms).</li><li>Sized (optional): sizes present and &gt;= min_qty (default 10) and not older than size_stale_ms (default 30s).</li></ul><p>Missing sizes are common because price_change messages don&#39;t carry size; we cache book sizes with a timestamp and only require them if REQUIRE_SIZES<strong>=1.</strong></p><p><strong>THE MATH</strong></p><p>For binary markets, YES + NO must sum to 1 at expiry. At the top of book:</p><ul><li>Long full-set edge: edge = 1 - (askY + askN). Buy both asks; positive edge = cheap.</li><li>Short full-set edge: edge = (bidY + bidN) - 1. Sell both bids; positive edge = rich.</li></ul><p>We log when edge &gt;= EDGE_MIN (default 0.002 = 0.2%). That&#39;s what produced lines like:</p><pre>EDGE ✅ LONG (+0.0020) [...] | buy Yes@0.3000 + No@0.6980 | cost=0.9980</pre><p>PROOF OF WORK:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*0QJ1gB1G9UPAgP3eBMyxYw.png" /><figcaption>Bot in action</figcaption></figure><p>At $200 notional, that’s ~$0.40 gross before fees/slippage. Profit ≈ edge × notional.</p><p><strong>THE BITCOIN THING THAT IS IN ALPHA(AKA not working as expected).</strong></p><p>Polymarket’s 15‑minute Bitcoin “Up/Down” binaries are chronically sloppy. We added a straddle logger that kicks in when:</p><ul><li>The market looks like “Bitcoin” + “15m” with outcomes Up/Down.</li><li>The sum of asks &lt; 1 and edge &gt;= EDGE_MIN.</li></ul><p>It prints a skewed allocation toward the cheaper leg (default 70/30). This mirrors an on‑chain wallet we observed: they rarely hedge 50/50; they overweight momentum on BTC and still capture the structural underpricing.</p><p>Example log:</p><pre>STRADDLE ⚡ BTC15m (+0.0045) [...] cost=0.9955 | cheap Down@0.4200 (w=70%) | exp Up@0.5750 (w=30%)</pre><p>No automated trading here, just a ready made playbook if you want to replicate it manually or wire an executor.</p><p><strong>PROCESSING</strong></p><ul><li>WebSocket in shards, asset IDs into chunks (default 200 per shard) to avoid oversized subscriptions.</li><li>Each incoming text frame is parsed once to an envelope, then dispatched to book or price_change.</li><li>Per quote: update two floats, optional sizes, two timestamps, then two edge checks (long/short) with early guard exits. The hot path is tiny and stays under a millisecond on a laptop.</li></ul><p>The per-second metrics ( sanity ws_msgs_s=...) explained why edges sometimes vanish:</p><ul><li>book_s near zero, price_change_s high -&gt; sizes missing. Relax REQUIRE_SIZES or wait for books.</li><li>skip_no_size_s high -&gt; same story; tune SIZE_STALE_MS or turn off size gating.</li><li>skip_lag_s high -&gt; fix timestamp units (normalize sec/ms/µs/ns) or sync your clock.</li><li>skip_stale_s high -&gt; widen PAIR_STALE_MS if legs arrive slightly out of sync.</li></ul><p>Once lag/size were under control, the bot started spitting real edges.</p><p>Key env knobs:</p><ul><li>DARKTOWER_EDGE_MIN (e.g., 0.001-0.003)</li><li>DARKTOWER_REQUIRE_SIZES=0 if books are sparse</li><li>DARKTOWER_SIZE_STALE_MS (keep sizes alive longer)</li><li>DARKTOWER_PAIR_STALE_MS / DARKTOWER_MAX_LAG_MS (freshness)</li><li>DARKTOWER_STRADDLE_BTC=1 and DARKTOWER_STRADDLE_SKEW_CHEAP (0.5-0.9) for the BTC 15m logger</li><li>Execution risk: filling one leg without the other hurts; atomicity or low latency helps.</li><li>Fees/slippage: 20 bps edges evaporate fast with taker + resolution fees; set EDGE_MIN above your fee stack.</li><li>Signal: the wallet we shadowed clearly uses momentum on BTC; a simple skew helps, but a real signal would look at short term price drift or CEX orderflow.</li><li>Polymarket binaries do misprice very often because sizes are missing or updates are out of sync, not because of deep inefficiency.</li><li>Subsecond processing + tiny per-quote work lets you scan hundreds of markets continuously.</li><li>Straddle on BTC 15m is a live edge, but can’t exploit it correctly. Still trying to reverse engineer the accounts that are succesfully exploiting it.</li></ul><p>I did this as a fun experiment, never expected to actually get edges and be able to process them this fast, so im still thinking on what I should do with this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e68509990126" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Warming Strategy Caches in Rails: From 15 Minute RAM Bombs to Millisecond Responses]]></title>
            <link>https://medium.com/@deadkennedyx/warming-strategy-caches-in-rails-from-15-minute-ram-bombs-to-millisecond-responses-a68c9f88729b?source=rss-d715ad084863------2</link>
            <guid isPermaLink="false">https://medium.com/p/a68c9f88729b</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Juan Carlos Garcia]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 06:28:30 GMT</pubDate>
            <atom:updated>2025-11-28T05:48:48.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zW6sRZJ0qlm5M7RmgsEilg.png" /></figure><p>I run a Rails app <a href="https://indy.trading/">https://indy.trading</a> that shows “strategies” based on politician and insider trading signals. The UX goal is simple: open the Strategies page and everything should load instantly: charts, metrics, the whole thing. No spinners, no “calculating…” placeholders.</p><p>The catch is that those charts aren’t trivial. Each strategy needs an equity curve built from thousands of trades and millions of daily prices. If I compute them on every request, my servers melt. If I precompute them all at once, my servers <em>also</em> melt just at 3am instead of noon.</p><p>This post is about the caching + warming setup I ended up with, the memory issues I hit, a 24-hour “slow warmer” path I explored, and why I ultimately picked autoscaling on Fly.io instead (for now).</p><h3>The problem</h3><p>I have three warmers that run nightly:</p><pre>namespace :warm do<br>  desc &quot;Nightly prewarm of historical caches + strategies &amp; leaderboards payloads&quot;<br>  task nightly: :environment do<br>    Warm::Historical.new.call<br>    Warm::StrategiesWarmer.new.call<br>    Warm::Leaderboards.new.call<br>  end<br>end</pre><p>The expensive one is Warm::StrategiesWarmer. It does two jobs:</p><ol><li>Precompute strategy “index” metrics (trades count, avg return, win rate, etc.)</li><li>Precompute an <strong>equity curve series</strong> per strategy that I render as a sparkline on the Strategies index.</li></ol><p>This is the equity curve builder:</p><pre>series = Strategies::EquityCurve.new(<br>  strategy: s,<br>  window_days: window_days,<br>  prices: prices,<br>  trades: s_trades,<br>  as_of_date: as_of<br>).call</pre><p>And that series is what drives the chart in the UI. In the controller I fetch cached series and pass them into the SVG sparkline partial:</p><pre>&lt;%= render &quot;strategies/sparkline&quot;,<br>  series: @series_by_id[s.id],<br>  range_label: &quot;ALL&quot; %&gt;</pre><p>So yes: <strong>EquityCurve = the historical performance line you see in the chart.</strong></p><h3>Why caching is mandatory</h3><p>My DB has:</p><ul><li>daily_prices: <strong>3+million rows</strong></li><li>congress_trades + insider_transactions: <strong>35k and growing</strong></li><li>Longest strategy (long/short): <strong>11,777 trades</strong></li></ul><p>The equity curve logic is path-dependent: weights change based on trade history, and long/short strategies rebalance weekly. That means I need to walk forward through time, apply returns, compound NAV, etc.</p><p>Even for one strategy, that’s not something you do in a request. For all strategies? Not a chance. So the architecture becomes:</p><ul><li><strong>Nightly warmer precomputes</strong></li><li><strong>Rails.cache stores</strong></li><li><strong>Controllers read</strong></li><li><strong>Users get responses in milliseconds</strong></li></ul><h3>How the warmer originally worked</h3><p>At a high level:</p><ol><li>Load all strategies.</li><li>For each window (all, 7d, 30d, 90d):</li></ol><ul><li>Fetch <strong>all trades for all strategies</strong></li><li>Compute bulk metrics</li><li>Compute equity curves in batches</li><li>Write cache keys for daily + “latest aliases”</li></ul><p><strong>Core loop:</strong></p><pre>strategies = Strategy.published.ordered.includes(:subject).to_a<br>WINDOWS.each do |w|<br>  trades_map = Strategies::TradeFetcher.fetch(strategies, window_days: w)<br>  rows = Strategies::BulkMetrics.new(strategies, trades_map, window_days: w).call<br>  write_rows_daily_and_latest(w, as_of, rows)<br>  warm_series_batched!(strategies, trades_map, window_days: w, as_of: as_of)<br>end</pre><p>Even though series warming was “batched,” the trades_map was built for <em>every</em> strategy up front. The memory profile was basically:</p><blockquote><em>trades for everything + prices for big symbol unions + Ruby object overhead</em></blockquote><p>Result: the warmer finished fast (5–10 minutes) but ate all RAM on my worker.</p><h3>First easy optimization: downsampling</h3><p>A friend of me pointed out: you can’t even show daily points on an SVG that’s ~160px wide. Storing 1250 daily points is pointless.</p><p>so added a downsampler:</p><pre>def downsample(series)<br>  max_pts = 500<br>  return series if series.size &lt;= max_pts<br>  stride = (series.size / max_pts.to_f).ceil<br>  series.each_with_index.select { |_, i| (i % stride).zero? }.map(&amp;:first)<br>end</pre><p>So caches store ~500 points max. That cuts payload size and makes SVG rendering cheap.</p><p>But it didn’t fix the RAM spike, because I still computed the full daily curve first and only downsampled at the end.</p><h3>Second optimization idea: slow warmers over 24 hours</h3><p>If the warmer only runs once per day, there’s no need for it to finish in 10 minutes. I don’t care if it takes an hour. I don’t even care if it takes a full day.</p><p>So I prototyped a Solid Queue pipeline that:</p><ul><li>runs <strong>one job per strategy</strong></li><li>enforces concurrency = 1</li><li>spreads jobs across the day</li><li>fetches prices in symbol slices to cap heap growth</li></ul><p>Conceptually:</p><ol><li>Orchestrator enqueues one StrategyJob per strategy, delayed into time slots.</li><li>Each job warms only that strategy’s equity curve.</li><li>Finalizer recomputes bulk metrics and writes the index/alias keys.</li></ol><p>That changes peak memory from:</p><blockquote><em>“symbols and prices for all strategies”</em></blockquote><p>to:</p><blockquote><em>“symbols and prices for one strategy”</em></blockquote><p>It also makes request-time fallback safe, because missing series are built per-strategy too.</p><p>From an engineering POV, this is the cleanest solution.</p><h3>The cost reality check</h3><p>I’m on Fly.io. My setup is:</p><ul><li><strong>App machine:</strong> shared-cpu-1x / 256MB</li><li><strong>Queue machine:</strong> shared-cpu-4x / 4GB<br> (this is where warmers run)</li></ul><p>The big queue VM only needs to be big during warmers. It’s idle the other ~23h45m.</p><p>Fly bills per-second for running Machines. If I only run big for ~15 minutes a day, the extra bill is tiny.</p><p>Roughly:</p><ul><li>Small all day: ~<strong>$1.9/mo</strong></li><li>Big all day: ~<strong>$23.7/mo</strong></li><li>Big 15 min/day: <strong>+$0.2/mo</strong> above small</li></ul><p>So two paths are both cheap:</p><ol><li>Make warmers slow enough to run on tiny workers all day.</li><li>Keep warmers fast, autoscale big just for the run.</li></ol><p>The difference is complexity + rollout risk.</p><h3>Why I chose autoscaling (for now)</h3><p>The 24-hour pipeline requires code surgery, careful testing, and a higher chance of regression.</p><p>Autoscaling doesn’t:</p><ul><li>keep app machines tiny</li><li>scale the queue machine up at 2am</li><li>run warmers fast</li><li>scale it back down</li></ul><p>The cost delta is negligible and the implementation is mostly config/scripting. I can ship it quickly and not risk breaking strategy curves.</p><p>So the pragmatic call was:</p><blockquote><em>Burst scale for warmers, stay tiny the rest of the time.</em></blockquote><p>I’ll probably revisit slow warmers later because the architecture is nicer. But autoscaling gets me 90% of the benefit immediately.</p><h3>What this architecture buys me</h3><ol><li><strong>Millisecond UX</strong></li></ol><ul><li>Index loads cached rows + cached series.</li><li>If a series is missing, I compute only that strategy on-demand.</li></ul><p>2. <strong>Stable web performance</strong></p><ul><li>Heavy compute is never in request paths.</li></ul><p>3.<strong> Controlled warm window</strong></p><ul><li>Warmers run while the queue machine is scaled up (fast, safe).</li></ul><p>4.<strong> Low monthly cost</strong></p><ul><li>Big resources only exist for minutes/day.</li></ul><h3>Lessons learned</h3><ul><li><strong>Cache keys matter.</strong><br> Daily keys + “latest alias” keys mean you can fall back gracefully:<br> today → yesterday → latest alias → on-demand.</li><li><strong>Downsampling is a UI optimization, not a compute optimization.</strong><br> It reduces payload and render time, but doesn’t fix warm-time memory unless you rework compute too.</li><li><strong>Ruby objects are expensive.</strong><br> A few million floats in nested hashes balloon into gigabytes. Streaming builds and slicing matter.</li><li><strong>Sometimes “less elegant” wins.</strong><br> Autoscaling is less pure than a fully incremental pipeline, but it’s simple, safe, and basically free at this scale.</li></ul><h3>What’s next</h3><p>If/when I go back to the 24-hour design, the next step is an “event-date equity curve”:</p><ul><li>compute only on trade dates + rebalance dates</li><li>fetch prices only for those dates</li><li>stay exact, do far fewer steps</li></ul><p>That reduces CPU <em>and</em> memory.</p><p>But for now, the combo of prewarming + downsampled caches + burst scaling gives me the UX I want at a cost that’s honestly hard to care about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a68c9f88729b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Blocks to Block Filters: A Practical Guide to Bitcoin Privacy with BIPs 157, 158 and others —…]]></title>
            <link>https://medium.com/@deadkennedyx/from-blocks-to-block-filters-a-practical-guide-to-bitcoin-privacy-with-bips-157-158-and-others-29212ec632e4?source=rss-d715ad084863------2</link>
            <guid isPermaLink="false">https://medium.com/p/29212ec632e4</guid>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[bitcoin-wallet]]></category>
            <category><![CDATA[privacy-protection]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Juan Carlos Garcia]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 04:23:38 GMT</pubDate>
            <atom:updated>2025-09-30T04:23:38.656Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Blocks to Block Filters: A Practical Guide to Bitcoin Privacy with BIPs 157, 158 and others — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9Mq21qcBpiUzwX6-5X5eA.jpeg" /></figure><p><strong>Intro</strong></p><p>Bitcoin is <strong>pseudonymous</strong>, not anonymous. The ledger is public: transactions are visible, and addresses can be clustered into wallet footprints.</p><p>Especially once any address is linked to your identity (e.g., via an exchange or reuse). On the network side, the first peers that see your transaction can link it to your IP unless you use privacy-preserving broadcast. Historically, many light wallets leaked interests through <strong>Bloom-filter SPV (BIP-37)</strong>, effectively hinting which addresses they cared about. The newer <strong>compact block filters (BIP-157/158)</strong> flip that model so wallets learn privately, leaking far less.</p><h3>What privacy problem light clients have (Bloom/SPV leaks).</h3><h4>SPV leaks</h4><p>Any Simplified Payment Verification approach leaks some info because you don’t verify the whole chain locally</p><ul><li><strong>Server-side leaks:</strong> Electrum-style/SPV servers may learn your xpub or address list → they know your balance, history, and when you spend.</li><li><strong>Network leaks:</strong> Broadcasting directly can tie your transactions/queries to your IP; peer selection/timing can reveal which blocks/txs you care about.</li><li><strong>On-chain linkage:</strong> Limited wallet features (address reuse, poor coin control) make heuristic clustering easier.</li></ul><h4>Bloom filter leaks(BIP 37)</h4><p>Older SPV/light wallets asked random peers for “transactions that match this Bloom filter.”</p><p>Because the filter is derived from your wallet’s addresses/scripts, a spying node can:</p><ul><li>Test candidates against your filter and infer which addresses are yours.</li><li>Combine multiple filter updates (“intersection attack”) to pinpoint your true set of addresses.</li><li>Link your addresses and spending patterns to your IP/identity.<br> Result: significant wallet deanonymization. (BIP37 is largely deprecated; many nodes disable it.)</li></ul><p>So lets dive into some concepts to explain how bip-158 and bip-157 fixes this issues.</p><h4>Compact Block</h4><p>A compact block filter is a tiny, compressed summary of what’s inside a Bitcoin block (specifically, the scripts/addresses that appear in that block). Think of it like a block’s “table of contents,” shrunk down.</p><p><strong>How they’re used (BIP157/158 “Neutrino”):</strong></p><ol><li>Your wallet computes the script patterns it cares about (derived from your keys/addresses).</li><li>It downloads the filter for each block from random peers (plus a chain of “filter headers” to verify integrity).</li><li>It tests locally: “Does this block <em>possibly</em> contain something of mine?”</li><li>Only if the answer is yes, it fetches the full block (or relevant tx) to verify.</li></ol><p>This way you never hand your addresses/xpubs to a server. Everyone downloads the same small filters, and the match check happens <strong>on your device </strong>locally, so peers can’t easily tell which addresses you’re interested in.</p><p>Some of the limits we will encounter with this is that you don’t get network cloak with this, which is easily solved by using tor/i2p for wallet syncs/transactions, so using this technique alongside with tor will provide privacy on both ends.</p><h3>Implementation</h3><p>Right now I’m developing a privacy wallet that is using bip 158 and bip 157 and Payjoin(bip 78)</p><p>The library I’m using for bip 158 and 157 is: <a href="https://github.com/DeadKennedyx/niebla-158">niebla-158</a></p><p>The idea is that niebla-158 in conjunction with <a href="https://github.com/cloudhead/nakamoto">nakamoto</a>, any dev can have an easy time integrating privacy into their wallet syncing process.</p><p>niebla-158 does the necessary interface and traits for easy integration with wallets and nakamoto provides the p2p connection for block checking.</p><h4>Why pushing this is important?</h4><p>Privacy is control. It reduces what others can infer or do to you from your data, today and in the future.</p><p>Laws, norms, and data brokers change. Data you leak today can be repurposed tomorrow.</p><p>You leak less, you blend in more, and you raise the cost of mass surveillance. It isn’t perfect anonymity, but it meaningfully increases the effort required to track you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29212ec632e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>